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
blockchain-development-kit/accelerators/corda-integration-accelerator/service-bus-integration/corda-transaction-builder/src/main/kotlin/net/corda/workbench/transactionBuilder/events/EventFactory.kt
bretf-ik
160,744,025
true
{"HTML": 3970966, "Python": 1081109, "Java": 880816, "C#": 487762, "Kotlin": 314832, "JavaScript": 161542, "PowerShell": 84190, "CSS": 23314, "PLpgSQL": 16377, "Shell": 12161, "Batchfile": 8685, "Dockerfile": 3541, "Scala": 840, "ASP": 105}
package net.corda.workbench.transactionBuilder.events import net.corda.workbench.commons.event.Event /** * Build events for storage. TODO it would * be nice to have typed classes here, but Event * is currently defined as a data class & so cant be extended */ object EventFactory { fun CORDA_APP_DEPLOYED(appname: String, network: String): Event { return Event(type = "CordaAppDeployed", aggregateId = network, payload = mapOf<String, Any>("appname" to appname, "network" to network)) } fun AGENT_STARTED(network: String, port: Int, pid: Long): Event { return Event(type = "AgentStarted", aggregateId = network, payload = mapOf("network" to network, "port" to port, "pid" to pid)) } fun AGENT_STOPPED(network: String, pid: Long, message: String): Event { return Event(type = "AgentStopped", aggregateId = network, payload = mapOf("network" to network, "pid" to pid, "message" to message)) } }
0
HTML
0
0
99360c7092810e8f5405f4fc8ebcfc6a3caa7901
1,166
blockchain
MIT License
app/src/main/java/com/kylecorry/trail_sense/weather/domain/sealevel/SeaLevelCalibrationFactory.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.weather.domain.sealevel import com.kylecorry.trail_sense.shared.UserPreferences import com.kylecorry.trail_sense.weather.domain.sealevel.kalman.KalmanSeaLevelCalibrationSettings import com.kylecorry.trail_sense.weather.domain.sealevel.kalman.KalmanSeaLevelCalibrationStrategy class SeaLevelCalibrationFactory { fun create(prefs: UserPreferences): ISeaLevelCalibrationStrategy { if (!prefs.weather.useSeaLevelPressure) { return NullSeaLevelCalibrationStrategy() } if (prefs.altimeterMode == UserPreferences.AltimeterMode.Override) { return SimpleSeaLevelCalibrationStrategy(prefs.weather.seaLevelFactorInTemp) } return KalmanSeaLevelCalibrationStrategy( KalmanSeaLevelCalibrationSettings( prefs.weather.altitudeOutlier, prefs.weather.altitudeSmoothing, prefs.weather.pressureSmoothing, prefs.weather.seaLevelFactorInTemp, prefs.weather.useAltitudeVariance ) ) } }
240
Kotlin
33
353
9d27ba8e10a45979859c8d4a8f2c8a7910559ec7
1,087
Trail-Sense
MIT License
pleo-antaeus-data/src/test/kotlin/io/pleo/antaeus/data/DatabaseExtension.kt
tiberiuemilian
428,192,517
true
{"Kotlin": 57972, "Shell": 1092, "Dockerfile": 287}
package io.pleo.antaeus.data import mu.KotlinLogging import org.h2.tools.Server import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.StdOutSqlLogger import org.jetbrains.exposed.sql.addLogger import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.transactions.transaction import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.BeforeAllCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext import org.testcontainers.containers.MySQLContainer import org.testcontainers.utility.DockerImageName import java.sql.Connection class DatabaseExtension : BeforeAllCallback, ExtensionContext.Store.CloseableResource, BeforeEachCallback, AfterEachCallback { companion object { private val logger = KotlinLogging.logger {} @JvmStatic private var withMysql: Boolean = System.getenv("withMysql")?.toBoolean() ?: false @JvmStatic private var started = false private const val testDatabase = "antaeus" // you can use root/test controller to connect to the test mysql container private const val testUser = "root" private const val testPass = "<PASSWORD>" private val tables = arrayOf(CustomerTable, InvoiceTable) lateinit var mysqlContainer: MySQLContainer<Nothing> lateinit var h2DbServer: Server lateinit var testDb: Database } override fun beforeAll(context: ExtensionContext?) { if (!started) { started = true logger.debug { "\"before all tests\" startup logic goes here" } // The following line registers a callback hook when the root test context is shut down // context!!.root.getStore(GLOBAL).put("any unique name", this); if (withMysql) { logger.info { "Create mysql test container." } mysqlContainer = MySQLContainer<Nothing>(DockerImageName.parse("mysql:8.0.27")).apply { withDatabaseName(testDatabase) withUsername(testUser) withPassword(<PASSWORD>) // to allow test database client connections withEnv("MYSQL_ROOT_HOST", "%") } mysqlContainer.start() testDb = Database.connect( url = mysqlContainer.jdbcUrl, driver = "com.mysql.cj.jdbc.Driver", user = testUser, password = <PASSWORD> ).also { TransactionManager.manager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE } } else { // with H2 mem database (super-fast) testDb = Database.connect( // Concurrency control mechanism and transaction isolation can be disabled so that we can check out the state of database // in the middle of a transaction from a database browser. (https://nimatrueway.github.io/2017/03/01/h2-inmem-browsing.html) // url = "jdbc:h2:mem:test;MODE=Mysql;MVCC=FALSE;MV_STORE=FALSE;LOCK_MODE=0;DB_CLOSE_DELAY=-1", url = "jdbc:h2:mem:$testDatabase;MODE=Mysql;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver", user = testUser, password = <PASSWORD> ).also { TransactionManager.manager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE } h2DbServer = Server.createTcpServer ("-tcp", "-tcpAllowOthers", "-tcpPort", "9092", "-tcpDaemon").start() } } } override fun beforeEach(context: ExtensionContext?) { transaction(testDb) { addLogger(StdOutSqlLogger) logger.debug { "Create all tables" } SchemaUtils.create(*tables) } } override fun afterEach(context: ExtensionContext?) { transaction(testDb) { addLogger(StdOutSqlLogger) logger.debug { "Drop all tables to ensure a clean slate on each run" } SchemaUtils.drop(*tables) } } override fun close() { if (withMysql) { logger.info { "Destroy mysql test container." } mysqlContainer.stop() } else { // H2 database h2DbServer.shutdown() } } }
0
Kotlin
0
0
a916f12e8a66c235cb5c6b4f6f00bb309f926c82
4,573
antaeus
Creative Commons Zero v1.0 Universal
composeApp/src/commonMain/kotlin/di/Koin.kt
Coding-Meet
740,487,604
false
{"Kotlin": 107587, "JavaScript": 707, "Swift": 659, "HTML": 401}
package di import org.koin.core.context.startKoin import org.koin.dsl.KoinAppDeclaration fun initKoin(appDeclaration: KoinAppDeclaration = {}) = startKoin { appDeclaration() modules( geminiServiceModule, databaseModule, geminiRepositoryModule, networkModule, useCaseModule, viewModelModule, platformModule() ) }
1
Kotlin
4
7
d1680ef03820bb5e6645ff16c88ad3b0e4a73bc8
430
Gemini-AI-KMP-App
MIT License
ktgram/src/main/kotlin/ru/lavafrai/ktgram/types/VideoChatStarted.kt
lavaFrai
812,095,309
false
{"Kotlin": 477598}
import kotlinx.serialization.Serializable import ru.lavafrai.ktgram.types.TelegramObject /** * This object represents a service message about a video chat started in the chat. Currently holds no information. */ @Serializable class VideoChatStarted : TelegramObject()
0
Kotlin
0
3
3b8e3d8aeb8a60445a84a57aaf91fda7baf038ea
269
ktgram
Apache License 2.0
product-hunt-api/src/main/kotlin/api.product.hunt/AuthorizationInterceptor.kt
shawnthye
420,680,965
false
{"Kotlin": 416438}
package api.product.hunt import okhttp3.Interceptor import okhttp3.Response /** * Temporary use developer key */ @Suppress("SpellCheckingInspection") private const val AUTHORIZATION = "Bearer YFvkSRZUDIZFnCnXAmthYqEfXAJj5803JoE8Yk6OLuU" internal class AuthorizationInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request().newBuilder() .addHeader("Authorization", AUTHORIZATION) .build() return chain.proceed(request) } }
0
Kotlin
0
0
15df4f3acc202e88f2de0e62549e6e5386440c9e
537
playground
MIT License
core/src/main/java/at/specure/info/cell/CellInfoWatcher.kt
minkiapps
296,042,018
true
{"Kotlin": 1267006, "Java": 588093, "HTML": 36596, "Shell": 4061}
/* * 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 at.specure.info.cell import android.telephony.CellInfo /** * Watcher that is responsible for tracking cellular connection info */ interface CellInfoWatcher { /** * Currently active data cellular network * NULL if there is no active cellular network */ val activeNetwork: CellNetworkInfo? val cellInfo: CellInfo? val allCellInfo: List<CellNetworkInfo> /** * Add listener to observe cell network changes */ fun addListener(listener: CellInfoChangeListener) /** * Remove listener from observing cell network changes */ fun removeListener(listener: CellInfoChangeListener) /** * Try update cellular network info without callbacks */ fun forceUpdate() /** * Callback that is used to observe cellular network changes tracked by [CellInfoWatcher] */ interface CellInfoChangeListener { /** * When cellular network change is detected this callback will be triggered * if no active network or cell network is available null will be returned */ fun onCellInfoChanged(activeNetwork: CellNetworkInfo?) } }
0
null
0
1
943954473818fcfbfd4ae0213fddade160abcbea
1,721
open-rmbt-android
Apache License 2.0
app/src/main/java/org/watsi/enrollment/di/modules/FragmentModule.kt
Meso-Health
227,515,211
false
null
package org.watsi.enrollment.di.modules import dagger.Module import dagger.android.ContributesAndroidInjector import org.watsi.enrollment.fragments.EditMemberFragment import org.watsi.enrollment.fragments.HomeFragment import org.watsi.enrollment.fragments.HouseholdFragment import org.watsi.enrollment.fragments.MemberNotFoundFragment import org.watsi.enrollment.fragments.MemberSearchFragment import org.watsi.enrollment.fragments.MemberSearchWithMembershipNumberFragment import org.watsi.enrollment.fragments.NewHouseholdFragment import org.watsi.enrollment.fragments.NewMemberFragment import org.watsi.enrollment.fragments.PaymentFragment import org.watsi.enrollment.fragments.RecentEditsFragment import org.watsi.enrollment.fragments.ReviewFragment import org.watsi.enrollment.fragments.StatsFragment import org.watsi.enrollment.fragments.StatusFragment @Module abstract class FragmentModule { @ContributesAndroidInjector abstract fun bindHomeFragment(): HomeFragment @ContributesAndroidInjector abstract fun bindRecentEditsFragment(): RecentEditsFragment @ContributesAndroidInjector abstract fun bindHouseholdFragment(): HouseholdFragment @ContributesAndroidInjector abstract fun bindMemberSearchFragment(): MemberSearchFragment @ContributesAndroidInjector abstract fun bindNewMemberFragment(): NewMemberFragment @ContributesAndroidInjector abstract fun bindNewHouseholdFragment(): NewHouseholdFragment @ContributesAndroidInjector abstract fun bindStatusFragment(): StatusFragment @ContributesAndroidInjector abstract fun bindEditMemberFragment(): EditMemberFragment @ContributesAndroidInjector abstract fun bindSearchFragment(): MemberSearchWithMembershipNumberFragment @ContributesAndroidInjector abstract fun bindStatsFragment(): StatsFragment @ContributesAndroidInjector abstract fun bindReviewFragment(): ReviewFragment @ContributesAndroidInjector abstract fun bindPaymentFragment(): PaymentFragment @ContributesAndroidInjector abstract fun bindMemberNotFoundFragment(): MemberNotFoundFragment }
0
Kotlin
3
1
bba562b15e5e34d3239f417c45c6ec4755510c68
2,060
meso-enrollment
Apache License 2.0
biometric/src/main/java/com/sn/biometric/BiometricListener.kt
emreesen27
487,868,347
false
{"Kotlin": 59960, "Ruby": 1173, "Shell": 173}
package com.sn.biometric interface BiometricListener { fun onFingerprintAuthenticationSuccess() fun onFingerprintAuthenticationFailure(errorMessage: String, errorCode: Int) }
0
Kotlin
1
6
39fe3fc0fab91481b37dfc609edd24275c2e7d02
183
Secretive
MIT License
app/src/main/java/com/mk2112/pv_fi/controller/questions/QTPATActivity.kt
MK2112
286,865,670
false
null
package com.mk2112.pv_fi.controller.questions import android.content.Intent import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.util.Log import android.view.View import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.mk2112.pv_fi.R import com.mk2112.pv_fi.controller.ResultActivity import com.mk2112.pv_fi.model.Resources import com.mk2112.pv_fi.model.dbManagement.DBManager import com.mk2112.pv_fi.model.questionModel.QuestionIDType import com.mk2112.pv_fi.model.questionModel.frames.QTPATFrame import kotlinx.android.synthetic.main.activity_inp.* import kotlinx.android.synthetic.main.activity_qtpat.* import kotlinx.android.synthetic.main.activity_question.* class QTPATActivity : AppCompatActivity(), View.OnClickListener { private var mCurrentQuestionCount = 1 private var mSelectedOptionPosition: Int = -1 private var mCorrectAnswers: Int = 0 private var mDBManager: DBManager? = null private var mQTPATFrame: QTPATFrame? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_qtpat) mDBManager = DBManager(this) mQTPATFrame = mDBManager!!.buildQUTPATFrame(intent.getIntExtra(Resources.QUESTIONID, 0)) mCurrentQuestionCount = intent.getIntExtra(Resources.QUESTIONCOUNTER, 0) mCorrectAnswers = intent.getIntExtra(Resources.CORRECTANSWERS, 0) setQuestion(mQTPATFrame!!, getQuizLength()) qtpat_textView_option_1.setOnClickListener(this) qtpat_textView_option_2.setOnClickListener(this) qtpat_textView_option_3.setOnClickListener(this) qtpat_textView_option_4.setOnClickListener(this) qtpat_btn_submit.setOnClickListener(this) } override fun onClick(v: View?) { when(v?.id) { R.id.qtpat_textView_option_1 -> {selectedOptionView(qtpat_textView_option_1, 1)} R.id.qtpat_textView_option_2 -> {selectedOptionView(qtpat_textView_option_2, 2)} R.id.qtpat_textView_option_3 -> {selectedOptionView(qtpat_textView_option_3, 3)} R.id.qtpat_textView_option_4 -> {selectedOptionView(qtpat_textView_option_4, 4)} R.id.qtpat_btn_submit -> { if (mSelectedOptionPosition == -1) { Toast.makeText(this, "Bitte wähle eine Antwort aus!", Toast.LENGTH_SHORT).show() } else if (mSelectedOptionPosition == 0) { mCurrentQuestionCount++ when { mCurrentQuestionCount <= getQuizLength() -> { val qt: QuestionIDType = mDBManager!!.getNewQuestionType(getProfessionNeed(), getProfession()) val intent: Intent intent = when { qt.questionType.equals("QTAT") -> { Intent(this, QTATActivity::class.java)} qt.questionType.equals("QTPAT") -> { Intent(this, QTPATActivity::class.java)} qt.questionType.equals("EPOP") -> { Intent(this, EPOPActivity::class.java)} qt.questionType.equals("ETOT") -> { Intent(this, ETOTActivity::class.java)} qt.questionType.equals("INP") -> { Intent(this, INPActivity::class.java)} qt.questionType.equals("TF") -> { Intent(this, TFActivity::class.java)} else -> { Intent(this, QTATActivity::class.java) } } intent.putExtra(Resources.QUESTIONID, qt.questionID) intent.putExtra(Resources.CORRECTANSWERS, mCorrectAnswers) intent.putExtra(Resources.QUESTIONCOUNTER, mCurrentQuestionCount) startActivity(intent) mDBManager!!.close() finish() } else -> { val intent = Intent(this, ResultActivity::class.java) intent.putExtra(Resources.CORRECTANSWERS, mCorrectAnswers) startActivity(intent) finish() } } } else { qtpat_textView_option_1.isClickable = false qtpat_textView_option_2.isClickable = false qtpat_textView_option_3.isClickable = false qtpat_textView_option_4.isClickable = false // This is to check if the answer is wrong Log.i(formatAnswerID(mQTPATFrame!!.answer).toString(), mSelectedOptionPosition.toString()) if (formatAnswerID(mQTPATFrame!!.answer) != mSelectedOptionPosition) { answerView(mSelectedOptionPosition, R.drawable.false_option_border_bg) } else { mCorrectAnswers++ mDBManager!!.markAsAnswered(intent.getIntExtra(Resources.QUESTIONID, 0)) } // This is for correct answer answerView(mQTPATFrame!!.answer, R.drawable.correct_option_border_bg ) if (mCurrentQuestionCount == getQuizLength()) { qtpat_btn_submit.text = Resources.BTN_END } else { qtpat_btn_submit.text = Resources.BTN_NEXT } mSelectedOptionPosition = 0 } } } } private fun formatAnswerID(answer: Int): Int { var smallestID = mQTPATFrame!!.answerOptions.get(0).id for (answerOption in mQTPATFrame!!.answerOptions) { if (answerOption.id < smallestID) { smallestID = answerOption.id } } return answer - (smallestID - 1) } /** * Genuinely just setting up what the user will see and interact with, no logic in here on whether maximum was reached * @param qtpatFrame carrying all the data of the question to be displayed * @param maxQuestions amount of questions to be asked within this quiz */ private fun setQuestion(qtpatFrame: QTPATFrame, maxQuestions: Int) { defaultOptionsView() qtpat_btn_submit.text = Resources.BTN_CHECK qtpat_progressBar.progress = mCurrentQuestionCount qtpat_progressBar.max = maxQuestions qtpat_textView_progress.text = "$mCurrentQuestionCount" + "/" + qtpat_progressBar.getMax() qtpat_textView_Question.text = formatQuestion(qtpatFrame.question) val res: android.content.res.Resources? = resources val resID = res!!.getIdentifier(mQTPATFrame!!.imageName, "drawable", packageName) qtpat_imageView.setImageResource(resID) qtpat_textView_option_1.text = qtpatFrame.answerOptions.get(0).answer qtpat_textView_option_2.text = qtpatFrame.answerOptions.get(1).answer qtpat_textView_option_3.text = qtpatFrame.answerOptions.get(2).answer qtpat_textView_option_4.text = qtpatFrame.answerOptions.get(3).answer } private fun formatQuestion(question: String): String { if (question.endsWith("?").not() && question.endsWith(".").not()) { return "$question?" } if (question.length > 100) { qtpat_textView_Question.textSize = 14.toFloat() } question.replace("[?]", "...") return question } /** * A function to set the view of selected option view. */ private fun selectedOptionView(tv: TextView, selectedOptionNum: Int) { defaultOptionsView() mSelectedOptionPosition = selectedOptionNum tv.setTextColor(Color.parseColor("#363A43")) tv.setTypeface(tv.typeface, Typeface.BOLD) tv.background = ContextCompat.getDrawable(this, R.drawable.selected_option_border_bg ) } /** * A function to set default options view when the new question is loaded or when the answer is reselected. */ private fun defaultOptionsView() { val options = ArrayList<TextView>() options.add(0, qtpat_textView_option_1) options.add(1, qtpat_textView_option_2) options.add(2, qtpat_textView_option_3) options.add(3, qtpat_textView_option_4) qtpat_btn_submit.text = Resources.BTN_CHECK for (option in options) { option.setTextColor(Color.parseColor("#7A8089")) option.typeface = Typeface.DEFAULT option.background = ContextCompat.getDrawable(this, R.drawable.default_option_border_bg ) } } /** * A function for answer view which is used to highlight the answer is wrong or right. */ private fun answerView(answer: Int, drawableView: Int) { var ans = answer if (answer < mQTPATFrame!!.answerOptions.get(0).id) { ans = answer + (mQTPATFrame!!.answerOptions.get(0).id - 1) } when (ans) { mQTPATFrame!!.answerOptions.get(0).id -> {renderTextView(qtpat_textView_option_1, drawableView)} mQTPATFrame!!.answerOptions.get(1).id -> {renderTextView(qtpat_textView_option_2, drawableView)} mQTPATFrame!!.answerOptions.get(2).id -> {renderTextView(qtpat_textView_option_3, drawableView)} mQTPATFrame!!.answerOptions.get(3).id -> {renderTextView(qtpat_textView_option_4, drawableView)} } } private fun renderTextView(textView: TextView, drawableView: Int) { textView.background = ContextCompat.getDrawable(this, drawableView) textView.setTypeface(null, Typeface.BOLD) textView.setTextColor(Color.parseColor("#DDDDDD")) } /** * Receive hard stored QuizLength */ private fun getQuizLength():Int { val settings = applicationContext.getSharedPreferences(Resources.SESSION_PREFS, 0) return settings.getInt(Resources.QUIZLENGTH, 1) } /** * Pulling in whether a Profession was chosen or not for Layout Setup */ private fun getProfessionNeed():Boolean { val settings = applicationContext.getSharedPreferences(Resources.SESSION_PREFS, 0) return settings.getBoolean(Resources.PROFESSIONNEEDED, false) } /** * Getting the previously hard saved profession from the shared Preference */ private fun getProfession():String { val settings = applicationContext.getSharedPreferences(Resources.SESSION_PREFS, 0) return if (settings.getString(Resources.PROFESSION, "").isNullOrEmpty()) {""} else {settings.getString(Resources.PROFESSION, "")!!} } }
2
Kotlin
0
0
25361c59c4629ed55c10e5207907f4beed6b1b07
10,980
FI-App
MIT License
idea/testData/multiModuleQuickFix/withTestDummy/common/common.kt
kwahome
116,138,043
true
{"Java": 27510398, "Kotlin": 26976066, "JavaScript": 156602, "HTML": 56752, "Lex": 18174, "Groovy": 14207, "ANTLR": 9797, "IDL": 8587, "Shell": 5436, "CSS": 4679, "Batchfile": 4437}
// "Create actual function for platform JVM" "true" expect fun <caret>testHelper()
0
Java
0
1
eb12cfd444934a6a7be03b036fb195e3cef697f8
83
kotlin
Apache License 2.0
app/src/main/java/com/seif/booksislandapp/domain/usecase/usecase/my_ads/exchange/GetMyExchangeAdsUseCase.kt
SeifEldinMohamed
570,587,114
false
null
package com.seif.booksislandapp.domain.usecase.usecase.my_ads.exchange import com.seif.booksislandapp.data.repository.ExchangeAdvertisementRepositoryImp import com.seif.booksislandapp.domain.model.adv.exchange.ExchangeAdvertisement import com.seif.booksislandapp.utils.Resource import kotlinx.coroutines.flow.Flow import javax.inject.Inject class GetMyExchangeAdsUseCase @Inject constructor( private val exchangeAdvertisementRepositoryImp: ExchangeAdvertisementRepositoryImp ) { suspend operator fun invoke(userId: String): Flow<Resource<ArrayList<ExchangeAdvertisement>, String>> { return exchangeAdvertisementRepositoryImp.fetchMyExchangeAds(userId) } }
0
Kotlin
0
0
d7ff7f448b774aaad929a39686f04de4fd0ec19e
677
Books-Island-App
Apache License 2.0
app/src/main/java/io/cricket/app/utils/Spannable.kt
amirishaque
375,128,729
false
null
package io.cricket.app.utils import android.content.Context import android.graphics.Typeface import android.text.* import android.text.style.* import androidx.core.content.res.ResourcesCompat import io.cricket.app.utils.font.CustomTypefaceSpan fun spannable(func: () -> SpannableString) = func() private fun span(s: CharSequence, o: Any) = (if (s is String) SpannableString(s) else s as? SpannableString ?: SpannableString("")).apply { setSpan(o, 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } operator fun SpannableString.plus(s: SpannableString) = SpannableString(TextUtils.concat(this, s)) operator fun SpannableString.plus(s: String) = SpannableString(TextUtils.concat(this, s)) fun bold(s: CharSequence) = span(s, StyleSpan(Typeface.BOLD)) fun bold(s: SpannableString) = span(s, StyleSpan(Typeface.BOLD)) fun italic(s: CharSequence) = span(s, StyleSpan(Typeface.ITALIC)) fun italic(s: SpannableString) = span(s, StyleSpan(Typeface.ITALIC)) fun underline(s: CharSequence) = span(s, UnderlineSpan()) fun underline(s: SpannableString) = span(s, UnderlineSpan()) fun strike(s: CharSequence) = span(s, StrikethroughSpan()) fun strike(s: SpannableString) = span(s, StrikethroughSpan()) fun sup(s: CharSequence) = span(s, SuperscriptSpan()) fun sup(s: SpannableString) = span(s, SuperscriptSpan()) fun sub(s: CharSequence) = span(s, SubscriptSpan()) fun sub(s: SpannableString) = span(s, SubscriptSpan()) fun size(size: Float, s: CharSequence) = span(s, RelativeSizeSpan(size)) fun size(size: Float, s: SpannableString) = span(s, RelativeSizeSpan(size)) fun color(color: Int, s: CharSequence) = span(s, ForegroundColorSpan(color)) fun color(color: Int, s: SpannableString) = span(s, ForegroundColorSpan(color)) fun background(color: Int, s: CharSequence) = span(s, BackgroundColorSpan(color)) fun background(color: Int, s: SpannableString) = span(s, BackgroundColorSpan(color)) fun url(url: String, s: CharSequence) = span(s, URLSpan(url)) fun url(url: String, s: SpannableString) = span(s, URLSpan(url)) fun normal(s: CharSequence) = span(s, SpannableString(s)) fun normal(s: SpannableString) = span(s, SpannableString(s)) fun Context.setBoldFontTypeSpan( fullText: String, font: Int ): SpannableStringBuilder { val str = fullText.split(" ") val spannableString = SpannableStringBuilder(fullText); if (!str.isEmpty() && str.size>1) { val typeface = ResourcesCompat.getFont(this, font) spannableString.setSpan( CustomTypefaceSpan("", typeface), 0, str[0].length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE ); } return spannableString }
0
Kotlin
0
0
42808ddd775b5ac6f7bff0d8cf518091588df844
2,643
Cricklub_livecode
MIT License
react-native-purchases-ui/android/src/main/java/com/revenuecat/purchases/react/ui/RNPaywallsModule.kt
RevenueCat
138,222,588
false
{"TypeScript": 83390, "JavaScript": 68229, "Objective-C": 29576, "Java": 19982, "Kotlin": 12735, "Ruby": 9888, "Shell": 2570, "Swift": 338, "HTML": 255, "C": 208}
package com.revenuecat.purchases.react.ui import android.util.Log import androidx.fragment.app.FragmentActivity import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.ReadableMap import com.revenuecat.purchases.hybridcommon.ui.PaywallResultListener import com.revenuecat.purchases.hybridcommon.ui.presentPaywallFromFragment internal class RNPaywallsModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { companion object { const val NAME = "RNPaywalls" } private val currentActivityFragment: FragmentActivity? get() { return when (val currentActivity = currentActivity) { is FragmentActivity -> currentActivity else -> { Log.e(NAME, "RevenueCat paywalls require application to use a FragmentActivity") null } } } override fun getName(): String { return NAME } @ReactMethod fun presentPaywall( options: ReadableMap, promise: Promise ) { val hashMap = options.toHashMap() val offeringIdentifier = hashMap["offeringIdentifier"] as String? val displayCloseButton = hashMap["displayCloseButton"] as Boolean? presentPaywall( null, offeringIdentifier, displayCloseButton, promise ) } @ReactMethod fun presentPaywallIfNeeded( options: ReadableMap, promise: Promise ) { val hashMap = options.toHashMap() val requiredEntitlementIdentifier = hashMap["requiredEntitlementIdentifier"] as String? val offeringIdentifier = hashMap["offeringIdentifier"] as String? val displayCloseButton = hashMap["displayCloseButton"] as Boolean? presentPaywall( requiredEntitlementIdentifier, offeringIdentifier, displayCloseButton, promise ) } private fun presentPaywall( requiredEntitlementIdentifier: String?, offeringIdentifier: String?, displayCloseButton: Boolean?, promise: Promise ) { val fragment = currentActivityFragment ?: return // TODO wire offeringIdentifier presentPaywallFromFragment( fragment = fragment, requiredEntitlementIdentifier = requiredEntitlementIdentifier, shouldDisplayDismissButton = displayCloseButton, paywallResultListener = object : PaywallResultListener { override fun onPaywallResult(paywallResult: String) { promise.resolve(paywallResult) } } ) } }
30
TypeScript
76
610
238e50ec4042cdb7edc3eb811e4dfc852e139741
2,888
react-native-purchases
MIT License
src/main/kotlin/ar/edu/utn/frba/tacs/tp/api/herocardsgame/request/CreateUserRequest.kt
tacs-2021-1c-tp-hero-cards
358,787,857
false
null
package ar.edu.utn.frba.tacs.tp.api.herocardsgame.request import ar.edu.utn.frba.tacs.tp.api.herocardsgame.service.HashService data class CreateUserRequest( val userName: String, val fullName: String, val password: String, val isAdmin: Boolean = false ) { fun buildPasswordHash() = HashService.calculatePasswordHash(userName, password) }
20
null
1
1
5ddb882bfdef41c04eaca7a68afacbb2999457bb
359
hero-cards-game
MIT License
domain/src/main/java/com/arch/repository/ToDoRepository.kt
droider91
617,918,021
false
null
package com.arch.repository import androidx.paging.PagingConfig import com.arch.entity.AddToDoResponse import com.arch.entity.ToDoData import com.arch.error.BaseError import com.arch.utils.Either interface ToDoRepository { suspend fun getToDoData(pagingConfig: PagingConfig): Either<BaseError, List<ToDoData>> suspend fun addToDo(toDoData: ToDoData): Either<BaseError, AddToDoResponse> suspend fun updateToDo(toDoData: ToDoData): Either<BaseError, AddToDoResponse> }
0
Kotlin
0
0
f4529d2cf2153a0ddc3195112466163c09de0d41
480
CleanArch-Blueprint
Apache License 2.0
edit/src/main/java/com/gallery/edit/enums/CropCornerShape.kt
sieunju
536,096,662
false
null
package com.gallery.edit.enums /** * Possible crop corner shape */ enum class CropCornerShape { RECTANGLE, OVAL }
3
Kotlin
1
6
b62dcd28dd83d5b021b0b0633cdde3734183dc7e
121
gallery
MIT License
chat/src/main/kotlin/com/imchat/chat/ChatApplication.kt
kp-marczynski
244,387,834
false
{"TypeScript": 13044, "Kotlin": 8268, "JavaScript": 5594, "CSS": 4994, "HTML": 3659}
package com.imchat.chat import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration import org.springframework.boot.runApplication @SpringBootApplication(exclude = [RabbitAutoConfiguration::class]) class ChatApplication fun main(args: Array<String>) { runApplication<ChatApplication>(*args) }
26
TypeScript
0
0
59b7b632e29f4dc4c0697b69467678f17553fdc0
383
im-chat
MIT License
theodolite-quarkus/src/main/kotlin/theodolite/util/DeploymentFailedException.kt
lorenzboguhn
381,325,175
true
{"Java": 190040, "Kotlin": 177078, "Jupyter Notebook": 23742, "Python": 6111, "Dockerfile": 2653, "Shell": 2566, "Smarty": 1812}
package theodolite.util class DeploymentFailedException(message:String): Exception(message) { }
0
null
0
0
94aaf3cea2b473608952357dd826f58414f4c399
97
theodolite
Apache License 2.0
src/main/kotlin/_1to50/Task22.kt
embuc
735,933,359
false
{"Kotlin": 132771, "Java": 75142}
package se.embuc._1to50 import se.embuc.Task // Names Scores class Task22(private val input: String) :Task { override fun solve(): Long { val names = input.split(",").map { it.replace("\"", "") }.sorted() return names.mapIndexed { index, name -> (name.sumOf { it - 'A' + 1 }) * (index + 1) }.sum().toLong() } }
0
Kotlin
0
1
fcb52f5125c9089447cb2673112c1516ae6a170a
323
projecteuler
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/DesktopCheckmark.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.DesktopCheckmark: ImageVector get() { if (_desktopCheckmark != null) { return _desktopCheckmark!! } _desktopCheckmark = fluentIcon(name = "Regular.DesktopCheckmark") { fluentPath { moveTo(23.0f, 6.5f) arcToRelative(5.5f, 5.5f, 0.0f, true, true, -11.0f, 0.0f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, 11.0f, 0.0f) close() moveTo(20.85f, 4.15f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, 0.0f) lineTo(16.5f, 7.79f) lineToRelative(-1.65f, -1.64f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, 0.7f) lineToRelative(2.0f, 2.0f) curveToRelative(0.2f, 0.2f, 0.5f, 0.2f, 0.7f, 0.0f) lineToRelative(4.0f, -4.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -0.7f) close() moveTo(20.5f, 15.75f) verticalLineToRelative(-3.48f) arcToRelative(6.52f, 6.52f, 0.0f, false, false, 1.5f, -1.08f) verticalLineToRelative(4.56f) curveToRelative(0.0f, 1.2f, -0.93f, 2.17f, -2.1f, 2.25f) horizontalLineToRelative(-4.4f) verticalLineToRelative(2.5f) horizontalLineToRelative(1.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(6.75f, 22.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f) lineTo(8.5f, 20.5f) lineTo(8.5f, 18.0f) lineTo(4.25f, 18.0f) curveToRelative(-1.2f, 0.0f, -2.17f, -0.92f, -2.24f, -2.1f) lineTo(2.0f, 15.76f) lineTo(2.0f, 5.25f) curveToRelative(0.0f, -1.2f, 0.93f, -2.17f, 2.1f, -2.25f) horizontalLineToRelative(7.92f) curveToRelative(-0.3f, 0.46f, -0.53f, 0.97f, -0.7f, 1.5f) lineTo(4.24f, 4.5f) curveToRelative(-0.38f, 0.0f, -0.7f, 0.28f, -0.74f, 0.65f) lineToRelative(-0.01f, 0.1f) verticalLineToRelative(10.5f) curveToRelative(0.0f, 0.38f, 0.28f, 0.7f, 0.65f, 0.74f) lineToRelative(0.1f, 0.01f) horizontalLineToRelative(15.5f) curveToRelative(0.38f, 0.0f, 0.7f, -0.28f, 0.74f, -0.65f) verticalLineToRelative(-0.1f) close() moveTo(14.0f, 18.0f) horizontalLineToRelative(-4.0f) verticalLineToRelative(2.5f) horizontalLineToRelative(4.0f) lineTo(14.0f, 18.0f) close() } } return _desktopCheckmark!! } private var _desktopCheckmark: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
3,147
compose-fluent-ui
Apache License 2.0
app/src/main/java/io/github/cnpog/gamingview/ui/gamingview/AppItem.kt
cnpog
877,409,789
false
{"Kotlin": 36356}
package io.github.cnpog.gamingview.ui.gamingview import android.content.pm.ApplicationInfo import io.github.cnpog.gamingview.settings.Mode import io.github.cnpog.gamingview.settings.Position data class AppItem( val applicationInfo: ApplicationInfo, val mode: Mode? = null, val position: Position? = null )
0
Kotlin
0
2
432af67578826207c712424787e8915cdea8f629
320
ZuiAdvancedGamingView
MIT License
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/util/TypeHints.kt
gagarski
314,041,476
false
null
package ski.gagar.vxutil.vertigram.util import com.fasterxml.jackson.databind.JavaType import org.apache.commons.lang3.StringUtils import org.reflections.Reflections import org.reflections.scanners.Scanners import ski.gagar.vxutil.uncheckedCast import ski.gagar.vxutil.uncheckedCastOrNull import ski.gagar.vxutil.vertigram.methods.JsonTgCallable import ski.gagar.vxutil.vertigram.methods.MultipartTgCallable import ski.gagar.vxutil.vertigram.methods.TgCallable import ski.gagar.vxutil.vertigram.util.json.TELEGRAM_JSON_MAPPER import java.lang.reflect.GenericDeclaration import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.TypeVariable private val TYPE_FACTORY = TELEGRAM_JSON_MAPPER.typeFactory private val <T: TgCallable<*>> Class<T>.responseType: JavaType get() { if (typeParameters.isNotEmpty()) throw IllegalArgumentException("$this should not have type parameters") var current: Class<*>? = this var params: Map<TypeVariable<*>, Type> = mapOf() while (current != null) { val type = current.genericSuperclass if (type !is ParameterizedType) { current = current.superclass continue } val rawType = type.rawType if (rawType == TgCallable::class.java) { val t = type.actualTypeArguments[0] val tInst = if (t is Class<*>) { t } else { params[t as TypeVariable<*>] } return TYPE_FACTORY.constructType(tInst) } params = rawType .uncheckedCast<GenericDeclaration>() .typeParameters .zip(type.actualTypeArguments) .associate { (k, v) -> val vInst = when (v) { is TypeVariable<*> -> { params[v] ?: throw AssertionError("oops") } is Class<*>, is ParameterizedType -> { v } else -> { throw AssertionError("oops") } } k to vInst } current = rawType.uncheckedCastOrNull<Class<*>>() } throw IllegalArgumentException("$this is not a subtype of TgCallable") } private fun getTgCallables() = Reflections("ski.gagar.vxutil.vertigram.methods", Scanners.SubTypes) .getSubTypesOf(TgCallable::class.java) .asSequence() .filter { !Modifier.isAbstract(it.modifiers) } .toSet() private val <T: TgCallable<*>> Class<T>.tgMethodName: String get() = getAnnotation(TgMethodName::class.java)?.name ?: StringUtils.uncapitalize(simpleName) internal object TypeHints { val callables = getTgCallables() val methodNames = callables.associateWith { it.tgMethodName } val doNotGenerateInTgVerticleMethodNames = methodNames .filter { (k, _) -> k.getAnnotation(DoNotGenerateInTgVerticle::class.java) != null } .values .toSet() val returnTypesByClass = callables.associateWith { it.responseType } object Json { private val callables = TypeHints.callables.filter { JsonTgCallable::class.java.isAssignableFrom(it) } val requestTypesByMethodName = callables.associate { it.tgMethodName to TYPE_FACTORY.constructType(it) } val returnTypesByMethodName = callables.associate { it.tgMethodName to it.responseType } } object Multipart { private val callables = TypeHints.callables.filter { MultipartTgCallable::class.java.isAssignableFrom(it) } val requestTypesByMethodName = callables.associate { it.tgMethodName to TYPE_FACTORY.constructType(it) } val returnTypesByMethodName = callables.associate { it.tgMethodName to it.responseType } } } internal fun <K, V> Map<K, V>.getOrAssert(key: K) = get(key) ?: throw AssertionError("oops")
0
Kotlin
0
0
c7730c307fc657e2ddf42cbe6f1f8a2f7e0f8166
4,353
vxutil
Apache License 2.0
src/main/java/com/impact/util/thread/ImpactThread.kt
GT-IMPACT
272,411,733
false
{"Gradle": 1, "Gradle Kotlin DSL": 6, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Kotlin": 48, "Java": 349, "JSON": 25}
package com.impact.util.thread import com.impact.core.Config import java.util.concurrent.Callable import java.util.concurrent.ExecutorService import java.util.concurrent.Executors object ImpactThread { private var service: ExecutorService = Executors.newFixedThreadPool(3) /** * Выполнить действие в пуле тредов и вернуть результат, если включено в конфиге */ fun <T> addAction(action: Callable<T>, onDone: (T) -> Unit) { if (Config.isEnabledExperimentalMultiThreading) onDone(service.submit(action).get()) else onDone(action.call()) } /** * Выполнить действие в пуле тредов, если включено в конфиге */ fun addAction(action: Runnable) { if (Config.isEnabledExperimentalMultiThreading) service.execute(action) else action.run() } }
0
Java
4
3
1320d520b6a96e18d609fd8ac3520b2a3f1f2f0c
864
Impact-Core
MIT License
domain/src/main/java/com/omdb/domain/models/MovieSearchResultModel.kt
helod91
258,808,503
false
null
package com.omdb.domain.models class MovieSearchResultModel( val movies: List<MovieSearchModel>?, val error: String?, val success: Boolean )
0
Kotlin
0
1
2c8ebf8cb6337d7635620b3db2d8fb0919157233
153
clean-movies
Apache License 2.0
examples/wa-articles/src/profile/java/com/anymore/wanandroid/articles/ArticlesApplication.kt
anymao
234,439,982
false
null
package com.anymore.wanandroid.articles import android.content.Context import com.alibaba.android.arouter.launcher.ARouter import com.anymore.andkit.AndkitApplication import com.anymore.andkit.annotations.Kiss import com.anymore.andkit.dagger.module.ApplicationModule import com.anymore.wanandroid.articles.di.component.DaggerArticlesModuleComponent /** * Created by anymore on 2020/1/25. */ @Kiss(value = ArticlesApplicationWrapper::class, priority = 99) class ArticlesApplication : AndkitApplication() { override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) DaggerArticlesModuleComponent.builder() .applicationModule(ApplicationModule(this)) .build() .inject(this) } override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { ARouter.openDebug() ARouter.openLog() } ARouter.init(this) } }
0
Kotlin
0
5
f0c89b016e16303840e61c60337c39e82bf8c872
954
Andkit
MIT License
app/src/main/java/com/yanbin/reactivestickynote/login/LoginScreen.kt
hungyanbin
378,550,510
false
null
package com.yanbin.reactivestickynote.login import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rxjava3.subscribeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.yanbin.reactivestickynote.R import com.yanbin.utils.subscribeBy import com.yanbin.utils.toMain @Composable fun LoginScreen( loginViewModel: LoginViewModel, toEditorPage: () -> Unit ) { val text by loginViewModel.text.subscribeAsState(initial = "") loginViewModel.toEditorPage .toMain() .subscribeBy (onNext = { toEditorPage() }) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { TextField( value = text, onValueChange = loginViewModel::onTextChanged, textStyle = MaterialTheme.typography.button ) Button( modifier = Modifier.padding(top = 8.dp), onClick = loginViewModel::onEnterClicked ) { Text( text = stringResource(id = R.string.login_button_enter), style = MaterialTheme.typography.button ) } } }
2
Kotlin
6
9
9d01c806c454a1c78d853b343e45d7470006cb29
1,753
ReactiveStickyNote
MIT License
app/src/main/java/edu/rosehulman/condrak/roseschedule/EditActivityRecyclerViewAdapter.kt
keith-cr
164,172,313
false
null
package edu.rosehulman.condrak.roseschedule import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import edu.rosehulman.condrak.roseschedule.EditActivityFragment.OnListFragmentInteractionListener import kotlinx.android.synthetic.main.fragment_edit.view.* class EditActivityRecyclerViewAdapter( private val schedule: Schedule, private val day: Int, private val mListener: OnListFragmentInteractionListener? ) : RecyclerView.Adapter<EditActivityRecyclerViewAdapter.ViewHolder>() { private val mOnClickListener: View.OnClickListener init { mOnClickListener = View.OnClickListener { v -> val item = v.tag as ClassPeriod // Notify the active callbacks interface (the activity, if the fragment is attached to // one) that an item has been selected. mListener?.onListFragmentInteraction(item, day) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.fragment_edit, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val period = schedule.days[day].periods[position] with(holder.mView) { tag = period setOnClickListener(mOnClickListener) periodTextView.text = period.periodText() if (period.hasLocation()) classTextView.text = resources.getString(R.string.class_text, period.className, period.classLocation) else classTextView.text = period.className } } override fun getItemCount(): Int = schedule.days[day].periods.size inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) }
0
Kotlin
0
0
1c371a063edb6ba014bc34e7195ee5d5aae7b10d
1,889
rose-schedule
MIT License
app/src/main/java/tech/borgranch/pokedex/ui/main/list/ListFragment.kt
BorgRancher
487,475,376
false
null
package tech.borgranch.pokedex.ui.main.list import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.xwray.groupie.GroupAdapter import com.xwray.groupie.viewbinding.GroupieViewHolder import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import tech.borgranch.pokedex.data.dto.PokemonItem import tech.borgranch.pokedex.databinding.FragmentListBinding import tech.borgranch.pokedex.databinding.ItemPokemonBinding import java.net.URI @AndroidEntryPoint class ListFragment : Fragment() { private var selectedIndex: Int = -1 interface OnFragmentInteractionListener { fun onFragmentInteraction(uri: URI) } private val viewModel by activityViewModels<ListViewModel>() private var pokemonOffset: Int = 0 private var _ui: FragmentListBinding? = null private val ui: FragmentListBinding get() = _ui!! private var groupAdaptor: GroupAdapter<GroupieViewHolder<ItemPokemonBinding>>? = null private val navArgs by navArgs<ListFragmentArgs>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _ui = FragmentListBinding.inflate(inflater, container, false) return ui.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bindUI() } private fun bindUI() { if (!viewModel.animShown) { ui.animationView.visibility = View.VISIBLE viewModel.animShown = true } else { ui.animationView.visibility = View.GONE } lifecycleScope.launchWhenResumed { navArgs.let { selectedIndex = it.selectedIndex } if (selectedIndex == -1) { selectedIndex = 0 viewModel.fetchNextPokemonList() } viewModel.pokemonPage.observe(viewLifecycleOwner) { pokemonOffset = it * viewModel.limit } viewModel.pokemonList.observe(viewLifecycleOwner) { pokemonList -> ui.progressBar.visibility = if (viewModel.isLoading()) View.VISIBLE else View.GONE pokemonList?.let { initRecyclerView(it.toPokemonCards()) if (ui.animationView.visibility == View.VISIBLE) { lifecycleScope.launch(Dispatchers.Default) { delay(2000) withContext(Dispatchers.Main) { ui.animationView.visibility = View.GONE ui.pokemonsList.visibility = View.VISIBLE } } } else { ui.pokemonsList.visibility = View.VISIBLE } if (selectedIndex != -1) { val lm = ui.pokemonsList.layoutManager as GridLayoutManager lm.scrollToPositionWithOffset(selectedIndex, 0) } } } } } private fun initRecyclerView(pokemonCards: List<PokemonListCard>) { groupAdaptor = GroupAdapter<GroupieViewHolder<ItemPokemonBinding>>().apply { updateAsync(pokemonCards) } ui.pokemonsList.apply { layoutManager = GridLayoutManager([email protected](), 2) adapter = groupAdaptor } ui.pokemonsList.addOnScrollListener(object : RecyclerView.OnScrollListener() { // Calculate when to fetch next pokemon list override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView.layoutManager as GridLayoutManager val visibleItemCount = layoutManager.childCount val totalItemCount = layoutManager.itemCount val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() if (firstVisibleItemPosition + visibleItemCount >= totalItemCount) { viewModel.fetchNextPokemonList() } } }) } private fun List<PokemonItem>.toPokemonCards(): List<PokemonListCard> { return this.map { pokemonItem -> PokemonListCard(pokemonItem) } } override fun onDestroyView() { super.onDestroyView() groupAdaptor = null _ui = null } }
0
Kotlin
0
0
2091247d06ca84424946d07409dedc59b1eb5e8e
5,006
ConnectedPokedex
Apache License 2.0
src/test/kotlin/com/expedia/graphql/dataFetchers/DataFetchPredicateTests.kt
d4rken
157,257,082
true
{"Kotlin": 238077, "Shell": 2933}
package com.expedia.graphql.dataFetchers import com.expedia.graphql.TopLevelObject import com.expedia.graphql.exceptions.GraphQLKotlinException import com.expedia.graphql.getTestSchemaConfigWithHooks import com.expedia.graphql.hooks.DataFetcherExecutionPredicate import com.expedia.graphql.hooks.SchemaGeneratorHooks import com.expedia.graphql.toSchema import graphql.ExceptionWhileDataFetching import graphql.GraphQL import graphql.schema.DataFetchingEnvironment import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import kotlin.reflect.KParameter import kotlin.test.assertEquals class DataFetchPredicateTests { @Test fun `A datafetcher execution is stopped if the predicate test is false`() { val config = getTestSchemaConfigWithHooks(PredicateHooks()) val schema = toSchema( listOf(TopLevelObject(QueryWithValidations())), config = config ) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute("{ greaterThan2Times10(greaterThan2: 1) }") val graphQLError = result.errors[0] assertEquals("DataFetchingException", graphQLError.errorType.name) val exception = (graphQLError as? ExceptionWhileDataFetching)?.exception assertEquals("The datafetcher cannot be executed due to: [Error(message=greaterThan2 is actually 1)]", exception?.message) assertTrue(exception is GraphQLKotlinException) } @Test fun `A datafetcher execution is stopped if the predicate test is false with complex argument under test`() { val config = getTestSchemaConfigWithHooks(PredicateHooks()) val schema = toSchema( listOf(TopLevelObject(QueryWithValidations())), config = config ) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute("{ complexPredicate(person: { age: 33, name: \"Alice\"}) }") val graphQLError = result.errors[0] assertEquals("DataFetchingException", graphQLError.errorType.name) val exception = (graphQLError as? ExceptionWhileDataFetching)?.exception assertEquals("The datafetcher cannot be executed due to: [Error(message=Not the right age), Error(message=Not the right name)]", exception?.message) assertTrue(exception is GraphQLKotlinException) } } class QueryWithValidations { fun greaterThan2Times10(greaterThan2: Int): Int = greaterThan2 * 10 fun complexPredicate(person: Person) = person.toString() } data class Person(val name: String, val age: Int) class PredicateHooks : SchemaGeneratorHooks { override val dataFetcherExecutionPredicate: DataFetcherExecutionPredicate? = TestDataFetcherPredicate() } class TestDataFetcherPredicate : DataFetcherExecutionPredicate { data class Error(val message: String) override fun <T> evaluate(value: T, parameter: KParameter, environment: DataFetchingEnvironment): T { val errors: List<Error> = when { parameter.name == "greaterThan2" && value is Int && value <= 2 -> listOf(Error("greaterThan2 is actually $value")) value is Person -> { val errors = mutableListOf<Error>() if (value.age < 42) errors.add(Error("Not the right age")) if (value.name != "Bob") errors.add(Error("Not the right name")) errors } else -> emptyList() } if (errors.isNotEmpty()) { val message = errors.joinToString(separator = ", ", prefix = "[", postfix = "]") throw GraphQLKotlinException("The datafetcher cannot be executed due to: $message") } return value } }
0
Kotlin
0
2
1d78a129b7f8e7b01c4bed063076a215ca4b29be
3,724
graphql-kotlin
Apache License 2.0
src/main/kotlin/org/neatutils/promon/api/exceptions/ProgressMonitorException.kt
MartinHaeusler
196,659,410
false
null
package org.neatutils.promon.api.exceptions import java.lang.RuntimeException open class ProgressMonitorException : 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
1
2dcf9bc5c8de0e9557daf693051156f2ea5fca49
609
promon4j
Apache License 2.0
ui-material/src/main/java/com/lu/magic/ui/recycler/MultiItemType.kt
Mingyueyixi
582,587,773
false
null
package com.lu.magic.ui.recycler import android.view.ViewGroup interface MultiItemType<E> { fun getItemViewType(adapter: MultiAdapter<E>, itemModel: E, position: Int): Boolean fun createViewHolder(adapter: MultiAdapter<E>, parent: ViewGroup, viewType: Int): MultiViewHolder<E> }
1
null
1
1
d912275f35ea039c4686c1e160a90ff4b8bba3b0
288
frame-ui
Mulan Permissive Software License, Version 2
dTrip-main/app/src/main/java/com/zzp/dtrip/fragment/NearbyFragment.kt
Dcelysia
865,949,432
false
{"Kotlin": 188427, "Java": 96523}
package com.zzp.dtrip.fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.zzp.dtrip.R import com.zzp.dtrip.activity.NearbyActivity import com.zzp.dtrip.activity.SearchActivity import com.zzp.dtrip.adapter.AddressAdapter import com.zzp.dtrip.data.BigData import com.zzp.dtrip.data.NearbyResult import com.zzp.dtrip.util.TencentAppService import com.zzp.dtrip.util.TencentRetrofitManager import retrofit2.Call import retrofit2.Callback import retrofit2.Response class NearbyFragment(private val keyword: String) : Fragment() { val nearbyAddressList = ArrayList<BigData>() private lateinit var recyclerView: RecyclerView private var adapter: AddressAdapter? = null private val KEY = "<KEY>" private val TAG = "NearbyFragment" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view: View = inflater.inflate(R.layout.fragment_nearby, container, false) initRecyclerView(view) getNearby(keyword) return view } private fun initRecyclerView(view: View) { recyclerView = view.findViewById(R.id.recycler_nearby) val layoutManager = LinearLayoutManager(context) recyclerView.layoutManager = layoutManager adapter = AddressAdapter(activity as NearbyActivity, nearbyAddressList) recyclerView.adapter = adapter recyclerView.addItemDecoration(DividerItemDecoration(activity as NearbyActivity, DividerItemDecoration.VERTICAL)) } private fun getNearby(keyword: String) { val appService = TencentRetrofitManager.create<TencentAppService>() val boundary = "nearby(${TripFragment.lat},${TripFragment.lng},1000)" val task = appService.getNearby(keyword, boundary, KEY) task.enqueue(object : Callback<NearbyResult> { override fun onResponse(call: Call<NearbyResult>, response: Response<NearbyResult>) { response.body()?.apply { if (this.status == 0) { if (nearbyAddressList.size != 0) { nearbyAddressList.clear() } for (obj in this.data) { val objs = BigData(obj) nearbyAddressList.add(objs) } if (keyword == "美食") { if (SearchActivity.resultList.isNotEmpty()) { SearchActivity.resultList.clear() } for (obj in nearbyAddressList) { SearchActivity.resultList.add(obj) } } adapter?.notifyDataSetChanged() } else { Toast.makeText( context, "请求错误", Toast.LENGTH_SHORT ).show() } } } override fun onFailure(call: Call<NearbyResult>, t: Throwable) { Log.d(TAG, "onFailure ==> $t") } }) } }
0
Kotlin
0
0
3e3774c4b36d6f07f1714f7876103c9d08910475
3,558
2024-shumei-app
Apache License 2.0
src/main/kotlin/com/iwayee/exam/api/system/ExamSystem.kt
andycai
339,348,293
false
null
package com.iwayee.exam.api.system import com.iwayee.exam.hub.Some object ExamSystem { fun getExamById(some: Some) { // } fun update(some: Some) { // } }
0
Kotlin
0
1
8e5195935a618d60ebadbf6a37812cdad0d7d3c6
173
riki-kotlin
MIT License
fluentui_core/src/main/java/com/microsoft/fluentui/theming/FluentUIContextThemeWrapper.kt
Anthonysidesapp
454,785,341
true
{"Kotlin": 884615}
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.fluentui.theming import android.content.Context import android.content.res.Resources import androidx.appcompat.view.ContextThemeWrapper import com.microsoft.fluentui.core.R class FluentUIContextThemeWrapper(base: Context,theme:Int = R.style.Base_Theme_FluentUI) : ContextThemeWrapper(base, theme) { override fun onApplyThemeResource(theme: Resources.Theme, resid: Int, first: Boolean) { // We don't want to force our styles on top of the user's. We want their styles to take precedence. theme.applyStyle(resid, false) } }
0
Kotlin
3
9
61cbb5799bba74342b342cd98680286a96f27f70
673
fluentui-android
MIT License
app/src/main/java/com/f0rx/youtube_dl_native/domain/response/BaseResponse.kt
f0rx
373,600,703
false
null
package com.f0rx.youtube_dl_native.domain.response interface BaseResponse { var message: String var commands: ArrayList<String>? var elapsedTime: Long? var out: String? var exitCode: Int? var error: String? }
0
Kotlin
0
0
0fa09951925866e7376bc7f7068100ab573f1ed3
233
Youtube-dl-AndroidNative
MIT License
BaseExtend/src/main/java/com/chen/baseextend/bean/news/MediaInfo.kt
chen397254698
268,411,455
false
null
package com.chen.baseextend.bean.news data class MediaInfo( val avatar_url: String?, val follow: Boolean?, val is_star_user: Boolean?, val media_id: Long?, val name: String?, val recommend_reason: String?, val recommend_type: Int?, val user_id: Long?, val user_verified: Boolean?, val verified_content: String? )
1
Kotlin
14
47
85ffc5e307c6171767e14bbfaf992b8d62ec1cc6
353
EasyAndroid
Apache License 2.0
app/src/main/java/com/karaketir/coachingapp/models/Ders.kt
FurkanKaraketir
568,077,420
false
{"Kotlin": 723127}
package com.karaketir.coachingapp.models class Ders( val dersAdi: String, val dersTuru: String, val dersSure: Int, val dersNumara:String )
0
Kotlin
0
0
8a594282aa9ce79f4f5455e0842382292b63169d
155
KTS-Kocluk-Takip-Sistemi
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/integration/person/AlertsIntegrationTest.kt
ministryofjustice
572,524,532
false
{"Kotlin": 921304, "Python": 32511, "Shell": 16913, "HTML": 6740, "Makefile": 1468, "Dockerfile": 1120, "Ruby": 216, "SCSS": 130, "JavaScript": 28}
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.integration.person import org.junit.jupiter.api.Test import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import uk.gov.justice.digital.hmpps.hmppsintegrationapi.integration.IntegrationTestBase class AlertsIntegrationTest : IntegrationTestBase() { final var path = "$basePath/$pnc/alerts" @Test fun `returns alerts for a person`() { callApi(path) .andExpect(status().isOk) .andExpect(content().json(getExpectedResponse("person-alerts"))) } @Test fun `returns PND alerts for a person`() { callApi("$path/pnd") .andExpect(status().isOk) .andExpect(content().json(getExpectedResponse("person-alerts-pnd"))) } }
3
Kotlin
1
2
ccdb90915ee338db16b40deb16da0df2fc876524
823
hmpps-integration-api
MIT License
core/testing/src/main/kotlin/com/lolo/io/onelist/core/testing/fake/FakeDataModule.kt
lolo-io
198,519,184
false
{"Kotlin": 363415, "Roff": 549}
package com.lolo.io.onelist.core.testing.fake import com.lolo.io.onelist.core.data.file_access.FileAccess import com.lolo.io.onelist.core.data.repository.OneListRepository import com.lolo.io.onelist.core.data.shared_preferences.SharedPreferencesHelper import org.koin.dsl.module fun fakeDataModule( repository: FakeOneListRepository = FakeOneListRepository(), sharedPreferencesHelper: SharedPreferencesHelper = FakeSharedPreferenceHelper(), fileAccess: FileAccess = FakeFileAccess() ) = module { single<SharedPreferencesHelper> { sharedPreferencesHelper } single<OneListRepository> { repository } single { fileAccess } }
14
Kotlin
26
92
ca7df6ec46344bde7c5e357d0784ecdfdecbb78e
687
OneList
MIT License
web/integration-core/src/jsMain/kotlin/androidx/compose/web/sample/tests/EventsTests.kt
vb0067
385,461,633
true
{"Kotlin": 672209, "Dockerfile": 5716, "Shell": 5673, "HTML": 2801, "PowerShell": 1708, "Groovy": 1415, "CSS": 1022, "JavaScript": 203}
package org.jetbrains.compose.web.sample.tests import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import org.jetbrains.compose.web.attributes.* import org.jetbrains.compose.web.css.* import org.jetbrains.compose.web.dom.* class EventsTests { val doubleClickUpdatesText by testCase { var state by remember { mutableStateOf("") } TestText(state) Div( attrs = { id("box") style { width(100.px) height(100.px) backgroundColor("red") } onDoubleClick { state = "Double Click Works!" } } ) { Text("Clickable Box") } } val focusInAndFocusOutUpdateTheText by testCase { var state by remember { mutableStateOf("") } TestText(state) Input(type = InputType.Text, attrs = { id("focusableInput") onFocusIn { state = "focused" } onFocusOut { state = "not focused" } }) } val focusAndBlurUpdateTheText by testCase { var state by remember { mutableStateOf("") } TestText(state) Input(type = InputType.Text, attrs = { id("focusableInput") onFocus { state = "focused" } onBlur { state = "blured" } }) } val scrollUpdatesText by testCase { var state by remember { mutableStateOf("") } TestText(state) Div( attrs = { id("box") style { property("overflow-y", "scroll") height(200.px) backgroundColor(Color.RGB(220, 220, 220)) } onScroll { state = "Scrolled" } } ) { repeat(500) { P { Text("Scrollable content in Div - $it") } } } } val selectEventUpdatesText by testCase { var state by remember { mutableStateOf("None") } P(attrs = { style { height(50.px) } }) { TestText(state) } Input(type = InputType.Text, attrs = { value("This is a text to be selected") id("selectableText") onSelect { state = "Text Selected" } }) } }
0
Kotlin
0
0
33b96344d97cdc0a065d3ad3df4e2acea1a74328
2,622
compose-jb
Apache License 2.0
app/src/main/java/com/poor/android/logic/model/network/cloud/ICloudService.kt
karrydev
415,566,722
false
null
package com.poor.android.logic.model.network.cloud import com.poor.android.logic.model.song.SearchSongsSuggestResponse import com.poor.android.logic.model.song.cloud.* import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface ICloudService { /** * 搜索推荐 * keywords:搜索关键字 */ @GET("search/suggest?type=mobile") fun searchSongsSuggest(@Query("keywords") keywords: String): Call<SearchSongsSuggestResponse> /** * 搜索歌曲 * keywords:搜索关键字 */ @GET("search?") fun searchCloudSongs(@Query("keywords") keywords: String): Call<SearchCloudSongsResponse> /** * 搜索歌曲详情 * ids:歌曲id,可传入多个 */ @GET("song/detail?") fun getCloudSongsDetail(@Query("ids") ids: String): Call<CloudSongsDetailResponse> /** * 获取指定歌曲的Mp3Url * id:歌曲id */ @GET("song/url?") fun getCloudSongMp3Url(@Query("id") id: Int): Call<CloudSongResponse> /** * 获取指定歌曲的歌词 * id:歌曲id */ @GET("lyric?") fun getCloudSongLyric(@Query("id") id: Int): Call<CloudSongLyric> }
0
Kotlin
0
1
a6b6d5987cddd771291e0caf17da7030c8476718
1,078
Poor
Apache License 2.0
src/main/kotlin/no/vingaas/pokermanager/service/security/CustomUserDetailsService.kt
tomandreaskv
810,388,706
false
{"Kotlin": 143404}
package no.vingaas.pokermanager.service.security import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Service @Service interface CustomUserDetailsService : UserDetailsService { }
0
Kotlin
0
1
76245f712deb230f6369d236fa6b440ac4e6553e
237
pokermanager-backend
Apache License 2.0
sources/js/values/Gap.kt
cybernetics
323,978,300
true
{"Kotlin": 245088}
@file:Suppress( "INLINE_EXTERNAL_DECLARATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", "NOTHING_TO_INLINE", "WRONG_BODY_OF_EXTERNAL_DECLARATION", ) package io.fluidsonic.css public external interface Gap : CssValue { public companion object { @CssDsl public inline val normal: Gap get() = Axis.normal public inline fun of(row: Axis, column: Axis): Gap = unsafe("$row $column") public inline fun unsafe(value: String): Gap = CssValue.unsafe(value) public inline fun variable(name: String): Variable = CssVariable.unsafe(name) } public interface Axis : Gap { public companion object { @CssDsl public inline val normal: Axis get() = unsafe("normal") public inline fun unsafe(value: String): Axis = CssValue.unsafe(value) public inline fun variable(name: String): Variable = CssVariable.unsafe(name) } public interface Variable : Axis, CssVariable<Axis> } public interface Variable : Gap, CssVariable<Gap> } @CssDsl public inline fun CssDeclarationBlockBuilder.columnGap(value: Gap.Axis) { property(columnGap, value) } @CssDsl public inline fun CssDeclarationBlockBuilder.gap(value: Gap) { property(gap, value) } @CssDsl public inline fun CssDeclarationBlockBuilder.gap(row: Gap.Axis, column: Gap.Axis) { gap(Gap.of(row = row, column = column)) } @CssDsl public inline fun CssDeclarationBlockBuilder.rowGap(value: Gap.Axis) { property(rowGap, value) } @Suppress("unused") public inline val CssProperties.columnGap: CssProperty<Gap> get() = CssProperty.unsafe("column-gap") @Suppress("unused") public inline val CssProperties.gap: CssProperty<Gap> get() = CssProperty.unsafe("gap") @Suppress("unused") public inline val CssProperties.rowGap: CssProperty<Gap> get() = CssProperty.unsafe("row-gap")
0
null
0
0
65b9463c57be79f8fcb5e5083df6907340388826
1,795
fluid-css
Apache License 2.0
ImagePicker/src/main/java/com/colourmoon/imagepicker/CMImagePicker.kt
colourmoon
663,337,093
false
null
package com.colourmoon.imagepicker import android.content.Context import android.content.Intent import com.colourmoon.imagepicker.activities.ImagePickerMainActivity import com.colourmoon.imagepicker.utils.BOTH import com.colourmoon.imagepicker.utils.CAMERA import com.colourmoon.imagepicker.utils.COMPRESSION_PERCENTAGE import com.colourmoon.imagepicker.utils.GALLERY import com.colourmoon.imagepicker.utils.ResultImage import com.colourmoon.imagepicker.utils.SELECTION_TYPE import com.colourmoon.imagepicker.utils.WANT_COMPRESSION import com.colourmoon.imagepicker.utils.WANT_CROP class CMImagePicker( private val activity: Context, private var resultImageCallback: ResultImage ) { private var crop: Boolean = false private var cameraOnly: Boolean = false private var galleyOnly: Boolean = false private var compress: Boolean = false private var compressionPercentage: Int = 100 fun allowCrop(crop: Boolean): CMImagePicker { this.crop = crop return this } fun allowCameraOnly(cameraOnly: Boolean): CMImagePicker { this.cameraOnly = cameraOnly return this } fun allowGalleyOnly(galleyOnly: Boolean): CMImagePicker { this.galleyOnly = galleyOnly return this } fun allowCompress(compress: Boolean, compressionPercentage: Int): CMImagePicker { this.compress = compress this.compressionPercentage = compressionPercentage return this } fun start() { val selection = if (cameraOnly && !galleyOnly) { CAMERA } else if (galleyOnly && !cameraOnly) { GALLERY } else { BOTH } resultImageCallback.result.launch( Intent( activity, ImagePickerMainActivity::class.java ).apply { putExtra(WANT_CROP, crop) putExtra(SELECTION_TYPE, selection) putExtra(WANT_COMPRESSION, compress) putExtra(COMPRESSION_PERCENTAGE, compressionPercentage) } ) } }
0
Kotlin
1
1
1580c5cfede3facf4cba833a49de26e7decf39e7
2,096
image-picker
MIT License
common/src/commonMain/kotlin/dev/inmo/micro_utils/common/MapDiff.kt
InsanusMokrassar
295,712,640
false
{"Kotlin": 1190548, "Python": 2464, "Shell": 1071}
package dev.inmo.micro_utils.common /** * Contains diff based on the comparison of objects with the same [K]. * * @param removed Contains map with keys removed from parent map * @param changed Contains map with keys values changed new map in comparison with old one * @param added Contains map with new keys and values */ data class MapDiff<K, V> @Warning(warning) constructor( val removed: Map<K, V>, val changed: Map<K, Pair<V, V>>, val added: Map<K, V> ) { fun isEmpty() = removed.isEmpty() && changed.isEmpty() && added.isEmpty() inline fun isNotEmpty() = !isEmpty() companion object { private const val warning = "This feature can be changed without any warranties. Use with caution and only in case you know what you are doing" fun <K, V> empty() = MapDiff<K, V>(emptyMap(), emptyMap(), emptyMap()) } } private inline fun <K, V> createCompareFun( strictComparison: Boolean ): (K, V, V) -> Boolean = if (strictComparison) { { _, first, second -> first === second } } else { { _, first, second -> first == second } } /** * Compare [this] [Map] with the [other] one in principle when [other] is newer than [this] * * @param compareFun Will be used to determine changed values */ fun <K, V> Map<K, V>.diff( other: Map<K, V>, compareFun: (K, V, V) -> Boolean ): MapDiff<K, V> { val removed: Map<K, V> = (keys - other.keys).associateWith { getValue(it) } val added: Map<K, V> = (other.keys - keys).associateWith { other.getValue(it) } val changed = keys.intersect(other.keys).mapNotNull { val old = getValue(it) val new = other.getValue(it) if (compareFun(it, old, new)) { return@mapNotNull null } else { it to (old to new) } }.toMap() return MapDiff( removed, changed, added ) } /** * Compare [this] [Map] with the [other] one in principle when [other] is newer than [this] * * @param strictComparison If true, will use strict (===) comparison for the values' comparison. Otherwise, standard * `equals` will be used */ fun <K, V> Map<K, V>.diff( other: Map<K, V>, strictComparison: Boolean = false ): MapDiff<K, V> = diff( other, compareFun = createCompareFun(strictComparison) ) /** * Will apply [mapDiff] to [this] [MutableMap] */ fun <K, V> MutableMap<K, V>.applyDiff( mapDiff: MapDiff<K, V> ) { mapDiff.apply { removed.keys.forEach { remove(it) } changed.forEach { (k, oldNew) -> put(k, oldNew.second) } added.forEach { (k, new) -> put(k, new) } } } /** * Will apply changes with [from] map into [this] one * * @param compareFun Will be used to determine changed values * * @return [MapDiff] applied to [this] [MutableMap] */ fun <K, V> MutableMap<K, V>.applyDiff( from: Map<K, V>, compareFun: (K, V, V) -> Boolean ): MapDiff<K, V> { return diff(from, compareFun).also { applyDiff(it) } } /** * Will apply changes with [from] map into [this] one * * @param strictComparison If true, will use strict (===) comparison for the values' comparison. Otherwise, standard * `equals` will be used * * @return [MapDiff] applied to [this] [MutableMap] */ fun <K, V> MutableMap<K, V>.applyDiff( from: Map<K, V>, strictComparison: Boolean = false ): MapDiff<K, V> = applyDiff( from, compareFun = createCompareFun(strictComparison) ) /** * Reverse [this] [MapDiff]. Result will contain [MapDiff.added] on [MapDiff.removed] (and vice-verse), all the * [MapDiff.changed] values will be reversed too */ fun <K, V> MapDiff<K, V>.reversed(): MapDiff<K, V> = MapDiff( removed = added, changed = changed.mapValues { (_, oldNew) -> oldNew.second to oldNew.first }, added = removed )
15
Kotlin
3
32
f09d92be32a3f792818edc28bbb27a9826f262b2
3,853
MicroUtils
Apache License 2.0
src/main/kotlin/main/Main.kt
Geno1024
199,681,896
true
{"Kotlin": 20907}
package main import data.Global import data.LogType import util.Archive import util.Prompt import java.io.File fun main(args: Array<String>) { val file = File(Global.defaultArchiveLocation) if (file.exists()) { Archive.loadKeywordsFromFile(file) Prompt.echo("Archived keyword loaded.",LogType.OK) } network.Server.start(8080) Prompt.run() }
0
Kotlin
0
0
e97a26cdd4c71f9119681204f90609e81fb693e0
379
qqbotkotlin
MIT License
app/src/main/java/com/akvelon/bitbuckler/model/repository/pullrequest/TrackedIssuesRepo.kt
akvelon
635,643,587
false
null
package com.akvelon.bitbuckler.model.repository.pullrequest import com.akvelon.bitbuckler.model.entity.issueTracker.TrackedIssue import kotlinx.coroutines.flow.Flow interface TrackedIssuesRepo { fun getAll(): Flow<List<TrackedIssue>> suspend fun insert(items: List<TrackedIssue>) suspend fun removeBy(uuid: String) suspend fun clear() }
0
Kotlin
0
1
b95918f9b8902c03dcbaf55071a1f51270b115e3
358
Bitbuckler-Android
MIT License
MyWidgets/app/src/main/java/com/mankart/mywidgets/RandomNumberWidget.kt
reskimulud
477,543,802
false
{"Kotlin": 122658, "Java": 1207}
package com.mankart.mywidgets import android.annotation.SuppressLint import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.os.Build import android.widget.RemoteViews /** * Implementation of App Widget functionality. */ class RandomNumberWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created } override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled } @SuppressLint("RemoteViewLayout") override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) if (WIDGET_CLICK == intent.action) { val appWidgetManager: AppWidgetManager = AppWidgetManager.getInstance(context) val views = RemoteViews(context.packageName, R.layout.random_number_widget) val lastUpdate = "Random: " + NumberGenerator.generate(100) val appWidgetId = intent.getIntExtra(WIDGET_ID_EXTRA, 0) views.setTextViewText(R.id.appwidget_text, lastUpdate) appWidgetManager.updateAppWidget(appWidgetId, views) } } @SuppressLint("RemoteViewLayout") private fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val lastUpdate = "Random: " + NumberGenerator.generate(100) // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.random_number_widget) views.setTextViewText(R.id.appwidget_text, lastUpdate) views.setOnClickPendingIntent(R.id.btn_click, getPendingIntentSelf(context, appWidgetId, WIDGET_CLICK)) // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views) } private fun getPendingIntentSelf(context: Context, appWidgetId: Int, action: String): PendingIntent { val intent = Intent(context, RandomNumberWidget::class.java) intent.action = action intent.putExtra(WIDGET_ID_EXTRA, appWidgetId) return PendingIntent.getBroadcast(context, appWidgetId, intent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE } else { 0 } ) } companion object { private const val WIDGET_CLICK = "android.appwidget.action.APPWIDGET_UPDATE" private const val WIDGET_ID_EXTRA = "widget_id_extra" } }
0
Kotlin
1
1
7eeb7b9b398fa0125e3b9312b4da70ac22d8e052
3,067
bpaai-dicoding
MIT License
android/src/main/kotlin/com/cloudwebrtc/webrtc/controller/MediaDevicesController.kt
krida2000
510,302,729
false
null
package com.cloudwebrtc.webrtc.controller import com.cloudwebrtc.webrtc.MediaDevices import com.cloudwebrtc.webrtc.Permissions import com.cloudwebrtc.webrtc.State import com.cloudwebrtc.webrtc.exception.GetUserMediaException import com.cloudwebrtc.webrtc.model.Constraints import com.cloudwebrtc.webrtc.proxy.MediaStreamTrackProxy import com.cloudwebrtc.webrtc.proxy.PeerConnectionProxy import com.cloudwebrtc.webrtc.utils.AnyThreadSink import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch /** * Controller of [MediaDevices] functional. * * @property messenger Messenger used for creating new [MethodChannel]s. * @param state State used for creating new [MediaStreamTrackProxy]s. */ class MediaDevicesController( private val messenger: BinaryMessenger, state: State, permissions: Permissions ) : MethodChannel.MethodCallHandler, EventChannel.StreamHandler { /** Underlying [MediaDevices] to perform [MethodCall]s on. */ private val mediaDevices = MediaDevices(state, permissions) /** Channel listened for [MethodCall]s. */ private val chan = MethodChannel(messenger, ChannelNameGenerator.name("MediaDevices", 0)) /** Event channel into which all [PeerConnectionProxy] events are sent. */ private val eventChannel = EventChannel(messenger, ChannelNameGenerator.name("MediaDevicesEvent", 0)) /** Event sink into which all [PeerConnectionProxy] events are sent. */ private var eventSink: AnyThreadSink? = null /** * Observer for the [MediaDevices] events, which will send all the events to the Flutter side via * [EventChannel]. */ private val eventObserver = object : MediaDevices.Companion.EventObserver { override fun onDeviceChange() { eventSink?.success(mapOf("event" to "onDeviceChange")) } } init { chan.setMethodCallHandler(this) eventChannel.setStreamHandler(this) mediaDevices.addObserver(eventObserver) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "enumerateDevices" -> { GlobalScope.launch(Dispatchers.Main) { try { result.success(mediaDevices.enumerateDevices().map { it.asFlutterResult() }) } catch (e: GetUserMediaException) { when (e.kind) { GetUserMediaException.Kind.Audio -> result.error("GetUserMediaAudioException", e.message, null) GetUserMediaException.Kind.Video -> result.error("GetUserMediaVideoException", e.message, null) } } } } "getUserMedia" -> { GlobalScope.launch(Dispatchers.Main) { val constraintsArg: Map<String, Any> = call.argument("constraints")!! try { val tracks = mediaDevices.getUserMedia(Constraints.fromMap(constraintsArg)) result.success( tracks.map { MediaStreamTrackController(messenger, it).asFlutterResult() }) } catch (e: GetUserMediaException) { when (e.kind) { GetUserMediaException.Kind.Audio -> result.error("GetUserMediaAudioException", e.message, null) GetUserMediaException.Kind.Video -> result.error("GetUserMediaVideoException", e.message, null) } } } } "setOutputAudioId" -> { val deviceId: String = call.argument("deviceId")!! mediaDevices.setOutputAudioId(deviceId) result.success(null) } } } override fun onListen(obj: Any?, sink: EventChannel.EventSink?) { if (sink != null) { eventSink = AnyThreadSink(sink) } } override fun onCancel(obj: Any?) { eventSink = null } }
0
Rust
0
0
146467b24dd16a2786c3843f773cd08da68bc83c
3,967
webrtc
MIT License
systemUIShared/src/com/android/systemui/unfold/util/JankMonitorTransitionProgressListener.kt
LawnchairLauncher
83,799,439
false
{"Java": 9665767, "Kotlin": 2674103, "AIDL": 30229, "Python": 17364, "Makefile": 3820, "Shell": 770}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.systemui.unfold.util import android.view.View import com.android.internal.jank.InteractionJankMonitor import com.android.internal.jank.InteractionJankMonitor.CUJ_UNFOLD_ANIM import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener import java.util.function.Supplier class JankMonitorTransitionProgressListener(private val attachedViewProvider: Supplier<View>) : TransitionProgressListener { private val interactionJankMonitor = InteractionJankMonitor.getInstance() override fun onTransitionStarted() { interactionJankMonitor.begin(attachedViewProvider.get(), CUJ_UNFOLD_ANIM) } override fun onTransitionFinished() { interactionJankMonitor.end(CUJ_UNFOLD_ANIM) } }
388
Java
1200
9,200
d91399d2e4c6acbeef9c0704043f269115bb688b
1,388
lawnchair
Apache License 2.0
app_dagger/src/main/java/siarhei/luskanau/places2/dagger/di/AppModule.kt
siarhei-luskanau
154,686,579
false
null
package siarhei.luskanau.places2.dagger.di import android.content.Context import dagger.Module import dagger.Provides import javax.inject.Singleton import siarhei.luskanau.places2.dagger.AppApplication import siarhei.luskanau.places2.dagger.di.viewmodel.ViewModelBinderModule import siarhei.luskanau.places2.dagger.di.viewmodel.ViewModelBuilderModule import siarhei.luskanau.places2.data.StubPlaceService import siarhei.luskanau.places2.domain.AppNavigationArgs import siarhei.luskanau.places2.domain.PlaceService import siarhei.luskanau.places2.domain.SchedulerSet import siarhei.luskanau.places2.navigation.DefaultAppNavigationArgs @Module( includes = [ ViewModelBinderModule::class, ViewModelBuilderModule::class ] ) class AppModule { @Provides @Singleton fun provideContext(application: AppApplication): Context = application.applicationContext @Provides @Singleton fun provideAppNavigation(): AppNavigationArgs = DefaultAppNavigationArgs() @Provides @Singleton fun provideSchedulerSet(): SchedulerSet = SchedulerSet.default() @Provides @Singleton fun providePlaceService(): PlaceService = StubPlaceService() }
0
Kotlin
0
0
0c00403160a2ac9d0a29b1e7005c64bfd971d1ea
1,201
siarhei.luskanau.places2
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/iotfleetwise/CanSignalDecoderPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.iotfleetwise import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.iotfleetwise.CfnDecoderManifest @Generated public fun buildCanSignalDecoderProperty(initializer: @AwsCdkDsl CfnDecoderManifest.CanSignalDecoderProperty.Builder.() -> Unit): CfnDecoderManifest.CanSignalDecoderProperty = CfnDecoderManifest.CanSignalDecoderProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
507
aws-cdk-kt
Apache License 2.0
chatkit-core/src/main/kotlin/com/pusher/chatkit/util/_Gson.kt
pusher
106,020,436
false
null
package com.pusher.chatkit.util import com.google.gson.JsonElement import com.google.gson.JsonObject import com.pusher.util.Result import com.pusher.util.orElse import elements.Error import elements.Errors internal fun JsonObject.getValue(key: String) : Result<JsonElement, Error> = get(key).orElse { Errors.other("Value for $key not found") } internal fun JsonElement.asString(): Result<String, Error> = takeIf { it.isJsonPrimitive }?.asJsonPrimitive?.asString.orElse { Errors.other("Expected a String") } internal fun JsonElement.asObject(): Result<JsonObject, Error> = takeIf { it.isJsonObject }?.asJsonObject.orElse { Errors.other("Expected an object") }
12
Kotlin
14
54
4bc7d96059a8d6ec66032c84819f77149b6c3296
675
chatkit-android
MIT License
app/src/main/java/com/antoine163/blesmartkey/MainActivity.kt
antoine163
871,630,355
false
{"Kotlin": 133915}
package com.antoine163.blesmartkey import android.Manifest import android.os.Build import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.RequiresApi import com.antoine163.blesmartkey.data.DevicesBleSettingsRepositoryApp import com.antoine163.blesmartkey.ui.BleSmartKeyScreen import com.antoine163.blesmartkey.ui.theme.BleSmartKeyTheme class MainActivity : ComponentActivity() { // Bluetooth permissions required for Android 12 (API 31) and above @RequiresApi(Build.VERSION_CODES.S) private val bluetoothPermissions = arrayOf( Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADMIN, ) private val requestBluetoothPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> permissions.entries.forEach { Log.d("BSK", "${it.key} = ${it.value}") } } @RequiresApi(Build.VERSION_CODES.S) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() requestBluetoothPermissions.launch(bluetoothPermissions) // Request permissions setContent { BleSmartKeyTheme { BleSmartKeyScreen( devicesBleSettingsRepository = DevicesBleSettingsRepositoryApp(this) ) } } } }
0
Kotlin
0
0
2b3781987bed7a110fac411ad62f901769ec650e
1,757
ble-smart-lock-android-app
MIT License
src/main/java/ISearchForwardAction.kt
takc923
151,843,269
false
null
import com.intellij.openapi.editor.actionSystem.EditorAction class ISearchForwardAction : EditorAction(IncrementalSearchHandler(false))
1
Kotlin
1
2
9fe978c98b68da48894c591c9e301edb90f902eb
137
isearch
Apache License 2.0
src/test/kotlin/no/nav/hm/grunndata/register/productagreement/ProductAgreementExcelImportTest.kt
navikt
572,421,718
false
{"Kotlin": 472723, "Dockerfile": 113, "Shell": 111}
package no.nav.hm.grunndata.register.productagreement import io.kotest.matchers.shouldBe import io.micronaut.test.annotation.MockBean import io.micronaut.test.extensions.junit5.annotation.MicronautTest import io.mockk.mockk import kotlinx.coroutines.runBlocking import no.nav.hm.grunndata.rapid.dto.AgreementDTO import no.nav.hm.grunndata.rapid.dto.AgreementPost import no.nav.hm.grunndata.register.REGISTER import no.nav.hm.grunndata.register.agreement.* import no.nav.hm.grunndata.register.supplier.SupplierData import no.nav.hm.grunndata.register.supplier.SupplierRegistrationDTO import no.nav.hm.grunndata.register.supplier.SupplierRegistrationService import no.nav.hm.rapids_rivers.micronaut.RapidPushService import org.junit.jupiter.api.Test import org.slf4j.LoggerFactory import java.time.LocalDateTime import java.util.* @MicronautTest class ProductAgreementExcelImportTest(private val supplierRegistrationService: SupplierRegistrationService, private val agreementRegistrationService: AgreementRegistrationService, private val delkontraktRegistrationRepository: DelkontraktRegistrationRepository, private val productAgreementImportExcelService: ProductAgreementImportExcelService) { @MockBean(RapidPushService::class) fun rapidPushService(): RapidPushService = mockk(relaxed = true) companion object { private val LOG = LoggerFactory.getLogger(ProductAgreementExcelImportTest::class.java) } @Test fun testImportExcel() { runBlocking { val supplierId = UUID.randomUUID() val testSupplier = supplierRegistrationService.save( SupplierRegistrationDTO( id = supplierId, supplierData = SupplierData( address = "address 4", homepage = "https://www.hompage.no", phone = "+47 12345678", email = "<EMAIL>", ), identifier = "$supplierId-unique-name", name = "Leverandør AS -$supplierId" ) ).toRapidDTO() val agreementId = UUID.randomUUID() val agreement = AgreementDTO(id = agreementId, published = LocalDateTime.now(), expired = LocalDateTime.now().plusYears(2), title = "Title of agreement", text = "some text", reference = "22-7601", identifier = "unik-ref1234", resume = "resume", posts = listOf( AgreementPost(identifier = "unik-post1", title = "Post title", description = "post description", nr = 1), AgreementPost(identifier = "unik-post2", title = "Post title 2", description = "post description 2", nr = 2) ), createdBy = REGISTER, updatedBy = REGISTER, created = LocalDateTime.now(), updated = LocalDateTime.now()) val delkontrakt1 = DelkontraktRegistration( id = UUID.randomUUID(), agreementId = agreementId, delkontraktData = DelkontraktData( title = "1: Delkontrakt", description = "Delkontrakt 1 description", sortNr = 1, refNr = "1" ), createdBy = REGISTER, updatedBy = REGISTER ) val delkontrakt2 = DelkontraktRegistration( id = UUID.randomUUID(), agreementId = agreementId, delkontraktData = DelkontraktData( title = "2: Delkontrakt", description = "Delkontrakt 2 description", sortNr = 2, refNr = "2" ), createdBy = REGISTER, updatedBy = REGISTER ) val delkontrakt1A = DelkontraktRegistration( id = UUID.randomUUID(), agreementId = agreementId, delkontraktData = DelkontraktData( title = "1A: Delkontrakt", description = "Delkontrakt 1A description", sortNr = 3, refNr = "1A" ), createdBy = REGISTER, updatedBy = REGISTER ) val delkontrakt1B = DelkontraktRegistration( id = UUID.randomUUID(), agreementId = agreementId, delkontraktData = DelkontraktData( title = "1B: Delkontrakt ", description = "Delkontrakt 1B description", sortNr = 3, refNr = "1B" ), createdBy = REGISTER, updatedBy = REGISTER ) val data = AgreementData( text = "some text", resume = "resume", identifier = UUID.randomUUID().toString()) val agreementRegistration = AgreementRegistrationDTO( id = agreementId, published = agreement.published, expired = agreement.expired, title = agreement.title, reference = agreement.reference, updatedByUser = "username", createdByUser = "username", agreementData = data ) agreementRegistrationService.save(agreementRegistration) delkontraktRegistrationRepository.save(delkontrakt1) delkontraktRegistrationRepository.save(delkontrakt2) delkontraktRegistrationRepository.save(delkontrakt1A) delkontraktRegistrationRepository.save(delkontrakt1B) ProductAgreementExcelImportTest::class.java.classLoader.getResourceAsStream("productagreement/katalog-test.xls").use { val productAgreements = productAgreementImportExcelService.importExcelFile(it!!) productAgreements.size shouldBe 4 } } } @Test fun testDelkontraktNrExtract() { val regex = "d(\\d+)([A-Z]*)r(\\d+)".toRegex() val del1 = "d1r1" val del2 = "d1Ar1" val del3 = "d1Br99" // mean no rank regex.find(del1)?.groupValues?.get(1) shouldBe "1" regex.find(del1)?.groupValues?.get(2) shouldBe "" regex.find(del1)?.groupValues?.get(3) shouldBe "1" regex.find(del2)?.groupValues?.get(1) shouldBe "1" regex.find(del2)?.groupValues?.get(2) shouldBe "A" regex.find(del2)?.groupValues?.get(3) shouldBe "1" regex.find(del3)?.groupValues?.get(1) shouldBe "1" regex.find(del3)?.groupValues?.get(2) shouldBe "B" regex.find(del3)?.groupValues?.get(3) shouldBe "99" } }
0
Kotlin
0
2
db890957ec6a2a73b33520e64a078213515827dd
6,780
hm-grunndata-register
MIT License
plugin/src/main/kotlin/io/osguima3/jooqdsl/plugin/context/FieldContextImpl.kt
Osguima3
178,733,114
false
null
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses */ package io.osguima3.jooqdsl.plugin.context import io.osguima3.jooqdsl.model.context.FieldContext import io.osguima3.jooqdsl.model.converter.Converter import io.osguima3.jooqdsl.plugin.converter.ConverterBuilder import java.lang.reflect.Modifier import java.math.BigDecimal import java.time.Instant import java.time.OffsetDateTime import java.util.UUID import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.isSubclassOf import kotlin.reflect.jvm.javaGetter class FieldContextImpl( private val context: JooqContext, private val tableName: String, private val name: String ) : FieldContext { private val instanceField = "INSTANCE" private val builder = ConverterBuilder(context) override fun type(userType: KClass<*>) = resolve(userType) override fun enum(userType: KClass<out Enum<*>>, databaseType: String?) = register(userType, builder.enum(userType, databaseType)) override fun <T : Any, U : Any> valueObject( converter: KClass<out Converter<T, U>>, userType: KClass<*>, databaseType: KClass<T>, valueType: KClass<U> ) = if (!userType.isValueObject) { throw IllegalArgumentException("Type $userType is not a value object.") } else if (valueType != userType.valueType) { throw IllegalArgumentException( "$userType.${userType.valueField.name}(): ${userType.valueType} is not of type $valueType.") } else { registerValueObject(userType, databaseType, converter) } override fun <T : Any, U : Any> custom( converter: KClass<out Converter<T, U>>, userType: KClass<U>, databaseType: KClass<T> ) = if (!converter.isObjectType) { throw IllegalArgumentException( "Converter $converter should be a kotlin `object` or have an $instanceField singleton field.") } else { registerAdapter(userType, databaseType, converter) } private fun resolve(userType: KClass<*>) = when { userType.isPrimitive -> Unit // No need to register userType.isEnum -> registerEnum(userType) userType.isValueObject -> resolveValueObject(userType) userType == Instant::class -> register(userType, OffsetDateTime::class, instantFrom, instantTo) else -> throw IllegalArgumentException("No default mapper available for $userType") } private fun resolveValueObject(userType: KClass<*>, valueType: KClass<*> = userType.valueType) = when { valueType.isPrimitive -> registerValueObject(userType) valueType == Instant::class -> registerValueObject(userType, OffsetDateTime::class, instantFrom, instantTo) else -> throw IllegalArgumentException("No default mapper available for $userType") } private fun register(userType: KClass<*>, converter: String) { context.registerForcedType(".*\\.$tableName\\.$name", userType, converter) } private fun register(userType: KClass<*>, databaseType: KClass<*>, from: String, to: String) { register(userType, builder.simple(userType, databaseType, from, to)) } private fun registerEnum(userType: KClass<*>) { register(userType, builder.enum(userType)) } private fun registerValueObject(userType: KClass<*>) { register(userType, builder.valueObject(userType)) } private fun registerValueObject(userType: KClass<*>, databaseType: KClass<*>, converter: KClass<*>) { register(userType, builder.valueObject(userType, databaseType, converter)) } private fun registerValueObject(userType: KClass<*>, databaseType: KClass<*>, from: String, to: String) { register(userType, builder.valueObject(userType, databaseType, from, to)) } private fun registerAdapter(userType: KClass<*>, databaseType: KClass<*>, converter: KClass<*>) { register(userType, builder.adapter(userType, databaseType, converter)) } private val instantFrom = "java.time.OffsetDateTime::toInstant" private val instantTo = "i -> java.time.OffsetDateTime.ofInstant(i, java.time.ZoneOffset.UTC)" private val KClass<*>.isPrimitive get() = when (this) { BigDecimal::class, String::class, UUID::class -> true else -> javaPrimitiveType != null } private val KClass<*>.isEnum get() = isSubclassOf(Enum::class) private val KClass<*>.isValueObject get() = isData && declaredMemberProperties.size == 1 private val KClass<*>.isObjectType get() = objectInstance != null || java.declaredFields.any { it.name == instanceField && it.type == java && Modifier.isStatic(it.modifiers) } private val KClass<*>.valueField get() = declaredMemberProperties.mapNotNull(KProperty<*>::javaGetter).single() private val KClass<*>.valueType get() = valueField.returnType.kotlin }
4
Kotlin
0
2
e9bf3ae30ec76f3af93599f4fce9a5097b446e91
5,849
jooq-dsl-maven-plugin
Apache License 2.0
core/src/main/java/com/m3u/core/architecture/viewmodel/BaseViewModel.kt
realOxy
592,741,804
false
null
package com.m3u.core.architecture.viewmodel import android.app.Application import android.content.Context import androidx.lifecycle.AndroidViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow /** * MVI architecture ViewModel. * 1. The `readable` and `writable` fields should be used in ViewModels themself. * 2. ViewModel should change writable value to update current state. * 3. It also provides context but not making memory lacking. */ abstract class BaseViewModel<S, in E>( application: Application, emptyState: S ) : AndroidViewModel(application), PlatformViewModel<S, E> { protected val writable: MutableStateFlow<S> = MutableStateFlow(emptyState) protected val readable: S get() = writable.value override val state: StateFlow<S> = writable.asStateFlow() abstract override fun onEvent(event: E) protected val context: Context get() = getApplication() }
0
null
2
28
804813cb45ecc334dfeeb8da4d8b74105590c83e
984
M3UAndroid
Apache License 2.0
src/main/kotlin/io/newm/kogmios/protocols/model/PoolParameters.kt
projectNEWM
469,781,993
false
null
package io.newm.kogmios.protocols.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class PoolParameters( @SerialName("poolParameters") val poolParameters: List<String> )
0
Kotlin
0
4
8cc723de46afb45e4c1a44cf153fd18b1d7436c0
238
kogmios
Apache License 2.0
grpc-order-management-service/src/main/kotlin/com/ribbontek/ordermanagement/repository/user/AddressTypeRepository.kt
ribbontek
834,289,255
false
{"Kotlin": 424897, "Shell": 26370, "HTML": 1565, "Dockerfile": 557, "PLpgSQL": 398}
package com.ribbontek.ordermanagement.repository.user import com.ribbontek.ordermanagement.exception.NotFoundException import com.ribbontek.ordermanagement.repository.abstracts.EntityCodeDescriptionRepository import org.springframework.stereotype.Repository @Repository interface AddressTypeRepository : EntityCodeDescriptionRepository<AddressTypeEntity> fun AddressTypeRepository.expectOneByCode(code: String): AddressTypeEntity = findByCode(code) ?: throw NotFoundException("Could not find address type by code $code")
0
Kotlin
0
0
bf1562b2e915dd0dc98d4623c624fc60ab317770
528
grpc-course
MIT License
app/src/main/java/com/statix/flash/QrScannerActivity.kt
StatiXOS
668,833,999
false
null
/* * SPDX-FileCopyrightText: 2022 The LineageOS Project * SPDX-License-Identifier: Apache-2.0 */ package com.statix.flash import com.statix.flash.camera.CameraMode @androidx.camera.camera2.interop.ExperimentalCamera2Interop @androidx.camera.core.ExperimentalZeroShutterLag class QrScannerActivity : CameraActivity() { override fun overrideInitialCameraMode() = CameraMode.QR }
0
Kotlin
1
0
5cc3da78929cbee409c31e8d433120593dcc1968
387
android_packages_apps_Statix_Flash
Apache License 2.0
app/src/main/java/ru/tech/imageresizershrinker/presentation/root/theme/emoji/Park.kt
T8RIN
478,710,402
false
null
package ru.tech.imageresizershrinker.presentation.root.theme.emoji import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush.Companion.radialGradient import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import ru.tech.imageresizershrinker.presentation.root.theme.Emoji val Emoji.Park: ImageVector get() { if (_park != null) { return _park!! } _park = Builder( name = "Park", defaultWidth = 1.0.dp, defaultHeight = 1.0.dp, viewportWidth = 128.0f, viewportHeight = 128.0f ).apply { path( fill = radialGradient( 0.283f to Color(0xFFAFE4FE), 0.702f to Color(0xFF84D4F9), 0.965f to Color(0xFF67C9F6), center = Offset(48.378f, 86.785f), radius = 81.003f ), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(116.62f, 124.26f) horizontalLineTo(11.32f) curveToRelative(-4.15f, 0.0f, -7.52f, -3.37f, -7.52f, -7.52f) verticalLineTo(11.44f) curveToRelative(0.0f, -4.15f, 3.37f, -7.52f, 7.52f, -7.52f) horizontalLineToRelative(105.3f) curveToRelative(4.15f, 0.0f, 7.52f, 3.37f, 7.52f, 7.52f) verticalLineToRelative(105.3f) curveToRelative(0.01f, 4.15f, -3.36f, 7.52f, -7.52f, 7.52f) close() } path( fill = SolidColor(Color(0xFFB4D218)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(124.15f, 76.05f) verticalLineTo(117.0f) curveToRelative(0.0f, 4.15f, -3.37f, 7.52f, -7.52f, 7.52f) horizontalLineTo(11.32f) curveToRelative(-4.15f, 0.0f, -7.52f, -3.37f, -7.52f, -7.52f) verticalLineTo(75.65f) reflectiveCurveToRelative(38.09f, -1.0f, 64.1f, -1.4f) curveToRelative(26.0f, -0.4f, 56.25f, 1.8f, 56.25f, 1.8f) close() } path( fill = SolidColor(Color(0xFF00C1ED)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(106.1f, 124.49f) horizontalLineTo(11.32f) curveToRelative(-3.82f, 0.0f, -6.97f, -2.85f, -7.46f, -6.53f) curveToRelative(0.0f, 0.0f, 5.14f, -2.57f, 10.16f, -3.98f) curveToRelative(5.01f, -1.41f, 19.27f, -5.17f, 18.8f, -11.75f) curveToRelative(-0.47f, -6.58f, -13.85f, -6.2f, -13.0f, -13.47f) curveToRelative(0.38f, -3.27f, 6.07f, -6.89f, 12.55f, -9.07f) curveToRelative(8.4f, -2.83f, 18.21f, -3.73f, 18.3f, -3.58f) curveToRelative(0.1f, 0.18f, -3.22f, 4.78f, -1.81f, 9.95f) curveToRelative(1.41f, 5.17f, 7.88f, 8.44f, 19.94f, 11.1f) reflectiveCurveToRelative(24.03f, 5.23f, 31.08f, 14.16f) curveToRelative(6.86f, 8.69f, 6.22f, 13.17f, 6.22f, 13.17f) close() } path( fill = radialGradient( 0.307f to Color(0xFF8CDBFC), 0.412f to Color(0xFF54D1F5), 0.514f to Color(0xFF23C7EE), 0.564f to Color(0xFF10C4EC), center = Offset(55.276f, 66.733f), radius = 114.301f ), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(7.73f, 123.58f) curveToRelative(1.07f, 0.58f, 2.29f, 0.91f, 3.59f, 0.91f) horizontalLineToRelative(88.24f) reflectiveCurveToRelative(-1.09f, -6.37f, -11.28f, -14.43f) curveToRelative(-6.74f, -5.33f, -13.39f, -6.77f, -20.76f, -8.49f) curveToRelative(-12.02f, -2.81f, -20.32f, -4.55f, -22.99f, -13.16f) curveToRelative(-1.58f, -5.12f, 0.66f, -7.95f, 0.35f, -8.42f) curveToRelative(-0.31f, -0.47f, -19.78f, 3.68f, -19.95f, 8.75f) curveToRelative(-0.17f, 5.27f, 12.82f, 4.26f, 12.77f, 13.42f) curveToRelative(-0.05f, 8.62f, -11.97f, 12.8f, -16.32f, 14.32f) curveToRelative(-9.4f, 3.3f, -13.65f, 7.1f, -13.65f, 7.1f) close() } path( fill = SolidColor(Color(0xFF79A5AB)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveToRelative(3.8f, 75.39f) lineToRelative(49.26f, 0.04f) lineToRelative(-5.24f, -7.95f) reflectiveCurveToRelative(-2.43f, -0.84f, -6.36f, -5.24f) reflectiveCurveToRelative(-14.31f, -20.1f, -17.11f, -24.59f) reflectiveCurveToRelative(-7.01f, -9.35f, -10.94f, -9.16f) curveToRelative(-3.93f, 0.19f, -9.61f, 2.52f, -9.61f, 2.52f) verticalLineToRelative(44.38f) close() } path( fill = SolidColor(Color(0xFFE0E0E0)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(3.79f, 26.33f) reflectiveCurveToRelative(2.35f, -0.63f, 4.9f, -0.49f) curveToRelative(3.55f, 0.19f, 7.56f, 3.31f, 7.56f, 3.31f) reflectiveCurveToRelative(-4.61f, -0.04f, -7.47f, 2.58f) curveTo(6.37f, 33.94f, 3.8f, 37.7f, 3.8f, 37.7f) lineToRelative(-0.01f, -11.37f) close() } path( fill = SolidColor(Color(0xFF86B4BB)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(64.08f, 42.75f) lineTo(51.1f, 70.74f) lineToRelative(1.95f, 3.98f) lineToRelative(18.39f, -1.42f) lineToRelative(11.63f, -38.05f) lineToRelative(-8.93f, -2.4f) close() } path( fill = SolidColor(Color(0xFF3E727B)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveToRelative(74.51f, 48.83f) lineToRelative(-3.08f, 9.08f) lineTo(70.0f, 68.79f) lineToRelative(34.0f, 2.93f) reflectiveCurveToRelative(14.48f, -33.09f, 14.41f, -33.32f) curveToRelative(-0.08f, -0.23f, -15.68f, -22.74f, -15.68f, -22.74f) lineTo(90.72f, 19.9f) lineToRelative(-9.83f, 12.53f) lineToRelative(-6.38f, 16.4f) close() } path( fill = SolidColor(Color(0xFF79A5AB)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(124.14f, 20.58f) reflectiveCurveToRelative(-5.21f, -4.62f, -8.21f, -5.67f) curveToRelative(-3.0f, -1.05f, -14.63f, -1.58f, -14.63f, -1.58f) lineToRelative(-10.2f, 3.69f) lineToRelative(-8.78f, 10.21f) lineTo(77.06f, 39.0f) lineToRelative(-2.7f, 10.13f) reflectiveCurveToRelative(1.75f, 2.02f, 2.59f, -1.71f) curveToRelative(0.66f, -2.9f, 1.53f, -6.62f, 5.21f, -14.72f) reflectiveCurveToRelative(11.27f, -15.49f, 17.56f, -14.71f) curveToRelative(4.92f, 0.61f, 7.24f, 7.79f, 8.36f, 12.97f) curveToRelative(1.13f, 5.18f, 1.69f, 15.32f, 1.69f, 15.32f) lineToRelative(-7.28f, 3.9f) lineToRelative(-4.35f, 12.46f) reflectiveCurveToRelative(-0.23f, 1.73f, -0.6f, 4.2f) curveToRelative(-0.38f, 2.48f, -0.38f, 5.18f, -0.38f, 5.18f) lineToRelative(20.19f, 0.68f) lineToRelative(6.79f, -4.87f) verticalLineTo(20.58f) close() } path( fill = SolidColor(Color(0xFFE0E0DF)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveToRelative(51.18f, 68.23f) lineToRelative(3.15f, 0.45f) reflectiveCurveToRelative(2.48f, -6.23f, 3.6f, -9.08f) curveToRelative(1.13f, -2.85f, 2.03f, -5.1f, 2.85f, -6.0f) curveToRelative(0.83f, -0.9f, 3.08f, -1.13f, 3.68f, -2.1f) curveToRelative(0.6f, -0.98f, 2.85f, -8.25f, 4.5f, -10.96f) curveToRelative(1.65f, -2.7f, 3.68f, -5.1f, 5.4f, -5.78f) curveToRelative(1.73f, -0.68f, 3.08f, -0.23f, 3.08f, -0.23f) reflectiveCurveToRelative(-2.1f, 5.78f, -3.15f, 10.36f) reflectiveCurveToRelative(-2.85f, 13.02f, -2.85f, 13.02f) reflectiveCurveToRelative(1.8f, -0.86f, 2.55f, -1.91f) reflectiveCurveToRelative(0.93f, -2.66f, 1.14f, -4.12f) curveToRelative(1.01f, -7.08f, 2.28f, -10.63f, 3.16f, -13.6f) curveToRelative(1.16f, -3.91f, 4.0f, -9.65f, 5.36f, -11.86f) curveToRelative(3.08f, -5.0f, 5.29f, -6.87f, 7.99f, -8.74f) curveToRelative(2.7f, -1.88f, 7.54f, -3.9f, 13.1f, -3.6f) curveToRelative(5.55f, 0.3f, 14.05f, 2.38f, 14.05f, 2.38f) reflectiveCurveToRelative(-6.21f, -4.82f, -14.69f, -4.74f) reflectiveCurveToRelative(-14.13f, 3.47f, -18.63f, 8.65f) reflectiveCurveToRelative(-6.98f, 12.31f, -6.98f, 12.31f) reflectiveCurveToRelative(-2.63f, -1.73f, -5.93f, -0.98f) reflectiveCurveToRelative(-6.38f, 1.95f, -9.68f, 7.58f) reflectiveCurveToRelative(-7.43f, 17.71f, -7.43f, 17.71f) lineToRelative(-4.27f, 11.24f) close() moveTo(111.66f, 51.05f) reflectiveCurveToRelative(-4.65f, -1.2f, -7.13f, 0.6f) curveToRelative(-1.77f, 1.29f, -3.22f, 3.93f, -4.73f, 8.93f) curveToRelative(-1.37f, 4.53f, -2.06f, 5.1f, -2.1f, 4.97f) curveToRelative(-0.18f, -0.54f, 0.59f, -8.53f, 1.5f, -12.17f) curveToRelative(0.68f, -2.7f, 2.54f, -6.94f, 6.68f, -7.88f) curveToRelative(4.65f, -1.06f, 5.63f, 2.92f, 5.78f, 5.55f) close() } path( fill = SolidColor(Color(0xFF79A5AB)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(93.72f, 26.66f) curveToRelative(-1.27f, -0.1f, -1.59f, 1.27f, -1.64f, 5.04f) curveToRelative(-0.06f, 4.13f, -0.38f, 7.65f, -0.38f, 7.65f) reflectiveCurveToRelative(-3.08f, 4.42f, -4.05f, 7.27f) curveToRelative(-0.98f, 2.85f, -1.88f, 5.63f, -2.4f, 8.33f) curveToRelative(-0.39f, 2.0f, -0.92f, 4.71f, 0.3f, 5.18f) curveToRelative(1.58f, 0.6f, 3.15f, -6.53f, 4.58f, -10.96f) curveToRelative(1.52f, -4.73f, 4.8f, -8.78f, 4.8f, -8.78f) reflectiveCurveToRelative(0.09f, -4.51f, 0.0f, -8.19f) curveToRelative(-0.04f, -1.27f, 0.12f, -5.44f, -1.21f, -5.54f) close() moveTo(86.29f, 30.71f) curveToRelative(-1.13f, 0.14f, -1.49f, 1.94f, -1.58f, 4.2f) curveToRelative(-0.09f, 2.25f, -0.08f, 3.83f, -0.08f, 3.83f) reflectiveCurveToRelative(-1.58f, 3.38f, -1.95f, 4.88f) reflectiveCurveToRelative(0.83f, 2.18f, 1.88f, 0.9f) curveToRelative(1.05f, -1.28f, 3.3f, -5.48f, 3.3f, -5.48f) reflectiveCurveToRelative(0.08f, -3.0f, 0.08f, -4.2f) curveToRelative(0.0f, -1.2f, 0.23f, -4.35f, -1.65f, -4.13f) close() } path( fill = SolidColor(Color(0xFFACE4FE)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(14.21f, 41.36f) curveToRelative(-0.1f, 0.0f, 0.42f, 1.2f, 0.71f, 2.77f) curveToRelative(0.36f, 1.93f, 0.73f, 6.36f, 0.85f, 13.4f) reflectiveCurveToRelative(0.47f, 14.6f, 0.47f, 14.6f) lineToRelative(5.12f, -1.51f) reflectiveCurveToRelative(-0.17f, -10.65f, -0.76f, -16.17f) reflectiveCurveToRelative(-1.42f, -8.35f, -2.91f, -10.75f) curveToRelative(-0.71f, -1.14f, -2.56f, -2.36f, -3.48f, -2.34f) close() } path( fill = SolidColor(Color(0xFFFCFDFE)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(16.78f, 50.62f) curveToRelative(0.93f, -0.12f, 0.92f, 1.74f, 0.99f, 4.83f) curveToRelative(0.06f, 2.68f, 0.17f, 4.3f, -0.47f, 4.36f) curveToRelative(-0.87f, 0.08f, -0.75f, -0.75f, -0.93f, -5.0f) curveToRelative(-0.12f, -2.73f, -0.27f, -4.1f, 0.41f, -4.19f) close() moveTo(18.86f, 52.47f) curveToRelative(-0.58f, 0.13f, -0.23f, 2.03f, -0.12f, 5.29f) curveToRelative(0.12f, 3.49f, -0.12f, 5.7f, 0.99f, 5.7f) curveToRelative(1.05f, 0.0f, 0.58f, -2.09f, 0.47f, -5.93f) curveToRelative(-0.11f, -3.37f, -0.3f, -5.29f, -1.34f, -5.06f) close() moveTo(15.6f, 72.37f) reflectiveCurveToRelative(1.11f, -1.63f, 2.5f, -1.92f) curveToRelative(1.4f, -0.29f, 1.92f, -0.12f, 1.92f, -0.12f) reflectiveCurveToRelative(0.81f, -2.33f, 3.9f, -2.27f) curveToRelative(3.08f, 0.06f, 4.13f, 4.36f, 4.13f, 4.36f) lineToRelative(-12.39f, 1.63f) lineToRelative(-0.06f, -1.68f) close() } path( fill = SolidColor(Color(0xFF0A7E1D)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(17.24f, 76.21f) reflectiveCurveToRelative(24.82f, -0.65f, 39.97f, -0.52f) curveToRelative(15.15f, 0.13f, 31.22f, 0.13f, 31.22f, 0.13f) reflectiveCurveToRelative(-8.62f, -17.24f, -9.28f, -17.11f) curveToRelative(-0.65f, 0.13f, -5.75f, 9.01f, -5.75f, 9.01f) reflectiveCurveToRelative(-5.55f, -9.64f, -6.07f, -9.9f) reflectiveCurveToRelative(-6.35f, 13.07f, -6.35f, 13.07f) lineToRelative(-2.53f, -3.92f) lineToRelative(-2.98f, 4.75f) lineToRelative(-3.88f, -8.43f) lineToRelative(-6.92f, 9.67f) reflectiveCurveToRelative(-1.37f, -0.43f, -3.07f, -0.51f) curveToRelative(-2.56f, -0.12f, -5.55f, 1.29f, -5.55f, 1.29f) reflectiveCurveToRelative(-5.49f, -1.83f, -9.28f, -1.83f) reflectiveCurveToRelative(-14.63f, 3.0f, -14.63f, 3.0f) lineToRelative(5.1f, 1.3f) close() } path( fill = SolidColor(Color(0xFF02AB47)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(50.49f, 61.52f) curveToRelative(0.58f, 0.14f, 1.58f, 2.82f, 1.58f, 2.82f) lineTo(48.11f, 74.0f) lineToRelative(-3.45f, -1.01f) curveToRelative(0.01f, 0.0f, 5.19f, -11.63f, 5.83f, -11.47f) close() moveTo(55.46f, 71.75f) lineToRelative(1.02f, 1.97f) lineToRelative(2.82f, -5.43f) reflectiveCurveToRelative(-0.85f, -1.57f, -1.04f, -1.56f) curveToRelative(-0.4f, 0.03f, -2.8f, 5.02f, -2.8f, 5.02f) close() moveTo(67.37f, 57.72f) curveToRelative(-1.09f, 0.05f, -6.39f, 13.14f, -6.39f, 13.14f) reflectiveCurveToRelative(1.4f, 2.04f, 1.52f, 2.06f) curveToRelative(0.76f, 0.11f, 5.95f, -13.53f, 5.95f, -13.53f) reflectiveCurveToRelative(-0.81f, -1.69f, -1.08f, -1.67f) close() } path( fill = SolidColor(Color(0xFF0A7E1D)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(82.64f, 78.76f) reflectiveCurveToRelative(-0.46f, 1.19f, 0.28f, 1.38f) reflectiveCurveToRelative(6.25f, 1.01f, 15.15f, 0.64f) curveToRelative(8.91f, -0.37f, 26.07f, -0.73f, 26.07f, -0.73f) lineToRelative(0.01f, -12.22f) reflectiveCurveToRelative(-7.35f, -16.99f, -8.27f, -16.81f) curveToRelative(-0.92f, 0.18f, -7.29f, 15.14f, -7.29f, 15.14f) reflectiveCurveToRelative(-2.58f, -4.72f, -3.03f, -4.9f) curveToRelative(-0.46f, -0.18f, -7.68f, 8.78f, -7.68f, 8.78f) reflectiveCurveToRelative(-4.68f, -13.32f, -5.42f, -13.41f) curveToRelative(-0.73f, -0.09f, -9.82f, 22.13f, -9.82f, 22.13f) close() } path( fill = SolidColor(Color(0xFF02AB47)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(91.41f, 54.25f) curveToRelative(-0.82f, 0.0f, -6.85f, 14.14f, -7.68f, 16.16f) curveToRelative(-0.83f, 2.02f, -3.65f, 8.57f, -3.28f, 9.12f) curveToRelative(0.37f, 0.55f, 3.8f, 0.82f, 3.8f, 0.82f) reflectiveCurveToRelative(3.89f, -11.32f, 5.54f, -15.0f) curveToRelative(1.65f, -3.67f, 3.51f, -7.31f, 3.51f, -7.31f) reflectiveCurveToRelative(-1.04f, -3.79f, -1.89f, -3.79f) close() moveTo(104.13f, 59.76f) curveToRelative(0.49f, -0.25f, 2.11f, 2.39f, 2.11f, 2.39f) reflectiveCurveToRelative(-6.15f, 10.65f, -6.61f, 10.84f) curveToRelative(-0.46f, 0.18f, -1.75f, -2.94f, -1.75f, -2.94f) reflectiveCurveToRelative(5.14f, -9.74f, 6.25f, -10.29f) close() } path( fill = SolidColor(Color(0xFF0A7E1D)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(3.81f, 112.79f) reflectiveCurveToRelative(4.02f, 0.57f, 7.08f, -1.55f) curveToRelative(4.41f, -3.06f, 4.66f, -6.34f, 4.66f, -6.34f) reflectiveCurveToRelative(1.17f, 1.64f, 5.73f, 1.73f) curveToRelative(4.56f, 0.09f, 6.52f, -3.79f, 6.42f, -4.32f) curveToRelative(-0.05f, -0.26f, -4.54f, -5.73f, -4.54f, -5.73f) lineTo(17.9f, 85.99f) lineToRelative(0.61f, -2.57f) lineToRelative(-7.7f, -10.29f) lineToRelative(-3.04f, -17.9f) reflectiveCurveToRelative(-0.81f, -1.7f, -1.34f, -1.25f) reflectiveCurveToRelative(-2.6f, 4.48f, -2.6f, 4.48f) lineToRelative(-0.02f, 54.33f) close() } path( fill = SolidColor(Color(0xFF00AA48)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(11.52f, 87.45f) curveToRelative(-1.78f, -0.18f, -3.49f, -2.69f, -3.85f, -8.95f) curveToRelative(-0.36f, -6.27f, 0.36f, -16.47f, -0.09f, -19.24f) curveToRelative(-0.45f, -2.77f, -1.16f, -5.28f, -1.16f, -5.28f) reflectiveCurveToRelative(0.36f, -0.9f, 1.07f, 0.09f) reflectiveCurveToRelative(4.48f, 7.52f, 6.27f, 11.99f) curveToRelative(1.79f, 4.48f, 7.84f, 15.23f, 8.77f, 16.83f) curveToRelative(1.62f, 2.78f, 2.87f, 5.13f, 0.72f, 5.22f) curveToRelative(-2.15f, 0.09f, -5.11f, -1.82f, -5.11f, -1.82f) reflectiveCurveToRelative(3.58f, 7.43f, 4.65f, 8.95f) reflectiveCurveToRelative(4.12f, 6.0f, 4.12f, 6.0f) reflectiveCurveToRelative(-0.54f, 1.79f, -3.4f, 0.98f) reflectiveCurveToRelative(-6.21f, -8.18f, -6.98f, -10.16f) curveToRelative(-0.75f, -1.93f, -0.85f, -3.65f, -0.75f, -4.47f) curveToRelative(0.18f, -1.52f, 1.47f, -1.84f, 1.47f, -1.84f) reflectiveCurveToRelative(-1.43f, -1.52f, -2.15f, -2.69f) curveToRelative(-0.72f, -1.16f, -1.52f, -2.77f, -1.52f, -2.77f) reflectiveCurveToRelative(0.63f, 7.43f, -2.06f, 7.16f) close() } path( fill = SolidColor(Color(0xFF0A7E1D)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(117.4f, 76.89f) reflectiveCurveToRelative(-18.44f, 5.46f, -19.15f, 6.27f) curveToRelative(-0.72f, 0.81f, -0.81f, 2.33f, 0.9f, 3.04f) reflectiveCurveToRelative(2.58f, 0.2f, 4.21f, 1.25f) curveToRelative(0.65f, 0.42f, -0.85f, 4.82f, -0.85f, 4.82f) reflectiveCurveToRelative(-7.75f, 2.53f, -7.88f, 3.65f) curveToRelative(-0.16f, 1.4f, 0.85f, 2.72f, 2.64f, 3.61f) curveToRelative(1.6f, 0.8f, 3.91f, 0.92f, 3.91f, 0.92f) reflectiveCurveToRelative(-9.01f, 6.84f, -8.57f, 8.54f) curveToRelative(0.45f, 1.7f, 2.38f, 4.53f, 6.71f, 4.42f) curveToRelative(3.94f, -0.1f, 4.56f, -1.52f, 6.71f, 0.09f) curveToRelative(2.15f, 1.61f, 2.07f, 5.31f, 7.88f, 4.92f) curveToRelative(4.03f, -0.27f, 5.02f, -2.82f, 7.07f, -3.85f) curveToRelative(1.65f, -0.82f, 3.19f, -0.93f, 3.19f, -0.93f) lineToRelative(-0.03f, -33.6f) lineToRelative(-6.74f, -3.15f) close() } path( fill = SolidColor(Color(0xFF02AB47)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(115.34f, 62.57f) curveToRelative(-2.06f, 0.12f, -3.13f, 5.28f, -7.25f, 10.29f) reflectiveCurveTo(98.21f, 83.2f, 98.21f, 83.2f) reflectiveCurveToRelative(0.48f, 1.22f, 1.92f, 1.21f) curveToRelative(2.06f, -0.02f, 3.67f, -1.88f, 5.28f, -1.25f) curveToRelative(1.61f, 0.63f, 1.34f, 3.4f, 3.85f, 3.58f) curveToRelative(2.51f, 0.18f, 5.91f, -3.13f, 8.14f, -3.22f) curveToRelative(2.24f, -0.09f, 2.24f, 2.24f, 4.39f, 2.15f) curveToRelative(2.15f, -0.09f, 2.36f, -1.08f, 2.36f, -1.08f) verticalLineToRelative(-6.82f) reflectiveCurveToRelative(-3.34f, -4.37f, -4.69f, -8.22f) curveToRelative(-1.34f, -3.85f, -2.59f, -7.07f, -4.12f, -6.98f) close() moveTo(109.35f, 90.41f) curveToRelative(3.04f, 0.08f, 5.82f, -2.77f, 9.58f, -2.42f) curveToRelative(3.76f, 0.36f, 3.94f, 4.56f, 3.49f, 6.27f) curveToRelative(-0.45f, 1.7f, -1.52f, 4.65f, -4.3f, 4.65f) curveToRelative(-2.77f, 0.0f, -2.86f, -1.61f, -4.56f, -1.43f) curveToRelative(-1.7f, 0.18f, -2.86f, 1.88f, -5.01f, 1.61f) reflectiveCurveToRelative(-3.13f, -2.33f, -4.74f, -2.6f) reflectiveCurveToRelative(-4.21f, 1.25f, -6.27f, 1.16f) curveToRelative(-2.06f, -0.09f, -2.93f, -1.81f, -2.93f, -1.81f) reflectiveCurveToRelative(0.42f, -1.5f, 1.85f, -2.3f) reflectiveCurveToRelative(2.6f, -1.34f, 4.48f, -3.13f) reflectiveCurveToRelative(2.41f, -2.95f, 2.41f, -2.95f) reflectiveCurveToRelative(2.69f, 2.86f, 6.0f, 2.95f) close() moveTo(105.05f, 108.66f) curveToRelative(3.11f, 0.0f, 2.51f, 4.48f, 6.35f, 5.19f) curveToRelative(3.85f, 0.72f, 9.04f, -7.07f, 6.27f, -11.1f) curveToRelative(-2.77f, -4.03f, -6.27f, 0.81f, -9.93f, -0.09f) curveToRelative(-3.67f, -0.9f, -3.67f, -2.6f, -6.44f, -2.51f) curveToRelative(-2.77f, 0.09f, -8.53f, 5.44f, -8.68f, 8.41f) curveToRelative(-0.09f, 1.79f, 2.77f, 2.66f, 5.55f, 2.24f) curveToRelative(2.76f, -0.41f, 5.45f, -2.14f, 6.88f, -2.14f) close() } path( fill = SolidColor(Color(0xFFFFFFFE)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(20.34f, 16.11f) curveToRelative(0.07f, 3.53f, 5.69f, 4.39f, 14.98f, 4.47f) curveToRelative(9.29f, 0.07f, 15.12f, -0.72f, 14.98f, -4.18f) reflectiveCurveToRelative(-10.73f, -4.1f, -16.2f, -4.32f) curveToRelative(-5.47f, -0.22f, -13.83f, 0.43f, -13.76f, 4.03f) close() moveTo(42.44f, 29.83f) curveToRelative(0.46f, 2.71f, 4.32f, 2.36f, 9.87f, 2.46f) curveToRelative(6.19f, 0.12f, 11.0f, 0.62f, 11.39f, -2.68f) curveToRelative(0.39f, -3.31f, -7.69f, -2.97f, -10.93f, -2.93f) curveToRelative(-3.25f, 0.05f, -10.88f, -0.11f, -10.33f, 3.15f) close() } } .build() return _park!! } private var _park: ImageVector? = null
9
null
47
514
c039548b804f7d716972bd5f3648fac26a17e806
28,304
ImageToolbox
Apache License 2.0
embrace-android-sdk/src/main/java/io/embrace/android/embracesdk/internal/anr/ndk/NativeThreadSamplerInstaller.kt
embrace-io
704,537,857
false
{"Kotlin": 2867942, "C": 190133, "Java": 177132, "C++": 13140, "CMake": 4261}
package io.embrace.android.embracesdk.anr.ndk import android.os.Handler import android.os.Looper import io.embrace.android.embracesdk.anr.AnrService import io.embrace.android.embracesdk.config.ConfigService import io.embrace.android.embracesdk.internal.SharedObjectLoader import io.embrace.android.embracesdk.logging.EmbLogger import io.embrace.android.embracesdk.payload.NativeThreadAnrSample import java.util.concurrent.atomic.AtomicBoolean internal class NativeThreadSamplerNdkDelegate : EmbraceNativeThreadSamplerService.NdkDelegate { external override fun setupNativeThreadSampler(is32Bit: Boolean): Boolean external override fun monitorCurrentThread(): Boolean external override fun startSampling(unwinderOrdinal: Int, intervalMs: Long) external override fun finishSampling(): List<NativeThreadAnrSample>? } internal class NativeThreadSamplerInstaller( private val sharedObjectLoader: SharedObjectLoader, private val logger: EmbLogger, ) { private val isMonitoring = AtomicBoolean(false) private var targetHandler: Handler? = null internal var currentThread: Thread? = null private fun prepareTargetHandler() { // We create a Handler here so that when the functionality is disabled locally // but enabled remotely, the config change callback also runs the install // on the target thread. if (Looper.myLooper() == null) { Looper.prepare() } val looper = Looper.myLooper() targetHandler = when { looper != null -> Handler(looper) else -> null } if (targetHandler == null) { logger.logError( "Native thread sampler init failed: Failed to create Handler for target native thread" ) return } } fun monitorCurrentThread( sampler: NativeThreadSamplerService, configService: ConfigService, anrService: AnrService ) { if (isMonitoringCurrentThread()) { return } else { // disable monitoring since we can end up here if monitoring was enabled, // but the target thread has changed isMonitoring.set(false) } currentThread = Thread.currentThread() if (!sharedObjectLoader.loadEmbraceNative()) { return } prepareTargetHandler() if (configService.anrBehavior.isNativeThreadAnrSamplingEnabled()) { monitorCurrentThread(sampler, anrService) } // always install the handler. if config subsequently changes we take the decision // to just ignore anr intervals, rather than attempting to uninstall the handler configService.addListener { onConfigChange(configService, sampler, anrService) } } private fun isMonitoringCurrentThread(): Boolean { return isMonitoring.get() && Thread.currentThread().id == currentThread?.id } private fun onConfigChange( configService: ConfigService, sampler: NativeThreadSamplerService, anrService: AnrService ) { targetHandler?.post( Runnable { if (configService.anrBehavior.isNativeThreadAnrSamplingEnabled() && !isMonitoring.get()) { monitorCurrentThread(sampler, anrService) } } ) } private fun monitorCurrentThread(sampler: NativeThreadSamplerService, anrService: AnrService) { synchronized(this) { if (!isMonitoring.get()) { logger.logInfo("Installing native sampling on '${Thread.currentThread().name}'") if (sampler.monitorCurrentThread()) { anrService.addBlockedThreadListener(sampler) isMonitoring.set(true) } } } } }
21
Kotlin
7
133
a7d76f379f1e190c0deaddbb783d63ac953fd1df
3,875
embrace-android-sdk
Apache License 2.0
app/src/main/java/mil/nga/msi/di/GeocoderModule.kt
ngageoint
588,211,646
false
{"Kotlin": 1876117}
package mil.nga.msi.di import android.app.Application import android.location.Geocoder import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class GeocoderModule { @Provides @Singleton fun provideGeocoder(application: Application): Geocoder { return Geocoder(application) } }
0
Kotlin
0
0
24d0765298274e7aa2d80ec0f147306a61d909ef
439
marlin-android
MIT License
src/main/java/com/cincinnatiai/grinchwalker/utils/TestWaiter.kt
nicholaspark09
227,241,567
false
{"INI": 1, "Gradle": 2, "Proguard": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 13, "Markdown": 1, "XML": 450, "Java Properties": 4, "Kotlin": 13, "JAR Manifest": 1, "Java": 2, "JSON": 145, "SQL": 4}
package com.cincinnatiai.grinchwalker.utils import android.app.Instrumentation import androidx.annotation.LayoutRes import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiSelector import androidx.test.uiautomator.Until private const val STATIC_WAIT = 600L private const val DEFAULT_TIMEOUT = 900L interface TestWaiterContract { fun waitUntilElementIsDisplayed(timeout: Long = DEFAULT_TIMEOUT, resourceId: String) fun staticWait(timeInMilliseconds: Long = STATIC_WAIT) fun waitUntilElementIsClickable(timeout: Long = DEFAULT_TIMEOUT, resourceId: String) fun waitUntilElementIsGone(timeout: Long = DEFAULT_TIMEOUT, resourceId: String) } class TestWaiter( val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation(), val device: UiDevice = UiDevice.getInstance(instrumentation) ) : TestWaiterContract { override fun waitUntilElementIsGone(timeout: Long, resourceId: String) { device.wait(Until.gone(By.res(resourceId)), timeout) } override fun waitUntilElementIsClickable(timeout: Long, resourceId: String) { device.wait(Until.findObject(By.clickable(true).res(resourceId)), timeout) } override fun waitUntilElementIsDisplayed(timeout: Long, resourceId: String) { device.findObject(UiSelector().resourceId(resourceId)).waitForExists(timeout) } override fun staticWait(timeInMilliseconds: Long) { try { Thread.sleep(timeInMilliseconds) } catch (e: InterruptedException) { e.printStackTrace() } } }
1
null
1
1
dfb360788f9095dd774c2e9309cbe3ff0d59c332
1,673
grinch
Apache License 2.0
lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/SuperfluousNameSpaceDetectorTest.kt
MaTriXy
116,227,290
true
{"Kotlin": 177642, "Java": 43098, "Shell": 1027}
package com.vanniktech.lintrules.android import com.android.tools.lint.checks.infrastructure.TestFiles.xml import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Test class SuperfluousNameSpaceDetectorTest { @Test fun androidNamespaceOnlyOnParent() { lint() .files(xml("res/layout/activity_home.xml", """ |<merge xmlns:android="http://schemas.android.com/apk/res/android"> | <TextView | android:layout_width="wrap_content"/> |</merge>""".trimMargin())) .issues(ISSUE_SUPERFLUOUS_NAME_SPACE) .run() .expectClean() } @Test fun androidNamespaceOnChild() { lint() .files(xml("res/layout/activity_home.xml", """ |<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"> | <TextView | xmlns:android="http://schemas.android.com/apk/res/android" | android:layout_width="wrap_content"/> |</LinearLayout>""".trimMargin())) .issues(ISSUE_SUPERFLUOUS_NAME_SPACE) .run() .expect(""" |res/layout/activity_home.xml:3: Warning: This name space is already declared and hence not needed. [SuperfluousNameSpace] | xmlns:android="http://schemas.android.com/apk/res/android" | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |0 errors, 1 warnings""".trimMargin()) } @Test fun androidNamespaceOnChildsChild() { lint() .files(xml("res/layout/activity_home.xml", """ |<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"> | <LinearLayout> | <TextView | xmlns:android="http://schemas.android.com/apk/res/android" | android:layout_width="wrap_content"/> | </LinearLayout> |</LinearLayout>""".trimMargin())) .issues(ISSUE_SUPERFLUOUS_NAME_SPACE) .run() .expect(""" |res/layout/activity_home.xml:4: Warning: This name space is already declared and hence not needed. [SuperfluousNameSpace] | xmlns:android="http://schemas.android.com/apk/res/android" | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |0 errors, 1 warnings""".trimMargin()) } }
0
Kotlin
0
0
06cf052b352bfcba7010b2f0e285f0ac327c332e
2,306
lint-rules
Apache License 2.0
app/src/main/java/com/core/app/AppFragment.kt
raxden
165,669,612
false
null
package com.core.app import androidx.databinding.ViewDataBinding import com.core.app.base.BaseViewModel import com.core.app.base.fragment.BaseViewModelFragment abstract class AppFragment<VM : BaseViewModel, VDB : ViewDataBinding> : BaseViewModelFragment<VM, VDB>() { override val layoutId: Int get() = javaClass.simpleName .decapitalize() .split("(?=\\p{Upper})".toRegex()) .joinToString(separator = "_") .toLowerCase() .takeIf { it.isNotEmpty() }?.let { resources.getIdentifier(it.replace("R.layout.", ""), "layout", context?.packageName) } ?: 0 }
1
null
1
1
9ad3b3d2fffdaa7abdf567320e8d6d9f98a67746
683
android-core
Apache License 2.0
app/src/main/java/dev/vengateshm/android_kotlin_compose_practice/graph_ql_app/countries_api/Country.kt
vengateshm
670,054,614
false
{"Kotlin": 1157445, "Java": 28903}
package dev.vengateshm.android_kotlin_compose_practice.graph_ql_app.countries_api // import dev.vengateshm.android_kotlin_compose_practice.GetCountriesByContinentQuery data class Country(val name: String, val capital: String, val currency: String) // fun GetCountriesByContinentQuery.Country.toModel() = // Country( // name = name, // capital = capital ?: "", // currency = currency ?: "", // )
0
Kotlin
0
1
382c1b29f62f521b252e9b973de085496e51fdc1
425
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
clients/kotlin/generated/src/main/kotlin/io/swagger/client/models/CauseUserIdCause.kt
zhiwei55
127,058,165
true
{"Java": 7756283, "C++": 3985373, "C#": 3367837, "PHP": 2639235, "HTML": 2016332, "Python": 1451773, "Swift": 1288941, "TypeScript": 1232093, "Ruby": 1108711, "JavaScript": 1092066, "Apex": 949936, "Perl": 725589, "Scala": 534194, "Objective-C": 470063, "Eiffel": 428606, "Shell": 359635, "ActionScript": 258239, "Go": 218997, "Dart": 184873, "Kotlin": 171556, "PowerShell": 171125, "Erlang": 123864, "Groovy": 94635, "Haskell": 82559, "Clojure": 47990, "Elixir": 29146, "Perl 6": 20660, "Makefile": 5984, "CSS": 4873, "CMake": 2735, "Batchfile": 1028}
/** * <NAME> * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 0.1.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.models /** * * @param _class * @param shortDescription * @param userId * @param userName */ data class CauseUserIdCause ( val _class: kotlin.String? = null, val shortDescription: kotlin.String? = null, val userId: kotlin.String? = null, val userName: kotlin.String? = null ) { }
0
Java
0
0
678b5477f5f9f00022b176c34b840055fb1b0a77
637
swaggy-jenkins
MIT License
controls-serial/src/main/kotlin/ru/mipt/npm/controls/serial/SerialPort.kt
mipt-npm
240,888,288
false
null
package ru.mipt.npm.controls.serial import jssc.SerialPort.* import jssc.SerialPortEventListener import ru.mipt.npm.controls.ports.AbstractPort import ru.mipt.npm.controls.ports.Port import ru.mipt.npm.controls.ports.PortFactory import space.kscience.dataforge.context.Context import space.kscience.dataforge.meta.Meta import space.kscience.dataforge.meta.int import space.kscience.dataforge.meta.string import kotlin.coroutines.CoroutineContext import jssc.SerialPort as JSSCPort /** * COM/USB port */ public class SerialPort private constructor( context: Context, private val jssc: JSSCPort, coroutineContext: CoroutineContext = context.coroutineContext, ) : AbstractPort(context, coroutineContext) { override fun toString(): String = "port[${jssc.portName}]" private val serialPortListener = SerialPortEventListener { event -> if (event.isRXCHAR) { val chars = event.eventValue val bytes = jssc.readBytes(chars) receive(bytes) } } init { jssc.addEventListener(serialPortListener) } /** * Clear current input and output buffers */ internal fun clearPort() { jssc.purgePort(PURGE_RXCLEAR or PURGE_TXCLEAR) } override suspend fun write(data: ByteArray) { jssc.writeBytes(data) } @Throws(Exception::class) override fun close() { jssc.removeEventListener() clearPort() if (jssc.isOpened) { jssc.closePort() } super.close() } public companion object : PortFactory { /** * Construct ComPort with given parameters */ public fun open( context: Context, portName: String, baudRate: Int = BAUDRATE_9600, dataBits: Int = DATABITS_8, stopBits: Int = STOPBITS_1, parity: Int = PARITY_NONE, coroutineContext: CoroutineContext = context.coroutineContext, ): SerialPort { val jssc = JSSCPort(portName).apply { openPort() setParams(baudRate, dataBits, stopBits, parity) } return SerialPort(context, jssc, coroutineContext) } override fun invoke(meta: Meta, context: Context): Port { val name by meta.string { error("Serial port name not defined") } val baudRate by meta.int(BAUDRATE_9600) val dataBits by meta.int(DATABITS_8) val stopBits by meta.int(STOPBITS_1) val parity by meta.int(PARITY_NONE) return open(context, name, baudRate, dataBits, stopBits, parity) } } }
3
Kotlin
3
9
a20fb97c02f6394fe49436f97373991bed2f8f6f
2,667
controls.kt
Apache License 2.0
src/main/kotlin/Main.kt
NiksonJD
573,448,986
false
{"Kotlin": 2105}
fun main(args: Array<String>) { val playField = " ".split("").filter { it != "" }.toMutableList() val winner = mutableListOf<String>() val winCombos = listOf("XXX", "OOO") var evenOdd = 0 val rows = "012345678036147258048246".map { it.digitToInt() }.chunked(3) fun updateTheGrid() { println("---------") for (r in rows.subList(0, 3)) println("| ${playField[r[0]]} ${playField[r[1]]} ${playField[r[2]]} |") println("---------") } updateTheGrid() start@ while (true) { println( "Enter two numbers separated by a space. The first number is the row number, " + "the second number is the column number. Current move ${if (evenOdd % 2 == 0 || evenOdd == 0) "X" else "O"}" ) val (a, b) = readln().split(" ").map { try { it.toInt() } catch (e: NumberFormatException) { 0 } } if (a == 0 || b == 0) { println("You should enter numbers!") continue@start } else if (a !in 1..3 || b !in 1..3) { println("Coordinates should be from 1 to 3!") continue@start } else if (playField[rows[a - 1][b - 1]] == " ") { playField[rows[a - 1][b - 1]] = if (++evenOdd % 2 == 0) "O" else "X" updateTheGrid() rows.forEach { if (winCombos.indexOf(playField[it[0]] + playField[it[1]] + playField[it[2]]) != -1) winner.add( playField[it[0]] ) } } else { println("This cell is occupied! Choose another one!") continue@start } if (winner.size > 1 || Math.abs(playField.filter { it == "X" }.size - playField.filter { it == "O" }.size) > 1) { println("Impossible") break } else if (winner.size == 1) { println("${winner[0]} wins") break } else if (playField.indexOf(" ") == -1) { println("Draw") break } } }
0
Kotlin
0
0
0a4bb1130a79def05be4e0408e51a718eda3227d
2,105
Kotlin_Tic-Tac-Toe
Apache License 2.0
presentation/src/main/java/com/sample/player/presentation/home/VideosAdapter.kt
ShivaniSoni22
391,935,457
false
null
package com.sample.player.presentation.home import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.ViewCompat import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.google.android.exoplayer2.Player import com.sample.player.databinding.ItemVideoBinding import com.sample.player.domain.model.video.Video import com.sample.player.presentation.util.PlayerStateCallback import com.sample.player.presentation.util.PlayerViewAdapter.Companion.releaseRecycledPlayers class VideosAdapter(val listener: (Video) -> Unit) : ListAdapter<Video, VideosAdapter.VideoViewHolder>(TagDU()), PlayerStateCallback { // private var mItemClickListener: OnItemClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder { return VideoViewHolder( ItemVideoBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: VideoViewHolder, position: Int) { holder.bind(getItem(position)) } override fun onViewRecycled(holder: VideosAdapter.VideoViewHolder) { val position = holder.adapterPosition releaseRecycledPlayers(position) super.onViewRecycled(holder) } // // fun setOnItemClickListener(mItemClickListener: OnItemClickListener?) { // this.mItemClickListener = mItemClickListener // } // // interface OnItemClickListener { // fun onItemClick(view: View, position: Int, video: Video) // } inner class VideoViewHolder(private val mBinding: ItemVideoBinding) : RecyclerView.ViewHolder(mBinding.root) { fun bind(video: Video) { ViewCompat.setTransitionName(mBinding.player, "playerView") // mBinding.root.setOnClickListener { // mItemClickListener!!.onItemClick( // mBinding.player, // adapterPosition, // video // ) // listener.invoke(video) // } mBinding.apply { txtTitle.text = video.title dataModel = video callback = this@VideosAdapter index = adapterPosition executePendingBindings() } itemView.setOnClickListener { listener.invoke(video) } } } private class TagDU : DiffUtil.ItemCallback<Video>() { override fun areItemsTheSame(oldItem: Video, newItem: Video) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Video, newItem: Video) = oldItem == newItem } companion object { const val TAG = "TagAdapter" } override fun onVideoDurationRetrieved(duration: Long, player: Player) { } override fun onVideoBuffering(player: Player) { } override fun onStartedPlaying(player: Player) { } override fun onFinishedPlaying(player: Player) { } }
0
Kotlin
0
0
77de8ad5e79ef532f46bc15eda22ef333878fdd1
3,119
CleanVideoPlayerSample
MIT License
presentation/src/main/java/com/sample/player/presentation/home/VideosAdapter.kt
ShivaniSoni22
391,935,457
false
null
package com.sample.player.presentation.home import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.ViewCompat import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.google.android.exoplayer2.Player import com.sample.player.databinding.ItemVideoBinding import com.sample.player.domain.model.video.Video import com.sample.player.presentation.util.PlayerStateCallback import com.sample.player.presentation.util.PlayerViewAdapter.Companion.releaseRecycledPlayers class VideosAdapter(val listener: (Video) -> Unit) : ListAdapter<Video, VideosAdapter.VideoViewHolder>(TagDU()), PlayerStateCallback { // private var mItemClickListener: OnItemClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder { return VideoViewHolder( ItemVideoBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: VideoViewHolder, position: Int) { holder.bind(getItem(position)) } override fun onViewRecycled(holder: VideosAdapter.VideoViewHolder) { val position = holder.adapterPosition releaseRecycledPlayers(position) super.onViewRecycled(holder) } // // fun setOnItemClickListener(mItemClickListener: OnItemClickListener?) { // this.mItemClickListener = mItemClickListener // } // // interface OnItemClickListener { // fun onItemClick(view: View, position: Int, video: Video) // } inner class VideoViewHolder(private val mBinding: ItemVideoBinding) : RecyclerView.ViewHolder(mBinding.root) { fun bind(video: Video) { ViewCompat.setTransitionName(mBinding.player, "playerView") // mBinding.root.setOnClickListener { // mItemClickListener!!.onItemClick( // mBinding.player, // adapterPosition, // video // ) // listener.invoke(video) // } mBinding.apply { txtTitle.text = video.title dataModel = video callback = this@VideosAdapter index = adapterPosition executePendingBindings() } itemView.setOnClickListener { listener.invoke(video) } } } private class TagDU : DiffUtil.ItemCallback<Video>() { override fun areItemsTheSame(oldItem: Video, newItem: Video) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Video, newItem: Video) = oldItem == newItem } companion object { const val TAG = "TagAdapter" } override fun onVideoDurationRetrieved(duration: Long, player: Player) { } override fun onVideoBuffering(player: Player) { } override fun onStartedPlaying(player: Player) { } override fun onFinishedPlaying(player: Player) { } }
0
Kotlin
0
0
77de8ad5e79ef532f46bc15eda22ef333878fdd1
3,119
CleanVideoPlayerSample
MIT License
domain/src/main/kotlin/dev/yacsa/domain/model/security/SecurityStatusDomainModel.kt
andrew-malitchuk
589,720,124
false
null
package dev.yacsa.domain.model.security import dev.yacsa.domain.model.base.BaseDomainModel data class SecurityStatusDomainModel( val isRooted: Boolean?, val somePiracyStuff: Boolean?, val isIntegrityOk: Boolean?, ) : BaseDomainModel
0
Kotlin
0
0
e35620cf1c66b4f76f0ed30d9c6d499acd134403
247
yet-another-compose-showcase-app
MIT License
app/src/main/java/com/example/musicevents/data/repositories/EventsRepositories.kt
alessandro-ricci6
790,644,239
false
{"Kotlin": 55931}
package com.example.musicevents.data.repositories import android.content.ContentResolver import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import com.example.musicevents.data.database.Event import com.example.musicevents.data.database.EventsDAO import com.example.musicevents.data.database.UserSaveEvent import kotlinx.coroutines.flow.Flow class EventsRepositories( private val eventsDAO: EventsDAO, private val contentResolver: ContentResolver, private val dataStore: DataStore<Preferences> ) { val events: Flow<List<Event>> = eventsDAO.getAll() suspend fun upsert(event: Event) { eventsDAO.upsert(event) } suspend fun userSaveEvent(userId: Int, event: Event){ eventsDAO.userSaveEvent(UserSaveEvent(userId = userId, eventId = event.id)) } }
0
Kotlin
0
0
f476a51cbde16615286e057fc443e9e1d50f03c5
839
MusicEvents
MIT License
node-ui/src/jvmMain/kotlin/com/rodev/nodeui/components/graph/GraphEvent.kt
r0astPiGGy
665,522,977
false
null
package com.rodev.nodeui.components.graph import com.rodev.nodeui.model.Node import java.util.* interface GraphEvent data class NodeAddEvent( val node: Node ) : GraphEvent object NodeClearEvent : GraphEvent
0
Kotlin
0
3
11dfc41d60c3482fb100ed8d2a8e5f77569836b2
214
JustBlueprints
MIT License
Kotlin/src/test/kotlin/codingdojo/SampleTest.kt
HoucemNaffati
369,012,591
true
{"CMake": 5584, "C++": 1876, "C": 326, "C#": 309, "Java": 265, "Kotlin": 229, "Go": 223}
package codingdojo; import org.junit.Test import kotlin.test.assertEquals class SampleTest { @Test fun sample() { assertEquals("expected", "actual"); } }
0
null
0
0
e5bd25f7d2a06fb6aa8eb37c2f71762172504029
186
starter
MIT License
src/client/kotlin/com/github/mystery2099/VoxelShapeUtilsClient.kt
Mystery2099
705,835,956
false
{"Kotlin": 7167, "Java": 522}
package com.github.mystery2099 import net.fabricmc.api.ClientModInitializer object VoxelShapeUtilsClient : ClientModInitializer { override fun onInitializeClient() { // This entrypoint is suitable for setting up client-specific logic, such as rendering. } }
0
Kotlin
0
0
19a2322eec775cfa061ed6c4e373f885bd94c4b7
263
VoxelShapeUtils
Creative Commons Zero v1.0 Universal
dd-sdk-android-gradle-plugin/src/main/kotlin/com/datadog/gradle/plugin/internal/GitRepositoryDetector.kt
DataDog
332,637,697
false
null
package com.datadog.gradle.plugin.internal import com.datadog.gradle.plugin.DdAndroidGradlePlugin.Companion.LOGGER import com.datadog.gradle.plugin.RepositoryDetector import com.datadog.gradle.plugin.RepositoryInfo import com.datadog.gradle.plugin.internal.sanitizer.GitRemoteUrlSanitizer import com.datadog.gradle.plugin.internal.sanitizer.UrlSanitizer import java.io.File import org.gradle.process.ExecOperations import org.gradle.process.internal.ExecException // TODO RUMM-1095 handle git submodules // TODO RUMM-1096 handle git subtrees // TODO RUMM-1093 let customer override `origin` with custom remote name internal class GitRepositoryDetector( @Suppress("UnstableApiUsage") private val execOperations: ExecOperations, private val urlSanitizer: UrlSanitizer = GitRemoteUrlSanitizer() ) : RepositoryDetector { @Suppress("StringLiteralDuplication") override fun detectRepositories( sourceSetRoots: List<File>, extensionProvidedRemoteUrl: String ): List<RepositoryInfo> { try { execOperations.execShell("git", "rev-parse", "--is-inside-work-tree") } catch (e: ExecException) { LOGGER.error("Project is not a git repository", e) return emptyList() } val remoteUrl = sanitizeUrl(resolveRemoteUrl(extensionProvidedRemoteUrl)) val commitHash = execOperations.execShell("git", "rev-parse", "HEAD").trim() val trackedFiles = listTrackedFilesPath(sourceSetRoots) return listOf( RepositoryInfo( remoteUrl, commitHash, trackedFiles ) ) } // region Internal private fun sanitizeUrl(remoteUrl: String): String { return urlSanitizer.sanitize(remoteUrl) } private fun resolveRemoteUrl(extensionProvidedRemoteUrl: String) = if (extensionProvidedRemoteUrl.isNotEmpty()) { extensionProvidedRemoteUrl } else { execOperations.execShell("git", "remote", "get-url", "origin").trim() } private fun listTrackedFilesPath( sourceSetRoots: List<File> ): List<String> { val files = mutableListOf<String>() sourceSetRoots.forEach { sourceSetRoot -> if (sourceSetRoot.exists() && sourceSetRoot.isDirectory) { listFilePathsInFolder(sourceSetRoot, files) } } return files } private fun listFilePathsInFolder( sourceSetRoot: File, files: MutableList<String> ) { // output will be relative to the project root val sourceSetFiles = execOperations.execShell( "git", "ls-files", "--full-name", // RUMM-1795 ensures path are reported from the repo root sourceSetRoot.absolutePath ) .trim() .lines() // we could use --deduplicate, but it was added to git just recently .toSet() files.addAll(sourceSetFiles) } // endregion }
5
Kotlin
9
9
f25e1141850510abeabf63563047e49d3f7c501f
3,041
dd-sdk-android-gradle-plugin
Apache License 2.0
app/src/main/java/com/example/employeeapp/data/local/AppDatabase.kt
me-sreekanth
458,563,782
false
{"Kotlin": 23411}
package com.example.employeeapp.data.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.employeeapp.data.entities.Employee @Database(entities = [Employee::class], version = 12, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun employeeDao(): EmployeeDao companion object { @Volatile private var instance: AppDatabase? = null fun getDatabase(context: Context): AppDatabase = instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } private fun buildDatabase(appContext: Context) = Room.databaseBuilder(appContext, AppDatabase::class.java, "employees") .fallbackToDestructiveMigration() .build() } }
0
Kotlin
0
0
b9f92ce1df73234bcc52b385b7ccbf7bf9cf6351
858
EmployeeApp
Apache License 2.0
komapper-core/src/main/kotlin/org/komapper/core/LoggerFacade.kt
komapper
349,909,214
false
null
package org.komapper.core import kotlin.reflect.KClass /** * The facade of logger. */ interface LoggerFacade { /** * Logs the sql statement. * * @param statement the sql statement * @param format the format of the sql statement */ fun sql(statement: Statement, format: (Int, StatementPart.Value) -> CharSequence) /** * Logs the sql statement with arguments. * * @param statement the sql statement * @param format the format of the sql statement */ fun sqlWithArgs(statement: Statement, format: (Any?, KClass<*>, Boolean) -> CharSequence) /** * Logs the beginning of transaction. * * @param transaction the transaction */ fun begin(transaction: String) /** * Logs the commit of transaction. * * @param transaction the transaction */ fun commit(transaction: String) /** * Logs the commit failure of transaction. * * @param transaction the transaction * @param cause the cause of failure */ fun commitFailed(transaction: String, cause: Throwable) /** * Logs the rollback of transaction. * * @param transaction the transaction */ fun rollback(transaction: String) /** * Logs the rollback failure of transaction. * * @param transaction the transaction * @param cause the cause of failure */ fun rollbackFailed(transaction: String, cause: Throwable) /** * Logs the suspending of transaction. * * @param transaction the transaction */ fun suspend(transaction: String) /** * Logs the resuming of transaction. * * @param transaction the transaction */ fun resume(transaction: String) fun trace(message: () -> String) fun debug(message: () -> String) fun info(message: () -> String) fun warn(message: () -> String) fun error(message: () -> String) } /** * The default implementation of [LoggerFacade]. */ class DefaultLoggerFacade(private val logger: Logger) : LoggerFacade { override fun sql(statement: Statement, format: (Int, StatementPart.Value) -> CharSequence) { logger.debug(LogCategory.SQL) { statement.toSql(format) } } override fun sqlWithArgs(statement: Statement, format: (Any?, KClass<*>, Boolean) -> CharSequence) { logger.trace(LogCategory.SQL_WITH_ARGS) { statement.toSqlWithArgs(format) } } override fun begin(transaction: String) { logger.trace(LogCategory.TRANSACTION) { "Begin: $transaction" } } override fun commit(transaction: String) { logger.trace(LogCategory.TRANSACTION) { "Commit: $transaction" } } override fun commitFailed(transaction: String, cause: Throwable) { logger.trace(LogCategory.TRANSACTION) { "Commit failed: $transaction, $cause" } } override fun rollback(transaction: String) { logger.trace(LogCategory.TRANSACTION) { "Rollback: $transaction" } } override fun rollbackFailed(transaction: String, cause: Throwable) { logger.trace(LogCategory.TRANSACTION) { "Rollback failed: $transaction, $cause" } } override fun suspend(transaction: String) { logger.trace(LogCategory.TRANSACTION) { "Suspend: $transaction" } } override fun resume(transaction: String) { logger.trace(LogCategory.TRANSACTION) { "Resume: $transaction" } } override fun trace(message: () -> String) { logger.trace(LogCategory.OTHER, message) } override fun debug(message: () -> String) { logger.debug(LogCategory.OTHER, message) } override fun info(message: () -> String) { logger.info(LogCategory.OTHER, message) } override fun warn(message: () -> String) { logger.warn(LogCategory.OTHER, message) } override fun error(message: () -> String) { logger.error(LogCategory.OTHER, message) } }
7
Kotlin
4
97
851b313c66645d60f2e86934a5036efbe435396a
4,116
komapper
Apache License 2.0
kotlin-client/src/main/kotlin/io/provenance/bilateral/query/SearchContract.kt
provenance-io
506,765,156
false
null
package io.provenance.bilateral.query import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeName import com.fasterxml.jackson.annotation.JsonValue import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming import com.fasterxml.jackson.databind.annotation.JsonSerialize import io.provenance.bilateral.interfaces.BilateralContractQueryMsg import io.provenance.bilateral.models.enums.BilateralRequestType import io.provenance.bilateral.serialization.CosmWasmBigIntegerToUintSerializer import java.math.BigInteger /** * The core request structure for searching the contract, using [io.provenance.bilateral.client.BilateralContractClient.searchAsks], * [io.provenance.bilateral.client.BilateralContractClient.searchBids], or the "OrNull" variants of those functions. * The result produced is paginated. * * @param searchType Defines the search target for the request. * @param pageSize The size of page to use for the search. If not specified, the [DEFAULT_PAGE_SIZE] value is used. * @param pageNumber The page number to request. If not specified, the [DEFAULT_PAGE_NUMBER] value is used. */ @JsonNaming(SnakeCaseStrategy::class) data class ContractSearchRequest( val searchType: ContractSearchType, @JsonSerialize(using = CosmWasmBigIntegerToUintSerializer::class) val pageSize: BigInteger? = null, @JsonSerialize(using = CosmWasmBigIntegerToUintSerializer::class) val pageNumber: BigInteger? = null, ) { companion object { val DEFAULT_PAGE_SIZE: BigInteger = BigInteger.TEN val MAX_PAGE_SIZE: BigInteger = 25.toBigInteger() val MIN_PAGE_SIZE: BigInteger = BigInteger.ONE val DEFAULT_PAGE_NUMBER: BigInteger = BigInteger.ONE val MIN_PAGE_NUMBER: BigInteger = BigInteger.ONE } internal fun searchAsks(): SearchAsks = SearchAsks(this) internal fun searchBids(): SearchBids = SearchBids(this) @JsonIgnore internal fun getLoggingSuffix(): String = when (this.searchType) { is ContractSearchType.All -> "[all]" is ContractSearchType.Type -> "[type], type = [${this.searchType.valueType}]" is ContractSearchType.Id -> "[id], id = [${this.searchType.id}]" is ContractSearchType.Owner -> "[owner], owner = [${this.searchType.owner}]" }.let { searchTypeString -> "searchType = $searchTypeString, pageSize = [${pageSize ?: "DEFAULT"}], pageNumber = [${pageNumber ?: "DEFAULT"}]" } } /** * An internal model used to search for [io.provenance.bilateral.models.AskOrder] values. * * @param search The search parameters for the request. */ @JsonNaming(SnakeCaseStrategy::class) @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) @JsonTypeName("search_asks") data class SearchAsks(val search: ContractSearchRequest) : BilateralContractQueryMsg { override fun toLoggingString(): String = "searchAsks, ${search.getLoggingSuffix()}" } /** * An internal model used to search for [io.provenance.bilateral.models.BidOrder] values. * * @param search The search parameters for the request. */ @JsonNaming(SnakeCaseStrategy::class) @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) @JsonTypeName("search_bids") data class SearchBids(val search: ContractSearchRequest) : BilateralContractQueryMsg { override fun toLoggingString(): String = "searchBids, ${search.getLoggingSuffix()}" } /** * The search parameters for a search request. Each type indicates a different target value by which to locate ask or * bid orders. */ sealed interface ContractSearchType { /** * Simply retrieves all stored ask or bid orders without any specialized target values. */ @JsonNaming(SnakeCaseStrategy::class) object All : ContractSearchType { @JsonValue fun serializeAs(): String = "all" } /** * Retrieves all ask or bid orders that match a specific [BilateralRequestType]. */ @JsonNaming(SnakeCaseStrategy::class) class Type private constructor(val valueType: Body) : ContractSearchType { constructor(valueType: BilateralRequestType) : this(Body(valueType)) @JsonNaming(SnakeCaseStrategy::class) class Body(val valueType: BilateralRequestType) } /** * Retrieves all ask or bid orders that match a specific ask or bid id. Ask and bid ids are unique, so this should * only ever produce a single result. */ @JsonNaming(SnakeCaseStrategy::class) class Id private constructor(val id: Body) : ContractSearchType { constructor(id: String) : this(Body(id)) @JsonNaming(SnakeCaseStrategy::class) class Body(val id: String) } /** * Retrieves all ask or bid orders that match a specific bech32 address owner. */ @JsonNaming(SnakeCaseStrategy::class) class Owner private constructor(val owner: Body) : ContractSearchType { constructor(owner: String) : this(Body(owner)) @JsonNaming(SnakeCaseStrategy::class) class Body(val owner: String) } }
0
Rust
0
0
96043cb5f4cb5a4322609c927038395bc9655363
5,195
metadata-bilateral-exchange
Apache License 2.0
domain/src/main/java/kr/ohyung/domain/exception/NoParamsException.kt
androiddevnotesforks
310,938,493
false
{"Kotlin": 243295}
/* * Created by <NAME> on 2020/09/19. */ package kr.ohyung.domain.exception internal class NoParamsException(message: String = "params never be null for this use case.") : Exception(message)
0
Kotlin
2
1
c1567d938af59c3ca09c8dc15675358ba1abc63a
194
android-mvi-redux
MIT License
app/src/test/java/org/simple/clinic/registration/name/RegistrationNameScreenLogicTest.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.registration.name import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.clearInvocations import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions import com.nhaarman.mockitokotlin2.whenever import io.reactivex.rxkotlin.ofType import io.reactivex.subjects.PublishSubject import org.junit.After import org.junit.Rule import org.junit.Test import org.simple.clinic.user.OngoingRegistrationEntry import org.simple.clinic.user.UserSession import org.simple.clinic.util.RxErrorsRule import org.simple.clinic.util.scheduler.TrampolineSchedulersProvider import org.simple.clinic.util.toOptional import org.simple.clinic.widgets.UiEvent import org.simple.mobius.migration.MobiusTestFixture import java.util.UUID class RegistrationNameScreenLogicTest { @get:Rule val rxErrorsRule = RxErrorsRule() private val uiEvents = PublishSubject.create<UiEvent>() private val ui = mock<RegistrationNameUi>() private val uiActions = mock<RegistrationNameUiActions>() private val userSession = mock<UserSession>() private val currentOngoingRegistrationEntry = OngoingRegistrationEntry( uuid = UUID.fromString("301a9ea3-caed-4e50-a144-bc5aad66a53d"), phoneNumber = "1111111111" ) private lateinit var testFixture: MobiusTestFixture<RegistrationNameModel, RegistrationNameEvent, RegistrationNameEffect> @After fun tearDown() { testFixture.dispose() } @Test fun `when next is clicked with a valid name then the ongoing entry should be updated with the name and the next screen should be opened`() { // given val input = "Ashok Kumar" val entryWithName = currentOngoingRegistrationEntry.withName(input) whenever(userSession.ongoingRegistrationEntry()).thenReturn(currentOngoingRegistrationEntry.toOptional()) // when setupController() uiEvents.onNext(RegistrationFullNameTextChanged(input)) uiEvents.onNext(RegistrationFullNameDoneClicked()) // then verify(userSession).saveOngoingRegistrationEntry(entryWithName) verify(uiActions).openRegistrationPinEntryScreen(entryWithName) verify(uiActions).preFillUserDetails(currentOngoingRegistrationEntry) verify(ui, times(2)).hideValidationError() verifyNoMoreInteractions(ui) verifyNoMoreInteractions(uiActions) } @Test fun `when screen is created then user's existing details should be pre-filled`() { // given val ongoingEntry = currentOngoingRegistrationEntry.withName("Ashok Kumar") whenever(userSession.ongoingRegistrationEntry()).thenReturn(ongoingEntry.toOptional()) // when setupController(ongoingRegistrationEntry = ongoingEntry) // then verify(uiActions).preFillUserDetails(ongoingEntry) verify(ui).hideValidationError() verifyNoMoreInteractions(ui) verifyNoMoreInteractions(uiActions) } @Test fun `proceed button clicks should only be accepted if the input name is valid`() { // given val validName = "Ashok" val invalidName = " " whenever(userSession.ongoingRegistrationEntry()).thenReturn(currentOngoingRegistrationEntry.toOptional()) // when setupController() verify(uiActions).preFillUserDetails(currentOngoingRegistrationEntry) uiEvents.onNext(RegistrationFullNameTextChanged(invalidName)) uiEvents.onNext(RegistrationFullNameDoneClicked()) // then verify(ui).hideValidationError() verify(ui).showEmptyNameValidationError() clearInvocations(ui, uiActions) // when uiEvents.onNext(RegistrationFullNameTextChanged(validName)) uiEvents.onNext(RegistrationFullNameDoneClicked()) // then val entryWithName = currentOngoingRegistrationEntry.withName(validName) verify(userSession).saveOngoingRegistrationEntry(entryWithName) verify(uiActions).openRegistrationPinEntryScreen(entryWithName) verify(ui, times(2)).hideValidationError() verifyNoMoreInteractions(ui) verifyNoMoreInteractions(uiActions) } @Test fun `when proceed is clicked with an empty name then an error should be shown`() { // when setupController() uiEvents.onNext(RegistrationFullNameTextChanged("")) uiEvents.onNext(RegistrationFullNameDoneClicked()) // then verify(userSession, never()).saveOngoingRegistrationEntry(any()) verify(uiActions).preFillUserDetails(currentOngoingRegistrationEntry) verify(ui).hideValidationError() verify(ui).showEmptyNameValidationError() verify(uiActions, never()).openRegistrationPinEntryScreen(any()) verifyNoMoreInteractions(ui) verifyNoMoreInteractions(uiActions) } @Test fun `when input text is changed then any visible errors should be removed`() { // when setupController() uiEvents.onNext(RegistrationFullNameTextChanged("")) // then verify(uiActions).preFillUserDetails(currentOngoingRegistrationEntry) verify(ui).hideValidationError() verifyNoMoreInteractions(ui) verifyNoMoreInteractions(uiActions) } private fun setupController( ongoingRegistrationEntry: OngoingRegistrationEntry = currentOngoingRegistrationEntry ) { val uiRenderer = RegistrationNameUiRenderer(ui) val effectHandler = RegistrationNameEffectHandler( schedulers = TrampolineSchedulersProvider(), userSession = userSession, uiActions = uiActions ) testFixture = MobiusTestFixture( events = uiEvents.ofType(), defaultModel = RegistrationNameModel.create(ongoingRegistrationEntry), init = RegistrationNameInit(), update = RegistrationNameUpdate(), effectHandler = effectHandler.build(), modelUpdateListener = uiRenderer::render ) testFixture.start() } }
7
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
5,845
simple-android
MIT License
BroadcastTest/app/src/main/java/com/example/broadcasttest/AnotherBroadcastReceiver.kt
yylykym
810,110,480
false
{"Kotlin": 192044}
package com.example.broadcasttest import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast class AnotherBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // This method is called when the BroadcastReceiver is receiving an Intent broadcast. Toast.makeText(context, "received in AnotherBroadcastReceiver", Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
bee0238fd6f42f53120761d504f43622f4d35bd3
497
android-study
Apache License 2.0
src/main/kotlin/de/eternalwings/vima/plugin/VideoContainer.kt
kumpelblase2
269,905,877
false
{"Gradle Kotlin DSL": 2, "Markdown": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 4, "Kotlin": 105, "JavaScript": 33, "JSON": 2, "HTML": 1, "EditorConfig": 1, "Vue": 41, "SCSS": 1, "CSS": 1, "Java": 1, "SQL": 8, "YAML": 1, "desktop": 1}
package de.eternalwings.vima.plugin import de.eternalwings.vima.domain.MetadataValue import de.eternalwings.vima.domain.Video class VideoContainer( val id: Int, val name: String, val location: String, val metadata: Map<Int,MetadataValue<*>> ) { internal var changed: Set<Int> = emptySet() private set fun hasMetadata(id: Int) = metadata.containsKey(id) private fun markChanged(metadataId: Int) { changed = changed + metadataId } internal fun <T> updateMetadata(id: Int, value: T?) { val metadata = this.metadata[id] ?: throw IllegalStateException("No such metadata with id $id") val originalMetadataValue = metadata as MetadataValue<T> if(originalMetadataValue.value != value) { originalMetadataValue.value = value markChanged(id) } } internal fun <T> getMetadataValue(id: Int): T? { val metadata = this.metadata[id] ?: throw IllegalStateException("No such metadata with id $id") return (metadata as MetadataValue<T>).value } companion object { fun fromVideo(video: Video): VideoContainer { val metadata = video.metadata!!.map { entry -> entry.key to entry.value.clone() }.toMap() return VideoContainer(video.id!!, video.name!!, video.location!!, metadata) } } }
0
Kotlin
0
0
168a342f93648054624415b5114ffb28edd93672
1,398
vimax
MIT License
plugins/client/graphql-kotlin-client-generator/src/main/kotlin/com/expediagroup/graphql/plugin/client/generator/exceptions/SchemaUnavailableException.kt
ExpediaGroup
148,706,161
false
{"Kotlin": 2410561, "MDX": 720089, "HTML": 12165, "JavaScript": 10447, "CSS": 297, "Dockerfile": 147}
package com.expediagroup.graphql.plugin.client.generator.exceptions /** * Exception thrown when specified schema file path is not found or unavailable */ internal class SchemaUnavailableException(schemaPath: String) : RuntimeException("Specified schema file=$schemaPath does not exist")
68
Kotlin
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
290
graphql-kotlin
Apache License 2.0
sample/src/main/java/com/zackratos/ultimatebarx/sample/extension/Res.kt
Zackratos
276,911,088
false
null
package com.zackratos.ultimatebarx.sample.extension import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import com.zackratos.ultimatebarx.sample.App /** * @Author : zackratos * @Date : 2021/8/23 7:55 下午 * @email : [email protected] * @Describe : */ @ColorInt fun getResColor(@ColorRes colorRes: Int): Int = ContextCompat.getColor(App.context, colorRes)
27
Kotlin
161
1,515
849ca37cd5ed46e5c5bad5b03dbe62a4fa803849
437
UltimateBarX
Apache License 2.0
app/src/androidTest/java/com/lowe/movies/ui/movieDetails/MovieDetailsActivityTest.kt
DurgeshKumar1995
395,519,968
false
null
package com.lowe.movies.ui.movieDetails import android.content.Intent import androidx.lifecycle.lifecycleScope import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.matcher.ViewMatchers.withContentDescription import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.google.gson.GsonBuilder import com.lowe.movies.dataSource.Result import com.lowe.movies.databinding.ActivityMovieDetailsBinding import com.lowe.movies.utils.IntentKeyStrings import junit.framework.TestCase.assertNotNull import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class MovieDetailsActivityTest { lateinit var activityScenario: ActivityScenario<MovieDetailsActivity> lateinit var movieModel: Result private lateinit var binding: ActivityMovieDetailsBinding private val movieModelString = "{\n" + " \"display_title\": \"White as Snow\",\n" + " \"mpaa_rating\": \"\",\n" + " \"critics_pick\": 0,\n" + " \"byline\": \"<NAME>\",\n" + " \"headline\": \"‘White as Snow’ Review: The Fairest of Them All\",\n" + " \"summary_short\": \"The director <NAME> spins the Snow White fairy tale into a thriller, with <NAME> as the jealous stepmother.\",\n" + " \"publication_date\": \"2021-08-12\",\n" + " \"opening_date\": null,\n" + " \"date_updated\": \"2021-08-12 15:14:03\",\n" + " \"link\": {\n" + " \"type\": \"article\",\n" + " \"url\": \"https://www.nytimes.com/2021/08/12/movies/white-as-snow-review.html\",\n" + " \"suggested_link_text\": \"Read the New York Times Review of White as Snow\"\n" + " },\n" + " \"multimedia\": {\n" + " \"type\": \"mediumThreeByTwo210\",\n" + " \"src\": \"https://static01.nyt.com/images/2021/08/12/arts/12white-as-snow1/12white-as-snow1-mediumThreeByTwo440.jpg\",\n" + " \"height\": 140,\n" + " \"width\": 210\n" + " }\n" + " }" @Before fun setUp() { val gsonBuilder = GsonBuilder() val gson = gsonBuilder.create() movieModel = gson.fromJson(movieModelString, Result::class.java) val intent = Intent(ApplicationProvider.getApplicationContext(), MovieDetailsActivity::class.java) intent.putExtra( IntentKeyStrings.shareMovieDataKey, movieModel ) // obviously use a const for key activityScenario = ActivityScenario.launch(intent) } @After fun tearDown() { activityScenario.close() } @Test fun onCreate() { activityScenario.onActivity { binding = ActivityMovieDetailsBinding.inflate(it.layoutInflater) assertNotNull(binding) assertNotNull(it.intent) val isIntentHaveData = it.intent.hasExtra(IntentKeyStrings.shareMovieDataKey) assertEquals(true, isIntentHaveData) val modelFromIntent = it.intent.getParcelableExtra<Result>(IntentKeyStrings.shareMovieDataKey) assertNotNull(modelFromIntent) it.lifecycleScope.launch { delay(2000) assertEquals(movieModel.headline, binding.headLine.text.toString()) } } } @Test fun onSupportNavigateUp() { onView(withContentDescription("Navigate up")).perform(click()) } }
0
Kotlin
0
0
6bf0257a3e66b851277541b6649855fe3d56560e
3,995
durgesh_movies
Apache License 2.0
test-app/src/androidTest/java/com/achhatra/threepio/testing/testapp/SignInActivityTest_Kotlin.kt
abdullah-chhatra
118,237,458
false
{"Java": 64163, "Kotlin": 36983}
package com.achhatra.threepio.testing.testapp import androidx.test.rule.ActivityTestRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.achhatra.threepio.testing.caffelatte.interactors.IButton import com.achhatra.threepio.testing.caffelatte.interactors.ICheckBox import com.achhatra.threepio.testing.caffelatte.interactors.IEditText import com.threepio.testing.SigninActivity import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD import com.achhatra.threepio.testing.caffelatte.interactors.IButton.forButton import com.achhatra.threepio.testing.caffelatte.interactors.ICheckBox.forCheckBox import com.achhatra.threepio.testing.caffelatte.interactors.IEditText.forEditText @Suppress("ClassName") @RunWith(AndroidJUnit4::class) class SignInActivityTest_Kotlin { @get:Rule var rule = ActivityTestRule(SigninActivity::class.java) private val userName = forEditText() .withId(R.id.user_name) .build() private val password = forEditText() .withId(R.id.password) .build() private val showPassword = forCheckBox() .withId(R.id.show_password) .build() private val signInButton = forButton() .withId(R.id.sign_in) .withText("Sign In") .build() @Test fun testInitialScreen() { userName .isDisplayed .hasHint("User Email") .hasEmptyText() .hasInputType(TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_EMAIL_ADDRESS) password .isDisplayed .hasHint("Password") .hasEmptyText() .hasInputType(TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD) showPassword .isDisplayed .hasText("Show password") .isNotChecked signInButton .isDisplayed .isNotEnabled } @Test fun testPasswordToggle() { val passwordText = "lkj3474" password.typeText(passwordText) showPassword.check() password.hasInputType(TYPE_CLASS_TEXT) showPassword.uncheck() password.hasInputType(TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD) } @Test fun testEnableSignInOnValidUserDetails() { userName.typeText("[email protected]") password.typeText("E948fkfj") signInButton.isEnabled } }
1
Java
1
3
4fae6e8f78c4081756aa06d5ea41b5bdce1db48d
2,341
threepio-testing
MIT License
kotlin-typescript/src/jsMain/generated/typescript/JSDocOptionalType.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Automatically generated - do not modify! package typescript sealed external interface JSDocOptionalType : JSDocType, HasType, JSDocTypeReferencingNode { override val kind: SyntaxKind.JSDocOptionalType val type: TypeNode }
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
235
kotlin-wrappers
Apache License 2.0
JetpackMvvm/src/main/java/com/example/jetpackmvvm/callback/databinding/ShortObservableField.kt
wuxiaoqi123
357,750,178
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "XML": 58, "Kotlin": 134, "Java": 7}
package com.example.jetpackmvvm.callback.databinding import androidx.databinding.ObservableField class ShortObservableField(value: Short = 0) : ObservableField<Short>(value) { override fun get(): Short { return super.get()!! } }
1
null
1
1
42029a8f055f04fb2c7ea3605fc408e57bbb267c
247
jntm
Apache License 2.0
profile/impl/src/main/kotlin/com/morfly/sample/profile/impl/userprofile/di/UserProfileComponent.kt
Morfly
398,528,749
false
null
package com.morfly.sample.profile.impl.userprofile.di import com.morfly.sample.common.di.SubfeatureScoped import com.morfly.sample.profile.impl.di.ProfileComponent import com.morfly.sample.profile.impl.userprofile.UserProfileViewModel import dagger.BindsInstance import dagger.Component @SubfeatureScoped @Component( modules = [UserProfileModule::class], dependencies = [ProfileComponent::class] ) interface UserProfileComponent { val viewModel: UserProfileViewModel @Component.Factory interface Factory { fun create( parent: ProfileComponent, @BindsInstance @UserId userId: String? ): UserProfileComponent } }
2
Kotlin
5
43
93b22c1e198955705ef31aaeadb2b091a90fcdd5
681
compose-arch-sample
MIT License
app/src/main/java/com/pyamsoft/splattrak/alert/date/TimeWindowDialog.kt
pyamsoft
368,037,078
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.splattrak.alert.date import android.app.Dialog import android.app.TimePickerDialog import android.graphics.drawable.Drawable import android.os.Bundle import android.text.format.DateFormat import androidx.annotation.CheckResult import androidx.appcompat.app.AppCompatDialogFragment import androidx.appcompat.content.res.AppCompatResources import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.lifecycleScope import com.pyamsoft.pydroid.core.requireNotNull import com.pyamsoft.pydroid.theme.attributeFromCurrentTheme import com.pyamsoft.pydroid.ui.util.show import com.pyamsoft.splattrak.ObjectGraph import java.time.LocalTime import javax.inject.Inject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class TimeWindowDialog : AppCompatDialogFragment() { @JvmField @Inject internal var presenter: TimeChangePresenter? = null /** * * Because the dialog background is transparent, we need to manually pull out the window * background as a drawable and insert it here */ @CheckResult private fun createDialogBackground(): Drawable { val act = requireActivity() val backgroundId = act.attributeFromCurrentTheme(android.R.attr.windowBackground) return AppCompatResources.getDrawable(act, backgroundId).requireNotNull() } @CheckResult private fun getHour(): Int { return requireArguments().getInt(KEY_HOUR, VALUE_INVALID_TIME).also { require(it >= 0) { "Must create with key $KEY_HOUR" } } } @CheckResult private fun getMinute(): Int { return requireArguments().getInt(KEY_MINUTE, VALUE_INVALID_TIME).also { require(it >= 0) { "Must create with key $KEY_MINUTE" } } } @CheckResult private fun getType(): TimeType { return requireArguments() .getString(KEY_TYPE, "") .also { require(it.isNotBlank()) { "Must create with key $KEY_TYPE" } } .let { TimeType.valueOf(it) } } private fun publishTimeSelected(hour: Int, minute: Int) { // Don't use viewLifecycleOwner since it is NULL without onCreateView lifecycleScope.launch(context = Dispatchers.Main) { presenter .requireNotNull() .send( type = getType(), hour = hour, minute = minute, ) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ObjectGraph.ApplicationScope.retrieve(requireActivity()).plusTimeWindow().create().inject(this) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { var fixedBackground: Drawable? = createDialogBackground() val listener = TimePickerDialog.OnTimeSetListener { view, hour, minute -> if (fixedBackground != null) { // Apply the fixed background here view.background = fixedBackground // And then we are done, now we handle times like usual fixedBackground = null } else { publishTimeSelected(hour, minute) } } val activity = requireActivity() val is24Time = DateFormat.is24HourFormat(activity) return TimePickerDialog(activity, listener, getHour(), getMinute(), is24Time).apply { // Run the programmatic method to call onTimeSet which should call the OnTimeSetListener, // and thus, set the background. this.onClick(this, Dialog.BUTTON_POSITIVE) } } override fun onDestroy() { super.onDestroy() presenter = null } companion object { private val TAG = TimeWindowDialog::class.java.name private const val VALUE_INVALID_TIME = -1 private const val KEY_HOUR = "key_hour" private const val KEY_MINUTE = "key_minute" private const val KEY_TYPE = "key_type" @JvmStatic @CheckResult private fun newInstance( hour: Int, minute: Int, type: TimeType, ): DialogFragment { return TimeWindowDialog().apply { arguments = Bundle().apply { putInt(KEY_HOUR, hour) putInt(KEY_MINUTE, minute) putString(KEY_TYPE, type.name) } } } @JvmStatic fun show(activity: FragmentActivity, type: TimeType, time: LocalTime?) { val source: LocalTime = time ?: LocalTime.now() newInstance(source.hour, source.minute, type).show(activity, TAG) } } }
1
Kotlin
0
3
b5d9ec2d1fe1341e7f609cf28d0ad4af95b91e07
5,016
splattrak
Apache License 2.0
LottoPop/app/src/main/java/com/prangbi/android/lottopop/controller/MainActivity.kt
hyuni
147,824,157
false
null
package com.prangbi.android.lottopop.controller import android.app.Activity import android.content.Intent import android.graphics.Color import android.graphics.ColorFilter import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import com.google.zxing.integration.android.IntentIntegrator import com.prangbi.android.lottopop.R import com.prangbi.android.lottopop.base.Definition import com.prangbi.android.lottopop.helper.Util import kotlinx.android.synthetic.main.main_activity.* /** * Created by Prangbi on 2017. 7. 12.. */ class MainActivity: AppCompatActivity() { /** * Variable */ private lateinit var mContext: Activity private val nLottoWinResultFragment = NLottoWinResultFragment() private val pLottoWinResultFragment = PLottoWinResultFragment() /** * Lifecycle */ override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme) super.onCreate(savedInstanceState) mContext = this setContentView(R.layout.main_activity) termsTextView.setOnClickListener(View.OnClickListener { Util.moveToWebActivity(mContext, "개인정보취급방침", Definition.TERMS_URL) }) bottomNLottoButtonLayout.setOnClickListener(View.OnClickListener { replaceToNLottoWinResultFragment() }) bottomPLottoButtonLayout.setOnClickListener(View.OnClickListener { replaceToPLottoWinResultFragment() }) bottomNLottoButtonLayout.performClick() } /** * Event */ override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_actionbar_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.qrCode -> { scanQrCode() return true } } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (null != result) { if (null != result.contents) { val intent = Intent(mContext, WebActivity::class.java) intent.putExtra("title", "당첨결과") intent.putExtra("url", result.contents) startActivity(intent) } else { Toast.makeText(mContext, "바코드를 읽지 못했습니다.", Toast.LENGTH_LONG).show() } } else { super.onActivityResult(requestCode, resultCode, data) } } /** * Function */ private fun replaceToNLottoWinResultFragment() { if(false == nLottoWinResultFragment.isVisible) { bottomNLottoImageView.setColorFilter(Color.parseColor("#FFFFFF")) bottomPLottoImageView.setColorFilter(Color.parseColor("#808080")) bottomNLottoTextView.setTextColor(Color.parseColor("#FFFFFF")) bottomPLottoTextView.setTextColor(Color.parseColor("#808080")) val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.fragmentLayout, nLottoWinResultFragment) transaction.commit() } } private fun replaceToPLottoWinResultFragment() { if(false == pLottoWinResultFragment.isVisible) { bottomNLottoImageView.setColorFilter(Color.parseColor("#808080")) bottomPLottoImageView.setColorFilter(Color.parseColor("#FFFFFF")) bottomNLottoTextView.setTextColor(Color.parseColor("#808080")) bottomPLottoTextView.setTextColor(Color.parseColor("#FFFFFF")) val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.fragmentLayout, pLottoWinResultFragment) transaction.commit() } } private fun scanQrCode() { IntentIntegrator(mContext).initiateScan() } }
0
Kotlin
0
0
9b29d4c094c0b7b5e07eb491dc0e15b7a9e5a694
4,139
LottoPop-Android
MIT License
app/src/main/java/com/akih/matarak/main/MainActivity.kt
Bangkit-MATAMU
368,188,139
false
null
package com.akih.matarak.main import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.akih.matarak.R import com.akih.matarak.databinding.ActivityMainBinding import com.akih.matarak.history.HistoryFragment import com.akih.matarak.home.HomeFragment import com.akih.matarak.hospital.HospitalFragment import com.akih.matarak.profile.ProfileFragment import com.akih.matarak.result.ResultActivity import com.canhub.cropper.CropImage import com.fxn.pix.Options import com.fxn.pix.Pix import com.github.florent37.runtimepermission.kotlin.askPermission import java.io.File class MainActivity : AppCompatActivity(), SetFragmentChange { companion object { private const val CAMERA_REQUEST_CODE = 2 } private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val homeFragment = HomeFragment() val hospitalFragment = HospitalFragment() val historyFragment = HistoryFragment() val profileFragment = ProfileFragment() askPermissions() setCurrentFragment(homeFragment) binding.bottomNavigationView.setOnNavigationItemSelectedListener { when (it.itemId) { R.id.miHome -> setCurrentFragment(homeFragment) R.id.miHospital -> setCurrentFragment(hospitalFragment) R.id.miHistory -> setCurrentFragment(historyFragment) R.id.miProfile -> setCurrentFragment(profileFragment) } true } binding.fab.setOnClickListener { Pix.start(this@MainActivity, Options.init() .setRequestCode(CAMERA_REQUEST_CODE) .setMode(Options.Mode.Picture)) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { if (requestCode == CAMERA_REQUEST_CODE) { val returnValue: ArrayList<String> = data?.getStringArrayListExtra(Pix.IMAGE_RESULTS) as ArrayList<String> CropImage.activity(Uri.fromFile(File(returnValue[0]))) .start(this) } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { val result = CropImage.getActivityResult(data) if (result != null) { // val file = File(result.getUriFilePath(this@MainActivity)!!) // val bitmap = BitmapFactory.decodeFile(file.absolutePath) goToResultActivity(result) } } }else if(resultCode == Activity.RESULT_OK && requestCode == 666){ Toast.makeText(applicationContext, "pindah", Toast.LENGTH_SHORT).show() } } private fun goToResultActivity(imageResult: CropImage.ActivityResult) { val intent = Intent(this, ResultActivity::class.java) intent.putExtra(ResultActivity.IMAGE_DATA, imageResult) startActivity(intent) } private fun setCurrentFragment(fragment: Fragment) = supportFragmentManager.beginTransaction().apply { replace(R.id.flFragment, fragment) commit() } private fun askPermissions(){ askPermission( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.CAMERA ){ }.onDeclined{ e -> if (e.hasDenied()){ e.denied.forEach{ } AlertDialog.Builder(this) .setMessage("Please Accept Our Permission") .setPositiveButton("Yes"){ _, _ -> e.askAgain() } .setNegativeButton("No"){ dialog, _ -> dialog.dismiss() } .show() } if (e.hasForeverDenied()){ e.foreverDenied.forEach { } e.goToSettings() } } } override fun changeFragmentTo(fragment: Fragment) { setCurrentFragment(fragment) } }
0
Kotlin
1
1
7e62b5037fe58e5c37b9a0d684144067d88fb265
4,607
Android-MATAMU
MIT License
compiler/testData/codegen/regressions/kt2655.kt
strategist922
8,551,947
false
{"Markdown": 16, "XML": 309, "Ant Build System": 7, "Ignore List": 4, "Maven POM": 24, "Kotlin": 4231, "Java": 2598, "CSS": 10, "JavaScript": 47, "HTML": 22, "Text": 1010, "Java Properties": 4, "INI": 1, "JFlex": 2, "Makefile": 1, "JAR Manifest": 1, "Batchfile": 2, "Shell": 2}
trait TextField { fun getText(): String fun setText(text: String) } class SimpleTextField : TextField { private var text = "" override fun getText() = text override fun setText(text: String) { this.text = text } } class TextFieldWrapper(textField: TextField) : TextField by textField fun box() : String { val textField = TextFieldWrapper(SimpleTextField()) textField.setText("OK") return textField.getText() }
1
null
1
1
5db0f2132c1f3613237ad05299d3f6118759fd03
457
kotlin
Apache License 2.0
app/src/test/java/tin/thurein/simple_recycler_view/UserListViewModelTest.kt
ThuReinTin
204,111,058
false
null
package tin.thurein.simple_recycler_view import androidx.arch.core.executor.testing.InstantTaskExecutorRule import org.hamcrest.CoreMatchers.equalTo import org.junit.Assert.assertNotNull import org.junit.Assert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import tin.thurein.simple_recycler_view.viewModels.UserListViewModel class UserListViewModelTest { @get:Rule var instantExecutorRule = InstantTaskExecutorRule() private lateinit var userListViewModel: UserListViewModel @Before @Throws(Exception::class) fun setUp() { userListViewModel = UserListViewModel() } @Test @Throws(Exception::class) fun testUserListViewModel() { assertNotNull(userListViewModel.mAdapter) assertNotNull(userListViewModel.userList) userListViewModel.syncUserList() assertThat(10, equalTo(userListViewModel.userList.size)) } }
0
Kotlin
0
0
dcf69dab4fd7bb492fac889216a8f5c72d3e4ba6
930
simple-recycler-view
MIT License
src/main/kotlin/org/hukehrs/kjsonrpc/client/OutgoingMethodCall.kt
HukehrsEngineering
156,509,288
false
null
package org.hukehrs.kjsonrpc.client import org.hukehrs.kjsonrpc.jsonrpc.JsonRpcObject import java.util.* data class OutgoingMethodCall(val id: Int, val method: String, val params: Array<Any>): JsonRpcObject() { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as OutgoingMethodCall if (id != other.id) return false if (method != other.method) return false if (!Arrays.equals(params, other.params)) return false return true } override fun hashCode(): Int { var result = id result = 31 * result + method.hashCode() result = 31 * result + Arrays.hashCode(params) return result } }
0
Kotlin
0
0
17a4d7d8961485317bbd1109193c19fb84f5f1bd
768
kjsonrpc
MIT License