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
conductor/src/test/java/com/bluelinelabs/conductor/util/ActivityProxy.kt
bluelinelabs
54,057,611
false
null
package com.bluelinelabs.conductor.util import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT import android.os.Bundle import androidx.annotation.IdRes import com.bluelinelabs.conductor.R import org.robolectric.Robolectric class ActivityProxy { @IdRes private val containerId = 4 private val activityController = Robolectric.buildActivity(TestActivity::class.java).apply { get().setTheme(R.style.Theme_AppCompat) } val activity: TestActivity get() = activityController.get() var view: AttachFakingFrameLayout = AttachFakingFrameLayout(activityController.get()) .also { it.id = containerId } set(value) { value.id = containerId field = value } fun create(savedInstanceState: Bundle?): ActivityProxy { activityController.create(savedInstanceState) return this } fun start(): ActivityProxy { activityController.start() view.setAttached(true) return this } fun resume(): ActivityProxy { activityController.resume() return this } fun pause(): ActivityProxy { activityController.pause() return this } fun saveInstanceState(outState: Bundle?): ActivityProxy { activityController.saveInstanceState(outState) return this } fun stop(detachView: Boolean): ActivityProxy { activityController.stop() if (detachView) { view.setAttached(false) } return this } fun destroy(): ActivityProxy { activityController.destroy() view.setAttached(false) return this } fun rotate(): ActivityProxy { val requestedPortrait = activity.requestedOrientation == SCREEN_ORIENTATION_PORTRAIT activity.requestedOrientation = if (requestedPortrait) { SCREEN_ORIENTATION_LANDSCAPE } else { SCREEN_ORIENTATION_PORTRAIT } return this } }
113
null
343
3,897
56bff9a5cf93818c53fb38874834fbfcbe3e4eb9
1,879
Conductor
Apache License 2.0
compiler/testData/diagnostics/tests/controlFlowAnalysis/fieldInitialization.kt
JetBrains
3,432,266
false
null
// !LANGUAGE: +AllowContractsForCustomFunctions +UseCallsInPlaceEffect // !USE_EXPERIMENTAL: kotlin.internal.ContractsDsl import kotlin.contracts.* @kotlin.contracts.ExperimentalContracts inline fun inlineMe(block: () -> Unit) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block() } @kotlin.contracts.ExperimentalContracts inline fun crossinlineMe(crossinline block: () -> Unit) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block() } @Suppress("NOTHING_TO_INLINE") @kotlin.contracts.ExperimentalContracts inline fun noinlineMe(noinline block: () -> Unit) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block() } @kotlin.contracts.ExperimentalContracts fun notinline(block: () -> Unit) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block() } @kotlin.contracts.ExperimentalContracts class Test { val a: String val b: String val c: String val d: String init { inlineMe { a = "allowed" } crossinlineMe { <!CAPTURED_VAL_INITIALIZATION!>b<!> = "not allowed" } noinlineMe { <!CAPTURED_VAL_INITIALIZATION!>c<!> = "not allowed" } notinline { <!CAPTURED_VAL_INITIALIZATION!>d<!> = "not allowed" } } } @kotlin.contracts.ExperimentalContracts class Test1 { val a: String = "" val b: String = "" val c: String = "" val d: String = "" init { inlineMe { <!VAL_REASSIGNMENT!>a<!> += "allowed" } crossinlineMe { <!CAPTURED_VAL_INITIALIZATION, VAL_REASSIGNMENT!>b<!> += "not allowed" } noinlineMe { <!CAPTURED_VAL_INITIALIZATION, VAL_REASSIGNMENT!>c<!> += "not allowed" } notinline { <!CAPTURED_VAL_INITIALIZATION, VAL_REASSIGNMENT!>d<!> += "not allowed" } } } @kotlin.contracts.ExperimentalContracts class Test2 { val a: String = "" val b: String = "" val c: String = "" val d: String = "" init { var blackhole = "" inlineMe { blackhole += a } crossinlineMe { blackhole += b } noinlineMe { blackhole += c } notinline { blackhole += d } } } @kotlin.contracts.ExperimentalContracts class Test4 { val a: String = "" val b: String = "" val c: String = "" val d: String = "" init { var <!ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE!>blackhole<!>: String inlineMe { blackhole = a } crossinlineMe { blackhole = b } noinlineMe { blackhole = c } notinline { blackhole = d } } }
166
null
5771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,870
kotlin
Apache License 2.0
app/src/main/java/com/arturostrowski/quiz/app/ui/main/interactor/MainInteractor.kt
Mesti193
215,134,193
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 151, "XML": 93, "Java": 1, "JSON": 2}
package com.arturostrowski.quiz.app.ui.main.interactor import com.arturostrowski.quiz.app.data.database.repository.user.User import com.arturostrowski.quiz.app.data.database.repository.user.UserRepo import com.arturostrowski.quiz.app.data.network.ApiHelper import com.arturostrowski.quiz.app.data.preferences.PreferenceHelper import com.arturostrowski.quiz.app.ui.base.interactor.BaseInteractor import io.reactivex.Observable import javax.inject.Inject class MainInteractor @Inject internal constructor(private val userRepo: UserRepo, preferenceHelper: PreferenceHelper, apiHelper: ApiHelper) : BaseInteractor(preferenceHelper = preferenceHelper, apiHelper = apiHelper), MainMVPInteractor { override fun getUserDetails() = Pair(preferenceHelper.getCurrentUserName(), preferenceHelper.getCurrentUserEmail()) override fun loadUser(): Observable<List<User>> = userRepo.loadUser() override fun logout() = userRepo.logout() }
0
Kotlin
0
0
1c0cef0108b0b90a4074f18b4690e5533214b41c
953
QuizApp
Apache License 2.0
app/src/main/java/com/kylecorry/trail_sense/tools/weather/infrastructure/subsystem/WeatherSubsystem.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.weather.infrastructure.subsystem import android.annotation.SuppressLint import android.content.Context import com.kylecorry.andromeda.core.cache.MemoryCachedValue import com.kylecorry.andromeda.core.topics.ITopic import com.kylecorry.andromeda.core.topics.Topic import com.kylecorry.andromeda.core.topics.generic.distinct import com.kylecorry.andromeda.preferences.Preferences import com.kylecorry.andromeda.sense.Sensors import com.kylecorry.sol.math.Range import com.kylecorry.sol.science.meteorology.* import com.kylecorry.sol.science.meteorology.clouds.CloudGenus import com.kylecorry.sol.units.Coordinate import com.kylecorry.sol.units.Distance import com.kylecorry.sol.units.Reading import com.kylecorry.sol.units.Temperature import com.kylecorry.trail_sense.R import com.kylecorry.trail_sense.shared.FeatureState import com.kylecorry.trail_sense.shared.UserPreferences import com.kylecorry.trail_sense.shared.data.DataUtils import com.kylecorry.trail_sense.shared.debugging.DebugWeatherCommand import com.kylecorry.trail_sense.shared.extensions.getOrNull import com.kylecorry.trail_sense.shared.extensions.onDefault import com.kylecorry.trail_sense.shared.extensions.onIO import com.kylecorry.trail_sense.shared.sensors.LocationSubsystem import com.kylecorry.trail_sense.weather.domain.* import com.kylecorry.trail_sense.weather.domain.forecasting.IWeatherForecaster import com.kylecorry.trail_sense.weather.domain.forecasting.WeatherForecaster import com.kylecorry.trail_sense.weather.domain.forecasting.temperatures.CalibratedTemperatureService import com.kylecorry.trail_sense.weather.domain.forecasting.temperatures.HistoricTemperatureService import com.kylecorry.trail_sense.weather.domain.forecasting.temperatures.ITemperatureService import com.kylecorry.trail_sense.weather.domain.sealevel.SeaLevelCalibrationFactory import com.kylecorry.trail_sense.weather.infrastructure.* import com.kylecorry.trail_sense.weather.infrastructure.commands.MonitorWeatherCommand import com.kylecorry.trail_sense.weather.infrastructure.commands.SendWeatherAlertsCommand import com.kylecorry.trail_sense.weather.infrastructure.persistence.CloudRepo import com.kylecorry.trail_sense.weather.infrastructure.persistence.WeatherRepo import com.kylecorry.trail_sense.weather.infrastructure.temperatures.HistoricTemperatureRepo import kotlinx.coroutines.delay import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.time.Duration import java.time.Instant import java.time.LocalDate import java.time.ZonedDateTime import java.util.* class WeatherSubsystem private constructor(private val context: Context) : IWeatherSubsystem { private val weatherRepo by lazy { WeatherRepo.getInstance(context) } private val temperatureRepo by lazy { HistoricTemperatureRepo(context) } private val cloudRepo by lazy { CloudRepo.getInstance(context) } private val prefs by lazy { UserPreferences(context) } private val sharedPrefs by lazy { Preferences(context) } private val location by lazy { LocationSubsystem.getInstance(context) } private var cachedValue = MemoryCachedValue<CurrentWeather>() private var validLock = Object() private var isValid = false private var updateWeatherMutex = Mutex() private val _weatherChanged = Topic() override val weatherChanged: ITopic = _weatherChanged private val _weatherMonitorState = com.kylecorry.andromeda.core.topics.generic.Topic( defaultValue = Optional.of( calculateWeatherMonitorState() ) ) override val weatherMonitorState: com.kylecorry.andromeda.core.topics.generic.ITopic<FeatureState> get() = _weatherMonitorState.distinct() private val _weatherMonitorFrequency = com.kylecorry.andromeda.core.topics.generic.Topic( defaultValue = Optional.of( calculateWeatherMonitorFrequency() ) ) override val weatherMonitorFrequency: com.kylecorry.andromeda.core.topics.generic.ITopic<Duration> get() = _weatherMonitorFrequency.distinct() override fun getWeatherMonitorState(): FeatureState { return weatherMonitorState.getOrNull() ?: FeatureState.Off } override fun getWeatherMonitorFrequency(): Duration { return weatherMonitorFrequency.getOrNull() ?: Duration.ofMinutes(15) } private val invalidationPrefKeys = listOf( R.string.pref_use_sea_level_pressure, R.string.pref_barometer_pressure_smoothing, R.string.pref_adjust_for_temperature, R.string.pref_forecast_sensitivity, R.string.pref_storm_alert_sensitivity, R.string.pref_altimeter_calibration_mode, R.string.pref_pressure_history, R.string.pref_temperature_smoothing ).map { context.getString(it) } private val weatherMonitorStatePrefKeys = listOf( R.string.pref_monitor_weather, R.string.pref_low_power_mode_weather, R.string.pref_low_power_mode ).map { context.getString(it) } private val weatherMonitorFrequencyPrefKeys = listOf( R.string.pref_weather_update_frequency ).map { context.getString(it) } init { // Keep them up to date weatherMonitorFrequency.subscribe { true } weatherMonitorState.subscribe { true } sharedPrefs.onChange.subscribe { key -> if (key in invalidationPrefKeys) { invalidate() } if (key in weatherMonitorStatePrefKeys) { val state = calculateWeatherMonitorState() _weatherMonitorState.publish(state) } if (key in weatherMonitorFrequencyPrefKeys) { val frequency = calculateWeatherMonitorFrequency() _weatherMonitorFrequency.publish(frequency) } true } weatherRepo.readingsChanged.subscribe { invalidate() true } cloudRepo.readingsChanged.subscribe { invalidate() true } } override suspend fun getWeather(): CurrentWeather = onIO { if (!isValid) { refresh() } cachedValue.getOrPut { populateCache() } } override suspend fun getHistory(): List<WeatherObservation> = onIO { val readings = getRawHistory() val precalibrated = calibrateHumidity(calibrateTemperatures(readings)) val calibrator = SeaLevelCalibrationFactory().create(prefs) val pressures = calibrator.calibrate(precalibrated) val combined = pressures.map { val reading = precalibrated.firstOrNull { r -> r.time == it.time } WeatherObservation( reading?.value?.id ?: 0L, it.time, it.value, Temperature.celsius(reading?.value?.temperature ?: 0f), reading?.value?.humidity ) } onIO { DebugWeatherCommand( context, readings, combined, prefs.weather.seaLevelFactorInTemp ).execute() } combined } override suspend fun getTemperature( time: ZonedDateTime, location: Coordinate?, elevation: Distance?, calibrated: Boolean ): Reading<Temperature> = onDefault { val service = getTemperatureService(location, elevation, calibrated) Reading(service.getTemperature(time), time.toInstant()) } override suspend fun getTemperatures( start: ZonedDateTime, end: ZonedDateTime, location: Coordinate?, elevation: Distance?, calibrated: Boolean ): List<Reading<Temperature>> = onDefault { val service = getTemperatureService(location, elevation, calibrated) service.getTemperatures(start, end) } override suspend fun getTemperatureRange( date: LocalDate, location: Coordinate?, elevation: Distance?, calibrated: Boolean ): Range<Temperature> = onDefault { val service = getTemperatureService(location, elevation, calibrated) service.getTemperatureRange(date) } override suspend fun getTemperatureRanges( year: Int, location: Coordinate?, elevation: Distance?, calibrated: Boolean ): List<Pair<LocalDate, Range<Temperature>>> = onDefault { val service = getTemperatureService(location, elevation, calibrated) service.getTemperatureRanges(year) } private suspend fun resolveLocation( location: Coordinate?, elevation: Distance? ): Pair<Coordinate, Distance> { val lookupLocation: Coordinate val lookupElevation: Distance if (location == null || elevation == null) { val last = weatherRepo.getLast() lookupLocation = last?.value?.location ?: this@WeatherSubsystem.location.location lookupElevation = last?.value?.altitude?.let { Distance.meters(it) } ?: this@WeatherSubsystem.location.elevation } else { lookupLocation = location lookupElevation = elevation } return lookupLocation to lookupElevation } override suspend fun getRawHistory(): List<Reading<RawWeatherObservation>> = onIO { if (!isValid) { refresh() } weatherRepo.getAll() .asSequence() .sortedBy { it.time } .filter { it.time <= Instant.now() } .map { if (it.value.location == Coordinate.zero) it.copy(value = it.value.copy(location = location.location)) else it } .toList() } override fun enableMonitor() { prefs.weather.shouldMonitorWeather = true WeatherUpdateScheduler.start(context) } override fun disableMonitor() { prefs.weather.shouldMonitorWeather = false WeatherUpdateScheduler.stop(context) } override suspend fun updateWeather(background: Boolean) { updateWeatherMutex.withLock { val last = weatherRepo.getLast()?.time val maxPeriod = getWeatherMonitorFrequency().dividedBy(3) if (last != null && Duration.between(last, Instant.now()).abs() < maxPeriod) { // Still send out the weather alerts, just don't log a new reading SendWeatherAlertsCommand(context).execute(getWeather()) return } MonitorWeatherCommand.create(context, background).execute() } } private suspend fun getTemperatureService( location: Coordinate?, elevation: Distance?, calibrated: Boolean ): ITemperatureService { val resolved = resolveLocation(location, elevation) val lookupLocation = resolved.first val lookupElevation = resolved.second val service = HistoricTemperatureService(temperatureRepo, lookupLocation, lookupElevation) if (calibrated) { return CalibratedTemperatureService(service, prefs.thermometer.calibrator) } return service } private suspend fun getWeatherForecaster( location: Coordinate?, elevation: Distance? ): IWeatherForecaster { val resolved = resolveLocation(location, elevation) val lookupLocation = resolved.first val lookupElevation = resolved.second val temperatureService = getTemperatureService(lookupLocation, lookupElevation, true) return WeatherForecaster(temperatureService, prefs.weather) } private fun invalidate() { synchronized(validLock) { isValid = false } _weatherChanged.publish() } private suspend fun refresh() { cachedValue.reset() delay(50) synchronized(validLock) { isValid = true } } override suspend fun getCloudHistory(): List<Reading<CloudGenus?>> = onIO { cloudRepo.getAll().sortedBy { it.time }.map { Reading(it.value.genus, it.time) } } private suspend fun populateCache(): CurrentWeather { val history = getHistory() val allClouds = getCloudHistory() val last = history.lastOrNull() val (location, elevation) = getLocationAndElevation(last?.id) val forecaster = getWeatherForecaster(location, elevation) return forecaster.forecast(history, allClouds) } private suspend fun getLocationAndElevation(lastReadingId: Long? = null): Pair<Coordinate, Distance> { val lastRawReading = lastReadingId?.let { weatherRepo.get(it) } val location = lastRawReading?.value?.location ?: location.location val elevation = lastRawReading?.value?.altitude?.let { Distance.meters(it) } ?: this.location.elevation return location to elevation } private fun calculateWeatherMonitorFrequency(): Duration { return prefs.weather.weatherUpdateFrequency } private fun calculateWeatherMonitorState(): FeatureState { return if (WeatherMonitorIsEnabled().isSatisfiedBy(context)) { FeatureState.On } else if (WeatherMonitorIsAvailable().not().isSatisfiedBy(context)) { FeatureState.Unavailable } else { FeatureState.Off } } // TODO: Extract this private fun calibrateTemperatures(readings: List<Reading<RawWeatherObservation>>): List<Reading<RawWeatherObservation>> { val smoothing = prefs.thermometer.smoothing return DataUtils.smoothTemporal( readings, smoothing, { it.temperature } ) { reading, smoothed -> reading.copy(temperature = smoothed) } } // TODO: Extract this private fun calibrateHumidity(readings: List<Reading<RawWeatherObservation>>): List<Reading<RawWeatherObservation>> { if (!Sensors.hasHygrometer(context)) { return readings } return DataUtils.smoothTemporal( readings, 0.1f, { it.humidity ?: 0f }) { reading, smoothed -> reading.copy(humidity = if (smoothed == 0f) null else smoothed) } } companion object { @SuppressLint("StaticFieldLeak") private var instance: WeatherSubsystem? = null @Synchronized fun getInstance(context: Context): WeatherSubsystem { if (instance == null) { instance = WeatherSubsystem(context.applicationContext) } return instance!! } const val COLD = 5f const val HOT = 32.5f } }
469
null
66
989
41176d17b498b2dcecbbe808fbe2ac638e90d104
14,740
Trail-Sense
MIT License
postgresql-async/src/main/java/com/github/mauricio/async/db/postgresql/encoders/PreparedStatementEncoderHelper.kt
dougEfresh
146,269,167
false
{"Markdown": 6, "Gradle": 4, "Shell": 2, "Procfile": 1, "Ignore List": 1, "Text": 1, "YAML": 1, "INI": 1, "Kotlin": 317, "Scala": 1, "XML": 3, "Java": 4}
/* * Copyright 2013 <NAME> * * <NAME> licenses this file to you 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.github.mauricio.async.db.postgresql.encoders import com.github.mauricio.async.db.postgresql.messages.backend.ServerMessage import com.github.mauricio.async.db.util.{Log, ByteBufferUtils} import com.github.mauricio.async.db.column.ColumnEncoderRegistry import java.nio.charset.Charset import io.netty.buffer.{Unpooled, ByteBuf} import scala.collection.mutable.ArrayBuffer object PreparedStatementEncoderHelper { final val log = Log.get[PreparedStatementEncoderHelper] } trait PreparedStatementEncoderHelper { import PreparedStatementEncoderHelper.log def writeExecutePortal( statementIdBytes: Array[Byte], query: String, values: Seq[Any], encoder: ColumnEncoderRegistry, charset: Charset, writeDescribe: Boolean = false ): ByteBuf = { if (log.isDebugEnabled) { log.debug(s"Preparing execute portal to statement ($query) - values (${values.mkString(", ")}) - ${charset}") } val bindBuffer = Unpooled.buffer(1024) bindBuffer.writeByte(ServerMessage.Bind) bindBuffer.writeInt(0) bindBuffer.writeBytes(statementIdBytes) bindBuffer.writeByte(0) bindBuffer.writeBytes(statementIdBytes) bindBuffer.writeByte(0) bindBuffer.writeShort(0) bindBuffer.writeShort(values.length) val decodedValues = if (log.isDebugEnabled) { new ArrayBuffer[String](values.size) } else { null } for (value <- values) { if (isNull(value)) { bindBuffer.writeInt(-1) if (log.isDebugEnabled) { decodedValues += null } } else { val encodedValue = encoder.encode(value) if (log.isDebugEnabled) { decodedValues += encodedValue } if (isNull(encodedValue)) { bindBuffer.writeInt(-1) } else { val content = encodedValue.getBytes(charset) bindBuffer.writeInt(content.length) bindBuffer.writeBytes(content) } } } if (log.isDebugEnabled) { log.debug(s"Executing portal - statement id (${statementIdBytes.mkString("-")}) - statement ($query) - encoded values (${decodedValues.mkString(", ")}) - original values (${values.mkString(", ")})") } bindBuffer.writeShort(0) ByteBufferUtils.writeLength(bindBuffer) if (writeDescribe) { val describeLength = 1 + 4 + 1 + statementIdBytes.length + 1 val describeBuffer = bindBuffer describeBuffer.writeByte(ServerMessage.Describe) describeBuffer.writeInt(describeLength - 1) describeBuffer.writeByte('P') describeBuffer.writeBytes(statementIdBytes) describeBuffer.writeByte(0) } val executeLength = 1 + 4 + statementIdBytes.length + 1 + 4 val executeBuffer = Unpooled.buffer(executeLength) executeBuffer.writeByte(ServerMessage.Execute) executeBuffer.writeInt(executeLength - 1) executeBuffer.writeBytes(statementIdBytes) executeBuffer.writeByte(0) executeBuffer.writeInt(0) val closeLength = 1 + 4 + 1 + statementIdBytes.length + 1 val closeBuffer = Unpooled.buffer(closeLength) closeBuffer.writeByte(ServerMessage.CloseStatementOrPortal) closeBuffer.writeInt(closeLength - 1) closeBuffer.writeByte('P') closeBuffer.writeBytes(statementIdBytes) closeBuffer.writeByte(0) val syncBuffer = Unpooled.buffer(5) syncBuffer.writeByte(ServerMessage.Sync) syncBuffer.writeInt(4) Unpooled.wrappedBuffer(bindBuffer, executeBuffer, syncBuffer, closeBuffer) } def isNull(value: Any): Boolean = value == null || value == None }
1
null
1
1
c16a5772b46331c582c4d14939e6c4cad09edb98
4,331
jasync-sql
Apache License 2.0
app/src/main/kotlin/com/digian/clean/features/movies/presentation/MoviesActivity.kt
alexforrester
193,843,187
false
null
package com.digian.clean.features.movies import android.os.Bundle import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AppCompatActivity import androidx.test.espresso.IdlingResource import com.digian.clean.R import com.digian.clean.features.movies.presentation.IdlingResource.SimpleIdlingResource /** * Created by <NAME> on 18/04/2019. */ class MoviesActivity : AppCompatActivity() { // The Idling Resource which will be null in production private var idlingResource : SimpleIdlingResource? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_movies) title = getString(R.string.popular_movies) } @VisibleForTesting fun getIdlingResource(): IdlingResource { if (idlingResource == null) { idlingResource = SimpleIdlingResource() } return idlingResource as SimpleIdlingResource } }
0
null
8
25
952399aa274ae4cf59b8a3827b8e8fba23a948e0
990
android-clean-architecture
Apache License 2.0
server/src/main/kotlin/com/example/internal/dbStorage/Helpers.kt
agilers-2021
408,805,593
false
{"Kotlin": 49657, "JavaScript": 19963, "HTML": 12856, "CSS": 5083, "Python": 2975, "Dockerfile": 719}
package com.example.internal.dbStorage import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.statements.InsertStatement import org.jetbrains.exposed.sql.transactions.TransactionManager // https://github.com/JetBrains/Exposed/issues/167#issuecomment-403837917 fun <T : Table> T.insertOrUpdate(vararg onDuplicateUpdateKeys: Column<*>, body: T.(InsertStatement<Number>) -> Unit) = InsertOrUpdate<Number>(onDuplicateUpdateKeys,this).apply { body(this) execute(TransactionManager.current()) } class InsertOrUpdate<Key : Any>( private val onDuplicateUpdateKeys: Array< out Column<*>>, table: Table, isIgnore: Boolean = false ) : InsertStatement<Key>(table, isIgnore) { override fun prepareSQL(transaction: Transaction): String { val onUpdateSQL = if(onDuplicateUpdateKeys.isNotEmpty()) { " ON DUPLICATE KEY UPDATE " + onDuplicateUpdateKeys.joinToString { "${transaction.identity(it)}=VALUES(${transaction.identity(it)})" } } else "" return super.prepareSQL(transaction) + onUpdateSQL } }
1
Kotlin
1
1
8c6ef1651728cb65551966fe3120d4737d37e568
1,168
memster
MIT License
TelegramBotAPI-extensions-api/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/api/edit/LiveLocation/StopChatMessageLiveLocation.kt
sleshJdev
289,571,865
true
{"Kotlin": 718048}
package com.github.insanusmokrassar.TelegramBotAPI.extensions.api.edit.LiveLocation import com.github.insanusmokrassar.TelegramBotAPI.bot.RequestsExecutor import com.github.insanusmokrassar.TelegramBotAPI.requests.edit.LiveLocation.EditChatMessageLiveLocation import com.github.insanusmokrassar.TelegramBotAPI.types.* import com.github.insanusmokrassar.TelegramBotAPI.types.buttons.InlineKeyboardMarkup import com.github.insanusmokrassar.TelegramBotAPI.types.chat.abstracts.Chat import com.github.insanusmokrassar.TelegramBotAPI.types.message.abstracts.ContentMessage import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.LocationContent suspend fun RequestsExecutor.editLiveLocation( chatId: ChatIdentifier, messageId: MessageIdentifier, latitude: Double, longitude: Double, replyMarkup: InlineKeyboardMarkup? = null ) = execute( EditChatMessageLiveLocation( chatId, messageId, latitude, longitude, replyMarkup ) ) suspend fun RequestsExecutor.editLiveLocation( chat: Chat, messageId: MessageIdentifier, latitude: Double, longitude: Double, replyMarkup: InlineKeyboardMarkup? = null ) = editLiveLocation(chat.id, messageId, latitude, longitude, replyMarkup) suspend fun RequestsExecutor.editLiveLocation( message: ContentMessage<LocationContent>, latitude: Double, longitude: Double, replyMarkup: InlineKeyboardMarkup? = null ) = editLiveLocation(message.chat, message.messageId, latitude, longitude, replyMarkup) suspend fun RequestsExecutor.editLiveLocation( chatId: ChatIdentifier, messageId: MessageIdentifier, location: Location, replyMarkup: InlineKeyboardMarkup? = null ) = execute( EditChatMessageLiveLocation( chatId, messageId, location.latitude, location.longitude, replyMarkup ) ) suspend fun RequestsExecutor.editLiveLocation( chat: Chat, messageId: MessageIdentifier, location: Location, replyMarkup: InlineKeyboardMarkup? = null ) = editLiveLocation(chat.id, messageId, location.latitude, location.longitude, replyMarkup) suspend fun RequestsExecutor.editLiveLocation( message: ContentMessage<LocationContent>, location: Location, replyMarkup: InlineKeyboardMarkup? = null ) = editLiveLocation(message.chat, message.messageId, location.latitude, location.longitude, replyMarkup)
0
null
0
0
cc0498a89a28ae8205f6f854534ec6f31be36cda
2,352
TelegramBotAPI
Apache License 2.0
app/src/main/java/com/example/c_19tracker/StateAdapter.kt
Rudra-cs
260,144,776
false
{"Kotlin": 6400}
package com.example.c_19tracker import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import kotlinx.android.synthetic.main.item_list.view.* class StateAdapter (val list: List<StatewiseItem>): BaseAdapter(){ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: LayoutInflater.from(parent.context) .inflate(R.layout.item_list,parent,false) val item = list[position] view.stateTV.text = item.state view.confirmedTV.text = SpannableDelta("${item.confirmed}\n ↑${item.deltaconfirmed ?: "0" }", "#FF0000", item.confirmed?.length ?: 0 ) view.activeTV.text = SpannableDelta("${item.active}\n ↑${item.deltaactive ?: "0" }", "#F55F20", item.active?.length ?: 0 ) view.recoveredTV.text = SpannableDelta("${item.recovered}\n ↑${item.deltarecovered ?: "0" }", "#19CD4C", item.recovered?.length ?: 0 ) view.deathTV.text = SpannableDelta("${item.deaths}\n ↑${item.deltadeaths ?: "0" }", "#D2B55B", item.deaths?.length ?: 0 ) return view } override fun getItem(position: Int) = list[position] override fun getItemId(position: Int) = position.toLong() override fun getCount() = list.size }
0
Kotlin
0
0
d0ee5b7dcc7b5e415aa2ee871bedde08866ec4e9
1,420
covid-19-tracker-india
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/mediapackage/CfnOriginEndpointHlsManifestPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.mediapackage import cloudshift.awscdk.common.CdkDslMarker import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.mediapackage.CfnOriginEndpoint /** * An HTTP Live Streaming (HLS) manifest configuration on a CMAF endpoint. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.mediapackage.*; * HlsManifestProperty hlsManifestProperty = HlsManifestProperty.builder() * .id("id") * // the properties below are optional * .adMarkers("adMarkers") * .adsOnDeliveryRestrictions("adsOnDeliveryRestrictions") * .adTriggers(List.of("adTriggers")) * .includeIframeOnlyStream(false) * .manifestName("manifestName") * .playlistType("playlistType") * .playlistWindowSeconds(123) * .programDateTimeIntervalSeconds(123) * .url("url") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-mediapackage-originendpoint-hlsmanifest.html) */ @CdkDslMarker public class CfnOriginEndpointHlsManifestPropertyDsl { private val cdkBuilder: CfnOriginEndpoint.HlsManifestProperty.Builder = CfnOriginEndpoint.HlsManifestProperty.builder() private val _adTriggers: MutableList<String> = mutableListOf() /** * @param adMarkers Controls how ad markers are included in the packaged endpoint. * Valid values: * * * `NONE` - Omits all SCTE-35 ad markers from the output. * * `PASSTHROUGH` - Creates a copy in the output of the SCTE-35 ad markers (comments) taken * directly from the input manifest. * * `SCTE35_ENHANCED` - Generates ad markers and blackout tags in the output based on the SCTE-35 * messages from the input manifest. */ public fun adMarkers(adMarkers: String) { cdkBuilder.adMarkers(adMarkers) } /** * @param adTriggers Specifies the SCTE-35 message types that AWS Elemental MediaPackage treats as * ad markers in the output manifest. * Valid values: * * * `BREAK` * * `DISTRIBUTOR_ADVERTISEMENT` * * `DISTRIBUTOR_OVERLAY_PLACEMENT_OPPORTUNITY` * * `DISTRIBUTOR_PLACEMENT_OPPORTUNITY` * * `PROVIDER_ADVERTISEMENT` * * `PROVIDER_OVERLAY_PLACEMENT_OPPORTUNITY` * * `PROVIDER_PLACEMENT_OPPORTUNITY` * * `SPLICE_INSERT` */ public fun adTriggers(vararg adTriggers: String) { _adTriggers.addAll(listOf(*adTriggers)) } /** * @param adTriggers Specifies the SCTE-35 message types that AWS Elemental MediaPackage treats as * ad markers in the output manifest. * Valid values: * * * `BREAK` * * `DISTRIBUTOR_ADVERTISEMENT` * * `DISTRIBUTOR_OVERLAY_PLACEMENT_OPPORTUNITY` * * `DISTRIBUTOR_PLACEMENT_OPPORTUNITY` * * `PROVIDER_ADVERTISEMENT` * * `PROVIDER_OVERLAY_PLACEMENT_OPPORTUNITY` * * `PROVIDER_PLACEMENT_OPPORTUNITY` * * `SPLICE_INSERT` */ public fun adTriggers(adTriggers: Collection<String>) { _adTriggers.addAll(adTriggers) } /** * @param adsOnDeliveryRestrictions The flags on SCTE-35 segmentation descriptors that have to be * present for AWS Elemental MediaPackage to insert ad markers in the output manifest. * For information about SCTE-35 in AWS Elemental MediaPackage , see [SCTE-35 Message Options in * AWS Elemental MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/ug/scte.html) . */ public fun adsOnDeliveryRestrictions(adsOnDeliveryRestrictions: String) { cdkBuilder.adsOnDeliveryRestrictions(adsOnDeliveryRestrictions) } /** * @param id The manifest ID is required and must be unique within the OriginEndpoint. * The ID can't be changed after the endpoint is created. */ public fun id(id: String) { cdkBuilder.id(id) } /** * @param includeIframeOnlyStream Applies to stream sets with a single video track only. * When true, the stream set includes an additional I-frame only stream, along with the other * tracks. If false, this extra stream is not included. */ public fun includeIframeOnlyStream(includeIframeOnlyStream: Boolean) { cdkBuilder.includeIframeOnlyStream(includeIframeOnlyStream) } /** * @param includeIframeOnlyStream Applies to stream sets with a single video track only. * When true, the stream set includes an additional I-frame only stream, along with the other * tracks. If false, this extra stream is not included. */ public fun includeIframeOnlyStream(includeIframeOnlyStream: IResolvable) { cdkBuilder.includeIframeOnlyStream(includeIframeOnlyStream) } /** * @param manifestName A short string that's appended to the end of the endpoint URL to create a * unique path to this endpoint. * The manifestName on the HLSManifest object overrides the manifestName that you provided on the * originEndpoint object. */ public fun manifestName(manifestName: String) { cdkBuilder.manifestName(manifestName) } /** * @param playlistType When specified as either `event` or `vod` , a corresponding * `EXT-X-PLAYLIST-TYPE` entry is included in the media playlist. * Indicates if the playlist is live-to-VOD content. */ public fun playlistType(playlistType: String) { cdkBuilder.playlistType(playlistType) } /** * @param playlistWindowSeconds Time window (in seconds) contained in each parent manifest. */ public fun playlistWindowSeconds(playlistWindowSeconds: Number) { cdkBuilder.playlistWindowSeconds(playlistWindowSeconds) } /** * @param programDateTimeIntervalSeconds Inserts `EXT-X-PROGRAM-DATE-TIME` tags in the output * manifest at the interval that you specify. * Additionally, ID3Timed metadata messages are generated every 5 seconds starting when the * content was ingested. * * Irrespective of this parameter, if any ID3Timed metadata is in the HLS input, it is passed * through to the HLS output. * * Omit this attribute or enter `0` to indicate that the `EXT-X-PROGRAM-DATE-TIME` tags are not * included in the manifest. */ public fun programDateTimeIntervalSeconds(programDateTimeIntervalSeconds: Number) { cdkBuilder.programDateTimeIntervalSeconds(programDateTimeIntervalSeconds) } /** * @param url The URL that's used to request this manifest from this endpoint. */ public fun url(url: String) { cdkBuilder.url(url) } public fun build(): CfnOriginEndpoint.HlsManifestProperty { if(_adTriggers.isNotEmpty()) cdkBuilder.adTriggers(_adTriggers) return cdkBuilder.build() } }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
6,882
awscdk-dsl-kotlin
Apache License 2.0
common/compose/src/main/kotlin/team/duckie/app/android/common/compose/ui/dialog/SelectableItemBottomSheetDialog.kt
duckie-team
503,869,663
false
{"Kotlin": 1819917}
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ @file:OptIn(ExperimentalMaterialApi::class) package team.duckie.app.android.common.compose.ui.dialog import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import kotlinx.collections.immutable.ImmutableList import team.duckie.app.android.common.kotlin.runIf import team.duckie.quackquack.ui.component.QuackImage import team.duckie.quackquack.ui.component.QuackSubtitle2 import team.duckie.quackquack.ui.modifier.quackClickable /** 여러 아이템 중 하나를 선택하는 형태의 [DuckieBottomSheetDialog] */ @Composable fun SelectableItemBottomSheetDialog( modifier: Modifier = Modifier, items: ImmutableList<BottomSheetItem>, navigationBarsPaddingVisible: Boolean = true, bottomSheetState: ModalBottomSheetState, closeSheet: () -> Unit, content: @Composable () -> Unit, ) { DuckieBottomSheetDialog( modifier = modifier, useHandle = true, sheetState = bottomSheetState, sheetContent = { LazyColumn( modifier = Modifier .fillMaxWidth() .runIf(navigationBarsPaddingVisible) { navigationBarsPadding() } .padding(bottom = 16.dp), ) { items(items) { item -> Row( modifier = Modifier .fillMaxWidth() .height(44.dp) .quackClickable( rippleEnabled = false, ) { item.onClick() closeSheet() } .padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically, ) { QuackImage( src = item.icon, size = DpSize(width = 24.dp, height = 24.dp), ) QuackSubtitle2( modifier = Modifier.padding(start = 8.dp), text = stringResource(id = item.text), ) } } } }, content = content, ) }
32
Kotlin
2
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
3,128
duckie-android
MIT License
app/src/main/java/com/cameronvwilliams/raise/util/ActiveCardDiffCallback.kt
RaiseSoftware
119,627,507
false
null
package com.cameronvwilliams.raise.util import androidx.recyclerview.widget.DiffUtil import com.cameronvwilliams.raise.data.model.ActiveCard class ActiveCardDiffCallback(private val current: List<ActiveCard>, private val next: List<ActiveCard>) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val currentItem = current[oldItemPosition] val nextItem = next[newItemPosition] return currentItem.player.name == nextItem.player.name } override fun getOldListSize() = current.size override fun getNewListSize() = next.size override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val currentItem = current[oldItemPosition] val nextItem = next[newItemPosition] return currentItem == nextItem } }
1
null
1
4
3cd0786dba77645efa5508a662478e5893037919
857
Raise-Android
MIT License
blog/src/main/kotlin/blog/HtmlController.kt
ideaplugins
132,205,373
true
{"Kotlin": 11966, "HTML": 1002}
package blog import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable @Controller class HtmlController(private val repository: ArticleRepository, private val markdownConverter: MarkdownConverter) { @GetMapping("/") fun blog(model: Model): String { model["title"] = "Blog" model["articles"] = repository.findAllByOrderByAddedAtDesc().map { it.render() } return "blog" } @GetMapping("/article/{slug}") fun article(@PathVariable slug: String, model: Model): String { val article = repository .findById(slug) .orElseThrow { IllegalArgumentException("Wrong article slug provided") } .render() model["title"] = article.title model["article"] = article return "article" } fun Article.render() = RenderedArticle( slug, title, markdownConverter.invoke(headline), markdownConverter.invoke(content), author, addedAt.format() ) data class RenderedArticle( val slug: String, val title: String, val headline: String, val content: String, val author: User, val addedAt: String) }
0
Kotlin
0
0
7f4ec2882e5d4aff7fffd800264f5e98616527c7
1,231
tut-spring-boot-kotlin
MIT License
libnavigation-core/src/main/java/com/mapbox/navigation/core/routerefresh/RouteRefreshController.kt
k4anubhav
439,334,238
false
null
package com.mapbox.navigation.core.routerefresh import com.mapbox.api.directions.v5.models.DirectionsRoute import com.mapbox.base.common.logger.Logger import com.mapbox.base.common.logger.model.Message import com.mapbox.base.common.logger.model.Tag import com.mapbox.navigation.base.route.RouteRefreshCallback import com.mapbox.navigation.base.route.RouteRefreshError import com.mapbox.navigation.base.route.RouteRefreshOptions import com.mapbox.navigation.core.directions.session.DirectionsSession import com.mapbox.navigation.core.trip.session.TripSession import com.mapbox.navigation.navigator.internal.MapboxNativeNavigatorImpl import com.mapbox.navigation.utils.internal.MapboxTimer /** * This class is responsible for refreshing the current direction route's traffic. * This does not support alternative routes. * * If the route is successfully refreshed, this class will update the [DirectionsSession]. */ internal class RouteRefreshController( private val routeRefreshOptions: RouteRefreshOptions, private val directionsSession: DirectionsSession, private val tripSession: TripSession, private val logger: Logger, private val routeDiffProvider: DirectionsRouteDiffProvider = DirectionsRouteDiffProvider(), ) { internal companion object { internal val TAG = Tag("MbxRouteRefreshController") } private val routerRefreshTimer = MapboxTimer().apply { restartAfterMillis = routeRefreshOptions.intervalMillis } private var currentRequestId: Long? = null /** * If route refresh is enabled, attach a refresh poller. * Cancel old timers, and cancel pending requests. */ fun restart(route: DirectionsRoute) { stop() if (route.routeOptions()?.enableRefresh() == true) { routerRefreshTimer.startTimer { refreshRoute(route) } } else if (route.routeOptions() == null) { logger.w( TAG, Message( """ Unable to refresh the route because routeOptions are missing. Use #fromJson(json, routeOptions, requestUuid) when deserializing the route or route response. """.trimIndent() ) ) } } /** * Cancel old timers, and cancel pending requests. */ fun stop() { routerRefreshTimer.stopJobs() currentRequestId?.let { directionsSession.cancelRouteRefreshRequest(it) currentRequestId = null } } private fun refreshRoute(route: DirectionsRoute) { val isValid = route.routeOptions()?.enableRefresh() == true && route.isUuidValidForRefresh() if (isValid) { val legIndex = tripSession.getRouteProgress()?.currentLegProgress?.legIndex ?: 0 currentRequestId?.let { directionsSession.cancelRouteRefreshRequest(it) } currentRequestId = directionsSession.requestRouteRefresh( route, legIndex, createRouteRefreshCallback(route, legIndex), ) } else { logger.w( TAG, Message( """ The route is not qualified for route refresh feature. See com.mapbox.navigation.base.extensions.supportsRouteRefresh extension for details. ${route.routeOptions()} """.trimIndent() ) ) } } private fun createRouteRefreshCallback( oldDirectionsRoute: DirectionsRoute, currentLegIndex: Int, ) = object : RouteRefreshCallback { override fun onRefresh(directionsRoute: DirectionsRoute) { logger.i(TAG, msg = Message("Successful route refresh")) val routeDiffs = routeDiffProvider.buildRouteDiffs( oldDirectionsRoute, directionsRoute, currentLegIndex, ) if (routeDiffs.isEmpty()) { logger.i(TAG, msg = Message("No changes to route annotations")) } else { for (diff in routeDiffs) { logger.i(TAG, msg = Message(diff)) } } val directionsSessionRoutes = directionsSession.routes.toMutableList() if (directionsSessionRoutes.isNotEmpty()) { directionsSessionRoutes[0] = directionsRoute directionsSession.setRoutes(directionsSessionRoutes) } currentRequestId = null } override fun onError(error: RouteRefreshError) { logger.e( TAG, msg = Message("Route refresh error: ${error.message}"), tr = error.throwable ) currentRequestId = null } } /** * Check if uuid is valid: * - [DirectionsRoute] is not **null**; * - uuid is not empty; * - uuid is not equal to [MapboxNativeNavigatorImpl.OFFLINE_UUID]. */ private fun DirectionsRoute?.isUuidValidForRefresh(): Boolean = this?.requestUuid() ?.let { uuid -> uuid.isNotEmpty() && uuid != MapboxNativeNavigatorImpl.OFFLINE_UUID } ?: false }
1
null
1
1
c7fd13f6c363e0902cf2e12d55d4bc3647700400
5,364
mapbox-navigation-android
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/pipelines/AddStageOptsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.pipelines import cloudshift.awscdk.common.CdkDslMarker import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.pipelines.AddStageOpts import software.amazon.awscdk.pipelines.StackSteps import software.amazon.awscdk.pipelines.Step /** * Options to pass to `addStage`. * * Example: * ``` * CodePipeline pipeline; * MyApplicationStage preprod = new MyApplicationStage(this, "PreProd"); * MyApplicationStage prod = new MyApplicationStage(this, "Prod"); * pipeline.addStage(preprod, AddStageOpts.builder() * .post(List.of( * ShellStep.Builder.create("Validate Endpoint") * .commands(List.of("curl -Ssf https://my.webservice.com/")) * .build())) * .build()); * pipeline.addStage(prod, AddStageOpts.builder() * .pre(List.of( * new ManualApprovalStep("PromoteToProd"))) * .build()); * ``` */ @CdkDslMarker public class AddStageOptsDsl { private val cdkBuilder: AddStageOpts.Builder = AddStageOpts.builder() private val _post: MutableList<Step> = mutableListOf() private val _pre: MutableList<Step> = mutableListOf() private val _stackSteps: MutableList<StackSteps> = mutableListOf() /** @param post Additional steps to run after all of the stacks in the stage. */ public fun post(vararg post: Step) { _post.addAll(listOf(*post)) } /** @param post Additional steps to run after all of the stacks in the stage. */ public fun post(post: Collection<Step>) { _post.addAll(post) } /** @param pre Additional steps to run before any of the stacks in the stage. */ public fun pre(vararg pre: Step) { _pre.addAll(listOf(*pre)) } /** @param pre Additional steps to run before any of the stacks in the stage. */ public fun pre(pre: Collection<Step>) { _pre.addAll(pre) } /** @param stackSteps Instructions for stack level steps. */ public fun stackSteps(stackSteps: StackStepsDsl.() -> Unit) { _stackSteps.add(StackStepsDsl().apply(stackSteps).build()) } /** @param stackSteps Instructions for stack level steps. */ public fun stackSteps(stackSteps: Collection<StackSteps>) { _stackSteps.addAll(stackSteps) } public fun build(): AddStageOpts { if (_post.isNotEmpty()) cdkBuilder.post(_post) if (_pre.isNotEmpty()) cdkBuilder.pre(_pre) if (_stackSteps.isNotEmpty()) cdkBuilder.stackSteps(_stackSteps) return cdkBuilder.build() } }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
2,733
awscdk-dsl-kotlin
Apache License 2.0
src/test/kotlin/no/nav/personbruker/dittnav/brukernotifikasjonbestiller/varsel/NokkelTestData.kt
navikt
331,545,066
false
{"Kotlin": 72259, "Dockerfile": 166}
package no.nav.personbruker.dittnav.brukernotifikasjonbestiller.nokkel import no.nav.brukernotifikasjon.schemas.input.NokkelInput object NokkelTestData { private const val defaultFodselsnr = "12345678910" private const val defaultGrupperingsid = "123" private const val defaultAppName = "defaultAppName" private const val defaultNamespace = "defaultNamespace" fun nokkel( eventId: String? = "12345678-1234-1234-1234-1234567890ab", fodselsnummer: String? = "12345678910", grupperingsid: String? = "123", appnavn: String? = "defaultAppName", namespace: String? = "defaultNamespace", ): NokkelInput { return NokkelInput( eventId, grupperingsid, fodselsnummer, namespace, appnavn ) } fun createNokkelInputWithEventId(eventId: String): NokkelInput { return NokkelInput( eventId, defaultGrupperingsid, defaultFodselsnr, defaultNamespace, defaultAppName ) } fun createNokkelInputWithEventIdAndGroupId(eventId: String, groupId: String): NokkelInput { return NokkelInput( eventId, groupId, defaultFodselsnr, defaultNamespace, defaultAppName ) } }
1
Kotlin
0
0
9df0ace75939834947d531a342f9153d9ad44633
1,355
dittnav-brukernotifikasjonbestiller
MIT License
app/src/main/java/com/bb4first/mycashtask/repository/auth/LoginRepository.kt
MostafaKader56
854,577,641
false
{"Kotlin": 123081}
package com.bb4first.mycashtask.repository.auth import com.bb4first.mycashtask.nerwork.api_helper.auth.LoginApiHelper import javax.inject.Inject class LoginRepository @Inject constructor(private val loginApiHelper: LoginApiHelper) { suspend fun login( email: String, password: String, deviceToken: String, ) = try { loginApiHelper.login( email = email, password = <PASSWORD>, deviceToken = deviceToken ) } catch (ex: Exception) { ex.printStackTrace() null } }
0
Kotlin
0
0
079a9042f703f1374f75331e4bff2edbfa65aebe
569
my_cash_task
MIT License
app/src/main/java/com/kieran/winnipegbusbackend/interfaces/ScheduledStopKey.kt
KieranL
40,154,002
false
null
package com.kieran.winnipegbusbackend.interfaces import java.io.Serializable interface ScheduledStopKey : Serializable, Comparable<Any> { override fun equals(other: Any?): Boolean }
8
Kotlin
0
2
cd67dafec7fce4b61028ea4e337059ae628cfb4e
187
Winnipeg-Transit-Plus
Apache License 2.0
compiler/testData/ir/irText/types/nullChecks/typeParameterWithMultipleNullableBounds.kt
JetBrains
3,432,266
false
null
// TARGET_BACKEND: JVM // FILE: typeParameterWithMultipleNullableBounds.kt fun <T> f(x: T): Int? where T : CharSequence?, T : Comparable<T>? { return x?.compareTo(x) } fun test() { f(J.s()) f(J.STRING) } // FILE: J.java public class J { public static String STRING = s() public static String s() { return null; } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
338
kotlin
Apache License 2.0
app/src/main/java/com/lnpdit/sunnyweather/test/http/MyRepository.kt
hepengNC
664,952,501
false
null
package com.lnpdit.sunnyweather.test.http import androidx.lifecycle.liveData import com.lnpdit.sunnyweather.test.login.model.LoginRequest import com.lnpdit.sunnyweather.test.login.network.LoginNetwork import kotlinx.coroutines.Dispatchers import kotlin.coroutines.CoroutineContext /** * Created by HePeng on 2023/7/13 */ object MyRepository { fun login(request: LoginRequest) = fire(Dispatchers.IO) { val loginResponse = LoginNetwork.login(request) Result.success(loginResponse) } fun getInfo(token: String) = fire(Dispatchers.IO) { val loginInfoResponse = LoginNetwork.getInfo(token) Result.success(loginInfoResponse) } fun getParkList(token: String, managerId: String) = fire(Dispatchers.IO) { val response = LoginNetwork.getParkList(token, managerId) Result.success(response) } private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) = liveData { val result = try { block() } catch (e: Exception) { Result.failure(e) } emit(result) } }
0
Kotlin
0
0
76c2a46e9ce7cd637f89eecfcb596ddd8d9dad9d
1,105
SunnyWeather
Apache License 2.0
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/presentation/staking/rebond/custom/CustomRebondFragment.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.staking.impl.presentation.staking.rebond.custom import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import coil.ImageLoader import dagger.hilt.android.AndroidEntryPoint import dev.chrisbanes.insetter.applyInsetter import jp.co.soramitsu.common.base.BaseFragment import jp.co.soramitsu.common.mixin.impl.observeRetries import jp.co.soramitsu.common.mixin.impl.observeValidations import jp.co.soramitsu.common.utils.bindTo import jp.co.soramitsu.common.view.setProgress import jp.co.soramitsu.common.view.viewBinding import jp.co.soramitsu.feature_staking_impl.R import jp.co.soramitsu.feature_staking_impl.databinding.FragmentRebondCustomBinding import javax.inject.Inject @AndroidEntryPoint class CustomRebondFragment : BaseFragment<CustomRebondViewModel>(R.layout.fragment_rebond_custom) { @Inject protected lateinit var imageLoader: ImageLoader private val binding by viewBinding(FragmentRebondCustomBinding::bind) override val viewModel: CustomRebondViewModel by viewModels() override fun initViews() { with(binding) { rebondToolbar.applyInsetter { type(statusBars = true) { padding() } } rebondToolbar.setHomeButtonListener { viewModel.backClicked() } rebondContinue.prepareForProgress(viewLifecycleOwner) rebondContinue.setOnClickListener { viewModel.confirmClicked() } } } override fun subscribe(viewModel: CustomRebondViewModel) { observeValidations(viewModel) observeRetries(viewModel) viewModel.showNextProgress.observe(binding.rebondContinue::setProgress) viewModel.assetModelFlow.observe { binding.rebondAmount.setAssetBalance(it.assetBalance) binding.rebondAmount.setAssetName(it.tokenName) binding.rebondAmount.setAssetImageUrl(it.imageUrl, imageLoader) } binding.rebondAmount.amountInput.bindTo(viewModel.enteredAmountFlow, lifecycleScope) viewModel.amountFiatFLow.observe { it?.let(binding.rebondAmount::setAssetBalanceFiatAmount) } viewModel.feeLiveData.observe(binding.rebondFee::setFeeStatus) } }
15
null
30
89
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
2,257
fearless-Android
Apache License 2.0
app/src/main/java/com/example/okcredit/Navigation/AccountFragmentActivity.kt
lucifernipun22
345,898,513
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 71, "XML": 190, "JSON": 22, "Java": 6}
package com.example.okcredit.Navigation import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.okcredit.R class AccountFragmentActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_account) } }
0
Kotlin
0
2
cc27ed6e6668b25637ea92b0fa039a951426b7af
356
okCredit
MIT License
server/PonyKtor/src/main/kotlin/Router.kt
evant
362,828,301
false
null
package me.tatarka.inject import io.ktor.application.call import io.ktor.response.respond import io.ktor.routing.Routing import io.ktor.routing.get import io.ktor.util.getOrFail import me.tatarka.inject.annotations.Inject import me.tatarka.inject.episodes.EpisodesController typealias router = (Routing) -> Unit /** * Sets up the app's routes by delegating to the relevant controller. */ @Inject fun router( episodesController: EpisodesController, routing: Routing, ) { routing.apply { get("episode/all") { call.respond(episodesController.allEpisodes(call.request.queryParameters)) } get("episode/{id}") { call.respond(episodesController.episode(call.parameters.getOrFail("id"))) } get("episode/by-overall/{number}") { call.respond(episodesController.episodeByOverall(call.parameters.getOrFail("number"))) } get("episode/by-season/{season}/{episode}") { val p = call.parameters call.respond(episodesController.episodeBySeason(p.getOrFail("season"), p.getOrFail("episode"))) } } }
2
Kotlin
2
7
2cea6e1ecc50df2f8f0b45e2fcc7e903eb3c98d7
1,124
kotlin-inject-samples
Apache License 2.0
shared/src/commonMain/kotlin/com/vasylt/composekmm/contacts/domain/ContactDataSource.kt
osisupermoses
734,461,368
false
null
package com.vasylt.composekmm.contacts.domain import kotlinx.coroutines.flow.Flow interface ContactDataSource { fun getContacts(): Flow<List<Contact>> fun getRecentContacts(amount: Int): Flow<List<Contact>> suspend fun insertContact(contact: Contact) suspend fun deleteContact(id: Long) }
0
Kotlin
0
0
b1313d5ed529aedf9819c45c316d118bf313c680
306
contact-list-app
Apache License 2.0
app/src/main/java/com/jaseem/apod/data/network/service/RetrofitApodApi.kt
Jaseemakhtar
570,799,517
false
null
package com.jaseem.apod.data.network.service import com.jaseem.apod.data.network.model.CosmosRemote import retrofit2.Response import retrofit2.http.GET interface RetrofitApodApi { @GET("obvious/take-home-exercise-data/trunk/nasa-pictures.json") suspend fun getAllCosmos(): Response<List<CosmosRemote>> }
0
Kotlin
0
0
c040ce5d7b32ca15088e0cd3bcdf64cb9d2dd894
315
AssignmentApod
Apache License 2.0
app/src/main/java/com/relieve/android/screen/fragment/walkthrough/WalkthroughFragment.kt
luxinfity
159,038,146
false
{"Kotlin": 106981, "Java": 1126}
package com.relieve.android.screen.fragment.walkthrough 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.FragmentPagerAdapter import androidx.navigation.fragment.findNavController import androidx.viewpager.widget.ViewPager import com.relieve.android.R import kotlinx.android.synthetic.main.fragment_walkthrough.* import kotlinx.android.synthetic.main.fragment_walkthrough_item.view.* class WalkthroughFragment : Fragment() { companion object { const val IMAGE_KEY = "IMAGE_KEY" const val TITLE_KEY = "TITLE_KEY" const val SUBTITLE_KEY = "SUBTITLE_KEY" } class WalkthroughItemFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { var image = "" var title = "" var subtitle = "" arguments?.also { image = it.getString(IMAGE_KEY, "") title = it.getString(TITLE_KEY, "") subtitle = it.getString(SUBTITLE_KEY, "") } return inflater.inflate(R.layout.fragment_walkthrough_item, container, false).apply { if (title.isNotEmpty()) tvWalkThroughTitle.text = title if (subtitle.isNotEmpty()) tvWalkThroughDetail.text = subtitle } } } override fun onCreateView (inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_walkthrough, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) render() } val fragments = listOf ( WalkthroughItemFragment().apply { arguments = Bundle() arguments?.apply { putString(IMAGE_KEY, "") putString(TITLE_KEY, "Tambahkan keluarga dan orang terpenting mu ke daftar kerabat") putString(SUBTITLE_KEY, "Jangan sampai kamu ketinggalan informasi mengenai kesehatan mereka") } }, WalkthroughItemFragment().apply { arguments = Bundle() arguments?.apply { putString(IMAGE_KEY, "") putString(TITLE_KEY, "Selalu ingat memberi kabar, dengan sekali tap") putString(SUBTITLE_KEY, "Notifikasi harian akan membuat mu selalu ingat memberitahu kondisi mu kepada kerabat") } }, WalkthroughItemFragment().apply { arguments = Bundle() arguments?.apply { putString(IMAGE_KEY, "") putString(TITLE_KEY, "Selalu waspada bencana dapat terjadi kapan saja") putString(SUBTITLE_KEY, "Relieve akan memperingatkan mu jika ada bencana terjadi di dekat mu, tetap tenang dan siap evakuasi") } }, WalkthroughItemFragment().apply { arguments = Bundle() arguments?.apply { putString(IMAGE_KEY, "") putString(TITLE_KEY, "Ingin tau kondisi terupdate suatu lokasi bencana?") putString(SUBTITLE_KEY, "Pantau terus perkembangan penanggulangan bencana, jangan lagi lewatkan informasi penting") } } ) private fun render() { vpWalkThrough.adapter = object : FragmentPagerAdapter(fragmentManager) { override fun getItem(position: Int) = fragments[position] override fun getCount() = fragments.size } vpWalkThrough.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { if (position == fragments.size - 1) { tvNexSlide.text = getString(R.string.done) } else { tvNexSlide.text = getString(R.string.next) } } }) dotsIndicator.setViewPager(vpWalkThrough) tvNexSlide.setOnClickListener { val current = vpWalkThrough.currentItem if (current < fragments.size - 1) { vpWalkThrough.setCurrentItem(current + 1, true) } else { findNavController().navigateUp() } } } }
0
Kotlin
0
0
7e0de304db66d60ad4f25846723fe048f7aefbb9
4,655
relieve_android
MIT License
benchmarks/commonMain/src/benchmarks/immutableMap/Remove.kt
Kotlin
59,769,494
false
{"Kotlin": 569271}
/* * Modified from the kotlinx.collections.immutable sources, which contained the following notice: * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package benchmarks.immutableMap import benchmarks.* import kotlinx.collections.immutable.PersistentMap import kotlinx.collections.immutable.persistentMapOf import kotlinx.benchmark.* @State(Scope.Benchmark) open class Remove { @Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000) var size: Int = 0 @Param(HAMT_IMPL, ORDERED_HAMT_IMPL, TREAP_IMPL) var implementation = "" @Param(ASCENDING_HASH_CODE, RANDOM_HASH_CODE, COLLISION_HASH_CODE, NON_EXISTING_HASH_CODE) var hashCodeType = "" private var keys = listOf<IntWrapper>() private var persistentMap = persistentMapOf<IntWrapper, String>() @Setup fun prepare() { keys = generateKeys(hashCodeType, size) persistentMap = persistentMapPut(implementation, keys) if (hashCodeType == NON_EXISTING_HASH_CODE) keys = generateKeys(hashCodeType, size) } @Benchmark fun remove(): PersistentMap<IntWrapper, String> { var map = persistentMap repeat(times = size) { index -> map = map.remove(keys[index]) } return map } }
50
Kotlin
53
996
c73ce02cf1214f14ec177cc6c2da15677ec98012
1,373
kotlinx.collections.immutable
Apache License 2.0
sceneview/src/main/java/io/github/sceneview/Filament.kt
SceneView
426,414,439
false
null
package io.github.sceneview import android.opengl.EGLContext import com.google.android.filament.* import com.google.android.filament.gltfio.AssetLoader import com.google.android.filament.gltfio.Gltfio import com.google.android.filament.gltfio.ResourceLoader import com.google.android.filament.gltfio.UbershaderProvider import com.google.android.filament.utils.Utils import com.google.ar.sceneform.rendering.GLHelper import io.github.sceneview.environment.IBLPrefilter import io.github.sceneview.math.Transform import io.github.sceneview.math.toColumnsFloatArray import java.lang.ref.WeakReference // TODO : Add the lifecycle aware management when filament dependents are all kotlined object Filament { init { Gltfio.init() com.google.android.filament.Filament.init() Utils.init() } private var eglContext: WeakReference<EGLContext>? = null private var _engine: WeakReference<Engine>? = null @JvmStatic val engine: Engine get() = _engine?.get() ?: (eglContext?.get() ?: GLHelper.makeContext()) .let { eglContext -> this.eglContext = WeakReference(eglContext) Engine.create(eglContext).also { engine -> _engine = WeakReference(engine) } } @JvmStatic val entityManager get() = EntityManager.get() @JvmStatic val transformManager get() = engine.transformManager @JvmStatic val renderableManager get() = engine.renderableManager @JvmStatic val lightManager get() = engine.lightManager private var _resourceLoader: ResourceLoader? = null @JvmStatic val resourceLoader: ResourceLoader get() = _resourceLoader ?: ResourceLoader( engine, true, true, false ).also { _resourceLoader = it } private var _materialProvider: UbershaderProvider? = null @JvmStatic val materialProvider get() = _materialProvider ?: UbershaderProvider(engine).also { _materialProvider = it } private var _assetLoader: AssetLoader? = null @JvmStatic val assetLoader: AssetLoader get() = _assetLoader ?: AssetLoader( engine, materialProvider, entityManager ).also { _assetLoader = it } private var _iblPrefilter: IBLPrefilter? = null @JvmStatic val iblPrefilter: IBLPrefilter get() = _iblPrefilter ?: IBLPrefilter(engine).also { _iblPrefilter = it } var retainers = 0 fun retain() { retainers++ } fun release() { retainers-- if (retainers == 0) { destroy() } } fun destroy() { // TODO: We still got some errors on this destroy due to this nightmare Renderable // Should be solved with RIP Renderable // _assetLoader?.destroy() _assetLoader = null _resourceLoader?.apply { asyncCancelLoad() evictResourceData() destroy() } _resourceLoader = null // TODO: Materials should be destroyed by their own _materialProvider?.destroyMaterials() _materialProvider?.destroy() _materialProvider = null _iblPrefilter?.destroy() _iblPrefilter = null _engine?.get()?.destroy() _engine?.clear() _engine = null eglContext?.get()?.let { GLHelper.destroyContext(it) } eglContext?.clear() eglContext = null } } fun Engine.createCamera() = createCamera(entityManager.create()) fun RenderableManager.Builder.build(entity: Int) = build(Filament.engine, entity) fun TransformManager.setTransform(@EntityInstance i: Int, worldTransform: Transform) = setTransform(i, worldTransform.toColumnsFloatArray())
29
null
90
440
9bd1e3dd6a51c8de36cf1a86db20f44bc63861fb
3,846
sceneview-android
Apache License 2.0
api/src/main/kotlin/org/kryptonmc/api/entity/animal/Parrot.kt
KryptonMC
255,582,002
false
null
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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 org.kryptonmc.api.entity.animal import org.kryptonmc.api.entity.animal.type.ParrotVariant /** * A parrot. */ public interface Parrot : Tamable { /** * The variant of this parrot. */ public var variant: ParrotVariant }
27
Kotlin
11
233
a9eff5463328f34072cdaf37aae3e77b14fcac93
982
Krypton
Apache License 2.0
app/src/main/java/com/denysnovoa/nzbmanager/common/framework/api/cache/NetworkCacheInterceptor.kt
denysnovoa
90,066,913
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Java": 2, "Kotlin": 110, "XML": 37}
package com.denysnovoa.nzbmanager.common.framework.api.cache import okhttp3.CacheControl import okhttp3.Interceptor import okhttp3.Response import java.util.concurrent.TimeUnit class NetworkCacheInterceptor : Interceptor { val CACHE_CONTROL = "Cache-Control" override fun intercept(chain: Interceptor.Chain): Response { val response = chain.proceed(chain.request()) val cacheControl = CacheControl.Builder().maxAge(2, TimeUnit.MINUTES).build() return response.newBuilder() .header(CACHE_CONTROL, cacheControl.toString()) .build() } }
0
Kotlin
0
1
8944e3bae4c073856f9856bf2e5064a6dadde4f7
609
radarrsonarr
Apache License 2.0
modules/wasm-binary/src/commonMain/kotlin/tree/sections/CodeSectionNode.kt
wasmium
761,480,110
false
{"Kotlin": 588711, "JavaScript": 203}
package org.wasmium.wasm.binary.tree.sections import org.wasmium.wasm.binary.tree.LocalVariable import org.wasmium.wasm.binary.tree.SectionKind import org.wasmium.wasm.binary.visitors.CodeSectionVisitor import org.wasmium.wasm.binary.visitors.ExpressionVisitor public class CodeSectionNode : SectionNode(SectionKind.CODE), CodeSectionVisitor { public val codes: MutableList<CodeType> = mutableListOf() public fun accept(codeSectionVisitor: CodeSectionVisitor) { for (code in codes) { val expressionVisitor = codeSectionVisitor.visitCode(code.locals) code.expression.accept(expressionVisitor) } codeSectionVisitor.visitEnd() } public override fun visitCode(locals: List<LocalVariable>): ExpressionVisitor { val expressionNode = ExpressionNode() codes.add(CodeType(locals, expressionNode)) return expressionNode } public override fun visitEnd() { // empty } }
0
Kotlin
0
3
f219d7133574e8ea81ce905393991212ca293cf4
973
wasmium-wasm-binary
Apache License 2.0
Browser/src/commonMain/kotlin/io/nacular/doodle/dom/impl/HtmlFactoryImpl.kt
nacular
108,631,782
false
null
package io.nacular.doodle.dom.impl import io.nacular.doodle.dom.Document import io.nacular.doodle.dom.HTMLButtonElement import io.nacular.doodle.dom.HTMLElement import io.nacular.doodle.dom.HTMLImageElement import io.nacular.doodle.dom.HTMLInputElement import io.nacular.doodle.dom.HtmlFactory internal class HtmlFactoryImpl(override val root: HTMLElement, private val document: Document): HtmlFactory { override fun <T: HTMLElement> create() = create("DIV") as T @Suppress("UNCHECKED_CAST") override fun <T: HTMLElement> create(tag: String) = document.createElement(tag) as T override fun createText(text: String) = document.createTextNode(text) override fun createImage(source: String) = create<HTMLImageElement>("IMG").apply { src = source; draggable = false } override fun createOrUse(tag: String, possible: HTMLElement?): HTMLElement = when { possible == null || possible.parentNode != null && !possible.nodeName.equals(tag, ignoreCase = true) -> create(tag) else -> possible } override fun createInput (): HTMLInputElement = create("INPUT" ) override fun createButton(): HTMLButtonElement = create("BUTTON") }
5
null
26
613
f7414d4c30cdd7632992071234223653e52b978c
1,175
doodle
MIT License
src/main/kotlin/com/willowtreeapps/fuzzywuzzy/ToStringFunction.kt
SEPIA-Framework
129,547,010
false
null
package com.willowtreeapps.fuzzywuzzy /** * Transforms an item of type T to a String. * * @param <T> The type of the item to transform. </T> */ interface ToStringFunction<T> { /** * Transforms the input item to a string. * * @param item The item to transform. * @return A string to use for comparing the item. */ fun apply(item: T): String companion object { /** * A default ToStringFunction that returns the input string; * used by methods that use plain strings in [FuzzySearch]. */ val NO_PROCESS: ToStringFunction<String> = object : ToStringFunction<String> { override fun apply(item: String): String { return item } } } }
0
null
15
93
96a1f63fa5a040be2ebbff616a73cf3eb1768bb7
766
sepia-assist-server
MIT License
project/Abschlussprojekt/CGAFramework/src/main/kotlin/cga/exercise/components/geometry/Skybox.kt
Me0li
396,713,586
true
{"Kotlin": 136754, "GLSL": 16286}
package cga.exercise.components.geometry import jdk.jfr.Unsigned import org.lwjgl.BufferUtils import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL15 import org.lwjgl.opengl.GL30.* import org.lwjgl.stb.* import java.nio.IntBuffer class Skybox { private var skyboxVertices: FloatArray = floatArrayOf( -1f, -1f, 1f, 1f, -1f, 1f, 1f, -1f, -1f, -1f, -1f, -1f, -1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, -1f, -1f, 1f, -1f ) private var skyboxIndices: IntArray = intArrayOf( //Rechts 1, 2, 6, 6, 5, 1, //Links 0, 4, 7, 7, 3, 0, //Oben 4, 5, 6, 6, 7, 4, //Unten 0, 3, 2, 2, 1, 0, //Hinten 0, 1, 5, 5, 4, 0, //Vorne 3, 7, 6, 6, 2, 3 ) private var skyboxVAO = 0 private var skyboxVBO = 0 private var skyboxIBO = 0 private var cubemapTexture = -1 init { skyboxVAO = glGenVertexArrays() skyboxVBO = glGenBuffers() skyboxIBO = glGenBuffers() glBindVertexArray(skyboxVAO) glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIBO) glBufferData(GL_ARRAY_BUFFER, skyboxVertices, GL_STATIC_DRAW) glBufferData(GL_ELEMENT_ARRAY_BUFFER, skyboxIndices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, false, 3*4, 0) } fun loadCubemap(textures: Array<String>){ cubemapTexture = glGenTextures() glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture) for (i in 0 until 6){ val x = BufferUtils.createIntBuffer(1) val y = BufferUtils.createIntBuffer(1) val nrChannels = BufferUtils.createIntBuffer(1) STBImage.stbi_set_flip_vertically_on_load(false) val data = STBImage.stbi_load(textures[i], x, y, nrChannels, 0) ?: throw Exception("Image file \"" + textures[i] + "\" couldn't be read:\n" + STBImage.stbi_failure_reason()) val width = x.get() val height = y.get() GL11.glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ) STBImage.stbi_image_free(data) } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE) glBindTexture(GL_TEXTURE_CUBE_MAP,0) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) } fun render(){ glActiveTexture(GL_TEXTURE0) glBindVertexArray(skyboxVAO) glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture) glDrawElements(GL_TRIANGLES, skyboxIndices.size, GL_UNSIGNED_INT, 0) glBindVertexArray(0) } }
0
Kotlin
0
0
2f40a8a67e97a0c033819ddf4b266fdb66433da6
3,350
CGA_Project
MIT License
src/main/kotlin/no/nav/familie/ef/mottak/config/ApplicationConfig.kt
blommish-test
359,384,928
true
{"Kotlin": 312719, "Shell": 269, "Dockerfile": 141}
package no.nav.familie.ef.mottak.config import com.fasterxml.jackson.module.kotlin.KotlinModule import no.nav.familie.http.config.RestTemplateBuilderBean import no.nav.familie.http.interceptor.BearerTokenClientInterceptor import no.nav.familie.http.interceptor.ConsumerIdClientInterceptor import no.nav.familie.http.interceptor.MdcValuesPropagatingClientInterceptor import no.nav.familie.log.filter.LogFilter import no.nav.familie.log.filter.RequestTimeFilter import no.nav.security.token.support.client.spring.oauth2.EnableOAuth2Client import no.nav.security.token.support.spring.api.EnableJwtTokenValidation import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Qualifier import org.springframework.boot.SpringBootConfiguration import org.springframework.boot.autoconfigure.domain.EntityScan import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.web.client.RestTemplateBuilder import org.springframework.boot.web.servlet.FilterRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Import import org.springframework.context.annotation.Primary import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.web.client.RestOperations import java.time.Duration import java.time.temporal.ChronoUnit @SpringBootConfiguration @ComponentScan("no.nav.familie.prosessering", "no.nav.familie.sikkerhet", "no.nav.familie.ef.mottak") @EnableJpaRepositories("no.nav.familie") @EntityScan(basePackages = ["no.nav.familie"]) @ConfigurationPropertiesScan @EnableOAuth2Client(cacheEnabled = true) @EnableJwtTokenValidation(ignore = ["org.springframework", "springfox.documentation.swagger"]) @EnableScheduling @Import(BearerTokenClientInterceptor::class, RestTemplateBuilderBean::class, MdcValuesPropagatingClientInterceptor::class, ConsumerIdClientInterceptor::class) class ApplicationConfig { private val logger = LoggerFactory.getLogger(ApplicationConfig::class.java) /** * Overskrever familie-felles sin, då timeouts ikke virker med den og proxy allerede er satt i issuer-proxyurl * Dvs, bruker ikke NaisProxyCustomizer */ @Bean("restTemplateUtenProxy") fun restTemplateBuilder(): RestTemplateBuilder { return RestTemplateBuilder() .setConnectTimeout(Duration.of(15, ChronoUnit.SECONDS)) .setReadTimeout(Duration.of(120, ChronoUnit.SECONDS)) } @Bean("restTemplateAzure") fun restTemplateAzure(@Qualifier("restTemplateUtenProxy") restTemplateBuilder: RestTemplateBuilder, mdcInterceptor: MdcValuesPropagatingClientInterceptor, bearerTokenClientInterceptor: BearerTokenClientInterceptor, consumerIdClientInterceptor: ConsumerIdClientInterceptor): RestOperations { return restTemplateBuilder .interceptors(mdcInterceptor, bearerTokenClientInterceptor, consumerIdClientInterceptor) .build() } @Bean("restTemplateUnsecured") fun restTemplate(@Qualifier("restTemplateUtenProxy") restTemplateBuilder: RestTemplateBuilder, mdcInterceptor: MdcValuesPropagatingClientInterceptor, consumerIdClientInterceptor: ConsumerIdClientInterceptor): RestOperations { return restTemplateBuilder .interceptors(mdcInterceptor, consumerIdClientInterceptor).build() } @Bean fun kotlinModule(): KotlinModule = KotlinModule() @Bean fun logFilter(): FilterRegistrationBean<LogFilter> { logger.info("Registering LogFilter filter") val filterRegistration = FilterRegistrationBean<LogFilter>() filterRegistration.filter = LogFilter() filterRegistration.order = 1 return filterRegistration } @Bean fun requestTimeFilter(): FilterRegistrationBean<RequestTimeFilter> { logger.info("Registering RequestTimeFilter filter") val filterRegistration = FilterRegistrationBean<RequestTimeFilter>() filterRegistration.filter = RequestTimeFilter() filterRegistration.order = 2 return filterRegistration } }
0
null
0
0
9719027a081bd3255bb3f429585612c90ec4f57d
4,480
familie-ef-mottak
MIT License
app/src/main/kotlin/com/leopold/mvp/annotation/UserScope.kt
agustarc
100,497,421
false
{"Kotlin": 39862}
package com.leopold.mvp.annotation import javax.inject.Scope /** * @author Leopold */ @Scope @Retention(AnnotationRetention.RUNTIME) annotation class UserScope
0
Kotlin
6
27
13a0fa0975b7251ae17ee9a96566a40c66f12193
163
MVPArchitecture
Apache License 2.0
booster-android-gradle-api/src/main/kotlin/com/didiglobal/booster/gradle/Project.kt
didi
182,968,735
false
{"Kotlin": 413557, "Java": 145867, "JavaScript": 1885}
package com.didiglobal.booster.gradle import com.android.build.api.variant.AndroidComponentsExtension import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.api.variant.LibraryAndroidComponentsExtension import com.android.build.api.variant.Variant import com.android.build.gradle.internal.SdkComponentsBuildService import com.android.build.gradle.internal.plugins.AppPlugin import com.android.build.gradle.internal.plugins.LibraryPlugin import com.android.build.gradle.internal.services.getBuildService import com.android.repository.Revision import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.artifacts.component.ComponentArtifactIdentifier import org.gradle.api.artifacts.component.ComponentIdentifier import org.gradle.api.artifacts.component.ProjectComponentIdentifier import org.gradle.api.artifacts.result.ResolvedArtifactResult import org.gradle.api.artifacts.result.ResolvedVariantResult import org.gradle.api.attributes.Attribute import org.gradle.api.attributes.AttributeContainer import org.gradle.api.capabilities.Capability import org.gradle.api.component.Artifact import org.gradle.api.plugins.JavaPlugin import org.gradle.api.plugins.JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME import org.gradle.api.provider.Provider import org.gradle.api.tasks.TaskProvider import org.gradle.maven.MavenPomArtifact import java.io.File import java.util.Optional import java.util.Stack /** * The gradle version */ val Project.gradleVersion: Revision get() = Revision.parseRevision(gradle.gradleVersion) val Project.androidSdkLocation: File get() = getBuildService(gradle.sharedServices, SdkComponentsBuildService::class.java).flatMap { it.sdkDirectoryProvider }.get().asFile val Project.isAndroid: Boolean get() = plugins.hasPlugin("com.android.application") || plugins.hasPlugin("com.android.dynamic-feature") || plugins.hasPlugin("com.android.library") val Project.isJava: Boolean get() = plugins.hasPlugin("java") || isJavaLibrary val Project.isJavaLibrary: Boolean get() = plugins.hasPlugin("java-library") @Suppress("UNCHECKED_CAST") fun <T> Project.getProperty(name: String, defaultValue: T): T { val value = findProperty(name) ?: return defaultValue return when (defaultValue) { is Boolean -> if (value is Boolean) value as T else value.toString().toBoolean() as T is Byte -> if (value is Byte) value as T else value.toString().toByte() as T is Short -> if (value is Short) value as T else value.toString().toShort() as T is Int -> if (value is Int) value as T else value.toString().toInt() as T is Float -> if (value is Float) value as T else value.toString().toFloat() as T is Long -> if (value is Long) value as T else value.toString().toLong() as T is Double -> if (value is Double) value as T else value.toString().toDouble() as T is String -> if (value is String) value as T else value.toString() as T else -> value as T } } /** * Returns the local android resources or empty list if the project is not an android project */ val Project.localAndroidResources: List<File> get() = when { isAndroid -> project.variants.mapNotNull(Variant::localAndroidResources).flatten() else -> emptyList() } @JvmOverloads fun Project.getUpstreamProjects( transitive: Boolean = true, filter: List<Variant>.() -> List<Variant> ): Set<Project> = getResolvedArtifacts(transitive, filter) { it.id.componentIdentifier as? ProjectComponentIdentifier }.map { rootProject.project(it.projectPath) }.toSet() /** * Returns the upstream artifacts of the target project, the dependencies can be filtered based on the target * project’s variant, such as filtering the dependencies corresponding to the `debug` variant of the target project. * * @param T the result of transform function * @param transitive whether to resolve the artifacts transitively * @param filter filter the dependencies by variant * @see [filterByNameOrBuildType] */ @JvmOverloads fun <T> Project.getResolvedArtifacts( transitive: Boolean = true, filter: List<Variant>.() -> List<Variant>, transform: (ResolvedArtifactResult) -> T? ): Set<T> = getResolvedArtifactResults(transitive, filter).mapNotNull { transform(it) }.toSet() @JvmOverloads fun Project.getResolvedArtifactResults( transitive: Boolean = true, filter: List<Variant>.() -> List<Variant> ): Set<ResolvedArtifactResult> = when { isAndroid -> getResolvedArtifactResultsRecursively(transitive) { variants.filter().map { v -> AGP.run { v.getDependencies(transitive) } }.flatten() } isJava -> getResolvedArtifactResultsRecursively(transitive) { configurations.getByName(RUNTIME_CLASSPATH_CONFIGURATION_NAME).resolvedConfiguration.resolvedArtifacts.map { ResolvedArtifactResultImpl(it.id, it.file) } } else -> emptySet() }.distinctBy { it.id.componentIdentifier }.toSet() /** * Returns the resolved artifact results recursively */ @JvmOverloads fun Project.getResolvedArtifactResultsRecursively( transitive: Boolean = true, resolve: Project.() -> List<ResolvedArtifactResult> ): Set<ResolvedArtifactResult> { val stack = Stack<Project>() val results = mutableMapOf<ComponentIdentifier, ResolvedArtifactResult>() stack.add(this) while (stack.isNotEmpty()) { val resolved = stack.pop().resolve().filterNot { results.containsKey(it.id.componentIdentifier) }.onEach { results[it.id.componentIdentifier] = it } if (!transitive) continue resolved.map { it.id.componentIdentifier }.filterIsInstance<ProjectComponentIdentifier>().map { rootProject.project(it.projectPath) }.let(stack::addAll) } return results.values.toSet() } /** * Returns the jar files which could be the outputs of the jar task or createFullJar task */ fun Project.getJars( filter: List<Variant>.() -> List<Variant> ): Set<File> = getJarTaskProviders(filter).map { it.get().outputs.files }.flatten().toSet() /** * Returns the jar task provider of all matched variants * * Android Project * - application: createFullJar * - library: bundleClasses * * Java Project * - jar */ fun Project.getJarTaskProviders( filter: List<Variant>.() -> List<Variant> ): Collection<TaskProvider<out Task>> = when { isAndroid -> when (getAndroidComponentsOrNull<AndroidComponentsExtension<*, *, *>>()) { is LibraryAndroidComponentsExtension -> variants.filter().mapNotNull(Variant::createFullJarTaskProvider) is ApplicationAndroidComponentsExtension -> variants.filter().mapNotNull(Variant::bundleClassesTaskProvider) else -> emptyList() } isJavaLibrary -> listOf(tasks.named(JavaPlugin.JAR_TASK_NAME)) else -> emptyList() } val Project.variants: List<Variant> get() = when (getAndroidComponentsOrNull<AndroidComponentsExtension<*, *, *>>()) { is ApplicationAndroidComponentsExtension -> plugins.getPlugin(AppPlugin::class.java) is LibraryAndroidComponentsExtension -> plugins.getPlugin(LibraryPlugin::class.java) else -> null }?.variantManager?.mainComponents?.map { it.variant }?.filterIsInstance<Variant>() ?: emptyList() private data class ResolvedArtifactResultImpl( private val artifactId: ComponentArtifactIdentifier, private val artifactFile: File ) : ResolvedArtifactResult { private val variant by lazy { object : ResolvedVariantResult { override fun getAttributes(): AttributeContainer = EmptyAttributes override fun getDisplayName(): String = id.displayName override fun getCapabilities(): MutableList<Capability> = mutableListOf() override fun getOwner(): ComponentIdentifier = artifactId.componentIdentifier override fun getExternalVariant(): Optional<ResolvedVariantResult> = Optional.empty() } } override fun getId(): ComponentArtifactIdentifier = artifactId override fun getType(): Class<out Artifact> = MavenPomArtifact::class.java override fun getFile(): File = artifactFile override fun getVariant(): ResolvedVariantResult = variant } private object EmptyAttributes : AttributeContainer { override fun getAttributes(): AttributeContainer = this override fun keySet(): MutableSet<Attribute<*>> = mutableSetOf() override fun <T : Any?> attribute(key: Attribute<T>, value: T): AttributeContainer = this override fun <T : Any?> getAttribute(key: Attribute<T>): T? = null override fun isEmpty(): Boolean = true override fun contains(key: Attribute<*>): Boolean = false override fun <T : Any?> attributeProvider(key: Attribute<T>, provider: Provider<out T>): AttributeContainer = this }
41
Kotlin
577
4,831
3a72faebf8590537983ca74c0012b69636da3b5d
8,985
booster
Apache License 2.0
core/src/main/kotlin/net/corda/core/internal/cordapp/CordappProviderInternal.kt
corda
70,137,417
false
{"Kotlin": 10675960, "Java": 275115, "C++": 239894, "Python": 37811, "Shell": 28324, "CSS": 23544, "Groovy": 14725, "CMake": 5393, "Dockerfile": 2574, "Batchfile": 1777, "PowerShell": 660, "C": 454}
package net.corda.core.internal.cordapp import net.corda.core.contracts.ContractAttachment import net.corda.core.contracts.ContractClassName import net.corda.core.cordapp.Cordapp import net.corda.core.cordapp.CordappProvider import net.corda.core.flows.FlowLogic import net.corda.core.internal.verification.AttachmentFixups interface CordappProviderInternal : CordappProvider { val appClassLoader: ClassLoader val attachmentFixups: AttachmentFixups val cordapps: List<CordappImpl> fun getCordappForFlow(flowLogic: FlowLogic<*>): Cordapp? /** * Similar to [getContractAttachmentID] except it returns the [ContractAttachment] object and also returns an optional second attachment * representing the legacy version (4.11 or earlier) of the contract, if one exists. */ fun getContractAttachments(contractClassName: ContractClassName): ContractAttachmentWithLegacy? } data class ContractAttachmentWithLegacy(val currentAttachment: ContractAttachment, val legacyAttachment: ContractAttachment? = null)
62
Kotlin
1077
3,989
d27aa0e6850d3804d0982024054376d452e7073a
1,039
corda
Apache License 2.0
src/main/java/me/shadowalzazel/mcodyssey/effects/tasks/HoneyedTask.kt
ShadowAlzazel
511,383,377
false
{"Kotlin": 932750}
package me.shadowalzazel.mcodyssey.effects.tasks import me.shadowalzazel.mcodyssey.constants.EffectTags import org.bukkit.Particle import org.bukkit.Sound import org.bukkit.entity.LivingEntity import org.bukkit.scheduler.BukkitRunnable // HONEYED task class HoneyedTask(private val honeyedVictim: LivingEntity, private val honeyCount: Int) : BukkitRunnable() { private var honeyCooldown = System.currentTimeMillis() // TODO: IS this shared?? private var counter = 0 override fun run() { honeyedVictim.also { counter += 1 // Check if still honeyed if (EffectTags.HONEYED !in it.scoreboardTags) { this.cancel() } // Particles and Sound with(it.world) { val someLocation = it.location.clone().add(0.0, 0.5, 0.0) spawnParticle(Particle.DRIPPING_HONEY, someLocation, 5, 0.35, 1.0, 0.35) spawnParticle(Particle.FALLING_HONEY, someLocation, 2, 0.35, 1.0, 0.35) spawnParticle(Particle.LANDING_HONEY, someLocation, 2, 0.35, 0.4, 0.35) playSound(someLocation, Sound.BLOCK_HONEY_BLOCK_STEP, 1.5F, 0.9F) } // Sticky it.velocity.y = 0.0 // Timing val timeElapsed = System.currentTimeMillis() - honeyCooldown if (honeyCount < counter || it.health <= 1.0 || timeElapsed > (honeyCount / 2) * 1000) { if (!it.isDead) { it.scoreboardTags.remove(EffectTags.HONEYED) } this.cancel() } } } }
0
Kotlin
0
3
61e54feb192473e37d0ef91992645d82f6f14099
1,565
MinecraftOdyssey
MIT License
core/src/test/kotlin/de/codecentric/hikaku/extensions/PathExtensionsTest.kt
codecentric
167,929,609
false
{"Kotlin": 731151, "RAML": 5024, "Shell": 1492}
package de.codecentric.hikaku.extensions import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.nio.file.Files.createTempDirectory import java.nio.file.Paths import kotlin.test.assertFailsWith class PathExtensionsTest { @Nested inner class CheckValidityTests { @Test fun `non-existing file throws an exception`() { assertFailsWith<IllegalArgumentException> { Paths.get("test-file-which-does-not-exist.spec").checkFileValidity() } } @Test fun `directory in validity check throws an exception`() { assertFailsWith<IllegalArgumentException> { createTempDirectory("tmp").checkFileValidity() } } @Test fun `existing file with invalid file extension throws an exception`() { assertFailsWith<IllegalArgumentException> { Paths.get(this::class.java.classLoader.getResource("test_file.txt").toURI()).checkFileValidity(".css") } } @Test fun `file is valid without extension check`() { //given val file = Paths.get(this::class.java.classLoader.getResource("test_file.txt").toURI()) //when file.checkFileValidity() //then //no exception is thrown } @Test fun `file is valid with extension check`() { //given val file = Paths.get(this::class.java.classLoader.getResource("test_file.txt").toURI()) //when file.checkFileValidity(".txt") //then //no exception is thrown } } }
19
Kotlin
19
193
b8a754f91b524b53a464167bf0abd6044caa25a4
1,693
hikaku
Apache License 2.0
katalog-testing/src/main/kotlin/com/bol/katalog/testing/TestClock.kt
csu-anzai
206,344,543
true
{"Kotlin": 518462, "TypeScript": 149231, "HTML": 52073, "Java": 44310, "CSS": 1442, "HCL": 1015, "Dockerfile": 653, "Shell": 528}
package com.bol.katalog.testing import java.time.Clock import java.time.Duration import java.time.Instant import java.time.ZoneId class TestClock(private var instant: Instant) : Clock() { override fun withZone(zone: ZoneId?): Clock = throw NotImplementedError() override fun getZone(): ZoneId = ZoneId.systemDefault() override fun instant() = instant suspend fun <T> withOffset(offset: Duration, block: suspend () -> T): T { val old = instant try { instant = instant.plus(offset) return block() } finally { instant = old } } }
0
null
0
0
e85038804bc7c146732461d3ce8decb8a5034ba6
621
katalog
Apache License 2.0
apps/mobile/src/main/kotlin/dev/marlonlom/cappajv/ui/theme/Theme.kt
marlonlom
766,685,767
false
{"Kotlin": 317290}
/* * Copyright 2024 Marlonlom * SPDX-License-Identifier: Apache-2.0 */ package dev.marlonlom.apps.cappajv.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat /** * Brand color schemes single object. * * @author marlonlom */ internal object BrandColorSchemes { val dark = darkColorScheme( primary = BrandColors.warmApricot2, onPrimary = BrandColors.stirlandMud, primaryContainer = BrandColors.notoriousNeanderthal, onPrimaryContainer = BrandColors.peachPuff, secondary = BrandColors.warmApricot, onSecondary = BrandColors.stirlandMud2, secondaryContainer = BrandColors.brown, onSecondaryContainer = BrandColors.peachPuff2, tertiary = BrandColors.gooseBill, onTertiary = BrandColors.ibexBrown, tertiaryContainer = BrandColors.bestialBrown, onTertiaryContainer = BrandColors.whisperingPeach, error = BrandColors.peachBud, errorContainer = BrandColors.chokecherry, onError = BrandColors.arcaviaRed, onErrorContainer = BrandColors.forgottenPink, background = BrandColors.kalaBlack, onBackground = BrandColors.springWood, surface = BrandColors.kalaBlack, onSurface = BrandColors.springWood, surfaceVariant = BrandColors.peppercornRent, onSurfaceVariant = BrandColors.hazyTaupe, outline = BrandColors.puttyYellow, inverseOnSurface = BrandColors.kalaBlack, inverseSurface = BrandColors.springWood, inversePrimary = BrandColors.spearShaft, surfaceTint = BrandColors.warmApricot2, outlineVariant = BrandColors.peppercornRent, scrim = BrandColors.black, ) val light = lightColorScheme( primary = BrandColors.spearShaft, onPrimary = BrandColors.white, primaryContainer = BrandColors.peachPuff, onPrimaryContainer = BrandColors.zinnwalditeBrown, secondary = BrandColors.spearShaft2, onSecondary = BrandColors.white, secondaryContainer = BrandColors.peachPuff2, onSecondaryContainer = BrandColors.zinnwalditeBrown, tertiary = BrandColors.brownie, onTertiary = BrandColors.white, tertiaryContainer = BrandColors.whisperingPeach, onTertiaryContainer = BrandColors.chocolateMelange, error = BrandColors.heartwarming, errorContainer = BrandColors.forgottenPink, onError = BrandColors.white, onErrorContainer = BrandColors.biltong, background = BrandColors.lavenderBlush, onBackground = BrandColors.kalaBlack, surface = BrandColors.lavenderBlush, onSurface = BrandColors.kalaBlack, surfaceVariant = BrandColors.naturale, onSurfaceVariant = BrandColors.peppercornRent, outline = BrandColors.camelsHump, inverseOnSurface = BrandColors.moonlitBeach, inverseSurface = BrandColors.acadia, inversePrimary = BrandColors.warmApricot2, surfaceTint = BrandColors.spearShaft, outlineVariant = BrandColors.hazyTaupe, scrim = BrandColors.black, ) } /** * Brand theme composable function for Cappajv app. * * @author marlonlom * * @param darkTheme True/False if dark theme is applied. * @param dynamicColor True/False if dynamic colors are applied. * @param content Composable ui contents. */ @ExperimentalMaterial3Api @Composable fun CappajvTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> BrandColorSchemes.dark else -> BrandColorSchemes.light } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.surface.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = BrandFont.appTypography, shapes = CappaShapes, content = content ) }
0
Kotlin
0
0
669e0b66b8f8822a67ab6e820c2f632137f81f3b
4,747
cappajv
Apache License 2.0
components/share/uploader/src/main/kotlin/com/flipperdevices/uploader/compose/content/ComposableSheetPending.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.uploader.compose.content import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.flipperdevices.core.ui.theme.LocalPallet import com.flipperdevices.core.ui.theme.LocalTypography import com.flipperdevices.share.uploader.R @Composable internal fun ComposableSheetPending( onShareLink: () -> Unit, onShareFile: () -> Unit, isLongLink: Boolean ) { Row( modifier = Modifier.fillMaxWidth().padding(top = 42.dp, bottom = 64.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { ComposableSheetAction( imageId = R.drawable.ic_share_link, titleId = R.string.share_via_secure_link_title, descId = if (isLongLink) R.string.share_via_secure_link_desc else null, onAction = onShareLink ) ComposableSheetAction( imageId = R.drawable.ic_share_file, titleId = R.string.share_export_file_title, descId = null, onAction = onShareFile ) } } @Composable private fun ComposableSheetAction( @DrawableRes imageId: Int, @StringRes titleId: Int, @StringRes descId: Int?, onAction: () -> Unit ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = Modifier .size(48.dp) .clip(CircleShape) .background(LocalPallet.current.shareSheetBackgroundAction.copy(alpha = 0.1f)) .clickable(onClick = onAction), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = imageId), contentDescription = null ) } Spacer(modifier = Modifier.height(12.dp)) Text( text = stringResource(id = titleId), style = LocalTypography.current.bodyM14.copy( color = LocalPallet.current.shareSheetBackgroundAction ) ) Spacer(modifier = Modifier.height(2.dp)) Text( text = descId?.let { stringResource(id = it) } ?: "", style = LocalTypography.current.subtitleR10.copy( color = LocalPallet.current.text30 ) ) } }
21
null
174
999
ef27b6b6a78a59b603ac858de2c88f75b743f432
3,241
Flipper-Android-App
MIT License
app/src/main/java/com/xiaoxin/toolkit/http/BaseException.kt
XiaoXin956
474,917,723
false
null
//package com.xiaoxin.toolkit.http // //import android.net.ParseException //import android.util.Log //import android.util.MalformedJsonException //import com.google.gson.JsonParseException //import com.xiaoxin.toolkit.HttpResponse //import org.json.JSONException //import retrofit2.HttpException //import java.io.FileNotFoundException //import java.net.ConnectException //import java.net.SocketTimeoutException //import java.net.UnknownHostException // ///** // * @author: Admin // * @date: 2022-03-24 // */ //class BaseException { // // companion object { // fun <T> exception(any: Any): HttpResponse<T> { // return if (any is HttpException) { // httpException(any) // } else if (any is JsonParseException || any is JSONException || any is ParseException || any is MalformedJsonException) { // HttpResponse(HttpResult.ParseException.code, HttpResult.ParseException.msg) // } else if (any is ConnectException) { // 连接异常 // HttpResponse(HttpResult.ConnectException.code, HttpResult.ConnectException.msg) // } else if (any is UnknownHostException) { // 主机异常 // HttpResponse(HttpResult.UnknownHostException.code, HttpResult.UnknownHostException.msg) // } else if (any is SocketTimeoutException) { // 连接 // HttpResponse(HttpResult.SocketTimeoutException.code, HttpResult.SocketTimeoutException.msg) // } else if (any is FileNotFoundException) { // 连接 // HttpResponse(HttpResult.FileNotFoundException.code, HttpResult.FileNotFoundException.msg) // } else { // 未捕捉异常,统一处理 // HttpResponse(HttpResult.ERROR.code, HttpResult.ERROR.msg) // } // } // // private fun <T> httpException(e: HttpException): HttpResponse<T> { // val httpError: HttpResponse<T>? // when (e.code()) { // 200 -> { // httpError = HttpResponse(code = HttpResult.HTTP200.code, msg = HttpResult.HTTP200.msg) // } // 201 -> { // httpError = HttpResponse(code = HttpResult.HTTP201.code, msg = HttpResult.HTTP201.msg) // } // 202 -> { // httpError = HttpResponse(code = HttpResult.HTTP202.code, msg = HttpResult.HTTP202.msg) // } // 300 -> { // httpError = HttpResponse(code = HttpResult.HTTP300.code, msg = HttpResult.HTTP300.msg) // } // 301 -> { // httpError = HttpResponse(code = HttpResult.HTTP301.code, msg = HttpResult.HTTP301.msg) // } // 302 -> { // httpError = HttpResponse(code = HttpResult.HTTP302.code, msg = HttpResult.HTTP302.msg) // } // 303 -> { // httpError = HttpResponse(code = HttpResult.HTTP303.code, msg = HttpResult.HTTP303.msg) // } // 304 -> { // httpError = HttpResponse(code = HttpResult.HTTP304.code, msg = HttpResult.HTTP304.msg) // } // 305 -> { // httpError = HttpResponse(code = HttpResult.HTTP305.code, msg = HttpResult.HTTP305.msg) // } // 306 -> { // httpError = HttpResponse(code = HttpResult.HTTP306.code, msg = HttpResult.HTTP306.msg) // } // 400 -> { // httpError = HttpResponse(code = HttpResult.HTTP400.code, msg = HttpResult.HTTP400.msg) // } // 401 -> { // httpError = HttpResponse(code = HttpResult.HTTP401.code, msg = HttpResult.HTTP401.msg) // } // 402 -> { // httpError = HttpResponse(code = HttpResult.HTTP402.code, msg = HttpResult.HTTP402.msg) // } // 404 -> { // httpError = HttpResponse(code = HttpResult.HTTP404.code, msg = HttpResult.HTTP404.msg) // } // 405 -> { // httpError = HttpResponse(code = HttpResult.HTTP405.code, msg = HttpResult.HTTP405.msg) // } // 406 -> { // httpError = HttpResponse(code = HttpResult.HTTP406.code, msg = HttpResult.HTTP406.msg) // } // 407 -> { // httpError = HttpResponse(code = HttpResult.HTTP407.code, msg = HttpResult.HTTP407.msg) // } // 408 -> { // httpError = HttpResponse(code = HttpResult.HTTP408.code, msg = HttpResult.HTTP408.msg) // } // 409 -> { // httpError = HttpResponse(code = HttpResult.HTTP409.code, msg = HttpResult.HTTP409.msg) // } // 410 -> { // httpError = HttpResponse(code = HttpResult.HTTP410.code, msg = HttpResult.HTTP410.msg) // } // 411 -> { // httpError = HttpResponse(code = HttpResult.HTTP411.code, msg = HttpResult.HTTP411.msg) // } // 412 -> { // httpError = HttpResponse(code = HttpResult.HTTP412.code, msg = HttpResult.HTTP412.msg) // } // 413 -> { // httpError = HttpResponse(code = HttpResult.HTTP413.code, msg = HttpResult.HTTP413.msg) // } // 414 -> { // httpError =HttpResponse(code = HttpResult.HTTP414.code, msg = HttpResult.HTTP414.msg) // } // 415 -> { // httpError = HttpResponse(code = HttpResult.HTTP415.code, msg = HttpResult.HTTP415.msg) // } // 416 -> { // httpError = HttpResponse(code = HttpResult.HTTP416.code, msg = HttpResult.HTTP416.msg) // } // 417 -> { // httpError = HttpResponse(code = HttpResult.HTTP417.code, msg = HttpResult.HTTP417.msg) // } // 500 -> { // httpError = HttpResponse(code = HttpResult.HTTP500.code, msg = HttpResult.HTTP500.msg) // } // 501 -> { // httpError = HttpResponse(code = HttpResult.HTTP501.code, msg = HttpResult.HTTP501.msg) // } // 502 -> { // httpError = HttpResponse(code = HttpResult.HTTP502.code, msg = HttpResult.HTTP502.msg) // } // 503 -> { // httpError = HttpResponse(code = HttpResult.HTTP503.code, msg = HttpResult.HTTP503.msg) // } // 504 -> { // httpError = HttpResponse(code = HttpResult.HTTP504.code, msg = HttpResult.HTTP504.msg) // } // 505 -> { // httpError = HttpResponse(code = HttpResult.HTTP505.code, msg = HttpResult.HTTP505.msg) // } // else -> { // httpError = HttpResponse(code = HttpResult.ERROR.code, msg = HttpResult.ERROR.msg) // } // } // return httpError // } // } // // //}
0
Kotlin
0
4
bdbf05f52535978e947e3c1f0803e0f9dc4377d2
7,338
Toolkit
Apache License 2.0
app/src/main/java/my/dictionary/free/view/dialogs/DialogBuilders.kt
viacheslavtitov
605,498,191
false
{"Kotlin": 171766}
package my.dictionary.free.view.dialogs class DialogBuilders { abstract class AbstractDialogBuilder : ISimpleInfoDialogBuilder { internal var title: String? = null internal var description: String? = null internal var okButtonTitle: String? = null internal var iconRes: Int? = null internal var iconTintColorRes: Int? = null internal var listener: SimpleInfoDialogListener? = null override fun listener(listener: SimpleInfoDialogListener?): ISimpleInfoDialogBuilder { this.listener = listener return this } override fun title(title: String?): ISimpleInfoDialogBuilder { this.title = title return this } override fun description(description: String?): ISimpleInfoDialogBuilder { this.description = description return this } override fun okButtonTitle(okButtonTitle: String?): ISimpleInfoDialogBuilder { this.okButtonTitle = okButtonTitle return this } override fun iconRes(iconRes: Int?): ISimpleInfoDialogBuilder { this.iconRes = iconRes return this } override fun iconTintColorRes(iconTintColorRes: Int?): ISimpleInfoDialogBuilder { this.iconTintColorRes = iconTintColorRes return this } } object SimpleInfoDialogBuilder : AbstractDialogBuilder(), ISimpleInfoDialogBuilder { override fun build(): SimpleInfoDialogFragment { return SimpleInfoDialogFragment.create( title = title, description = description, iconRes = iconRes, iconTintColorRes = iconTintColorRes, buttonOkTitle = okButtonTitle, listener = listener ) } } object TwoButtonDialogBuilder : AbstractDialogBuilder(), ITwoButtonDialogBuilder { private var buttonCancelTitle: String? = null override fun cancelButtonTitle(cancelButtonTitle: String?): ITwoButtonDialogBuilder { this.buttonCancelTitle = cancelButtonTitle return this } override fun listener(listener: TwoButtonsDialogListener?): ITwoButtonDialogBuilder { this.listener = listener return this } override fun title(title: String?): ITwoButtonDialogBuilder { return super.title(title) as ITwoButtonDialogBuilder } override fun description(description: String?): ITwoButtonDialogBuilder { return super.description(description) as ITwoButtonDialogBuilder } override fun okButtonTitle(okButtonTitle: String?): ITwoButtonDialogBuilder { return super.okButtonTitle(okButtonTitle) as ITwoButtonDialogBuilder } override fun iconRes(iconRes: Int?): ITwoButtonDialogBuilder { return super.iconRes(iconRes) as ITwoButtonDialogBuilder } override fun iconTintColorRes(iconTintColorRes: Int?): ISimpleInfoDialogBuilder { return super.iconTintColorRes(iconTintColorRes) as ITwoButtonDialogBuilder } override fun build(): TwoButtonDialogFragment { return TwoButtonDialogFragment.create( title = title, description = description, iconRes = iconRes, iconTintColorRes = iconTintColorRes, buttonOkTitle = okButtonTitle, buttonCancelTitle = buttonCancelTitle, listener = listener as TwoButtonsDialogListener? ) } } }
0
Kotlin
0
0
a77bd30985f2f3005ae6a693a4a1a59c84573520
3,665
Easy-Dictionary-Android
MIT License
Tutorial1-1Paging-Room/src/main/java/com/smarttoolfactory/tutorial1_1pagingwithdb/WordRepository.kt
SmartToolFactory
216,348,965
false
null
package com.smarttoolfactory.tutorial1_1pagingwithdb import android.app.Application import androidx.lifecycle.LiveData import androidx.paging.DataSource import androidx.paging.LivePagedListBuilder import androidx.paging.PagedList import com.smarttoolfactory.tutorial1_1pagingwithdb.data.Word import com.smarttoolfactory.tutorial1_1pagingwithdb.data.WordDao import com.smarttoolfactory.tutorial1_1pagingwithdb.data.WordRoomDatabase import java.util.concurrent.Executors // Note that in order to unit test the WordRepository, you have to remove the Application // dependency. This adds complexity and much more code, and this sample is not about testing. // See the BasicSample in the android-architecture-components repository at // https://github.com/googlesamples class WordRepository(application: Application) { private val executor = Executors.newSingleThreadExecutor() private val wordDao: WordDao // Room executes all queries on a separate thread. // Observed LiveData will notify the observer when the data has changed. val allWordsPaged: LiveData<PagedList<Word>> val allWords: LiveData<List<Word>> init { val db = WordRoomDatabase.getDatabase( application ) wordDao = db.wordDao() // Create a config for paged list val config = PagedList.Config.Builder() .setPageSize(15) // ⚠️ set placeholders false to diplay shorter scrollbar // Disables null placeholders .setEnablePlaceholders(false) .setPrefetchDistance(8) // Max size MUST BE >= 2 * page size + prefetch distance .setMaxSize(50) .build() // Returns for Page Size = 15, Prefetch distance = 8 // 🎃 WordPagedListAdapter onBindViewHolder() position: 37 // 🥶 WordPagedListAdapter getCurrentList(): 45 // 🎃 WordPagedListAdapter onBindViewHolder() position: 23 // 🥶 WordPagedListAdapter getCurrentList(): 45 // Create factory for paged list val dataSourceFactory: DataSource.Factory<Int, Word> = wordDao.getWordsPaged() val pagedListBuilder = LivePagedListBuilder(dataSourceFactory, config) // PageList<Word> allWordsPaged = pagedListBuilder.build() // List<Word> allWords = wordDao.getWords() } // You must call this on a non-UI thread or your app will crash. // Like this, Room ensures that you're not doing any long running operations on the main // thread, blocking the UI. fun insert(word: Word) { executor.execute { println("WordRepository insert ${word.word} TO index: ${wordDao.insert(word)}") } } fun getItemCount(): LiveData<Int> { return wordDao.getRowCount() } }
1
null
1
2
cd06e85b6da809c3749a4cbfc2002b7dc2e82731
2,802
Paging-Library-Tutorials
Apache License 2.0
failgood/test/failgood/junit/it/fixtures/SimpleClassTestFixture.kt
failgood
323,114,755
false
{"Kotlin": 411790, "Java": 130}
package failgood.junit.it.fixtures import failgood.internal.TestFixture import failgood.testCollection @TestFixture class SimpleClassTestFixture { val tests = testCollection("the root context (with brackets)") { it("the test name") {} } }
38
Kotlin
4
31
bfb8a1e22350143fc27b12f295ad78d22541a792
245
failgood
MIT License
backend/src/main/kotlin/br/tapajos/example/application/port/input/CreateObjectsUseCase.kt
yanBrandao
311,519,801
false
null
package br.tapajos.example.application.port.input import br.tapajos.example.application.domain.Objectt interface CreateObjectsUseCase { fun execute(objectt: Objectt): Objectt }
0
Kotlin
0
0
4789957f09e2ef8fb874836aa4dd19eb4dc58f83
182
image_and_action
MIT License
app/src/main/java/com/ninjahoahong/unstoppable/home/HomeKey.kt
ninjahoahong
99,034,743
false
null
package com.ninjahoahong.unstoppable.home import com.ninjahoahong.unstoppable.utils.BaseKey import kotlinx.android.parcel.Parcelize @Parcelize data class HomeKey(val tag: String) : BaseKey() { constructor() : this("HomeKey") override fun createFragment() = HomeFragment() }
0
Kotlin
0
0
0aa900980f928c7b7bdc175a5265b7fbfb60e7e0
284
unstoppable
MIT License
app/src/main/java/com/elementary/tasks/settings/calendar/CalendarSettingsFragment.kt
naz013
165,067,747
false
{"Kotlin": 2971145, "HTML": 20925}
package com.elementary.tasks.settings.calendar import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.elementary.tasks.R import com.elementary.tasks.core.os.Permissions import com.elementary.tasks.core.utils.GoogleCalendarUtils import com.elementary.tasks.core.utils.ThemeProvider import com.elementary.tasks.core.utils.ui.Dialogues import com.elementary.tasks.databinding.DialogWithSeekAndTitleBinding import com.elementary.tasks.databinding.FragmentSettingsCalendarBinding import com.elementary.tasks.navigation.fragments.BaseSettingsFragment import org.koin.android.ext.android.inject import java.util.Locale class CalendarSettingsFragment : BaseSettingsFragment<FragmentSettingsCalendarBinding>() { private val googleCalendarUtils by inject<GoogleCalendarUtils>() private var mItemSelect: Int = 0 private var mDataList: MutableList<GoogleCalendarUtils.CalendarItem> = mutableListOf() private val currentPosition: Int get() { return findPosition(mDataList) } override fun inflate( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = FragmentSettingsCalendarBinding.inflate(inflater, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initFuturePrefs() initRemindersPrefs() initFirstDayPrefs() binding.eventsImportPrefs.setOnClickListener { safeNavigation { CalendarSettingsFragmentDirections.actionCalendarSettingsFragmentToFragmentEventsImport() } } binding.reminderColorPrefs.setDependentView(binding.reminderInCalendarPrefs) binding.reminderColorPrefs.setOnClickListener { showColorPopup(prefs.reminderColor, getString(R.string.reminders_color)) { color -> prefs.reminderColor = color initRemindersColorPrefs() } } initRemindersColorPrefs() binding.todayColorPrefs.setOnClickListener { showColorPopup(prefs.todayColor, getString(R.string.today_color)) { color -> prefs.todayColor = color initTodayColorPrefs() } } initTodayColorPrefs() binding.birthdayColorPrefs.setOnClickListener { showColorPopup(prefs.birthdayColor, getString(R.string.birthdays_color)) { color -> prefs.birthdayColor = color initBirthdaysColorPrefs() } } initBirthdaysColorPrefs() initExportToCalendarPrefs() initEventDurationPrefs() initSelectCalendarPrefs() initExportToStockPrefs() } private fun showColorPopup(current: Int, title: String, onSave: (Int) -> Unit) { withActivity { act -> dialogues.showColorDialog(act, current, title, ThemeProvider.colorsForSliderThemed(act)) { onSave.invoke(it) } } } private fun initFirstDayPrefs() { binding.startDayPrefs.setOnClickListener { showFirstDayDialog() } showFirstDay() } private fun showFirstDay() { val items = arrayOf(getString(R.string.sunday), getString(R.string.monday)) binding.startDayPrefs.setDetailText(items[prefs.startDay]) } private fun showFirstDayDialog() { withContext { val builder = dialogues.getMaterialDialog(it) builder.setCancelable(true) builder.setTitle(getString(R.string.first_day)) val items = arrayOf(getString(R.string.sunday), getString(R.string.monday)) mItemSelect = prefs.startDay builder.setSingleChoiceItems(items, mItemSelect) { _, which -> mItemSelect = which } builder.setPositiveButton(getString(R.string.ok)) { dialogInterface, _ -> prefs.startDay = mItemSelect showFirstDay() dialogInterface.dismiss() } builder.setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.dismiss() } builder.create().show() } } private fun initRemindersColorPrefs() { binding.reminderColorPrefs.setViewColor( ThemeProvider.colorReminderCalendar(requireContext(), prefs) ) } private fun initRemindersPrefs() { binding.reminderInCalendarPrefs.isChecked = prefs.isRemindersInCalendarEnabled binding.reminderInCalendarPrefs.setOnClickListener { changeRemindersPrefs() } } private fun changeRemindersPrefs() { val isChecked = binding.reminderInCalendarPrefs.isChecked binding.reminderInCalendarPrefs.isChecked = !isChecked prefs.isRemindersInCalendarEnabled = !isChecked } private fun initFuturePrefs() { binding.featureRemindersPrefs.isChecked = prefs.isFutureEventEnabled binding.featureRemindersPrefs.setOnClickListener { changeFuturePrefs() } } private fun changeFuturePrefs() { val isChecked = binding.featureRemindersPrefs.isChecked binding.featureRemindersPrefs.isChecked = !isChecked prefs.isFutureEventEnabled = !isChecked } override fun getTitle(): String = getString(R.string.calendar) private fun initBirthdaysColorPrefs() { binding.birthdayColorPrefs.setViewColor( ThemeProvider.colorBirthdayCalendar(requireContext(), prefs) ) } private fun initTodayColorPrefs() { binding.todayColorPrefs.setViewColor( ThemeProvider.colorCurrentCalendar(requireContext(), prefs) ) } private fun initExportToStockPrefs() { binding.exportToStockPrefs.isChecked = prefs.isStockCalendarEnabled binding.exportToStockPrefs.setOnClickListener { changeExportToStockPrefs() } } private fun changeExportToStockPrefs() { val isChecked = binding.exportToStockPrefs.isChecked binding.exportToStockPrefs.isChecked = !isChecked prefs.isStockCalendarEnabled = !isChecked } private fun initSelectCalendarPrefs() { binding.selectCalendarPrefs.setOnClickListener { tryToShowSelectCalendarDialog() } binding.selectCalendarPrefs.setDependentView(binding.exportToCalendarPrefs) showCurrentCalendar() } private fun initEventDurationPrefs() { binding.eventDurationPrefs.setOnClickListener { showEventDurationDialog() } binding.eventDurationPrefs.setDependentView(binding.exportToCalendarPrefs) showEventDuration() } private fun showEventDuration() { binding.eventDurationPrefs.setDetailText( String.format( Locale.getDefault(), getString(R.string.x_minutes), prefs.calendarEventDuration.toString() ) ) } private fun showEventDurationDialog() { val builder = dialogues.getMaterialDialog(requireContext()) builder.setTitle(R.string.event_duration) val b = DialogWithSeekAndTitleBinding.inflate(layoutInflater) b.seekBar.addOnChangeListener { _, value, _ -> b.titleView.text = String.format( Locale.getDefault(), getString(R.string.x_minutes), value.toInt().toString() ) } b.seekBar.stepSize = 1f b.seekBar.valueFrom = 0f b.seekBar.valueTo = 120f val duration = prefs.calendarEventDuration b.seekBar.value = duration.toFloat() b.titleView.text = String.format( Locale.getDefault(), getString(R.string.x_minutes), duration.toString() ) builder.setView(b.root) builder.setPositiveButton(R.string.ok) { _, _ -> prefs.calendarEventDuration = b.seekBar.value.toInt() showEventDuration() } builder.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() } val dialog = builder.create() dialog.show() Dialogues.setFullWidthDialog(dialog, requireActivity()) } private fun changeExportToCalendarPrefs() { permissionFlow.askPermissions(listOf(Permissions.READ_CALENDAR, Permissions.WRITE_CALENDAR)) { val isChecked = binding.exportToCalendarPrefs.isChecked binding.exportToCalendarPrefs.isChecked = !isChecked prefs.isCalendarEnabled = !isChecked if (binding.exportToCalendarPrefs.isChecked && !showSelectCalendarDialog()) { prefs.isCalendarEnabled = false binding.exportToCalendarPrefs.isChecked = false } } } private fun tryToShowSelectCalendarDialog() { permissionFlow.askPermissions(listOf(Permissions.READ_CALENDAR, Permissions.WRITE_CALENDAR)) { showSelectCalendarDialog() } } private fun showSelectCalendarDialog(): Boolean { mDataList.clear() mDataList.addAll(googleCalendarUtils.getCalendarsList()) if (mDataList.isEmpty()) { return false } val names = mDataList.map { it.name }.toTypedArray() val builder = dialogues.getMaterialDialog(requireContext()) builder.setTitle(R.string.choose_calendar) mItemSelect = currentPosition builder.setSingleChoiceItems(names, mItemSelect) { _, i -> mItemSelect = i } builder.setPositiveButton(R.string.save) { dialog, _ -> if (mItemSelect != -1 && mItemSelect < mDataList.size) { prefs.defaultCalendarId = mDataList[mItemSelect].id } dialog.dismiss() showCurrentCalendar() } builder.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() } builder.create().show() return true } private fun showCurrentCalendar() { val calendars = googleCalendarUtils.getCalendarsList() val pos = findPosition(calendars) if (calendars.isNotEmpty() && pos != -1 && pos < calendars.size) { val name = calendars[pos].name binding.selectCalendarPrefs.setDetailText(name) } else { binding.selectCalendarPrefs.setDetailText(null) } } private fun initExportToCalendarPrefs() { binding.exportToCalendarPrefs.setOnClickListener { changeExportToCalendarPrefs() } binding.exportToCalendarPrefs.isChecked = prefs.isCalendarEnabled } private fun findPosition(list: List<GoogleCalendarUtils.CalendarItem>): Int { if (list.isEmpty()) return -1 val id = prefs.defaultCalendarId for (i in list.indices) { val item = list[i] if (item.id == id) { return i } } return -1 } }
0
Kotlin
3
6
a6eecfda739be05a4b84e7d47284cd9e2bc782d6
9,898
reminder-kotlin
Apache License 2.0
android-kit-base/src/test/kotlin/com/mparticle/kits/CommerceEventUtilsTest.kt
mParticle
42,615,957
false
null
package com.mparticle.kits import org.junit.Assert import org.junit.Test class CommerceEventUtilsTest { @Test @Throws(Exception::class) fun testNullProductExpansion() { Assert.assertNotNull(CommerceEventUtils.expand(null)) Assert.assertEquals(0, CommerceEventUtils.expand(null).size.toLong()) } }
28
null
62
58
d8c70f35fad1ad0c794eb06f1c1671a0ce20e194
331
mparticle-android-sdk
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/extraCheckers/UselessCallOnNotNullChecker/isNullOrEmptyFromJava.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FILE: SomeUtil.java public class SomeUtil { public static boolean isNullOrEmpty(Object value) { return value == null; } } // FILE: main.kt interface Foo fun test(p: Foo) { SomeUtil.isNullOrEmpty(p) }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
227
kotlin
Apache License 2.0
app/src/main/java/com/dscoding/parkingspotfinder/data/ParkingSpotMapper.kt
diogosantos41
720,518,624
false
{"Kotlin": 27614}
package com.dscoding.parkingspotfinder.data import com.dscoding.parkingspotfinder.domain.ParkingSpot fun ParkingSpotEntity.toParkingSpot(): ParkingSpot { return ParkingSpot( lat = lat, lng = lng, id = id ) } fun ParkingSpot.toParkingSpotEntity(): ParkingSpotEntity { return ParkingSpotEntity( lat = lat, lng = lng, id = id ) }
0
Kotlin
0
0
1ec8ca38e0704838206a65940b13cca43db32832
393
parking-spot-finder-android
MIT License
composeApp/src/commonMain/kotlin/com/calvin/box/movie/navigation/ScreenContainer.kt
lhzheng880828
834,021,637
false
{"Kotlin": 829774, "Java": 712396, "JavaScript": 198922, "Shell": 3042, "Ruby": 2141, "Batchfile": 1261, "Swift": 1155, "HTML": 334, "CSS": 102}
package com.calvin.box.movie.navigation import androidx.compose.runtime.compositionLocalOf import cafe.adriel.voyager.core.screen.Screen import com.calvin.box.movie.model.VideoModel interface ScreenContainer { fun goToVideoPlayerScreen(currentVideo: VideoModel): Screen } val LocalScreenContainer = compositionLocalOf<ScreenContainer> { error("screen container not found") }
0
Kotlin
0
1
55c3464e1026b95a3c7b1c967d98dc172d27263d
387
MovieBox
Apache License 2.0
src/main/kotlin/no/nav/familie/ks/sak/kjerne/eøs/vilkårsvurdering/VilkårsvurderingTidslinjer.kt
navikt
533,308,075
false
{"Kotlin": 2778706, "Shell": 1039, "Dockerfile": 141}
package no.nav.familie.ks.sak.kjerne.eøs.vilkårsvurdering import no.nav.familie.ks.sak.common.tidslinje.beskjærEtter import no.nav.familie.ks.sak.common.tidslinje.inneholder import no.nav.familie.ks.sak.common.tidslinje.tomTidslinje import no.nav.familie.ks.sak.common.tidslinje.utvidelser.kombiner import no.nav.familie.ks.sak.common.tidslinje.utvidelser.kombinerMed import no.nav.familie.ks.sak.kjerne.behandling.steg.vilkårsvurdering.domene.Vilkårsvurdering import no.nav.familie.ks.sak.kjerne.personident.Aktør import no.nav.familie.ks.sak.kjerne.personopplysninggrunnlag.domene.PersonType import no.nav.familie.ks.sak.kjerne.personopplysninggrunnlag.domene.PersonopplysningGrunnlag class VilkårsvurderingTidslinjer( vilkårsvurdering: Vilkårsvurdering, personopplysningGrunnlag: PersonopplysningGrunnlag ) { private val barna: List<Aktør> = personopplysningGrunnlag.barna.map { it.aktør } private val søker: Aktør = personopplysningGrunnlag.søker.aktør private val aktørTilPersonResultater = vilkårsvurdering.personResultater.associateBy { it.aktør } private val vilkårResultaterTidslinjeMap = aktørTilPersonResultater.entries.associate { (aktør, personResultat) -> aktør to personResultat.vilkårResultater.groupBy { it.vilkårType } .map { it.value.tilVilkårRegelverkResultatTidslinje() } } private val søkersTidslinje: SøkersTidslinjer = SøkersTidslinjer(this, søker) private val barnasTidslinjer: Map<Aktør, BarnetsTidslinjer> = barna.associateWith { BarnetsTidslinjer(this, it) } fun barnasTidslinjer(): Map<Aktør, BarnetsTidslinjer> = barnasTidslinjer.entries.associate { it.key to it.value } class SøkersTidslinjer(tidslinjer: VilkårsvurderingTidslinjer, aktør: Aktør) { val vilkårResultatTidslinjer = tidslinjer.vilkårResultaterTidslinjeMap[aktør] ?: listOf(tomTidslinje()) val regelverkResultatTidslinje = vilkårResultatTidslinjer.kombiner { kombinerVilkårResultaterTilRegelverkResultat(PersonType.SØKER, it) } } class BarnetsTidslinjer(tidslinjer: VilkårsvurderingTidslinjer, aktør: Aktør) { private val søkersTidslinje = tidslinjer.søkersTidslinje val vilkårResultatTidslinjer = tidslinjer.vilkårResultaterTidslinjeMap[aktør] ?: listOf(tomTidslinje()) val egetRegelverkResultatTidslinje = vilkårResultatTidslinjer.kombiner { kombinerVilkårResultaterTilRegelverkResultat(PersonType.BARN, it) } val regelverkResultatTidslinje = egetRegelverkResultatTidslinje .kombinerMed(søkersTidslinje.regelverkResultatTidslinje) { barnetsResultat, søkersResultat -> barnetsResultat.kombinerMed(søkersResultat) }.beskjærEtter(søkersTidslinje.regelverkResultatTidslinje) } fun harBlandetRegelverk(): Boolean { return søkersTidslinje.regelverkResultatTidslinje.inneholder(RegelverkResultat.OPPFYLT_BLANDET_REGELVERK) || barnasTidslinjer().values.any { it.egetRegelverkResultatTidslinje.inneholder(RegelverkResultat.OPPFYLT_BLANDET_REGELVERK) } } }
3
Kotlin
1
2
f798d3ec05f042b5648ffe04eae645866ca0e24b
3,122
familie-ks-sak
MIT License
src/main/kotlin/no/nav/familie/ks/sak/kjerne/eøs/vilkårsvurdering/VilkårsvurderingTidslinjer.kt
navikt
533,308,075
false
{"Kotlin": 2778706, "Shell": 1039, "Dockerfile": 141}
package no.nav.familie.ks.sak.kjerne.eøs.vilkårsvurdering import no.nav.familie.ks.sak.common.tidslinje.beskjærEtter import no.nav.familie.ks.sak.common.tidslinje.inneholder import no.nav.familie.ks.sak.common.tidslinje.tomTidslinje import no.nav.familie.ks.sak.common.tidslinje.utvidelser.kombiner import no.nav.familie.ks.sak.common.tidslinje.utvidelser.kombinerMed import no.nav.familie.ks.sak.kjerne.behandling.steg.vilkårsvurdering.domene.Vilkårsvurdering import no.nav.familie.ks.sak.kjerne.personident.Aktør import no.nav.familie.ks.sak.kjerne.personopplysninggrunnlag.domene.PersonType import no.nav.familie.ks.sak.kjerne.personopplysninggrunnlag.domene.PersonopplysningGrunnlag class VilkårsvurderingTidslinjer( vilkårsvurdering: Vilkårsvurdering, personopplysningGrunnlag: PersonopplysningGrunnlag ) { private val barna: List<Aktør> = personopplysningGrunnlag.barna.map { it.aktør } private val søker: Aktør = personopplysningGrunnlag.søker.aktør private val aktørTilPersonResultater = vilkårsvurdering.personResultater.associateBy { it.aktør } private val vilkårResultaterTidslinjeMap = aktørTilPersonResultater.entries.associate { (aktør, personResultat) -> aktør to personResultat.vilkårResultater.groupBy { it.vilkårType } .map { it.value.tilVilkårRegelverkResultatTidslinje() } } private val søkersTidslinje: SøkersTidslinjer = SøkersTidslinjer(this, søker) private val barnasTidslinjer: Map<Aktør, BarnetsTidslinjer> = barna.associateWith { BarnetsTidslinjer(this, it) } fun barnasTidslinjer(): Map<Aktør, BarnetsTidslinjer> = barnasTidslinjer.entries.associate { it.key to it.value } class SøkersTidslinjer(tidslinjer: VilkårsvurderingTidslinjer, aktør: Aktør) { val vilkårResultatTidslinjer = tidslinjer.vilkårResultaterTidslinjeMap[aktør] ?: listOf(tomTidslinje()) val regelverkResultatTidslinje = vilkårResultatTidslinjer.kombiner { kombinerVilkårResultaterTilRegelverkResultat(PersonType.SØKER, it) } } class BarnetsTidslinjer(tidslinjer: VilkårsvurderingTidslinjer, aktør: Aktør) { private val søkersTidslinje = tidslinjer.søkersTidslinje val vilkårResultatTidslinjer = tidslinjer.vilkårResultaterTidslinjeMap[aktør] ?: listOf(tomTidslinje()) val egetRegelverkResultatTidslinje = vilkårResultatTidslinjer.kombiner { kombinerVilkårResultaterTilRegelverkResultat(PersonType.BARN, it) } val regelverkResultatTidslinje = egetRegelverkResultatTidslinje .kombinerMed(søkersTidslinje.regelverkResultatTidslinje) { barnetsResultat, søkersResultat -> barnetsResultat.kombinerMed(søkersResultat) }.beskjærEtter(søkersTidslinje.regelverkResultatTidslinje) } fun harBlandetRegelverk(): Boolean { return søkersTidslinje.regelverkResultatTidslinje.inneholder(RegelverkResultat.OPPFYLT_BLANDET_REGELVERK) || barnasTidslinjer().values.any { it.egetRegelverkResultatTidslinje.inneholder(RegelverkResultat.OPPFYLT_BLANDET_REGELVERK) } } }
3
Kotlin
1
2
f798d3ec05f042b5648ffe04eae645866ca0e24b
3,122
familie-ks-sak
MIT License
system/src/main/kotlin/cn/soybean/system/projection/tenant/TenantDeletedProjection.kt
soybeanjs
467,859,867
false
{"Kotlin": 341265, "HTML": 244772, "Python": 958, "Makefile": 571}
package cn.soybean.system.projection.tenant import cn.soybean.shared.domain.aggregate.AggregateEventEntity import cn.soybean.shared.projection.Projection import cn.soybean.system.domain.event.tenant.TenantDeletedEventBase import io.quarkus.hibernate.reactive.panache.common.WithTransaction import io.smallrye.mutiny.Uni import jakarta.enterprise.context.ApplicationScoped @ApplicationScoped class TenantDeletedProjection : Projection { @WithTransaction override fun process(eventEntity: AggregateEventEntity): Uni<Unit> { TODO() } override fun supports(eventType: String): Boolean = eventType == TenantDeletedEventBase.TENANT_DELETED_V1 }
4
Kotlin
89
212
59063051768682aded5680c868dff79cb9e9c3c9
666
soybean-admin-quarkus
MIT License
app/src/test/java/reach52/marketplace/community/Common.kt
reach52
422,514,975
false
{"Kotlin": 1436380, "Java": 18303}
package reach52.marketplace.community import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.NetworkInfo import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.schedulers.Schedulers import org.mockito.Mockito fun <T> When(methodCall: T) = Mockito.`when`(methodCall) fun commonSetup(context: Context?){ RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() } if(context != null) { val cm = Mockito.mock(ConnectivityManager::class.java) val nc = Mockito.mock(NetworkCapabilities::class.java) val netInfo = Mockito.mock(NetworkInfo::class.java) When(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?).thenReturn(cm) When(nc!!.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)).thenReturn(true) When(cm!!.activeNetworkInfo).thenReturn(netInfo) When(cm.activeNetworkInfo.isConnected).thenReturn(true) } } fun goOffline(context: Context) { val cm = Mockito.mock(ConnectivityManager::class.java) val nc = Mockito.mock(NetworkCapabilities::class.java) val netInfo = Mockito.mock(NetworkInfo::class.java) When(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?).thenReturn(cm) When(nc!!.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)).thenReturn(false) When(cm!!.activeNetworkInfo).thenReturn(netInfo) When(cm.activeNetworkInfo.isConnected).thenReturn(false) }
0
Kotlin
0
0
629c52368d06f978f19238d0bd865f4ef84c23d8
1,476
Marketplace-Community-Edition
MIT License
app/src/test/java/com/example/typingmaster/KeystrokesRepositoryTest.kt
malikdawar
756,851,091
false
null
package com.example.threatfabric import com.example.threatfabric.data.db.KeystrokesDao import com.example.threatfabric.data.db.KeystrokesData import com.example.threatfabric.data.repository.KeystrokesRepository import junit.framework.TestCase.assertEquals import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner /** * KeystrokesRepositoryTest- Unit tests for the KeystrokesRepository * @author Malik Dawar */ @RunWith(MockitoJUnitRunner::class) class KeystrokesRepositoryTest { @Mock private lateinit var keystrokesDao: KeystrokesDao private lateinit var keystrokesRepository: KeystrokesRepository @Before fun setup() { keystrokesRepository = KeystrokesRepository(keystrokesDao) } @Test fun `test addKeystrokes`() = runBlocking { // Given val keystrokesData = KeystrokesData( username = "Jeo don", keyPressTime = 0, keyReleaseTime = 1, keyCode = 1, phoneOrientation = 1, ) // When keystrokesRepository.insertKeystrokesData(keystrokesData) // Then verify(keystrokesDao).insertKeystrokesData(keystrokesData) } @Test fun `test getAllKeystrokes`() { runBlocking { // Given val testDataList = listOf( KeystrokesData( username = "Jeo don1", keyPressTime = 0, keyReleaseTime = 1, keyCode = 1, phoneOrientation = 2, ), KeystrokesData( username = "Jeo don2", keyPressTime = 10, keyReleaseTime = 10, keyCode = 11, phoneOrientation = 12, ), ) `when`(keystrokesDao.getAllKeystrokes()).thenReturn(testDataList) // When val result = keystrokesRepository.getAllKeystrokes() // Then assertEquals(testDataList, result) } } }
0
null
0
1
5b7750196eb5aebb7301b066f0e63b987b379dec
2,442
TypingMaster
MIT License
telegram-bot/src/commonMain/kotlin/eu/vendeli/tgbot/utils/builders/EntitiesCtxBuilder.kt
vendelieu
496,567,172
false
{"Kotlin": 925708, "CSS": 356}
package eu.vendeli.tgbot.utils.builders import eu.vendeli.tgbot.interfaces.TgAction import eu.vendeli.tgbot.types.EntityType import eu.vendeli.tgbot.types.EntityType.Blockquote import eu.vendeli.tgbot.types.EntityType.Bold import eu.vendeli.tgbot.types.EntityType.BotCommand import eu.vendeli.tgbot.types.EntityType.Cashtag import eu.vendeli.tgbot.types.EntityType.Code import eu.vendeli.tgbot.types.EntityType.CustomEmoji import eu.vendeli.tgbot.types.EntityType.Email import eu.vendeli.tgbot.types.EntityType.Hashtag import eu.vendeli.tgbot.types.EntityType.Italic import eu.vendeli.tgbot.types.EntityType.Mention import eu.vendeli.tgbot.types.EntityType.PhoneNumber import eu.vendeli.tgbot.types.EntityType.Pre import eu.vendeli.tgbot.types.EntityType.Spoiler import eu.vendeli.tgbot.types.EntityType.Strikethrough import eu.vendeli.tgbot.types.EntityType.TextLink import eu.vendeli.tgbot.types.EntityType.TextMention import eu.vendeli.tgbot.types.EntityType.Underline import eu.vendeli.tgbot.types.EntityType.Url import eu.vendeli.tgbot.types.MessageEntity import eu.vendeli.tgbot.types.User import eu.vendeli.tgbot.utils.encodeWith import kotlinx.serialization.json.JsonArray import kotlin.jvm.JvmName @Suppress("TooManyFunctions") interface EntitiesExtBuilder { fun EntitiesExtBuilder.addEntity(entity: MessageEntity) operator fun String.minus(other: String): String = this + other // operators operator fun String.minus(other: Pair<EntityType, String>): String { addEntity(MessageEntity(other.first, length, other.second.length)) return this + other.second } operator fun Pair<EntityType, String>.minus(other: String): String { addEntity(MessageEntity(first, 0, second.length)) return second + other } operator fun <T> String.minus(other: Triple<EntityType, String, T?>): String { val entity = when (other.first) { Pre -> MessageEntity( Pre, length, other.second.length, language = other.third?.toString(), ) TextLink -> MessageEntity( TextLink, length, other.second.length, url = other.third?.toString(), ) CustomEmoji -> MessageEntity( CustomEmoji, length, other.second.length, customEmojiId = other.third?.toString(), ) TextMention -> MessageEntity( TextMention, length, other.second.length, user = other.third as? User, ) else -> throw IllegalArgumentException("An unexpected EntityType - ${other.first}.") } addEntity(entity) return this + other.second } operator fun <T> Triple<EntityType, String, T?>.minus(other: String): String { val entity = when (first) { Pre -> MessageEntity(Pre, 0, second.length, language = third?.toString()) TextLink -> MessageEntity(TextLink, 0, second.length, url = third?.toString()) CustomEmoji -> MessageEntity(CustomEmoji, 0, second.length, customEmojiId = third?.toString()) TextMention -> MessageEntity(TextMention, 0, second.length, user = third as? User) else -> throw IllegalArgumentException("An unexpected EntityType - $first.") } addEntity(entity) return this.second + other } // functions fun EntitiesExtBuilder.mention(block: () -> String) = Mention to block() fun EntitiesExtBuilder.hashtag(block: () -> String) = Hashtag to block() fun EntitiesExtBuilder.cashtag(block: () -> String) = Cashtag to block() fun EntitiesExtBuilder.botCommand(block: () -> String) = BotCommand to block() fun EntitiesExtBuilder.url(block: () -> String) = Url to block() fun EntitiesExtBuilder.email(block: () -> String) = Email to block() fun EntitiesExtBuilder.phoneNumber(block: () -> String) = PhoneNumber to block() fun EntitiesExtBuilder.bold(block: () -> String) = Bold to block() fun EntitiesExtBuilder.italic(block: () -> String) = Italic to block() fun EntitiesExtBuilder.underline(block: () -> String) = Underline to block() fun EntitiesExtBuilder.strikethrough(block: () -> String) = Strikethrough to block() fun EntitiesExtBuilder.spoiler(block: () -> String) = Spoiler to block() fun EntitiesExtBuilder.blockquote(block: () -> String) = Blockquote to block() fun EntitiesExtBuilder.code(block: () -> String) = Code to block() fun EntitiesExtBuilder.customEmoji( customEmojiId: String? = null, block: () -> String, ) = Triple(CustomEmoji, block(), customEmojiId) @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("pre") fun EntitiesExtBuilder.pre( language: String? = null, block: () -> String, ) = Triple(Pre, block(), language) @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("textLink") fun EntitiesExtBuilder.textLink( url: String? = null, block: () -> String, ) = Triple(TextLink, block(), url) @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("textMention") fun EntitiesExtBuilder.textMention( user: User? = null, block: () -> String, ) = Triple(TextMention, block(), user) } interface EntitiesCtxBuilder<Action : TgAction<*>> : EntitiesExtBuilder { @Suppress("UNCHECKED_CAST", "unused") override fun EntitiesExtBuilder.addEntity(entity: MessageEntity) { this as TgAction<*> val oldEntity = (parameters[entitiesFieldName] as? JsonArray)?.toMutableList() ?: mutableListOf() parameters[entitiesFieldName] = oldEntity.also { it.add(entity.encodeWith(MessageEntity.serializer())) }.let { JsonArray(it) } } }
6
Kotlin
9
165
c1ddf4a42c577410af31249dc650858320668263
5,862
telegram-bot
Apache License 2.0
app/src/main/java/com/cuong/moviehero/ui/components/TitleBar.kt
cuonghuynhvan
471,910,042
false
{"Kotlin": 141883}
package com.cuong.moviehero.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.cuong.moviehero.R import com.cuong.moviehero.ui.theme.MovieHeroTheme @Composable fun TitleBar( modifier: Modifier = Modifier, title: String = stringResource(id = R.string.app_name), startContent: @Composable (modifier: Modifier) -> Unit = {}, ) { BoxWithConstraints( modifier = modifier .fillMaxWidth() .background(MaterialTheme.colors.primaryVariant) .statusBarsPadding() .height(50.dp), ) { Text( modifier = Modifier.align(Alignment.Center), text = title, style = MaterialTheme.typography.h2.copy(MaterialTheme.colors.onPrimary), ) startContent(modifier = Modifier.align(Alignment.CenterStart)) } } @Preview(showBackground = true) @Composable fun TitleBarPreview() { MovieHeroTheme { Column( Modifier .fillMaxWidth() .background(Color.White) .padding(16.dp) ) { TitleBar() } } }
0
Kotlin
0
0
36bc4b4d840343e7f7b63bc70f81546f8b49665d
1,605
MovieHero
MIT License
androidApp/src/main/java/com/ramitsuri/podcasts/android/ui/ThemePreview.kt
ramitsuri
760,212,962
false
{"Kotlin": 558852, "Shell": 9622, "Swift": 296}
package com.ramitsuri.podcasts.android.ui import android.content.res.Configuration import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, name = "Dark") @Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, name = "Light") annotation class ThemePreview @Composable fun PreviewTheme(content: @Composable () -> Unit) { AppTheme { Surface { content() } } }
2
Kotlin
0
1
b43522bae0113efa5eceb5505c19c8b57cfb27d9
567
podcasts
MIT License
app/src/main/java/com/kardia/membership/features/utils/AppLog.kt
trungthaihieu93-dev
359,315,080
false
null
package com.kardia.membership.features.utils import android.util.Log import com.kardia.membership.BuildConfig class AppLog { companion object { @JvmStatic fun e(tag: String, message: String) { if (BuildConfig.DEBUG) Log.e(tag, message) } fun e(tag: String, message: String, s: Throwable) { if (BuildConfig.DEBUG) Log.e(tag, message, s) } fun d(tag: String, message: String) { if (BuildConfig.DEBUG) Log.d(tag, message) } } }
0
null
0
0
00e51171479e259edbccf36ee155dc8e4489e40f
528
kai-membership-kotlin
MIT License
error-handler-rest/src/main/java/com/halcyonmobile/errorhandlerrest/exception/SerializationException.kt
halcyonmobile
266,983,268
false
null
package com.halcyonmobile.errorhandlerrest.exception import com.halcyonmobile.errorparsing.NetworkException /** * Exception representing any kind of serialization failure. * * @see [com.halcyonmobile.errorhandlerrest.SerializationExceptionConverter] */ class SerializationException(throwable: Throwable) : NetworkException(throwable, null, null)
15
Kotlin
0
4
d18da91eba263ee3218ca058ad4b30b975da369d
351
error-handler
Apache License 2.0
app/src/main/java/com/petnagy/superexchange/databinding/RecyclerViewBindingAdapter.kt
petnagy
151,879,510
false
null
package com.petnagy.superexchange.databinding import android.databinding.BindingAdapter import android.support.annotation.LayoutRes import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import com.petnagy.superexchange.recyclerview.ListItemViewModel import com.petnagy.superexchange.recyclerview.RecyclerViewAdapter import com.petnagy.superexchange.recyclerview.SpaceItemDecorator /*** * RecyclerView realted binding adapters, to use it in view. */ @BindingAdapter("source") fun setupRecyclerViewSource(recyclerView: RecyclerView, source: List<ListItemViewModel>) { getAdapter(recyclerView).items = source.toMutableList() } @BindingAdapter("itemLayout") fun setupRecyclerViewItemLayout(recyclerView: RecyclerView, @LayoutRes itemLayout: Int) { getAdapter(recyclerView).itemLayout = itemLayout } private fun getAdapter(recyclerView: RecyclerView): RecyclerViewAdapter { var adapter: RecyclerViewAdapter? = recyclerView.adapter as? RecyclerViewAdapter if (adapter == null) { recyclerView.layoutManager = GridLayoutManager(recyclerView.context, 1) adapter = RecyclerViewAdapter() recyclerView.adapter = adapter val space = 8 recyclerView.addItemDecoration(SpaceItemDecorator(space)) } return adapter }
0
Kotlin
0
0
8b8df7312a209c9b2b8c2b0737d78e365b9791cc
1,312
super_exchange
Apache License 2.0
analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataStubBuilder.kt
JetBrains
278,369,660
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.decompiler.common import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.compiled.ClsStubBuilder import com.intellij.psi.impl.compiled.ClassFileStubBuilder import com.intellij.psi.stubs.PsiFileStub import com.intellij.util.indexing.FileContent import org.jetbrains.kotlin.idea.decompiler.stubBuilder.* import org.jetbrains.kotlin.metadata.deserialization.TypeTable import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol import org.jetbrains.kotlin.serialization.deserialization.ProtoBasedClassDataFinder import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer import org.jetbrains.kotlin.serialization.deserialization.getClassId open class KotlinMetadataStubBuilder( private val version: Int, private val fileType: FileType, private val serializerProtocol: () -> SerializerExtensionProtocol, private val readFile: (VirtualFile, ByteArray) -> FileWithMetadata? ) : ClsStubBuilder() { override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + version override fun buildFileStub(content: FileContent): PsiFileStub<*>? { val virtualFile = content.file assert(virtualFile.fileType == fileType) { "Unexpected file type ${virtualFile.fileType}" } val file = readFile(virtualFile, content.content) ?: return null when (file) { is FileWithMetadata.Incompatible -> { return createIncompatibleAbiVersionFileStub() } is FileWithMetadata.Compatible -> { val packageProto = file.proto.`package` val packageFqName = file.packageFqName val nameResolver = file.nameResolver val components = ClsStubBuilderComponents( ProtoBasedClassDataFinder(file.proto, nameResolver, file.version), AnnotationLoaderForStubBuilderImpl(serializerProtocol()), virtualFile ) val context = components.createContext(nameResolver, packageFqName, TypeTable(packageProto.typeTable)) val fileStub = createFileStub(packageFqName, isScript = false) createPackageDeclarationsStubs( fileStub, context, ProtoContainer.Package(packageFqName, context.nameResolver, context.typeTable, source = null), packageProto ) for (classProto in file.classesToDecompile) { createClassStub( fileStub, classProto, nameResolver, nameResolver.getClassId(classProto.fqName), source = null, context = context ) } return fileStub } } } }
191
Kotlin
4372
71
b6789690db56407ae2d6d62746fb69dc99d68c84
2,979
intellij-kotlin
Apache License 2.0
core/src/main/java/org/futo/circles/core/feature/whats_new/WhatsNewDialog.kt
circles-project
615,347,618
false
{"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922}
package org.futo.circles.core.feature.whats_new import android.app.ActionBar import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.InsetDrawable import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.LayoutInflater import android.widget.TextView import androidx.appcompat.app.AppCompatDialog import org.futo.circles.core.R import org.futo.circles.core.base.CirclesAppConfig import org.futo.circles.core.databinding.DialogWhatsNewBinding import org.futo.circles.core.feature.markdown.MarkdownParser import org.futo.circles.core.provider.PreferencesProvider class WhatsNewDialog(context: Context) : AppCompatDialog(context) { private val binding = DialogWhatsNewBinding.inflate(LayoutInflater.from(context)) private val preferencesProvider by lazy { PreferencesProvider(context) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) setCancelable(false) window?.apply { setBackgroundDrawable(InsetDrawable(ColorDrawable(Color.TRANSPARENT), 20)) setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT) } setupViews() } private fun setupViews() { with(binding) { tvTitle.text = context.getString(R.string.whats_new_in_format, CirclesAppConfig.appVersionName) btnDone.setOnClickListener { preferencesProvider.storeWhatsNewShowedFor(CirclesAppConfig.appVersionCode) dismiss() } tvDescription.apply { movementMethod = ScrollingMovementMethod() val text = CirclesAppConfig.changelog.replace("-", "\n*") tvDescription.setText(MarkdownParser.parse(text), TextView.BufferType.SPANNABLE) } } } companion object { fun showIfNeed(context: Context) { val wasShownFor = PreferencesProvider(context).getWhatsNewShowedForVersion() val currentVersionCode = CirclesAppConfig.appVersionCode / 100 if (currentVersionCode > wasShownFor) WhatsNewDialog(context).show() } } }
8
Kotlin
4
29
7edec708f9c491a7b6f139fc2f2aa3e2b7149112
2,309
circles-android
Apache License 2.0
model-datastructure/src/commonMain/kotlin/org/modelix/model/operations/MoveNodeOp.kt
modelix
533,211,353
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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.modelix.model.operations import org.modelix.model.api.ITree import org.modelix.model.api.IWriteTransaction import org.modelix.model.lazy.IDeserializingKeyValueStore class MoveNodeOp(val childId: Long, val targetPosition: PositionInRole) : AbstractOperation() { fun withPos(newTarget: PositionInRole): MoveNodeOp { return if (newTarget == targetPosition) { this } else { MoveNodeOp(childId, newTarget) } } override fun apply(transaction: IWriteTransaction, store: IDeserializingKeyValueStore): IAppliedOperation { val sourcePosition = getNodePosition(transaction.tree, childId) transaction.moveChild(targetPosition.nodeId, targetPosition.role, targetPosition.index, childId) return Applied(sourcePosition) } override fun toString(): String { return "MoveNodeOp ${childId.toString(16)}->$targetPosition" } override fun toCode(): String { return """t.moveChild(0x${targetPosition.nodeId.toString(16)}, "${targetPosition.role}", ${targetPosition.index}, 0x${childId.toString(16)})""" } inner class Applied(val sourcePosition: PositionInRole) : AbstractOperation.Applied(), IAppliedOperation { override fun getOriginalOp() = this@MoveNodeOp override fun invert(): List<IOperation> { return listOf(MoveNodeOp(childId, sourcePosition)) } } override fun captureIntend(tree: ITree, store: IDeserializingKeyValueStore): IOperationIntend { val capturedTargetPosition = CapturedInsertPosition( targetPosition.index, tree.getChildren(targetPosition.nodeId, targetPosition.role).toList().toLongArray() ) return Intend(capturedTargetPosition) } inner class Intend(val capturedTargetPosition: CapturedInsertPosition) : IOperationIntend { override fun restoreIntend(tree: ITree): List<IOperation> { if (!tree.containsNode(childId)) return listOf(NoOp()) val newSourcePosition = getNodePosition(tree, childId) if (!tree.containsNode(targetPosition.nodeId)) { return listOf( withPos(getDetachedNodesEndPosition(tree)) ) } if (getAncestors(tree, targetPosition.nodeId).contains(childId)) return listOf(NoOp()) val newTargetPosition = if (tree.containsNode(targetPosition.nodeId)) { val newTargetIndex = capturedTargetPosition.findIndex(tree.getChildren(targetPosition.nodeId, targetPosition.role).toList().toLongArray()) targetPosition.withIndex(newTargetIndex) } else { getDetachedNodesEndPosition(tree) } return listOf(withPos(newTargetPosition)) } override fun getOriginalOp() = this@MoveNodeOp } }
49
null
9
6
48aa04bf386063b4093424166a263cee7cc69983
3,429
modelix.core
Apache License 2.0
compiler/testData/diagnostics/tests/collectionLiterals/basicCollectionLiterals.fir.kt
android
263,405,600
false
null
// !WITH_NEW_INFERENCE // !CHECK_TYPE // !DIAGNOSTICS: -UNUSED_VARIABLE, -UNSUPPORTED fun test() { val a = [] val b: Array<Int> = [] val c = [1, 2] val d: Array<Int> = [1, 2] val e: Array<String> = [1] val f: IntArray = [1, 2] val g = [f] } fun check() { [1, 2] checkType { <!UNRESOLVED_REFERENCE!>_<!><Array<Int>>() } [""] checkType { <!UNRESOLVED_REFERENCE!>_<!><Array<String>>() } val f: IntArray = [1] [f] checkType { <!UNRESOLVED_REFERENCE!>_<!><Array<IntArray>>() } [1, ""] checkType { <!UNRESOLVED_REFERENCE!>_<!><Array<Any>>() } }
0
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
591
kotlin
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/kinesisanalyticsv2/InputLambdaProcessorPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.kinesisanalyticsv2 import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplication @Generated public fun buildInputLambdaProcessorProperty(initializer: @AwsCdkDsl CfnApplication.InputLambdaProcessorProperty.Builder.() -> Unit): CfnApplication.InputLambdaProcessorProperty = CfnApplication.InputLambdaProcessorProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
519
aws-cdk-kt
Apache License 2.0
graphql/src/main/kotlin/com/joe/quizzy/graphql/dataloaders/ResponseGradeLoader.kt
josephlbarnett
257,994,447
false
{"Kotlin": 272662, "Vue": 101105, "TypeScript": 72127, "JavaScript": 1728, "HTML": 880, "Dockerfile": 482}
package com.joe.quizzy.graphql.dataloaders import com.joe.quizzy.api.models.Grade import com.joe.quizzy.persistence.api.GradeDAO import com.trib3.graphql.execution.CoroutineMappedBatchLoader import org.dataloader.BatchLoaderEnvironment import java.util.UUID /** * Batch load Response ID -> Grade */ class ResponseGradeLoader(private val gradeDAO: GradeDAO) : CoroutineMappedBatchLoader<UUID, Grade>() { override val dataLoaderName = "responsegrades" override suspend fun loadSuspend(keys: Set<UUID>, environment: BatchLoaderEnvironment): Map<UUID, Grade> { return gradeDAO.forResponses(keys.toList()) } }
9
Kotlin
0
2
ea6b1f4114b1afa5884f457b7f236a23ccf89d5c
634
quizzy
Apache License 2.0
keel-core/src/main/kotlin/com/netflix/spinnaker/keel/enforcers/EnvironmentExclusionEnforcer.kt
danielpeach
352,888,129
true
{"Kotlin": 2770258, "Java": 20143, "Shell": 1691, "Slim": 359}
package com.netflix.spinnaker.keel.enforcers import com.netflix.spectator.api.Registry import com.netflix.spectator.api.histogram.PercentileTimer import com.netflix.spinnaker.keel.api.DeliveryConfig import org.springframework.core.env.Environment as SpringEnvironment import com.netflix.spinnaker.keel.api.Environment import com.netflix.spinnaker.keel.api.constraints.ConstraintStatus.PENDING import com.netflix.spinnaker.keel.api.verification.VerificationContext import com.netflix.spinnaker.keel.api.verification.VerificationRepository import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.withContext import org.springframework.stereotype.Component import java.time.Clock import java.time.Duration import java.time.Instant /** * Exception thrown when it's not safe to take action against the environment because * something is already acting on it. */ open class EnvironmentCurrentlyBeingActedOn(message: String) : Exception(message) { } class ActiveVerifications(val active: Collection<VerificationContext>, deliveryConfig: DeliveryConfig, environment: Environment) : EnvironmentCurrentlyBeingActedOn("active verifications in ${deliveryConfig.name} ${environment.name} against versions ${active.map {it.version}}") /** * This class enforces two safety properties of the verification behavior: * * P1: Two verifications should never execute concurrently against the same environment. * * For example, if the acme/tests:stable test container is currently running in the staging environment, * keel should not launch any other verifications in the staging environment. * * P2: Verifications against an environment should never happen concurrently with a deployment in an environment. * * For example, if the fnord-v123.deb artifact is being deployed to an EC2 cluster in the staging environment, * keel should not launch verifications while this is happening. * * * The enforcer works by granting the client a lease if the guard conditions are met. * A lease is a lock that has an expiration time. Leases expire to protect against the situation * where an instance takes a lease and then terminates unexpectedly before releasing it. * * If a client is unable to get a lease, the enforcer will throw a EnvironmentCurrentlyBeingActedOn exception. * */ @Component class EnvironmentExclusionEnforcer( private val springEnv: SpringEnvironment, private val repository: VerificationRepository, spectator: Registry, private val clock: Clock ) { private val enforcementEnabled: Boolean get() = springEnv.getProperty("keel.enforcement.environment-exclusion.enabled", Boolean::class.java, true) /** * Percentile timer builder for measuring how long the checks take. * * We use the default percentile time range: 10ms to 1 minute */ private val timerBuilder = PercentileTimer.builder(spectator).withName("keel.enforcement.environment.check.duration") /** * To get a verification lease against an environment, need: * * 1. An environment lease * 2. No active deployments * 3. No active verifications */ fun <T> withVerificationLease(context: VerificationContext, action: () -> T) : T { val startTime = clock.instant() if (enforcementEnabled) { val environment = context.environment val deliveryConfig = context.deliveryConfig ensureNoActiveDeployments(deliveryConfig, environment) ensureNoActiveVerifications(deliveryConfig, environment) } recordDuration("verification", startTime) return action.invoke() } /** * To get an actuation lease against an environment, need: * * 1. An environment lease * 2. No active verifications * * It's ok if other actuations (e.g., deployments) are going on. */ suspend fun <T> withActuationLease(deliveryConfig: DeliveryConfig, environment: Environment, action: suspend () -> T) : T { val startTime = clock.instant() if (enforcementEnabled) { // use IO context since the checks call the database, which wil block the coroutine's thread withContext(IO) { ensureNoActiveVerifications(deliveryConfig, environment) } } recordDuration("actuation", startTime) return action.invoke() } /** * @throws EnvironmentCurrentlyBeingActedOn if there's an active deployment */ private fun ensureNoActiveDeployments(deliveryConfig: DeliveryConfig, environment: Environment) { /** * To be implemented in a future PR. */ } /** * * Checks if any verifications in the [environment] of [deliveryConfig] are in the [PENDING] state * * @throws ActiveVerifications if there's an active verification */ private fun ensureNoActiveVerifications(deliveryConfig: DeliveryConfig, environment: Environment) { val activeVerifications = repository.getContextsWithStatus(deliveryConfig, environment, PENDING) if(activeVerifications.isNotEmpty()) { throw ActiveVerifications(activeVerifications, deliveryConfig, environment) } } /** * Emit a metric with the duration of the check time from [startTime] to now. * * Tag with key: "action", value: [actionType] */ private fun recordDuration(actionType: String, startTime: Instant) { timerBuilder .withTag("action", actionType) .build() .record(Duration.between(startTime, clock.instant())) } }
0
null
0
0
dbe1677897a6dbbea4682d11c52dc0ad46818c26
5,370
keel
Apache License 2.0
demo-exoplayer/src/main/java/toro/demo/exoplayer/DemoItemsFragment.kt
mukashivn
128,860,769
false
null
/* * Copyright (c) 2018 Nam Nguyen, nam@ene.im * * 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 toro.demo.exoplayer import android.annotation.SuppressLint import android.content.Context import android.net.Uri import android.os.Bundle import android.os.Handler import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView.Adapter import android.support.v7.widget.RecyclerView.ViewHolder import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.ui.PlayerView import com.google.android.exoplayer2.util.Util import im.ene.toro.ToroPlayer import im.ene.toro.ToroUtil import im.ene.toro.exoplayer.Config import im.ene.toro.exoplayer.ExoPlayerViewHelper import im.ene.toro.exoplayer.Playable.DefaultEventListener import im.ene.toro.exoplayer.Playable.EventListener import im.ene.toro.exoplayer.ToroExo import im.ene.toro.media.PlaybackInfo import im.ene.toro.widget.Container import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_demo_items.recyclerView import toro.demo.exoplayer.common.DemoItem import toro.demo.exoplayer.common.DemoMediaDrm import toro.demo.exoplayer.common.DemoRepository import toro.demo.exoplayer.common.VideoItem /** * @author eneim (2018/03/05). */ class DemoItemsFragment : Fragment(), (DemoItem) -> Config { companion object { fun newInstance() = DemoItemsFragment() } private val configCache = HashMap<DemoMediaDrm, Config>() // (DemoItem) -> Config override fun invoke(item: DemoItem): Config { val defaultConfig = DemoApp.config!! if (Util.SDK_INT < 18) return defaultConfig // Step 1: process 1st level Videos. val drmList = item.samples.filter { it.drmScheme != null }.map { it -> DemoMediaDrm(it.drmScheme!!, it.drmLicenseUrl, false) }.distinctBy { it.hashCode() } var config = configCache[drmList.firstOrNull()] if (config == null) { config = drmList.map { it -> ToroExo.with(requireContext()).createDrmSessionManager(it, Handler()) }.run { defaultConfig.newBuilder().setDrmSessionManagers(this.toTypedArray()).build() } drmList.forEach { configCache[it] = config } } return config!! } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, st: Bundle?): View? { return inflater.inflate(R.layout.fragment_demo_items, container, false) } private val adapter: DemoAdapter by lazy { DemoAdapter(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView.adapter = adapter DemoRepository().loadDemoItems(requireContext()) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { adapter.setItems(it) } } } //// ViewHolder class DemoItemViewHolder(itemView: View) : ViewHolder(itemView), ToroPlayer { override fun getPlayerView() = playerView override fun getCurrentPlaybackInfo() = helper?.latestPlaybackInfo ?: PlaybackInfo() override fun initialize(container: Container, playbackInfo: PlaybackInfo?) { val videoUri = videoItem!!.uri if (videoUri != null && helper == null) { helper = ExoPlayerViewHelper(this, Uri.parse(videoUri), videoItem!!.extension, act!!.invoke(demoItem!!)) } if (listener == null) { listener = object : DefaultEventListener() { @SuppressLint("SetTextI18n") override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { super.onPlayerStateChanged(playWhenReady, playbackState) playerStatus.text = "State: $playbackState, play: $playWhenReady" } @SuppressLint("SetTextI18n") override fun onPlayerError(error: ExoPlaybackException?) { super.onPlayerError(error) playerStatus.text = "Error: ${error?.localizedMessage}" } } helper!!.addEventListener(listener!!) } helper!!.initialize(container, playbackInfo) } override fun play() { helper?.play() } override fun pause() { helper?.pause() } override fun isPlaying() = helper?.isPlaying ?: false override fun release() { if (listener != null) { helper?.removeEventListener(listener) listener = null } helper?.release() helper = null } override fun wantsToPlay() = ToroUtil.visibleAreaOffset(this, itemView.parent) > 0.85 override fun getPlayerOrder() = adapterPosition override fun onSettled(container: Container?) { } private val playerView: PlayerView = itemView.findViewById(R.id.itemVideo) private val itemName: TextView = itemView.findViewById(R.id.itemName) private val itemVideos: View = itemView.findViewById(R.id.itemVideos) private val playerStatus: TextView = itemView.findViewById(R.id.playerStatus) private var demoItem: DemoItem? = null private var helper: ExoPlayerViewHelper? = null private var listener: EventListener? = null private var videoItem: VideoItem? = null private var act: ((DemoItem) -> Config)? = null fun bind(item: DemoItem, act: (DemoItem) -> Config) { this.act = act this.demoItem = item if (demoItem?.samples?.isNotEmpty()!!) { videoItem = demoItem?.samples!![0] } if (demoItem?.name?.isNotEmpty()!!) { itemName.text = demoItem?.name } if (demoItem!!.samples.isEmpty()) itemVideos.visibility = View.GONE else itemVideos.visibility = View.VISIBLE if (videoItem?.uri == null) { if (videoItem!!.playlist?.isNotEmpty()!!) { videoItem = videoItem!!.playlist!![0] } } playerStatus.text = "Idle" } } class DemoAdapter(private val act: (DemoItem) -> Config) : Adapter<DemoItemViewHolder>() { private val items = arrayListOf<DemoItem>() private var inflater: LayoutInflater? = null private fun inflater(context: Context): LayoutInflater { if (inflater == null || inflater!!.context !== context) { inflater = LayoutInflater.from(context) } return inflater!! } fun setItems(newItems: List<DemoItem>) { items.clear() items.addAll(newItems) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DemoItemViewHolder { return DemoItemViewHolder(inflater(parent.context) .inflate(R.layout.view_holder_demo_item, parent, false) ) } override fun getItemCount() = items.size override fun onBindViewHolder(holder: DemoItemViewHolder, position: Int) { holder.bind(items[position], act) } }
1
null
1
1
6b2a38e6a735b6f4e05dda2590a6bd60a6e4f50b
7,258
toro
Apache License 2.0
Problems/Algorithms/278. First Bad Version/FirstBadVersion.kt
xuedong
189,745,542
false
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Python": 498, "Kotlin": 443, "Java": 343, "Go": 55, "C++": 150, "Rust": 141, "Ruby": 2, "Dart": 1, "Erlang": 1, "Racket": 1, "Elixir": 1, "Scala": 2, "C": 2, "JavaScript": 22, "C#": 2, "Shell": 2, "SQL": 34, "JSON": 1, "Swift": 1, "TSX": 1}
/* The isBadVersion API is defined in the parent class VersionControl. fun isBadVersion(version: Int) : Boolean {} */ class Solution: VersionControl() { override fun firstBadVersion(n: Int) : Int { var left = 1 var right = n while (left < right) { val mid = left + (right - left) / 2 val isBad = isBadVersion(mid) if (isBad) { right = mid } else { left = mid + 1 } } return right } }
0
Kotlin
0
1
eb637d11ca27ac57b296aad1114a9c86b3dad1aa
560
leet-code
MIT License
app/src/main/java/com/github/pierry/test/asset/presentation/model/RiskInfo.kt
Pierry
181,939,647
false
null
package com.github.pierry.test.asset.presentation.model data class RiskInfo( val title: String, val risk: Int )
0
Kotlin
0
1
24667ca844f8a5dbcd745599523cd71af8854ae4
128
test-android-example
MIT License
data/src/main/java/com/teamwiney/data/network/model/response/RecommendWine.kt
AdultOfNineteen
639,481,288
false
{"Kotlin": 875700}
package com.teamwiney.data.network.model.response import com.google.gson.annotations.SerializedName data class RecommendWine( @SerializedName("wineId") val wineId: Long, @SerializedName("name") val name: String, @SerializedName("country") val country: String, @SerializedName("type") val type: String, @SerializedName("varietal") val varietal: List<String>, @SerializedName("price") val price: Int ) fun RecommendWine.toDomain() = RecommendWine( wineId = this.wineId, name = this.name, country = this.country, type = this.type, varietal = this.varietal, price = this.price )
19
Kotlin
1
12
5c001d291d145548dcf006799a10fcd7639e10ef
649
WINEY-Android
MIT License
marvel-app-stater-main/app/src/main/java/daniel/lop/io/marvelappstarter/data/local/MarvelConverters.kt
pedroabreudev
607,452,286
false
null
package daniel.lop.io.marvelappstarter.data.local import androidx.room.TypeConverter import com.google.gson.Gson import daniel.lop.io.marvelappstarter.data.model.ThumbnailModel class MarvelConverters { @TypeConverter fun fromThumbnail(thumbnailModel: ThumbnailModel) : String = Gson().toJson(thumbnailModel) @TypeConverter fun toThumbnail(thumbnailModel: String) : ThumbnailModel = Gson().fromJson(thumbnailModel, ThumbnailModel::class.java) }
0
Kotlin
1
0
d87dfbb110e5503e238ddbbaa53c766e96a5ec17
471
Mobile-Development-Courses
MIT License
compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/receiver.kt
JakeWharton
99,388,807
false
null
// !LANGUAGE: +AllowContractsForCustomFunctions +UseReturnsEffect // !USE_EXPERIMENTAL: kotlin.contracts.ExperimentalContracts // !DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER // !WITH_NEW_INFERENCE import kotlin.contracts.* fun Any?.isNull(): Boolean { contract { returns(false) implies (this@isNull != null) } return this == null } fun smartcastOnReceiver(x: Int?) { if (x.isNull()) { x.<!AMBIGUITY!>inc<!>() } else { x.dec() } } class UnstableReceiver { var x: Int? = 42 fun smartcastOnUnstableReceiver() { if (x.isNull()) { x.<!AMBIGUITY!>inc<!>() } else { x.<!AMBIGUITY!>dec<!>() } } }
34
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
724
kotlin
Apache License 2.0
compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/receiver.kt
JakeWharton
99,388,807
false
null
// !LANGUAGE: +AllowContractsForCustomFunctions +UseReturnsEffect // !USE_EXPERIMENTAL: kotlin.contracts.ExperimentalContracts // !DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER // !WITH_NEW_INFERENCE import kotlin.contracts.* fun Any?.isNull(): Boolean { contract { returns(false) implies (this@isNull != null) } return this == null } fun smartcastOnReceiver(x: Int?) { if (x.isNull()) { x.<!AMBIGUITY!>inc<!>() } else { x.dec() } } class UnstableReceiver { var x: Int? = 42 fun smartcastOnUnstableReceiver() { if (x.isNull()) { x.<!AMBIGUITY!>inc<!>() } else { x.<!AMBIGUITY!>dec<!>() } } }
34
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
724
kotlin
Apache License 2.0
src/main/kotlin/com/mairwunnx/projectessentials/core/impl/vanilla/commands/GiveCommand.kt
KuroNoSeiHai
269,961,473
true
{"Kotlin": 564654, "Java": 145273, "Groovy": 4174}
/** * This command implementation by Mojang. * And decompiled with idea source code was converted * to kotlin code. * Also added some logic, for example checking on * permissions, and for some commands shorten aliases. * * 1. This can be bad code. * 2. This file can be not formatter pretty. */ package com.mairwunnx.projectessentials.core.impl.vanilla.commands import com.mairwunnx.projectessentials.core.api.v1.SETTING_LOC_ENABLED import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAPI import com.mairwunnx.projectessentials.core.api.v1.commands.CommandAliases import com.mairwunnx.projectessentials.core.api.v1.extensions.hoverEventFrom import com.mairwunnx.projectessentials.core.api.v1.extensions.textComponentFrom import com.mairwunnx.projectessentials.core.api.v1.permissions.hasPermission import com.mojang.brigadier.CommandDispatcher import com.mojang.brigadier.arguments.IntegerArgumentType import com.mojang.brigadier.exceptions.CommandSyntaxException import net.minecraft.command.CommandException import net.minecraft.command.CommandSource import net.minecraft.command.Commands import net.minecraft.command.arguments.EntityArgument import net.minecraft.command.arguments.ItemArgument import net.minecraft.command.arguments.ItemInput import net.minecraft.entity.player.PlayerEntity import net.minecraft.entity.player.ServerPlayerEntity import net.minecraft.util.SoundCategory import net.minecraft.util.SoundEvents import net.minecraft.util.text.Style import net.minecraft.util.text.TranslationTextComponent import kotlin.math.min internal object GiveCommand : VanillaCommandBase() { private var aliases = configuration.take().aliases.give + "give" private fun tryAssignAliases() { CommandAliases.aliases["give"] = aliases.toMutableList() } fun register(dispatcher: CommandDispatcher<CommandSource>) { CommandAPI.removeCommand("give") tryAssignAliases() aliases.forEach { command -> dispatcher.register( Commands.literal(command).then( Commands.argument( "targets", EntityArgument.players() ).then( Commands.argument( "item", ItemArgument.item() ).executes { p_198493_0_ -> giveItem( p_198493_0_.source, ItemArgument.getItem(p_198493_0_, "item"), EntityArgument.getPlayers(p_198493_0_, "targets"), 1 ) }.then( Commands.argument( "count", IntegerArgumentType.integer(1) ).executes { p_198495_0_ -> giveItem( p_198495_0_.source, ItemArgument.getItem(p_198495_0_, "item"), EntityArgument.getPlayers(p_198495_0_, "targets"), IntegerArgumentType.getInteger(p_198495_0_, "count") ) } ) ) ) ) } } private fun checkPermissions(source: CommandSource) { try { if (!hasPermission(source.asPlayer(), "native.give", 2)) { throw CommandException( textComponentFrom( source.asPlayer(), generalConfiguration.getBool(SETTING_LOC_ENABLED), "native.command.restricted" ).setStyle( Style().setHoverEvent( hoverEventFrom( source.asPlayer(), generalConfiguration.getBool(SETTING_LOC_ENABLED), "native.command.restricted_hover", "native.give", "2" ) ) ) ) } } catch (e: CommandSyntaxException) { // ignored, because command executed by server. } } @Throws(CommandSyntaxException::class) private fun giveItem( source: CommandSource, itemIn: ItemInput, targets: Collection<ServerPlayerEntity>, count: Int ): Int { checkPermissions(source) for (serverplayerentity in targets) { var i = count while (i > 0) { @Suppress("DEPRECATION") val j = min(itemIn.item.maxStackSize, i) i -= j val itemstack = itemIn.createStack(j, false) val flag = serverplayerentity.inventory.addItemStackToInventory(itemstack) if (flag && itemstack.isEmpty) { itemstack.count = 1 val itementity1 = serverplayerentity.dropItem(itemstack, false) itementity1?.makeFakeItem() serverplayerentity.world.playSound( null as PlayerEntity?, serverplayerentity.posX, serverplayerentity.posY, serverplayerentity.posZ, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.2f, ((serverplayerentity.rng.nextFloat() - serverplayerentity.rng.nextFloat()) * 0.7f + 1.0f) * 2.0f ) serverplayerentity.container.detectAndSendChanges() } else { val itementity = serverplayerentity.dropItem(itemstack, false) if (itementity != null) { itementity.setNoPickupDelay() itementity.ownerId = serverplayerentity.uniqueID } } } } if (targets.size == 1) { source.sendFeedback( TranslationTextComponent( "commands.give.success.single", count, itemIn.createStack(count, false).textComponent, targets.iterator().next().displayName ), true ) } else { source.sendFeedback( TranslationTextComponent( "commands.give.success.single", count, itemIn.createStack(count, false).textComponent, targets.size ), true ) } return targets.size } }
0
Kotlin
0
0
6bdd903e1c98858003922051971b40a96174f50a
6,797
ProjectEssentials-Core
MIT License
platform/platform-impl/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectModelSynchronizer.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.configurationStore.StoreReloadManager import com.intellij.configurationStore.isFireStorageFileChangedEvent import com.intellij.diagnostic.Activity import com.intellij.diagnostic.StartUpMeasurer.startActivity import com.intellij.ide.highlighter.ModuleFileType import com.intellij.ide.highlighter.ProjectFileType import com.intellij.openapi.Disposable import com.intellij.openapi.application.writeAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ProjectLoadingErrorsNotifier import com.intellij.openapi.module.impl.ModuleManagerEx import com.intellij.openapi.module.impl.UnloadedModulesListStorage import com.intellij.openapi.project.ExternalStorageConfigurationManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.getExternalConfigurationDir import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.platform.backend.workspace.* import com.intellij.platform.backend.workspace.impl.internal import com.intellij.platform.diagnostic.telemetry.helpers.Milliseconds import com.intellij.platform.diagnostic.telemetry.helpers.MillisecondsMeasurer import com.intellij.platform.workspace.jps.* import com.intellij.platform.workspace.jps.entities.ModuleEntity import com.intellij.platform.workspace.jps.serialization.impl.* import com.intellij.platform.workspace.jps.serialization.impl.JpsProjectEntitiesLoader.createProjectSerializers import com.intellij.platform.workspace.storage.DummyParentEntitySource import com.intellij.platform.workspace.storage.EntitySource import com.intellij.platform.workspace.storage.MutableEntityStorage import com.intellij.platform.workspace.storage.VersionedStorageChange import com.intellij.platform.workspace.storage.instrumentation.EntityStorageInstrumentationApi import com.intellij.platform.workspace.storage.instrumentation.MutableEntityStorageInstrumentation import com.intellij.platform.workspace.storage.url.VirtualFileUrlManager import com.intellij.project.stateStore import com.intellij.util.PlatformUtils.* import com.intellij.workspaceModel.ide.EntitiesOrphanage import com.intellij.workspaceModel.ide.getJpsProjectConfigLocation import com.intellij.workspaceModel.ide.impl.* import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LegacyCustomLibraryEntitySource import io.opentelemetry.api.metrics.Meter import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.util.JpsPathUtil import java.util.* import java.util.concurrent.atomic.AtomicReference /** * Manages serialization and deserialization from JPS format (*.iml and *.ipr files, .idea directory) for a workspace model in the IDE. */ @Service(Service.Level.PROJECT) class JpsProjectModelSynchronizer(private val project: Project) : Disposable { companion object { fun getInstance(project: Project): JpsProjectModelSynchronizer = project.service() private val LOG = logger<JpsProjectModelSynchronizer>() private val jpsLoadProjectToEmptyStorageTimeMs = MillisecondsMeasurer() private val reloadProjectEntitiesTimeMs = MillisecondsMeasurer() private val applyLoadedStorageTimeMs = MillisecondsMeasurer() private val saveChangedProjectEntitiesTimeMs = MillisecondsMeasurer() private fun setupOpenTelemetryReporting(meter: Meter) { val jpsLoadProjectToEmptyStorageTimeCounter = meter.counterBuilder("jps.load.project.to.empty.storage.ms").buildObserver() val reloadProjectEntitiesTimeCounter = meter.counterBuilder("jps.reload.project.entities.ms").buildObserver() val applyLoadedStorageTimeCounter = meter.counterBuilder("jps.apply.loaded.storage.ms").buildObserver() val saveChangedProjectEntitiesTimeCounter = meter.counterBuilder("jps.save.changed.project.entities.ms").buildObserver() meter.batchCallback( { jpsLoadProjectToEmptyStorageTimeCounter.record(jpsLoadProjectToEmptyStorageTimeMs.asMilliseconds()) reloadProjectEntitiesTimeCounter.record(reloadProjectEntitiesTimeMs.asMilliseconds()) applyLoadedStorageTimeCounter.record(applyLoadedStorageTimeMs.asMilliseconds()) saveChangedProjectEntitiesTimeCounter.record(saveChangedProjectEntitiesTimeMs.asMilliseconds()) }, jpsLoadProjectToEmptyStorageTimeCounter, reloadProjectEntitiesTimeCounter, applyLoadedStorageTimeCounter, saveChangedProjectEntitiesTimeCounter ) } init { setupOpenTelemetryReporting(jpsMetrics.meter) } } private val incomingChanges = Collections.synchronizedList(ArrayList<JpsConfigurationFilesChange>()) private val virtualFileManager: VirtualFileUrlManager = WorkspaceModel.getInstance(project).getVirtualFileUrlManager() private lateinit var fileContentReader: JpsFileContentReaderWithCache private val serializers = AtomicReference<JpsProjectSerializers?>() private val sourcesToSave = Collections.synchronizedSet(HashSet<EntitySource>()) private var activity: Activity? = null private var childActivity: Activity? = null fun needToReloadProjectEntities(): Boolean { if (StoreReloadManager.getInstance(project).isReloadBlocked() || serializers.get() == null) { return false } synchronized(incomingChanges) { return incomingChanges.isNotEmpty() } } @OptIn(EntityStorageInstrumentationApi::class) suspend fun reloadProjectEntities() = reloadProjectEntitiesTimeMs.addMeasuredTime { if (StoreReloadManager.getInstance(project).isReloadBlocked()) { LOG.debug("Skip reloading because it's blocked") return@addMeasuredTime } val serializers = serializers.get() if (serializers == null) { LOG.debug("Skip reloading because initial loading wasn't performed yet") return@addMeasuredTime } val changes = getAndResetIncomingChanges() if (changes == null) { LOG.debug("Skip reloading because there are no changed files") return@addMeasuredTime } LOG.debug { "Reload entities from changed files:\n$changes" } val unloadedModuleNameHolder = UnloadedModulesListStorage.getInstance(project).unloadedModuleNameHolder val reloadingResult = loadAndReportErrors { serializers.reloadFromChangedFiles(changes, fileContentReader, unloadedModuleNameHolder, it) } fileContentReader.clearCache() LOG.debugValues("Changed entity sources", reloadingResult.affectedSources) if (reloadingResult.affectedSources.isEmpty() && !(reloadingResult.builder as MutableEntityStorageInstrumentation).hasChanges() && !(reloadingResult.unloadedEntityBuilder as MutableEntityStorageInstrumentation).hasChanges() && !(reloadingResult.orphanageBuilder as MutableEntityStorageInstrumentation).hasChanges()) { return@addMeasuredTime } val description = "Reload entities after changes in JPS configuration files" val affectedEntityFilter: (EntitySource) -> Boolean = { it in reloadingResult.affectedSources || (it is JpsImportedEntitySource && !it.storedExternally && it.internalFile in reloadingResult.affectedSources) || it is DummyParentEntitySource } applyLoadedEntities(affectedEntityFilter, reloadingResult.builder, reloadingResult.unloadedEntityBuilder, reloadingResult.orphanageBuilder, description) { sourcesToSave.removeAll(reloadingResult.affectedSources) } } @OptIn(EntityStorageInstrumentationApi::class) private suspend fun applyLoadedEntities(sourcesFilter: (EntitySource) -> Boolean, builder: MutableEntityStorage, unloadedEntityBuilder: MutableEntityStorage, orphanageBuilder: MutableEntityStorage, description: String, onSuccessCallback: () -> Unit) { class CalculationResult(val builderSnapshot: BuilderSnapshot, val unloadBuilderSnapshot: BuilderSnapshot, val unloadedBuilderCopy: MutableEntityStorage, val modulesToLoad: List<String>, val modulesToUnload: List<String>) @OptIn(EntityStorageInstrumentationApi::class) fun calculateChanges(): CalculationResult { val workspaceModelImpl = WorkspaceModel.getInstance(project) as WorkspaceModelImpl val unloadBuilderSnapshot = workspaceModelImpl.getUnloadBuilderSnapshot() // Update builder of unloaded entities if ((unloadedEntityBuilder as MutableEntityStorageInstrumentation).hasChanges()) { unloadBuilderSnapshot.builder.replaceBySource(sourcesFilter, unloadedEntityBuilder.toSnapshot()) } // Update builder of regular entities val builderSnapshot = workspaceModelImpl.getBuilderSnapshot() builderSnapshot.builder.replaceBySource(sourcesFilter, builder.toSnapshot()) val unloadedBuilderCopy = MutableEntityStorage.from(unloadBuilderSnapshot.builder.toSnapshot()) val moduleManagerEx = ModuleManagerEx.getInstanceEx(project) val (modulesToLoad, modulesToUnload) = moduleManagerEx.calculateUnloadModules(builderSnapshot.builder, unloadedBuilderCopy) return CalculationResult(builderSnapshot, unloadBuilderSnapshot, unloadedBuilderCopy, modulesToLoad, modulesToUnload) } @OptIn(EntityStorageInstrumentationApi::class) fun applyLoadedChanges(calculationResult: CalculationResult): Boolean { val workspaceModelImpl = WorkspaceModel.getInstance(project) as WorkspaceModelImpl val moduleManagerEx = ModuleManagerEx.getInstanceEx(project) // TODO If we don't have changes in [UNLOAD] part, it doesn't make sense to use this method val isSuccessful = workspaceModelImpl.replaceProjectModel(calculationResult.builderSnapshot.getStorageReplacement(), calculationResult.unloadBuilderSnapshot.getStorageReplacement()) if (!isSuccessful) return false moduleManagerEx.updateUnloadedStorage(calculationResult.modulesToLoad, calculationResult.modulesToUnload) addUnloadedModuleEntities(calculationResult.unloadedBuilderCopy) if ((orphanageBuilder as MutableEntityStorageInstrumentation).hasChanges()) { EntitiesOrphanage.getInstance(project).update { it.applyChangesFrom(orphanageBuilder) } } onSuccessCallback() return true } suspend fun applyChangesWithRetry(retryCount: Int): Boolean { for (i in 1..retryCount) { LOG.info("Attempt $i: $description") val calculationResult = calculateChanges() val isSuccessful = writeAction { applyLoadedChanges(calculationResult) } if (isSuccessful) { LOG.info("Attempt $i: Changes were successfully applied") return true } } return false } val isSuccessful = applyChangesWithRetry(2) if (isSuccessful) return // Fallback strategy after the two unsuccessful attempts to apply the changes writeAction { LOG.info("Fallback strategy after the unsuccessful attempts to apply the changes from BGT") val calculationResult = calculateChanges() applyLoadedChanges(calculationResult) } } private inline fun <T> loadAndReportErrors(action: (ErrorReporter) -> T): T { val reporter = IdeErrorReporter(project) val result = action(reporter) val errors = reporter.errors if (errors.isNotEmpty()) { ProjectLoadingErrorsNotifier.getInstance(project).registerErrors(errors) } return result } private fun registerListener() { fun isParentOfStorageFiles(dir: VirtualFile): Boolean { if (dir.name == Project.DIRECTORY_STORE_FOLDER) return true val grandParent = dir.parent return grandParent != null && grandParent.name == Project.DIRECTORY_STORE_FOLDER } fun isStorageFile(file: VirtualFile): Boolean { val fileName = file.name if ((FileUtilRt.extensionEquals(fileName, ModuleFileType.DEFAULT_EXTENSION) || FileUtilRt.extensionEquals(fileName, ProjectFileType.DEFAULT_EXTENSION)) && !file.isDirectory) return true val parent = file.parent return parent != null && isParentOfStorageFiles(parent) } val connection = project.messageBus.connect(this) connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { //todo support move/rename //todo optimize: filter events before creating lists var addedUrls: MutableList<String>? = null var removedUrls: MutableList<String>? = null var changedUrls: MutableList<String>? = null // JPS model is loaded from *.iml files, files in .idea directory (modules.xml), // files from directories in .idea (libraries) and *.ipr file, so we can ignore all other events to speed up processing for (event in events) { if (isFireStorageFileChangedEvent(event)) { when (event) { is VFileCreateEvent -> { val fileName = event.childName if ((FileUtilRt.extensionEquals(fileName, ModuleFileType.DEFAULT_EXTENSION) && !event.isDirectory) || isParentOfStorageFiles(event.parent) && !event.isEmptyDirectory) { if (addedUrls == null) { addedUrls = mutableListOf() } addedUrls.add(JpsPathUtil.pathToUrl(event.path)) } } is VFileDeleteEvent -> { if (isStorageFile(event.file)) { if (removedUrls == null) { removedUrls = mutableListOf() } removedUrls.add(JpsPathUtil.pathToUrl(event.path)) } } is VFileContentChangeEvent -> { if (isStorageFile(event.file)) { if (changedUrls == null) { changedUrls = mutableListOf() } changedUrls.add(JpsPathUtil.pathToUrl(event.path)) } } } } } if (!addedUrls.isNullOrEmpty() || !removedUrls.isNullOrEmpty() || !changedUrls.isNullOrEmpty()) { val change = JpsConfigurationFilesChange(addedFileUrls = addedUrls ?: emptyList(), removedFileUrls = removedUrls ?: emptyList(), changedFileUrls = changedUrls ?: emptyList()) incomingChanges.add(change) project.serviceIfCreated<StoreReloadManager>()?.scheduleProcessingChangedFiles() } } }) val listener = object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { LOG.debug("Marking changed entities for save") for (change in event.getAllChanges()) { change.oldEntity?.entitySource?.let { if (it !is JpsGlobalFileEntitySource) sourcesToSave.add(it) } change.newEntity?.entitySource?.let { if (it !is JpsGlobalFileEntitySource) sourcesToSave.add(it) } } } } connection.subscribe(WorkspaceModelTopics.CHANGED, listener) connection.subscribe(WorkspaceModelTopics.UNLOADED_ENTITIES_CHANGED, object : WorkspaceModelUnloadedStorageChangeListener { override fun changed(event: VersionedStorageChange) { listener.changed(event) } }) } suspend fun loadProjectToEmptyStorage(project: Project): LoadedProjectEntities? { val start = Milliseconds.now() val configLocation = getJpsProjectConfigLocation(project)!! LOG.debug { "Initial loading of project located at $configLocation" } activity = startActivity("project workspace model loading") childActivity = activity?.startChild("serializers creation") val serializers = prepareSerializers() registerListener() val builder = MutableEntityStorage.create() val orphanage = MutableEntityStorage.create() val unloadedEntitiesBuilder = MutableEntityStorage.create() val loadedProjectEntities = if (!WorkspaceModelInitialTestContent.hasInitialContent) { childActivity = childActivity?.endAndStart("loading entities from files") val unloadedModuleNamesHolder = UnloadedModulesListStorage.getInstance(project).unloadedModuleNameHolder val sourcesToUpdate = loadAndReportErrors { serializers.loadAll(fileContentReader, builder, orphanage, unloadedEntitiesBuilder, unloadedModuleNamesHolder, it) } fileContentReader.clearCache() (WorkspaceModel.getInstance(project) as? WorkspaceModelImpl)?.entityTracer?.printInfoAboutTracedEntity(builder, "JPS files") childActivity = childActivity?.endAndStart("applying entities from global storage") val mutableStorage = MutableEntityStorage.create() GlobalWorkspaceModel.getInstance().applyStateToProjectBuilder(project, mutableStorage) builder.applyChangesFrom(mutableStorage) childActivity = childActivity?.endAndStart("applying loaded changes (in queue)") LoadedProjectEntities(builder, orphanage, unloadedEntitiesBuilder, sourcesToUpdate) } else { childActivity?.end() childActivity = null activity?.end() activity = null null } jpsLoadProjectToEmptyStorageTimeMs.addElapsedTime(start) WorkspaceModelFusLogger.logLoadingJpsFromIml(Milliseconds.now().minus(start).value) return loadedProjectEntities } suspend fun applyLoadedStorage(projectEntities: LoadedProjectEntities?) = applyLoadedStorageTimeMs.addMeasuredTime { if (projectEntities == null) { return@addMeasuredTime } val description = "Apply JPS storage (iml files)" val sourceFilter = { entitySource: EntitySource -> entitySource is JpsFileEntitySource // covers all global SDK and libraries || entitySource is JpsFileDependentEntitySource || entitySource is CustomModuleEntitySource || entitySource is DummyParentEntitySource // covers CIDR related entities || entitySource is LegacyCustomLibraryEntitySource // covers custom libraries } childActivity = childActivity?.endAndStart("applying loaded changes") applyLoadedEntities(sourceFilter, projectEntities.builder, projectEntities.unloadedEntitiesBuilder, projectEntities.orphanageBuilder, description) { sourcesToSave.clear() sourcesToSave.addAll(projectEntities.sourcesToUpdate) } childActivity?.end() childActivity = null activity?.end() activity = null } suspend fun loadProject(project: Project) { applyLoadedStorage(loadProjectToEmptyStorage(project)) } @OptIn(EntityStorageInstrumentationApi::class) private fun addUnloadedModuleEntities(diff: MutableEntityStorage) { if ((diff as MutableEntityStorageInstrumentation).hasChanges()) { WorkspaceModel.getInstance(project).internal.updateUnloadedEntities("Add new unloaded modules") { updater -> updater.applyChangesFrom(diff) } } } // IDEA-288703 fun hasNoSerializedJpsModules(): Boolean { return !isIntelliJ() && // todo: https://youtrack.jetbrains.com/issue/IDEA-291451#focus=Comments-27-5967781.0-0 !isRider() && !isFleetBackend() && // https://youtrack.jetbrains.com/issue/IDEA-323592#focus=Comments-27-7967807.0-0 (prepareSerializers() as JpsProjectSerializersImpl).moduleSerializers.isEmpty() } private fun prepareSerializers(): JpsProjectSerializers { val existingSerializers = this.serializers.get() if (existingSerializers != null) return existingSerializers val serializers = createSerializers() this.serializers.set(serializers) return serializers } private fun createSerializers(): JpsProjectSerializers { val configLocation: JpsProjectConfigLocation = getJpsProjectConfigLocation(project)!! fileContentReader = (project.stateStore as ProjectStoreWithJpsContentReader).createContentReader() val externalStoragePath = project.getExternalConfigurationDir() val externalStorageConfigurationManager = ExternalStorageConfigurationManager.getInstance(project) val fileInDirectorySourceNames = FileInDirectorySourceNames.from(WorkspaceModel.getInstance(project).currentSnapshot) val context = IdeSerializationContext(virtualFileManager, fileContentReader, fileInDirectorySourceNames, externalStorageConfigurationManager) return createProjectSerializers(configLocation, externalStoragePath, context) } fun saveChangedProjectEntities(writer: JpsFileContentWriter) = saveChangedProjectEntitiesTimeMs.addMeasuredTime { LOG.debug("Saving project entities") val data = serializers.get() if (data == null) { LOG.debug("Skipping save because initial loading wasn't performed") return@addMeasuredTime } val storage = WorkspaceModel.getInstance(project).currentSnapshot val unloadedEntitiesStorage = WorkspaceModel.getInstance(project).internal.currentSnapshotOfUnloadedEntities val affectedSources = synchronized(sourcesToSave) { val copy = HashSet(sourcesToSave) sourcesToSave.clear() copy } LOG.debugValues("Saving affected entities", affectedSources) data.saveEntities(storage, unloadedEntitiesStorage, affectedSources, writer) } fun convertToDirectoryBasedFormat() { val newSerializers = createSerializers() WorkspaceModel.getInstance(project).updateProjectModel("Convert to directory based format") { newSerializers.changeEntitySourcesToDirectoryBasedFormat(it) } val moduleSources = WorkspaceModel.getInstance(project).currentSnapshot.entities(ModuleEntity::class.java).map { it.entitySource } val unloadedModuleSources = WorkspaceModel.getInstance(project).internal.currentSnapshotOfUnloadedEntities.entities( ModuleEntity::class.java).map { it.entitySource } synchronized(sourcesToSave) { // trigger save for modules.xml sourcesToSave.addAll(moduleSources) sourcesToSave.addAll(unloadedModuleSources) } serializers.set(newSerializers) } @TestOnly fun markAllEntitiesAsDirty() { val allSources = WorkspaceModel.getInstance(project).currentSnapshot.entitiesBySource { true }.mapTo(HashSet()) { it.entitySource } + WorkspaceModel.getInstance(project).internal.currentSnapshotOfUnloadedEntities.entitiesBySource { true }.mapTo( HashSet()) { it.entitySource } synchronized(sourcesToSave) { sourcesToSave.addAll(allSources) } } private fun getAndResetIncomingChanges(): JpsConfigurationFilesChange? { synchronized(incomingChanges) { if (incomingChanges.isEmpty()) return null val combinedChanges = combineChanges() incomingChanges.clear() return combinedChanges } } private fun combineChanges(): JpsConfigurationFilesChange { val singleChange = incomingChanges.singleOrNull() if (singleChange != null) { return singleChange } val allAdded = LinkedHashSet<String>() val allRemoved = LinkedHashSet<String>() val allChanged = LinkedHashSet<String>() for (change in incomingChanges) { allChanged.addAll(change.changedFileUrls) for (addedUrl in change.addedFileUrls) { if (allRemoved.remove(addedUrl)) { allChanged.add(addedUrl) } else { allAdded.add(addedUrl) } } for (removedUrl in change.removedFileUrls) { allChanged.remove(removedUrl) if (!allAdded.remove(removedUrl)) { allRemoved.add(removedUrl) } } } return JpsConfigurationFilesChange(allAdded, allRemoved, allChanged) } override fun dispose() { } @TestOnly fun getSerializers(): JpsProjectSerializersImpl = serializers.get() as JpsProjectSerializersImpl } class LoadedProjectEntities( val builder: MutableEntityStorage, val orphanageBuilder: MutableEntityStorage, val unloadedEntitiesBuilder: MutableEntityStorage, val sourcesToUpdate: List<EntitySource> )
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
24,802
intellij-community
Apache License 2.0
app/src/main/java/com/ahmet/kotlinanimalapp/service/AnimalDatabase.kt
ahmetufan
487,898,639
false
{"Kotlin": 25223}
package com.ahmet.kotlinanimalapp.service import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.ahmet.kotlinanimalapp.model.Model2 @Database(entities = [Model2::class], version = 1) abstract class AnimalDatabase:RoomDatabase() { abstract fun animalDao2(): AnimalDao companion object { @Volatile private var instance: AnimalDatabase?=null private val lock=Any() operator fun invoke(context:Context)= instance ?: synchronized(lock) { instance ?: makeDatabase(context).also { instance =it } } private fun makeDatabase(context: Context)= Room.databaseBuilder( context.applicationContext, AnimalDatabase::class.java,"animaldatabase").build() } }
0
Kotlin
0
0
f54e704e51c131c4d770883ef7c311b84c8499e4
831
AnimalApp
MIT License
common/src/main/java/com/revenuecat/purchases/common/Backend.kt
RevenueCat
127,346,826
false
null
// Purchases // // Copyright © 2019 RevenueCat, Inc. All rights reserved. // package com.revenuecat.purchases.common import android.net.Uri import com.revenuecat.purchases.PurchaserInfo import com.revenuecat.purchases.PurchasesError import com.revenuecat.purchases.PurchasesErrorCode import com.revenuecat.purchases.common.attribution.AttributionNetwork import org.json.JSONException import org.json.JSONObject private const val HTTP_STATUS_CREATED = 201 private const val UNSUCCESSFUL_HTTP_STATUS_CODE = 300 const val HTTP_SERVER_ERROR_CODE = 500 const val HTTP_NOT_FOUND_ERROR_CODE = 404 const val ATTRIBUTES_ERROR_RESPONSE_KEY = "attributes_error_response" const val ATTRIBUTE_ERRORS_KEY = "attribute_errors" /** @suppress */ internal typealias PurchaserInfoCallback = Pair<(PurchaserInfo) -> Unit, (PurchasesError) -> Unit> /** @suppress */ typealias PostReceiptCallback = Pair<PostReceiptDataSuccessCallback, PostReceiptDataErrorCallback> /** @suppress */ typealias CallbackCacheKey = List<String> /** @suppress */ typealias OfferingsCallback = Pair<(JSONObject) -> Unit, (PurchasesError) -> Unit> /** @suppress */ typealias PostReceiptDataSuccessCallback = (PurchaserInfo, body: JSONObject) -> Unit /** @suppress */ typealias PostReceiptDataErrorCallback = (PurchasesError, shouldConsumePurchase: Boolean, body: JSONObject?) -> Unit class Backend( private val apiKey: String, private val dispatcher: Dispatcher, private val httpClient: HTTPClient ) { internal val authenticationHeaders = mapOf("Authorization" to "Bearer ${this.apiKey}") @get:Synchronized @set:Synchronized @Volatile var callbacks = mutableMapOf<CallbackCacheKey, MutableList<PurchaserInfoCallback>>() @get:Synchronized @set:Synchronized @Volatile var postReceiptCallbacks = mutableMapOf<CallbackCacheKey, MutableList<PostReceiptCallback>>() @get:Synchronized @set:Synchronized @Volatile var offeringsCallbacks = mutableMapOf<String, MutableList<OfferingsCallback>>() fun close() { this.dispatcher.close() } fun performRequest( path: String, body: Map<String, Any?>?, onError: (PurchasesError) -> Unit, onCompleted: (PurchasesError?, Int, JSONObject) -> Unit ) { enqueue(object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( path, body, authenticationHeaders ) } override fun onError(error: PurchasesError) { onError(error) } override fun onCompletion(result: HTTPClient.Result) { val error = if (!result.isSuccessful()) { result.toPurchasesError().also { errorLog(it) } } else { null } onCompleted(error, result.responseCode, result.body) } }) } private fun enqueue( call: Dispatcher.AsyncCall, randomDelay: Boolean = false ) { if (!dispatcher.isClosed()) { dispatcher.enqueue(call, randomDelay) } } fun getPurchaserInfo( appUserID: String, appInBackground: Boolean, onSuccess: (PurchaserInfo) -> Unit, onError: (PurchasesError) -> Unit ) { val path = "/subscribers/" + encode(appUserID) val cacheKey = listOf(path) val call = object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( "/subscribers/" + encode(appUserID), null, authenticationHeaders ) } override fun onCompletion(result: HTTPClient.Result) { synchronized(this@Backend) { callbacks.remove(cacheKey) }?.forEach { (onSuccess, onError) -> try { if (result.isSuccessful()) { onSuccess(result.body.buildPurchaserInfo()) } else { onError(result.toPurchasesError().also { errorLog(it) }) } } catch (e: JSONException) { onError(e.toPurchasesError().also { errorLog(it) }) } } } override fun onError(error: PurchasesError) { synchronized(this@Backend) { callbacks.remove(cacheKey) }?.forEach { (_, onError) -> onError(error) } } } synchronized(this@Backend) { callbacks.addCallback(call, cacheKey, onSuccess to onError, randomDelay = appInBackground) } } @SuppressWarnings("LongParameterList", "ForbiddenComment") fun postReceiptData( purchaseToken: String, appUserID: String, isRestore: Boolean, observerMode: Boolean, subscriberAttributes: Map<String, Map<String, Any?>>, receiptInfo: ReceiptInfo, storeAppUserID: String?, onSuccess: PostReceiptDataSuccessCallback, onError: PostReceiptDataErrorCallback ) { val cacheKey = listOfNotNull( purchaseToken, appUserID, isRestore.toString(), observerMode.toString(), subscriberAttributes.toString(), receiptInfo.toString(), storeAppUserID ) val body = mapOf( "fetch_token" to purchaseToken, "product_id" to receiptInfo.productID, "app_user_id" to appUserID, "is_restore" to isRestore, "presented_offering_identifier" to receiptInfo.offeringIdentifier, "observer_mode" to observerMode, "price" to receiptInfo.price, "currency" to receiptInfo.currency, "attributes" to subscriberAttributes.takeUnless { it.isEmpty() }, "normal_duration" to receiptInfo.duration, "intro_duration" to receiptInfo.introDuration, "trial_duration" to receiptInfo.trialDuration, "store_user_id" to storeAppUserID ).filterValues { value -> value != null } val call = object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( "/receipts", body, authenticationHeaders ) } override fun onCompletion(result: HTTPClient.Result) { synchronized(this@Backend) { postReceiptCallbacks.remove(cacheKey) }?.forEach { (onSuccess, onError) -> try { if (result.isSuccessful()) { onSuccess(result.body.buildPurchaserInfo(), result.body) } else { onError( result.toPurchasesError().also { errorLog(it) }, result.responseCode < HTTP_SERVER_ERROR_CODE, result.body ) } } catch (e: JSONException) { onError(e.toPurchasesError().also { errorLog(it) }, false, null) } } } override fun onError(error: PurchasesError) { synchronized(this@Backend) { postReceiptCallbacks.remove(cacheKey) }?.forEach { (_, onError) -> onError( error, false, null ) } } } synchronized(this@Backend) { postReceiptCallbacks.addCallback(call, cacheKey, onSuccess to onError) } } fun getOfferings( appUserID: String, appInBackground: Boolean, onSuccess: (JSONObject) -> Unit, onError: (PurchasesError) -> Unit ) { val path = "/subscribers/" + encode(appUserID) + "/offerings" val call = object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( path, null, authenticationHeaders ) } override fun onError(error: PurchasesError) { synchronized(this@Backend) { offeringsCallbacks.remove(path) }?.forEach { (_, onError) -> onError(error) } } override fun onCompletion(result: HTTPClient.Result) { synchronized(this@Backend) { offeringsCallbacks.remove(path) }?.forEach { (onSuccess, onError) -> if (result.isSuccessful()) { try { onSuccess(result.body) } catch (e: JSONException) { onError(e.toPurchasesError().also { errorLog(it) }) } } else { onError(result.toPurchasesError().also { errorLog(it) }) } } } } synchronized(this@Backend) { offeringsCallbacks.addCallback(call, path, onSuccess to onError, randomDelay = appInBackground) } } private fun encode(string: String): String { return Uri.encode(string) } fun postAttributionData( appUserID: String, network: AttributionNetwork, data: JSONObject, onSuccessHandler: () -> Unit ) { if (data.length() == 0) return val body = mapOf( "network" to network.serverValue, "data" to data ) enqueue(object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( "/subscribers/" + encode(appUserID) + "/attribution", body, authenticationHeaders ) } override fun onCompletion(result: HTTPClient.Result) { if (result.isSuccessful()) { onSuccessHandler() } } }) } fun createAlias( appUserID: String, newAppUserID: String, onSuccessHandler: () -> Unit, onErrorHandler: (PurchasesError) -> Unit ) { enqueue(object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( "/subscribers/" + encode(appUserID) + "/alias", mapOf("new_app_user_id" to newAppUserID), authenticationHeaders ) } override fun onError(error: PurchasesError) { onErrorHandler(error) } override fun onCompletion(result: HTTPClient.Result) { if (result.isSuccessful()) { onSuccessHandler() } else { onErrorHandler(result.toPurchasesError().also { errorLog(it) }) } } }) } fun logIn( appUserID: String, newAppUserID: String, onSuccessHandler: (PurchaserInfo, Boolean) -> Unit, onErrorHandler: (PurchasesError) -> Unit ) { enqueue(object : Dispatcher.AsyncCall() { override fun call(): HTTPClient.Result { return httpClient.performRequest( "/subscribers/identify", mapOf( "new_app_user_id" to newAppUserID, "app_user_id" to appUserID ), authenticationHeaders ) } override fun onError(error: PurchasesError) { onErrorHandler(error) } override fun onCompletion(result: HTTPClient.Result) { if (result.isSuccessful()) { val created = result.responseCode == HTTP_STATUS_CREATED if (result.body.length() > 0) { val purchaserInfo = result.body.buildPurchaserInfo() onSuccessHandler(purchaserInfo, created) } else { onErrorHandler(PurchasesError(PurchasesErrorCode.UnknownError) .also { errorLog(it) }) } } else { onErrorHandler(result.toPurchasesError().also { errorLog(it) }) } } }) } private fun HTTPClient.Result.isSuccessful(): Boolean { return responseCode < UNSUCCESSFUL_HTTP_STATUS_CODE } private fun <K, S, E> MutableMap<K, MutableList<Pair<S, E>>>.addCallback( call: Dispatcher.AsyncCall, cacheKey: K, functions: Pair<S, E>, randomDelay: Boolean = false ) { if (!containsKey(cacheKey)) { this[cacheKey] = mutableListOf(functions) enqueue(call, randomDelay) } else { this[cacheKey]!!.add(functions) } } }
7
null
34
167
3663eb4ad21a76930b136d9e3dd1293b1680d493
13,648
purchases-android
MIT License
src/nativeMain/kotlin/Main.kt
Kotlin
709,686,971
false
{"Kotlin": 51}
fun main() { println("Hello, Kotlin/Native!") }
1
Kotlin
2
4
891fb5162a19ed17f7dff6a49ee58121b28e9f1c
52
kmp-native-wizard
Apache License 2.0
module_home/src/main/java/com/czl/module_home/activity/MainActivity.kt
pigletzzzzzz
516,985,475
false
{"Kotlin": 723880, "Java": 176802}
package com.czl.module_home.activity import com.alibaba.android.arouter.facade.annotation.Route import com.ashokvarma.bottomnavigation.BottomNavigationBar import com.ashokvarma.bottomnavigation.BottomNavigationItem import com.czl.lib_base.adapter.ViewPagerFmAdapter import com.czl.lib_base.base.AppManager import com.czl.lib_base.base.BaseActivity import com.czl.lib_base.config.AppConstants import com.czl.lib_base.route.RouteCenter import com.czl.module_home.BR import com.czl.module_home.R import com.czl.module_home.databinding.ActivityMainBinding import com.czl.module_home.viewmodel.MainViewModel import me.yokeyword.fragmentation.SupportFragment @Route(path = AppConstants.Router.Home.A_MAIN) class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() { private var touchTime: Long = 0L override fun initContentView(): Int { return R.layout.activity_main } override fun initVariableId(): Int { return BR.viewModel } override fun useBaseLayout(): Boolean { return false } override fun initViewObservable() { viewModel.uc.tabChangeLiveEvent.observe(this,{ binding.viewPager2.setCurrentItem(it,false) }) viewModel.uc.pageChangeLiveEvent.observe(this,{ binding.bottomBar.selectTab(it) }) } override fun initData() { initBottomBar() initViewPager() } private fun initViewPager(){ binding.viewPager2.isUserInputEnabled = false val homeFragment = RouteCenter.navigate(AppConstants.Router.Home.F_HOME) as SupportFragment//首页 val courseFragment = RouteCenter.navigate(AppConstants.Router.Course.F_COURSE) as SupportFragment//课程 val announceFragment = RouteCenter.navigate(AppConstants.Router.Announcement.F_ANNOU) as SupportFragment//公告 val mineFragment = RouteCenter.navigate(AppConstants.Router.Mine.F_MINE) as SupportFragment//个人中心 val fragments = arrayListOf(homeFragment,courseFragment,announceFragment,mineFragment) binding.viewPager2.apply { adapter = ViewPagerFmAdapter(supportFragmentManager,lifecycle,fragments) offscreenPageLimit = fragments.size } } private fun initBottomBar() { binding.bottomBar.apply { setMode(BottomNavigationBar.MODE_FIXED) setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC) addItem( BottomNavigationItem( R.mipmap.icon_sy_y, R.string.home_sy ).setActiveColorResource(com.czl.lib_base.R.color.base_color_2284FA) .setInactiveIconResource(R.mipmap.icon_sy_n) ) addItem( BottomNavigationItem( R.mipmap.icon_kc_y, R.string.home_kc ).setActiveColorResource(com.czl.lib_base.R.color.base_color_2284FA) .setInactiveIconResource(R.mipmap.icon_kc_n) ) addItem( BottomNavigationItem( R.mipmap.icon_gg_y, R.string.home_gg ).setActiveColorResource(com.czl.lib_base.R.color.base_color_2284FA) .setInactiveIconResource(R.mipmap.icon_gg_n) ) addItem( BottomNavigationItem( R.mipmap.icon_wd_y, R.string.home_wd ).setActiveColorResource(com.czl.lib_base.R.color.base_color_2284FA) .setInactiveIconResource(R.mipmap.icon_wd_n) ) setFirstSelectedPosition(0) initialise() } } override fun onBackPressedSupport() { if (System.currentTimeMillis() - touchTime < 2000L) { AppManager.instance.appExit() } else { touchTime = System.currentTimeMillis() showNormalToast(getString(R.string.home_main_press_again)) } } }
0
Kotlin
0
0
a3276c0149c7d2d3284a6a4d83fa5cb3874664e9
4,002
XPZX-New_Kotlin
Apache License 2.0
app/src/main/java/com/suyash/creditmanager/presentation/cc_detail/CCDetailViewModel.kt
suyash01
732,788,266
false
{"Kotlin": 282293}
package com.suyash.creditmanager.presentation.cc_detail import androidx.datastore.core.DataStore import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.suyash.creditmanager.data.settings.AppSettings import com.suyash.creditmanager.domain.model.CreditCard import com.suyash.creditmanager.domain.use_case.CreditCardUseCases import com.suyash.creditmanager.domain.use_case.EMIUseCases import com.suyash.creditmanager.domain.use_case.TransactionUseCases import com.suyash.creditmanager.domain.util.DateFormat import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CCDetailViewModel @Inject constructor( private val creditCardUseCases: CreditCardUseCases, private val transactionUseCases: TransactionUseCases, private val emiUseCases: EMIUseCases, private val dataStore: DataStore<AppSettings>, savedStateHandle: SavedStateHandle ): ViewModel() { var creditCard: CreditCard? = null var countryCode: String = "IN" var dateFormat: DateFormat = DateFormat.DDMMYYYY private var getCCDataJob: Job? = null private val _eventFlow = MutableSharedFlow<UiEvent>() val eventFlow = _eventFlow.asSharedFlow() init { viewModelScope.launch { dataStore.data.collect { countryCode = it.countryCode dateFormat = it.dateFormat } } savedStateHandle.get<Int>("ccId")?.let { getCreditCardData(it) } } fun onEvent(event: CCDetailEvent) { when (event) { is CCDetailEvent.BackPressed -> { viewModelScope.launch { _eventFlow.emit(UiEvent.NavigateUp) } } } } private fun getCreditCardData(it: Int) { getCCDataJob?.cancel() getCCDataJob = creditCardUseCases.getCreditCard(it).onEach { creditCard -> this.creditCard = creditCard }.launchIn(viewModelScope) } sealed class UiEvent { data class ShowSnackbar(val message: String): UiEvent() data object NavigateUp: UiEvent() } }
0
Kotlin
0
0
ea4bcd5c53d1b66c54ba144d0772378c5b4f566e
2,422
credit-manager
Apache License 2.0
app/src/main/java/com/example/skindiseasedetectionapp/model/UserModel.kt
Capstone-2022-C22-PS080
500,401,347
false
{"Kotlin": 126529}
package com.example.skindiseasedetectionapp.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class UserModel( var userId : String? = null, var email: String? = null, var name: String? = null, var default_profile: Int? = null, var photo_profile: String? = null, ) : Parcelable
0
Kotlin
1
0
389db0480b81f4ef88c0394783718e18963694bc
334
sskin-mobile
MIT License
src/main/kotlin/com/msg/gcms/domain/clubMember/service/impl/DelegateHeadServiceImpl.kt
GSM-MSG
592,816,374
false
null
package com.msg.gcms.domain.clubMember.service.impl import com.msg.gcms.domain.auth.domain.Role import com.msg.gcms.domain.club.domain.repository.ClubRepository import com.msg.gcms.domain.club.exception.ClubNotFoundException import com.msg.gcms.domain.club.exception.HeadNotSameException import com.msg.gcms.domain.club.exception.NotClubMemberException import com.msg.gcms.domain.clubMember.domain.repository.ClubMemberRepository import com.msg.gcms.domain.clubMember.presentation.data.dto.ChangeHeadDto import com.msg.gcms.domain.clubMember.presentation.data.dto.DelegateHeadDto import com.msg.gcms.domain.clubMember.service.DelegateHeadService import com.msg.gcms.domain.clubMember.util.UpdateClubHeadUtil import com.msg.gcms.domain.user.domain.repository.UserRepository import com.msg.gcms.domain.user.exception.UserNotFoundException import com.msg.gcms.global.fcm.enums.SendType import com.msg.gcms.global.util.MessageSendUtil import com.msg.gcms.global.util.UserUtil import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional(rollbackFor = [Exception::class]) class DelegateHeadServiceImpl( private val clubRepository: ClubRepository, private val clubMemberRepository: ClubMemberRepository, private val userRepository: UserRepository, private val updateClubHeadUtil: UpdateClubHeadUtil, private val userUtil: UserUtil, private val messageSendUtil: MessageSendUtil ) : DelegateHeadService { override fun execute(clubId: Long, delegateHeadDto: DelegateHeadDto): ChangeHeadDto { val club = (clubRepository.findByIdOrNull(clubId) ?: throw ClubNotFoundException()) val user = userUtil.fetchCurrentUser() val head = club.user if (head != user && !user.roles.contains(Role.ROLE_ADMIN)) throw HeadNotSameException() if (!userRepository.existsById(delegateHeadDto.uuid)) throw UserNotFoundException() val clubMember = clubMemberRepository.findAllByClub(club) .find { it.user.id == delegateHeadDto.uuid } ?: throw NotClubMemberException() updateClubHeadUtil.updateClubHead(club, clubMember, head) messageSendUtil.send(clubMember.user, "부장 위임", "${club.name}의 부장으로 위임되셨습니다.", SendType.CLUB) return ChangeHeadDto(clubMember.user, head) } }
9
null
0
8
d55e8ed3f343acca0c3937cf07b6fcfb8dd30598
2,431
GCMS-BackEnd
MIT License
src/main/kotlin/furhatos/app/cardgame/flow/trackUsers.kt
horotat
518,806,515
false
{"Kotlin": 252871, "JavaScript": 58777, "Java": 21569, "FreeMarker": 16510, "HTML": 4928, "CSS": 4484}
package furhatos.app.cardgame.flow import furhatos.app.cardgame.ActionPlayersUpdate import furhatos.app.cardgame.SenseSpeechDetected import furhatos.app.cardgame.attendCheck import furhatos.app.cardgame.leftToRight import furhatos.event.CustomEvent import furhatos.event.Event import furhatos.event.actions.ActionConfigRecognizer import furhatos.event.actions.ActionListen import furhatos.event.monitors.MonitorListenStart import furhatos.event.senses.SenseSpeech import furhatos.event.senses.SenseSpeechStart import furhatos.flow.kotlin.* fun FlowControlRunner.updateUsersOnGUI() { send(ActionPlayersUpdate(left = users.list.any {it.head.location.x < 0}, right = users.list.any {it.head.location.x > 0})) } val TrackUsers: State = state(null) { onUserEnter { updateUsersOnGUI() } onUserLeave { updateUsersOnGUI() } onEvent<ActionConfigRecognizer>(instant = true) { println("Recognizer primed with: " + it.phrases) } onEvent<MonitorListenStart> { furhat.ledStrip.solid(java.awt.Color.GRAY) } onEvent<SenseSpeech> { furhat.ledStrip.solid(java.awt.Color.BLACK) } onEvent<SenseSpeechStart>(instant=true) { if (users.count == 1) { raise(SenseSpeechDetected(user=users.list[0])) } } onEvent("SenseSpeechChannel", instant=true) { if (users.count > 1 && furhat.isListening) { raise(SenseSpeechDetected(user=users.leftToRight[it.getInteger("channel")])) } } }
0
Kotlin
0
0
a95aa619831614f5347cb7ffee762bbb32735211
1,518
Card-Game-21
Creative Commons Attribution 4.0 International
app/src/main/java/com/halfminute/itmadness/WordsJson.kt
Stensel8
722,087,681
false
{"Kotlin": 100847, "Java": 36512}
package com.halfminute.itmadness object WordsJson { @JvmField val myWords = """ { "easyWords": [ { "frWord": "Bonjour", "nlWord": "Goeiedag", "enWord": "Hello", "deWord": "Hallo" }, { "frWord": "Annuler", "nlWord": "Afzeggen", "enWord": "To cancel", "deWord": "Stornieren" }, { "frWord": "Voir", "nlWord": "Zien", "enWord": "To see", "deWord": "Sehen" }, { "frWord": "Prendre", "nlWord": "Nemen", "enWord": "To take", "deWord": "Nehmen" }, { "frWord": "Voiture", "nlWord": "Auto", "enWord": "Car", "deWord": "Auto" }, { "frWord": "Chaise", "nlWord": "Stoel", "enWord": "Chair", "deWord": "Stuhl" }, { "frWord": "Bonhomme", "nlWord": "Man", "enWord": "Guy", "deWord": "Mann" }, { "frWord": "Armoire", "nlWord": "Kleerkast", "enWord": "Wardrobe", "deWord": "Schrank" }, { "frWord": "Gentil", "nlWord": "Lief", "enWord": "Kind", "deWord": "Nett" }, { "frWord": "Jouer", "nlWord": "Spelen", "enWord": "Play", "deWord": "Spielen" }, { "frWord": "Écrire", "nlWord": "Schrijven", "enWord": "Write", "deWord": "Schreiben" }, { "frWord": "Sale", "nlWord": "Vuil", "enWord": "Dirty", "deWord": "Schmutzig" }, { "frWord": "Mer", "nlWord": "Zee", "enWord": "Sea", "deWord": "Meer" }, { "frWord": "Mère", "nlWord": "Moeder", "enWord": "Mother", "deWord": "Mutter" }, { "frWord": "Frère", "nlWord": "Broer", "enWord": "Brother", "deWord": "Bruder" }, { "frWord": "Tenir", "nlWord": "Vasthouden", "enWord": "To hold", "deWord": "Halten" }, { "frWord": "Tête", "nlWord": "Hoofd", "enWord": "Head", "deWord": "Kopf" }, { "frWord": "Mains", "nlWord": "Handen", "enWord": "Hands", "deWord": "Hände" }, { "frWord": "Oiseau", "nlWord": "Vogel", "enWord": "Bird", "deWord": "Vogel" }, { "frWord": "Arbre", "nlWord": "Boom", "enWord": "Tree", "deWord": "Baum" }, { "frWord": "Sol", "nlWord": "Vloer", "enWord": "Floor", "deWord": "Boden" }, { "frWord": "<NAME>", "nlWord": "Rugzak", "enWord": "Backpack", "deWord": "Rucksack" }, { "frWord": "Neveu", "nlWord": "Neef", "enWord": "Nephew", "deWord": "Neffe" }, { "frWord": "Trois", "nlWord": "Drie", "enWord": "Three", "deWord": "Drei" }, { "frWord": "Treize", "nlWord": "Dertien", "enWord": "Thirteen", "deWord": "Dreizehn" }, { "frWord": "Devenir", "nlWord": "Worden", "enWord": "To become", "deWord": "Werden" }, { "frWord": "Courir", "nlWord": "Remmen", "enWord": "To run", "deWord": "Laufen" }, { "frWord": "Trente", "nlWord": "Dertig", "enWord": "Thirty", "deWord": "Dreißig" }, { "frWord": "Meilleur", "nlWord": "Beste", "enWord": "Best", "deWord": "Beste" }, { "frWord": "Ongle", "nlWord": "Nagel", "enWord": "Nail", "deWord": "Nagel" }, { "frWord": "Forme", "nlWord": "Vorm", "enWord": "Shape", "deWord": "Form" }, { "frWord": "Près", "nlWord": "Dichtbij", "enWord": "Near", "deWord": "Nahe" }, { "frWord": "Amour", "nlWord": "Liefde", "enWord": "Love", "deWord": "Liebe" }, { "frWord": "Jeu", "nlWord": "Spel", "enWord": "Game", "deWord": "Spiel" }, { "frWord": "Balle", "nlWord": "Bal", "enWord": "Ball", "deWord": "Ball" }, { "frWord": "Chambre", "nlWord": "Kamer", "enWord": "Room", "deWord": "Zimmer" }, { "frWord": "Trouver", "nlWord": "Vinden", "enWord": "To find", "deWord": "Finden" }, { "frWord": "Poubelle", "nlWord": "Vuilnisbak", "enWord": "Trash can", "deWord": "Mülleimer" }, { "frWord": "Bouteille", "nlWord": "Fles", "enWord": "Bottle", "deWord": "Flasche" }, { "frWord": "Chose", "nlWord": "Iets", "enWord": "Thing", "deWord": "Sache" }, { "frWord": "Dessin", "nlWord": "Tekening", "enWord": "Drawing", "deWord": "Zeichnung" }, { "frWord": "Crayon", "nlWord": "Potlood", "enWord": "Pencil", "deWord": "Bleistift" }, { "frWord": "Utiliser", "nlWord": "Gebruiken", "enWord": "To use", "deWord": "Benutzen" }, { "frWord": "Comment", "nlWord": "Hoe", "enWord": "How", "deWord": "Wie" }, { "frWord": "Cours", "nlWord": "Lessen", "enWord": "Classes", "deWord": "Unterricht" }, { "frWord": "Devoir", "nlWord": "Plicht", "enWord": "Duty", "deWord": "Pflicht" }, { "frWord": "Jeter", "nlWord": "Gooien", "enWord": "Throw", "deWord": "Werfen" }, { "frWord": "Anniversaire", "nlWord": "Verjaardag", "enWord": "Birthday", "deWord": "Geburtstag" }, { "frWord": "Faire", "nlWord": "Doen", "enWord": "To do", "deWord": "Machen" }, { "frWord": "Frigo", "nlWord": "Koelkast", "enWord": "Freezer", "deWord": "Kühlschrank" }, { "frWord": "Corde", "nlWord": "Touw", "enWord": "Rope", "deWord": "Seil" }, { "frWord": "Oreille", "nlWord": "Oor", "enWord": "Ear", "deWord": "Ohr" }, { "frWord": "Boucle d'oreille", "nlWord": "Oorbel", "enWord": "Earring", "deWord": "Ohrring" }, { "frWord": "Soin", "nlWord": "Zorg", "enWord": "Care", "deWord": "Pflege" }, { "frWord": "Visage", "nlWord": "Gezicht", "enWord": "Face", "deWord": "Gesicht" }, { "frWord": "Orteille", "nlWord": "Teen", "enWord": "Toe", "deWord": "Zeh" }, { "frWord": "Smartphone", "nlWord": "Smartphone", "enWord": "Smartphone", "deWord": "Smartphone" }, { "frWord": "USB-C", "nlWord": "USB-C", "enWord": "USB-C", "deWord": "USB-C" }, { "frWord": "Ordinateur portable", "nlWord": "Laptop", "enWord": "Laptop", "deWord": "Laptop" }, { "frWord": "Word", "nlWord": "Word", "enWord": "Word", "deWord": "Word" }, { "frWord": "PowerPoint", "nlWord": "PowerPoint", "enWord": "PowerPoint", "deWord": "PowerPoint" }, { "frWord": "Excel", "nlWord": "Excel", "enWord": "Excel", "deWord": "Excel" }, { "frWord": "Outlook", "nlWord": "Outlook", "enWord": "Outlook", "deWord": "Outlook" }, { "frWord": "Google", "nlWord": "Google", "enWord": "Google", "deWord": "Google" }, { "frWord": "Voiture", "nlWord": "Auto", "enWord": "Car", "deWord": "Auto" }, { "frWord": "Enschede", "nlWord": "Enschede", "enWord": "Enschede", "deWord": "Enschede" }, { "frWord": "Train", "nlWord": "Trein", "enWord": "Train", "deWord": "Zug" }, { "frWord": "A35", "nlWord": "A35", "enWord": "A35", "deWord": "A35" }, { "frWord": "Tablette", "nlWord": "Tablet", "enWord": "Tablet", "deWord": "Tablet" }, { "frWord": "Hacker", "nlWord": "Hacker", "enWord": "Hacker", "deWord": "Hacker" }, { "frWord": "Zwolle", "nlWord": "Zwolle", "enWord": "Zwolle", "deWord": "Zwolle" }, { "frWord": "Java", "nlWord": "Java", "enWord": "Java", "deWord": "Java" }, { "frWord": "Processeur", "nlWord": "Processor", "enWord": "Processor", "deWord": "Prozessor" }, { "frWord": "Overijssel", "nlWord": "Overijssel", "enWord": "Overijssel", "deWord": "Overijssel" }, { "frWord": "Blackboard", "nlWord": "Blackboard", "enWord": "Blackboard", "deWord": "Schultafel" }, { "frWord": "Youtube", "nlWord": "Youtube", "enWord": "Youtube", "deWord": "Youtube" }, { "frWord": "Vapeur", "nlWord": "Stoom", "enWord": "Steam", "deWord": "Dampf" }, { "frWord": "Bicyclette", "nlWord": "Fiets", "enWord": "Bicycle", "deWord": "Fahrrad" }, { "frWord": "Berlin", "nlWord": "Berlijn", "enWord": "Berlin", "deWord": "Berlin" }, { "frWord": "Nijverdal", "nlWord": "Nijverdal", "enWord": "Nijverdal", "deWord": "Nijverdal" }, { "frWord": "iOS", "nlWord": "iOS", "enWord": "iOS", "deWord": "iOS" }, { "frWord": "Android", "nlWord": "Android", "enWord": "Android", "deWord": "Android" }, { "frWord": "Casque d'écoute", "nlWord": "Hoofdtelefoon", "enWord": "Headphones", "deWord": "Kopfhörer" }, { "frWord": "Verge", "nlWord": "Berm", "enWord": "Verge", "deWord": "Böschung" }, { "frWord": "Windows Phone", "nlWord": "Windows Phone", "enWord": "Windows Phone", "deWord": "Windows Phone" }, { "frWord": "Ubuntu", "nlWord": "Ubuntu", "enWord": "Ubuntu", "deWord": "Ubuntu" }, { "frWord": "<NAME>", "nlWord": "<NAME>", "enWord": "<NAME>", "deWord": "<NAME>" }, { "frWord": "Half-Duplex", "nlWord": "Half-Duplex", "enWord": "Half-Duplex", "deWord": "Halbduplex" }, { "frWord": "Duplex intégral", "nlWord": "Full-Duplex", "enWord": "Full-Duplex", "deWord": "Vollduplex" }, { "frWord": "Voie unique", "nlWord": "enkelbaans spoor", "enWord": "Single track", "deWord": "Eingleisige Strecke" }, { "frWord": "Carte à puce OV", "nlWord": "OV-Chipkaart", "enWord": "OV chip card", "deWord": "OV-Chipkarte" }, { "frWord": "Tunnel", "nlWord": "Tunnel", "enWord": "Tunnel", "deWord": "Tunnel" }, { "frWord": "Plaque d'immatriculation", "nlWord": "Nummerplaat", "enWord": "license plate", "deWord": "Kennzeichen" }, { "frWord": "QWERTY", "nlWord": "QWERTY", "enWord": "QWERTY", "deWord": "QWERTZ" }, { "frWord": "formation professionnelle supérieure", "nlWord": "hbo-opleiding", "enWord": "Higher professional education", "deWord": "Höhere Berufsbildung" }, { "frWord": "Pédale d'accélérateur", "nlWord": "gaspedaal", "enWord": "accelerator pedal", "deWord": "Gaspedal" }, { "frWord": "Pédale de frein", "nlWord": "rempedaal", "enWord": "brake pedal", "deWord": "Bremspedal" }, { "frWord": "Pédale d'embrayage", "nlWord": "koppelingspedaal", "enWord": "clutch pedal", "deWord": "Kupplungspedal" }, { "frWord": "Scanner d'empreintes digitales", "nlWord": "Vingerafdrukscanner", "enWord": "Fingerprintscanner", "deWord": "Fingerabdruckscanner" }, { "frWord": "OLED", "nlWord": "OLED", "enWord": "OLED", "deWord": "OLED" }, { "frWord": "LCD", "nlWord": "LCD", "enWord": "LCD", "deWord": "LCD" }, { "frWord": "LED", "nlWord": "LED", "enWord": "LED", "deWord": "LED" } ], "mediumWords": [ { "frWord": "Phrase", "nlWord": "Zin", "enWord": "Sentence", "deWord": "Satz" }, { "frWord": "Hématome", "nlWord": "Blauwe plek", "enWord": "Bruise", "deWord": "Bluterguss" }, { "frWord": "Dinde", "nlWord": "Kalkoen", "enWord": "Turkey", "deWord": "Truthahn" }, { "frWord": "Chou", "nlWord": "Cabbage", "enWord": "Kool", "deWord": "Kohl" }, { "frWord": "Légumes", "nlWord": "Groenten", "enWord": "Vegetables", "deWord": "Gemüse" }, { "frWord": "Boîte de conserve", "nlWord": "Een blik", "enWord": "A can", "deWord": "Dose" }, { "frWord": "Garder", "nlWord": "Bewaren", "enWord": "Keep", "deWord": "Behalten" }, { "frWord": "Santé", "nlWord": "Gezondheid", "enWord": "Health", "deWord": "Gesundheit" }, { "frWord": "Poignée", "nlWord": "Handvat", "enWord": "Handle", "deWord": "Griff" }, { "frWord": "Bureau", "nlWord": "Kantoor", "enWord": "Office", "deWord": "Büro" }, { "frWord": "Brosse", "nlWord": "Borstel", "enWord": "Brush", "deWord": "Bürste" }, { "frWord": "Rater", "nlWord": "Missen", "enWord": "Fail", "deWord": "Versagen" }, { "frWord": "Lire", "nlWord": "Lezen", "enWord": "Read", "deWord": "Lesen" }, { "frWord": "Déplacer", "nlWord": "Verplaatsen", "enWord": "Move", "deWord": "Bewegen" }, { "frWord": "Jupe", "nlWord": "Rok", "enWord": "Skirt", "deWord": "Rock" }, { "frWord": "Écharpe", "nlWord": "Sjaal", "enWord": "Scarf", "deWord": "Schal" }, { "frWord": "Équitation", "nlWord": "Paardrijden", "enWord": "Horse-riding", "deWord": "Reiten" }, { "frWord": "Frissonner", "nlWord": "Huiveren", "enWord": "Shiver", "deWord": "Frischeln" }, { "frWord": "Cinéma", "nlWord": "Bioscoop", "enWord": "Theatre", "deWord": "Kino" }, { "frWord": "Écureuil", "nlWord": "Eekhoorn", "enWord": "Squirrel", "deWord": "Eichhörnchen" }, { "frWord": "Mâcher", "nlWord": "Kauwen", "enWord": "Chew", "deWord": "Kauen" }, { "frWord": "Cueillir", "nlWord": "Plukken", "enWord": "Pluck", "deWord": "Pflücken" }, { "frWord": "Chercher", "nlWord": "Zoeken", "enWord": "Seek", "deWord": "Suchen" }, { "frWord": "Usine", "nlWord": "Fabriek", "enWord": "Factory", "deWord": "Fabrik" }, { "frWord": "Froid", "nlWord": "Koud", "enWord": "Cold", "deWord": "Kalt" }, { "frWord": "Contour", "nlWord": "Omtrek", "enWord": "Outline", "deWord": "Umriss" }, { "frWord": "Lumineux", "nlWord": "Light", "enWord": "Bright", "deWord": "Leuchtend" }, { "frWord": "Ancien", "nlWord": "Voormalig", "enWord": "Former", "deWord": "Ehemalig" }, { "frWord": "Supprime", "nlWord": "Verwijdert", "enWord": "Delete", "deWord": "Löschen" }, { "frWord": "Rayure", "nlWord": "Kras", "enWord": "Scratch", "deWord": "Kratzer" }, { "frWord": "Plier", "nlWord": "Plooien", "enWord": "Fold", "deWord": "Falten" }, { "frWord": "Devoir", "nlWord": "Plicht", "enWord": "Duty", "deWord": "Pflicht" }, { "frWord": "Obligatoire", "nlWord": "Verplicht", "enWord": "Mandatory", "deWord": "Verpflichtend" }, { "frWord": "Traduction", "nlWord": "Vertaling", "enWord": "Translation", "deWord": "Übersetzung" }, { "frWord": "Compétences", "nlWord": "Vaardigheden", "enWord": "Skills", "deWord": "Fähigkeiten" }, { "frWord": "Coq", "nlWord": "Haan", "enWord": "Rooster", "deWord": "Hahn" }, { "frWord": "Vers", "nlWord": "Richting", "enWord": "Towards", "deWord": "Richtung" }, { "frWord": "Verre", "nlWord": "Beker", "enWord": "Glass", "deWord": "Glas" }, { "frWord": "Paramètres", "nlWord": "Instellingen", "enWord": "Settings", "deWord": "Einstellungen" }, { "frWord": "Règles", "nlWord": "Regels", "enWord": "Rules", "deWord": "Regeln" }, { "frWord": "évident", "nlWord": "duidelijk", "enWord": "obvious", "deWord": "Offensichtlich" }, { "frWord": "conscience", "nlWord": "bewustzijn", "enWord": "awareness", "deWord": "Bewusstsein" }, { "frWord": "foudre", "nlWord": "bliksem", "enWord": "lightning", "deWord": "Blitz" }, { "frWord": "queue", "nlWord": "staart", "enWord": "tail", "deWord": "Schwanz" }, { "frWord": "onglet", "nlWord": "tabblad", "enWord": "tab", "deWord": "Registerkarte" }, { "frWord": "creuser", "nlWord": "graven", "enWord": "dig", "deWord": "Grab" }, { "frWord": "bénéficier", "nlWord": "genieten", "enWord": "benefit", "deWord": "Profitieren" }, { "frWord": "finalement", "nlWord": "uiteindelijk", "enWord": "eventually", "deWord": "Schließlich" }, { "frWord": "en fait", "nlWord": "eigenlijk", "enWord": "actually", "deWord": "Eigentlich" }, { "frWord": "médicament", "nlWord": "geneesmiddel", "enWord": "medicine", "deWord": "Medizin" }, { "frWord": "médecin", "nlWord": "arts", "enWord": "doctor", "deWord": "Arzt" }, { "frWord": "blessé", "nlWord": "gewond", "enWord": "injured", "deWord": "Verletzt" }, { "frWord": "bouillir", "nlWord": "koken", "enWord": "boil", "deWord": "Kochen" }, { "frWord": "démarrer", "nlWord": "beginnen", "enWord": "start", "deWord": "Starten" }, { "frWord": "garantir", "nlWord": "verzekeren", "enWord": "ensure", "deWord": "Gewährleisten" }, { "frWord": "brille", "nlWord": "schijnt", "enWord": "shine", "deWord": "Leuchten" }, { "frWord": "accomplir", "nlWord": "bereiken", "enWord": "achieve", "deWord": "Erreichen" }, { "frWord": "sévère", "nlWord": "streng", "enWord": "harsh", "deWord": "Streng" }, { "frWord": "lourd", "nlWord": "zwaar", "enWord": "heavy", "deWord": "Schwer" }, { "frWord": "grave", "nlWord": "ernstig", "enWord": "severe", "deWord": "schwerwiegend" }, { "frWord": "faible", "nlWord": "zwak", "enWord": "weak", "deWord": "schwach" }, { "frWord": "corps", "nlWord": "lichaam", "enWord": "body", "deWord": "Körper" }, { "frWord": "clavier", "nlWord": "toetsenbord", "enWord": "keyboard", "deWord": "Tastatur" }, { "frWord": "connaissances", "nlWord": "kennis", "enWord": "knowledge", "deWord": "Kenntnisse" }, { "frWord": "bassin", "nlWord": "bekken", "enWord": "pelvis", "deWord": "Becken" }, { "frWord": "trottoir", "nlWord": "stoep", "enWord": "pavement", "deWord": "Gehweg" }, { "frWord": "silencieux", "nlWord": "stil", "enWord": "quiet", "deWord": "leise" }, { "frWord": "grimper", "nlWord": "klimmen", "enWord": "climb", "deWord": "klettern" }, { "frWord": "renard", "nlWord": "vos", "enWord": "fox", "deWord": "Fuchs" }, { "frWord": "météo", "nlWord": "weer", "enWord": "weather", "deWord": "Wetter" }, { "frWord": "cuir", "nlWord": "leer", "enWord": "leather", "deWord": "Leder" }, { "frWord": "enregistrer", "nlWord": "opnemen", "enWord": "record", "deWord": "aufzeichnen" }, { "frWord": "réunion", "nlWord": "vergadering", "enWord": "meeting", "deWord": "Besprechung" }, { "frWord": "équipe", "nlWord": "ploeg", "enWord": "team", "deWord": "Team" }, { "frWord": "malchance", "nlWord": "pech", "enWord": "bad luck", "deWord": "Pech" }, { "frWord": "avertissement", "nlWord": "waarschuwing", "enWord": "warning", "deWord": "Warnung" }, { "frWord": "prudent", "nlWord": "voorzichtig", "enWord": "cautious", "deWord": "vorsichtig" }, { "frWord": "voyage", "nlWord": "tocht", "enWord": "journey", "deWord": "Reise" }, { "nlWord": "Plasma", "frWord": "Plasma", "enWord": "Plasma", "deWord": "Plasma" }, { "nlWord": "Qled", "frWord": "Qled", "enWord": "Qled", "deWord": "Qled" }, { "nlWord": "Kabelbaan", "frWord": "Téléphérique", "enWord": "Cable car", "deWord": "Seilbahn" }, { "nlWord": "Matrixbord", "frWord": "Panneau à messages variables", "enWord": "Variable message sign", "deWord": "Variable Nachrichtentafel" }, { "nlWord": "Snelweg", "frWord": "Autoroute", "enWord": "Highway", "deWord": "Autobahn" }, { "nlWord": "Autoweg", "frWord": "Route express", "enWord": "Expressway", "deWord": "Schnellstraße" }, { "nlWord": "Spitsstrook", "frWord": "Voie de dépassement en période de pointe", "enWord": "Shoulder lane (during rush hours)", "deWord": "Standstreifen (während Stoßzeiten)" }, { "nlWord": "Thinkpad", "frWord": "Thinkpad", "enWord": "Thinkpad", "deWord": "Thinkpad" }, { "nlWord": "Touchscreen", "frWord": "Écran tactile", "enWord": "Touchscreen", "deWord": "Touchscreen" }, { "nlWord": "Luidspreker", "frWord": "Haut-parleur", "enWord": "Loudspeaker", "deWord": "Lautsprecher" }, { "nlWord": "Microfoon", "frWord": "Microphone", "enWord": "Microphone", "deWord": "Mikrofon" }, { "nlWord": "Hond", "frWord": "Chien", "enWord": "Dog", "deWord": "Hund" }, { "nlWord": "<NAME>", "frWord": "<NAME>", "enWord": "House of Representatives", "deWord": "<NAME>" }, { "nlWord": "<NAME>", "frWord": "<NAME>", "enWord": "Senate", "deWord": "<NAME>" }, { "nlWord": "Alpen", "frWord": "Alpes", "enWord": "Alps", "deWord": "Alpen" }, { "nlWord": "Locomotief", "frWord": "Locomotive", "enWord": "Locomotive", "deWord": "Lokomotive" }, { "nlWord": "File", "frWord": "Embouteillage", "enWord": "Traffic jam", "deWord": "Stau" }, { "nlWord": "Snelwegvinget", "frWord": "Bande d'arrêt d'urgence sur l'autoroute", "enWord": "Emergency lane on the highway", "deWord": "Standstreifen auf der Autobahn" }, { "nlWord": "Venetië", "frWord": "Venise", "enWord": "Venice", "deWord": "Venedig" }, { "nlWord": "Gardameer", "frWord": "<NAME>", "enWord": "<NAME>", "deWord": "Gardasee" }, { "nlWord": "Power Over Ethernet", "frWord": "Power Over Ethernet", "enWord": "Power Over Ethernet", "deWord": "Power over Ethernet" }, { "nlWord": "Ethernet Kabel", "frWord": "Câble Ethernet", "enWord": "Ethernet cable", "deWord": "Ethernet-Kabel" }, { "nlWord": "AVG", "frWord": "AVG", "enWord": "AVG", "deWord": "AVG" }, { "nlWord": "Datacenter", "frWord": "Centre de données", "enWord": "Datacenter", "deWord": "Rechenzentrum" }, { "nlWord": "Packet Tracer", "frWord": "Packet Tracer", "enWord": "Packet Tracer", "deWord": "Packet Tracer" }, { "nlWord": "Wireshark", "frWord": "Wireshark", "enWord": "Wireshark", "deWord": "Wireshark" }, { "nlWord": "VOG", "frWord": "Déclaration de comportement", "enWord": "Certificate of Conduct", "deWord": "<NAME>" }, { "nlWord": "Limburg", "frWord": "Limbourg", "enWord": "Limburg", "deWord": "Limburg" }, { "nlWord": "België", "frWord": "Belgique", "enWord": "Belgium", "deWord": "Belgien" }, { "nlWord": "Treinvervangende Bus", "frWord": "Bus de remplacement pour le train", "enWord": "Replacement bus for the train", "deWord": "Ersatzbus für den Zug" }, { "nlWord": "APK", "frWord": "CTM (Contrôle Technique des Moteurs)", "enWord": "MOT (Ministry of Transport) inspection", "deWord": "Hauptuntersuchung (HU)" }, { "nlWord": "DMZ", "frWord": "DMZ (Zone démilitarisée)", "enWord": "DMZ (Demilitarized Zone)", "deWord": "DMZ (Entmilitarisierte Zone)" }, { "nlWord": "Twente", "frWord": "Twente", "enWord": "Twente", "deWord": "Twente" }, { "nlWord": "SSD", "frWord": "SSD (Disque SSD)", "enWord": "SSD (Solid State Drive)", "deWord": "SSD (Festkörperlaufwerk)" }, { "nlWord": "HDD", "frWord": "HDD (Disque dur)", "enWord": "HDD (Hard Disk Drive)", "deWord": "HDD (Festplattenlaufwerk)" }, { "nlWord": "Studiepunten", "frWord": "Crédits d'études", "enWord": "Study credits", "deWord": "Studienpunkte" }, { "nlWord": "A1", "frWord": "A1", "enWord": "A1", "deWord": "A1" }, { "nlWord": "Aanhanger", "frWord": "Remorque", "enWord": "Trailer", "deWord": "Anhänger" }, { "nlWord": "Rubrics", "frWord": "Rubriques", "enWord": "Rubrics", "deWord": "Rubriken" }, { "nlWord": "Taakbalk", "frWord": "Barre des tâches", "enWord": "Taskbar", "deWord": "Taskleiste" }, { "nlWord": "Startmenu", "frWord": "Menu Démarrer", "enWord": "Start menu", "deWord": "Startmenü" }, { "nlWord": "Snelheidsmeter", "frWord": "Compteur de vitesse", "enWord": "Speedometer", "deWord": "Tachometer" }, { "nlWord": "DVD-speler", "frWord": "Lecteur DVD", "enWord": "DVD player", "deWord": "DVD-Player" }, { "nlWord": "MFA (Multi-Factor Authenticatie)", "frWord": "MFA (Facteur d'authentification multiple)", "enWord": "MFA (Multi-Factor Authentication)", "deWord": "MFA (Mehrstufige Authentifizierung)" }, { "nlWord": "MacOS", "frWord": "MacOS", "enWord": "MacOS", "deWord": "MacOS" }, { "nlWord": "Tweede kamer verkiezingen", "frWord": "Élections de la Deuxième Chambre", "enWord": "House of Representatives elections", "deWord": "Wahlen zum Zweiten Haus der Abgeordneten" }, { "nlWord": "Duitsland", "frWord": "Allemagne", "enWord": "Germany", "deWord": "Deutschland" }, { "nlWord": "Oostenrijk", "frWord": "Autriche", "enWord": "Austria", "deWord": "Österreich" }, { "nlWord": "AZERTY", "frWord": "AZERTY", "enWord": "AZERTY", "deWord": "AZERTY" }, { "nlWord": "Megekko", "frWord": "Megekko", "enWord": "Megekko", "deWord": "Megekko" } ], "HardWords": [ { "frWord": "novateur", "nlWord": "innovatief", "enWord": "innovative", "deWord": "innovativ" }, { "frWord": "klaxonner", "nlWord": "toeteren", "enWord": "honk", "deWord": "hupen" }, { "frWord": "courant", "nlWord": "stroom", "enWord": "current", "deWord": "Strom" }, { "frWord": "éclore", "nlWord": "uitkomen", "enWord": "hatch", "deWord": "schlüpfen" }, { "frWord": "mastodonte", "nlWord": "kolos", "enWord": "juggernaut", "deWord": "Mammut" }, { "frWord": "graisse", "nlWord": "vet", "enWord": "grease", "deWord": "Fett" }, { "frWord": "sans pilote", "nlWord": "onbemand", "enWord": "unmanned", "deWord": "unbemannt" }, { "frWord": "interpréter", "nlWord": "interpreteren", "enWord": "construe", "deWord": "interpretieren" }, { "frWord": "insulter", "nlWord": "uitschelden", "enWord": "abuse", "deWord": "beleidigen" }, { "frWord": "achever", "nlWord": "afmaken", "enWord": "complete", "deWord": "vollenden" }, { "frWord": "tromperie", "nlWord": "bedrog", "enWord": "deception", "deWord": "Täuschung" }, { "frWord": "retard", "nlWord": "vertraging", "enWord": "delay", "deWord": "Verzögerung" }, { "frWord": "finalement", "nlWord": "uiteindelijk", "enWord": "eventually", "deWord": "schließlich" }, { "frWord": "preuve", "nlWord": "bewijs", "enWord": "evidence", "deWord": "Beweis" }, { "frWord": "évincer", "nlWord": "verdringen", "enWord": "evict", "deWord": "verdrängen" }, { "frWord": "essence", "nlWord": "benzine", "enWord": "petrol", "deWord": "Benzin" }, { "frWord": "empêcher", "nlWord": "tegenhouden", "enWord": "prevent", "deWord": "verhindern" }, { "frWord": "soulager", "nlWord": "verlichten", "enWord": "relieve", "deWord": "erleichtern" }, { "frWord": "raisonnable", "nlWord": "redelijk", "enWord": "sensible", "deWord": "vernünftig" }, { "frWord": "librairie", "nlWord": "boekhandel", "enWord": "bookshop", "deWord": "Buchhandlung" }, { "frWord": "pot-de-vin", "nlWord": "smeergeld", "enWord": "bribe", "deWord": "Bestechung" }, { "frWord": "adhérer", "nlWord": "aansluiten", "enWord": "accede", "deWord": "beitreten" }, { "frWord": "abnégation", "nlWord": "zelfverloochening", "enWord": "self-denial", "deWord": "Selbstverleugnung" }, { "frWord": "puériculture", "nlWord": "kinderverzorging", "enWord": "childcare", "deWord": "Kinderpflege" }, { "nlWord": "IDE", "frWord": "Environnement de développement intégré", "enWord": "Integrated Development Environment", "deWord": "Integrierte Entwicklungsumgebung" }, { "nlWord": "Exploit", "frWord": "Exploitation", "enWord": "Exploit", "deWord": "Ausnutzung" }, { "nlWord": "Compiler", "frWord": "Compilateur", "enWord": "Compiler", "deWord": "Compiler" }, { "nlWord": "Operating System", "frWord": "Système d'exploitation", "enWord": "Operating System", "deWord": "Betriebssystem" }, { "nlWord": "Apple", "frWord": "Pomme", "enWord": "Apple", "deWord": "Apfel" }, { "nlWord": "iOS", "frWord": "iOS", "enWord": "iOS", "deWord": "iOS" }, { "nlWord": "Azure", "frWord": "Azure", "enWord": "Azure", "deWord": "Azure" }, { "nlWord": "Virtual Machine (VM)", "frWord": "Machine virtuelle (VM)", "enWord": "Virtual Machine (VM)", "deWord": "Virtuelle Maschine (VM)" }, { "nlWord": "Antivirus", "frWord": "Antivirus", "enWord": "Antivirus", "deWord": "Antivirus" }, { "nlWord": "Ransomware", "frWord": "Ransomware", "enWord": "Ransomware", "deWord": "Ransomware" }, { "nlWord": "CVE", "frWord": "CVE (Common Vulnerabilities and Exposures)", "enWord": "CVE (Common Vulnerabilities and Exposures)", "deWord": "CVE (Gemeinsame Schwachstellen und Expositionen)" }, { "nlWord": "Databreach", "frWord": "Violation de données", "enWord": "Databreach", "deWord": "Datenleck" }, { "nlWord": "big.LITTLE", "frWord": "big.LITTLE", "enWord": "big.LITTLE", "deWord": "big.LITTLE" }, { "nlWord": "ARM", "frWord": "ARM", "enWord": "ARM", "deWord": "ARM" }, { "nlWord": "x64", "frWord": "x64", "enWord": "x64", "deWord": "x64" }, { "nlWord": "GPU", "frWord": "GPU (Unité de traitement graphique)", "enWord": "GPU (Graphics Processing Unit)", "deWord": "GPU (Grafikprozessor)" }, { "nlWord": "CPU", "frWord": "CPU (Unité centrale de traitement)", "enWord": "CPU (Central Processing Unit)", "deWord": "CPU (Zentrale Verarbeitungseinheit)" }, { "nlWord": "RAM", "frWord": "RAM (Mémoire vive)", "enWord": "RAM (Random Access Memory)", "deWord": "RAM (Arbeitsspeicher)" }, { "nlWord": "Raspberry Pi", "frWord": "Raspberry Pi", "enWord": "Raspberry Pi", "deWord": "Raspberry Pi" }, { "nlWord": "Flipper Zero", "frWord": "Flipper Zero", "enWord": "Flipper Zero", "deWord": "Flipper Zero" }, { "nlWord": "IO board", "frWord": "Carte d'E/S", "enWord": "IO board (Input/Output board)", "deWord": "E/A-Platine" }, { "nlWord": "Thunderbolt", "frWord": "Thunderbolt", "enWord": "Thunderbolt" }, { "nlWord": "Thunderbolt", "frWord": "Thunderbolt", "enWord": "Thunderbolt", "deWord": "Thunderbolt" }, { "nlWord": "Linux kernel", "frWord": "Noyau Linux", "enWord": "Linux kernel", "deWord": "Linux-Kernel" }, { "nlWord": "Tizen", "frWord": "Tizen", "enWord": "Tizen", "deWord": "Tizen" }, { "nlWord": "Citrix", "frWord": "Citrix", "enWord": "Citrix", "deWord": "Citrix" }, { "nlWord": "RDS", "frWord": "RDS (Services Bureau à distance)", "enWord": "RDS (Remote Desktop Services)", "deWord": "RDS (Remote Desktop Services)" }, { "nlWord": "RDP Protocol", "frWord": "Protocole RDP", "enWord": "RDP Protocol (Remote Desktop Protocol)", "deWord": "RDP-Protokoll (Remote Desktop Protocol)" }, { "nlWord": "ICMP protocol", "frWord": "Protocole ICMP", "enWord": "ICMP protocol (Internet Control Message Protocol)", "deWord": "ICMP-Protokoll (Internet Control Message Protocol)" }, { "nlWord": "Broadcast", "frWord": "Diffusion", "enWord": "Broadcast", "deWord": "Broadcast" }, { "nlWord": "Unicast", "frWord": "Unicast", "enWord": "Unicast", "deWord": "Unicast" }, { "nlWord": "Anycast", "frWord": "Anycast", "enWord": "Anycast", "deWord": "Anycast" }, { "nlWord": "MitM attack", "frWord": "Attaque de l'homme du milieu", "enWord": "Man-in-the-Middle (MitM) attack", "deWord": "Man-in-the-Middle (MitM)-Angriff" }, { "nlWord": "SEO", "frWord": "SEO (Optimisation des moteurs de recherche)", "enWord": "SEO (Search Engine Optimization)", "deWord": "SEO (Suchmaschinenoptimierung)" }, { "nlWord": "SEO poisoning", "frWord": "Empoisonnement SEO", "enWord": "SEO poisoning", "deWord": "SEO-Vergiftung" }, { "nlWord": "Google", "frWord": "Google", "enWord": "Google", "deWord": "Google" }, { "nlWord": "LinkedIn", "frWord": "LinkedIn", "enWord": "LinkedIn", "deWord": "LinkedIn" }, { "nlWord": "Facebook", "frWord": "Facebook", "enWord": "Facebook", "deWord": "Facebook" }, { "nlWord": "Microsoft 365", "frWord": "Microsoft 365", "enWord": "Microsoft 365", "deWord": "Microsoft 365" }, { "nlWord": "PaaS", "frWord": "PaaS (Plateforme en tant que service)", "enWord": "PaaS (Platform as a Service)", "deWord": "PaaS (Plattform als Dienst)" }, { "nlWord": "SaaS", "frWord": "SaaS (Logiciel en tant que service)", "enWord": "SaaS (Software as a Service)", "deWord": "SaaS (Software als Dienst)" }, { "nlWord": "IaaS", "frWord": "IaaS (Infrastructure en tant que service)", "enWord": "IaaS (Infrastructure as a Service)", "deWord": "IaaS (Infrastruktur als Dienst)" }, { "nlWord": "IntelliJ", "frWord": "IntelliJ", "enWord": "IntelliJ", "deWord": "IntelliJ" }, { "nlWord": "PyCharm", "frWord": "PyCharm", "enWord": "PyCharm", "deWord": "PyCharm" }, { "nlWord": "Jetbrains", "frWord": "JetBrains", "enWord": "JetBrains", "deWord": "JetBrains" }, { "nlWord": "Commandline", "frWord": "Ligne de commande", "enWord": "Commandline", "deWord": "Befehlszeile" }, { "nlWord": "Powershell", "frWord": "PowerShell", "enWord": "PowerShell", "deWord": "PowerShell" }, { "nlWord": "UEFI / BIOS", "frWord": "UEFI / BIOS", "enWord": "UEFI / BIOS", "deWord": "UEFI / BIOS" }, { "nlWord": "Firmware", "frWord": "Micrologiciel", "enWord": "Firmware", "deWord": "Firmware" }, { "nlWord": "Programmeertaal", "frWord": "Langage de programmation", "enWord": "Programming language", "deWord": "Programmiersprache" }, { "nlWord": "DDOS", "frWord": "DDoS (Attaque par déni de service distribué)", "enWord": "DDoS (Distributed Denial of Service) attack", "deWord": "DDoS (Verteilter Denial-of-Service-Angriff)" }, { "nlWord": "IDS systeem", "frWord": "Système IDS (Système de détection d'intrusion)", "enWord": "IDS system (Intrusion Detection System)", "deWord": "IDS-System (Intrusion Detection System)" }, { "nlWord": "DNS protocool", "frWord": "Protocole DNS", "enWord": "DNS protocol", "deWord": "DNS-Protokoll (Domain Name System)" }, { "nlWord": "DHCP protocool", "frWord": "Protocole DHCP", "enWord": "DHCP protocol", "deWord": "DHCP-Protokoll (Dynamic Host Configuration Protocol)" }, { "nlWord": "Secure Boot", "frWord": "Amorçage sécurisé", "deWord": "Sicheres Booten" }, { "nlWord": "CSM", "frWord": "CSM (Compatibilité avec le système de base)", "enWord": "CSM (Compatibility Support Module)", "deWord": "CSM (Kompatibilitäts-Support-Modul)" }, { "nlWord": "Wordpress", "frWord": "WordPress", "enWord": "WordPress", "deWord": "WordPress" }, { "nlWord": "PHP", "frWord": "PHP", "enWord": "PHP", "deWord": "PHP" }, { "nlWord": "Database", "frWord": "Base de données", "enWord": "Database", "deWord": "Datenbank" }, { "nlWord": "GitHub", "frWord": "GitHub", "enWord": "GitHub", "deWord": "GitHub" }, { "nlWord": "HTML", "frWord": "HTML (Langage de balisage hypertexte)", "enWord": "HTML (Hypertext Markup Language)", "deWord": "HTML (Hypertext Auszeichnungssprache)" }, { "nlWord": "Lightning kabel", "frWord": "Câble Lightning", "enWord": "Lightning cable", "deWord": "Lightning-Kabel" }, { "nlWord": "AD", "frWord": "AD (Active Directory)", "enWord": "AD (Active Directory)", "deWord": "AD (Active Directory)" }, { "nlWord": "Azure AD", "frWord": "Azure AD (Active Directory)", "enWord": "Azure AD (Active Directory)", "deWord": "Azure AD (Active Directory)" }, { "nlWord": "Microsoft Entra", "frWord": "Microsoft 365 (Entreprise)", "enWord": "Microsoft 365 (Enterprise)", "deWord": "Microsoft Entra" }, { "nlWord": "Visual Studio Code (VSC)", "frWord": "Visual Studio Code (VSC)", "enWord": "Visual Studio Code (VSC)", "deWord": "Visual Studio Code (VSC)" }, { "nlWord": "Firewall", "frWord": "Firewall", "enWord": "Firewall", "deWord": "Firewall" }, { "nlWord": "Client", "frWord": "Client", "enWord": "Client", "deWord": "Client" }, { "nlWord": "Server", "frWord": "Serveur", "enWord": "Server", "deWord": "Server" }, { "nlWord": "API", "frWord": "API (Interface de programmation d'application)", "enWord": "API (Application Programming Interface)", "deWord": "API (Schnittstelle für Anwendungsprogrammierung)" }, { "nlWord": "Solana", "frWord": "Solana", "enWord": "Solana", "deWord": "Solana" }, { "nlWord": "Ethereum", "frWord": "Ethereum", "enWord": "Ethereum", "deWord": "Ethereum" }, { "nlWord": "Bitcoin", "frWord": "Bitcoin", "enWord": "Bitcoin", "deWord": "Bitcoin" }, { "nlWord": "Monero", "frWord": "Monero", "enWord": "Monero", "deWord": "Monero" }, { "nlWord": "XRP", "frWord": "XRP", "enWord": "XRP", "deWord": "XRP" }, { "nlWord": "Avalanche", "frWord": "Avalanche", "enWord": "Avalanche", "deWord": "Avalanche" }, { "nlWord": "Fantom", "frWord": "Fantom", "enWord": "Fantom", "deWord": "Fantom" }, { "nlWord": "Litecoin", "frWord": "Litecoin", "enWord": "Litecoin", "deWord": "Litecoin" }, { "nlWord": "Blackboard", "frWord": "Blackboard", "enWord": "Blackboard", "deWord": "Blackboard" }, { "nlWord": "Brightspace", "frWord": "Brightspace", "enWord": "Brightspace", "deWord": "Brightspace" }, { "nlWord": "SQL", "frWord": "SQL (Langage de requête structuré)", "enWord": "SQL (Structured Query Language)", "deWord": "SQL (Strukturierte Abfragesprache)" }, { "nlWord": "Encryptie", "frWord": "Cryptage", "enWord": "Encryption", "deWord": "Verschlüsselung" }, { "nlWord": "Byte", "frWord": "Octet", "enWord": "Byte", "deWord": "Byte" }, { "nlWord": "Bit", "frWord": "Bit", "enWord": "Bit", "deWord": "Bit" }, { "nlWord": "Bug", "frWord": "Bogue", "enWord": "Bug", "deWord": "Bug" }, { "nlWord": "Malware", "frWord": "Logiciel malveillant", "enWord": "Malware", "deWord": "Malware" }, { "nlWord": "VPN", "frWord": "VPN (Réseau privé virtuel)", "enWord": "VPN (Virtual Private Network)", "deWord": "VPN (Virtuelles privates Netzwerk)" }, { "nlWord": "IPv4", "frWord": "IPv4", "enWord": "IPv4", "deWord": "IPv4" }, { "nlWord": "IPv6", "frWord": "IPv6", "enWord": "IPv6", "deWord": "IPv6" }, { "nlWord": "Patch", "frWord": "Correctif", "enWord": "Patch", "deWord": "Patch" }, { "nlWord": "LAN", "frWord": "LAN (Réseau local)", "enWord": "LAN (Local Area Network)", "deWord": "LAN (lokales Netzwerk)" }, { "nlWord": "WAN", "frWord": "WAN (Réseau étendu)", "enWord": "WAN (Wide Area Network)", "deWord": "WAN (Weitverkehrsnetz)" }, { "nlWord": "PfSense", "frWord": "PfSense", "enWord": "PfSense", "deWord": "PfSense" }, { "nlWord": "LG", "frWord": "LG", "enWord": "LG", "deWord": "LG" }, { "nlWord": "Samsung", "frWord": "Samsung", "enWord": "Samsung", "deWord": "Samsung" }, { "nlWord": "IBM", "frWord": "IBM", "enWord": "IBM", "deWord": "IBM" }, { "nlWord": "WatchOS", "frWord": "WatchOS", "enWord": "WatchOS", "deWord": "WatchOS" }, { "nlWord": "Lenovo", "frWord": "Lenovo", "enWord": "Lenovo", "deWord": "Lenovo" }, { "nlWord": "Oneplus", "frWord": "OnePlus", "enWord": "OnePlus", "deWord": "Oneplus" }, { "nlWord": "WearOS", "frWord": "WearOS", "enWord": "WearOS", "deWord": "WearOS" }, { "nlWord": "USB-PD", "frWord": "USB Power Delivery", "enWord": "USB Power Delivery (USB-PD)", "deWord": "USB Power Delivery (USB-PD)" } ] } """.trimIndent() }
3
Kotlin
0
1
88b638f644e0509e68dbde4228243aa6dcd93136
46,290
Half-a-Minute-IT-Madness-Android
MIT License
app/src/androidTest/java/com/freshdigitable/udonroad2/user/UserActivityRobot.kt
akihito104
149,869,805
false
{"YAML": 4, "Gradle Kotlin DSL": 7, "JSON": 1, "Kotlin": 263, "Java Properties": 10, "Shell": 1, "Text": 1, "Ignore List": 17, "Batchfile": 1, "EditorConfig": 1, "Gradle": 12, "Proguard": 17, "XML": 147, "Java": 3, "INI": 7, "PlantUML": 3}
/* * Copyright (c) 2020. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad2.user import android.view.View import androidx.annotation.IdRes import androidx.test.espresso.Espresso.onView import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import androidx.test.espresso.ViewInteraction import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.matcher.BoundedMatcher import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom import androidx.test.espresso.matcher.ViewMatchers.withId import com.freshdigitable.udonroad2.R import com.freshdigitable.udonroad2.test.ActivityRobot import com.freshdigitable.udonroad2.test.FabVerify import com.google.android.material.tabs.TabLayout import org.hamcrest.Description import org.hamcrest.Matcher fun onUserActivity(block: UserActivityRobot.() -> Unit): UserActivityRobot { return UserActivityRobot().apply(block) } class UserActivityRobot : ActivityRobot { companion object { private val fab: ViewInteraction = onView(withId(R.id.user_fab)) } fun clickPagerTabWithPosition(position: Int) { onView(ofViewPagerTabWithPosition(R.id.user_tabContainer, position)) .perform(selectViewPagerTabItem()) } infix fun verify(block: Verify.() -> Unit) { Verify().apply(block) } class Verify : ActivityRobot.VerifyRobot, FabVerify by FabVerify.get(fab) } fun ofViewPagerTabWithPosition( @IdRes tabLayoutId: Int, position: Int ): Matcher<View> = object : BoundedMatcher<View, TabLayout.TabView>(TabLayout.TabView::class.java) { override fun describeTo(description: Description?) { description?.appendText("tab position: $position") } override fun matchesSafely(item: TabLayout.TabView): Boolean { return item.tab?.parent?.id == tabLayoutId && item.tab?.position == position } } fun selectViewPagerTabItem(): ViewAction = object : ViewAction { override fun getConstraints(): Matcher<View> = isAssignableFrom(TabLayout.TabView::class.java) override fun getDescription(): String = "click ViewPager tab item" override fun perform(uiController: UiController?, view: View?) { val v = view as TabLayout.TabView val tab = v.tab ?: throw IllegalStateException() val position = tab.position requireNotNull(tab.parent).setScrollPosition(position, 0f, false) click().perform(uiController, view) } }
21
null
1
1
7ec50f204fda79cf222b24623f22e80d05301555
3,045
UdonRoad2
Apache License 2.0
oauth2-authorization-server-starter/src/test/kotlin/com/labijie/infra/oauth2/testing/ITwofactorUSerDetailsSerializationTester.kt
hongque-pro
308,310,231
false
{"Kotlin": 246983}
package com.labijie.infra.oauth2.testing import com.fasterxml.jackson.core.type.TypeReference import com.labijie.infra.json.JacksonHelper import com.labijie.infra.oauth2.serialization.jackson.OAuth2JacksonModule import com.labijie.infra.oauth2.testing.component.TestingIdentityService import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.jackson2.CoreJackson2Module import org.springframework.security.jackson2.SecurityJackson2Modules import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module import kotlin.test.Test import kotlin.test.assertEquals class ITwofactorUSerDetailsSerializationTester { val testUer = TestingIdentityService().getUserByName("SerTester") private val objectMapper = JacksonHelper.defaultObjectMapper.copy().apply { this.registerModule(CoreJackson2Module()) val classLoader = JdbcOAuth2AuthorizationService::class.java.classLoader val securityModules = SecurityJackson2Modules.getModules(classLoader) this.registerModules(securityModules) this.registerModule(OAuth2AuthorizationServerJackson2Module()) this.registerModule(OAuth2JacksonModule()) } private fun writeMap(data: Map<String, Any>): String { return try { objectMapper.writeValueAsString(data) } catch (ex: Exception) { throw IllegalArgumentException(ex.message, ex) } } private fun readMap(data: String): Map<String, Any> { if (data.isBlank()) { return mapOf() } return try { objectMapper.readValue(data, object : TypeReference<Map<String, Any>>() {}) } catch (ex: Exception) { throw IllegalArgumentException(ex.message, ex) } } @Test fun testSerialize(){ val testData = mapOf<String, Any>( "a" to "1234556", "b" to 123456, "c" to testUer ) val json = objectMapper.writeValueAsString(testData) } @Test fun deserializeMap(){ val principal = UsernamePasswordAuthenticationToken(testUer, "PROTE") val json = objectMapper.writeValueAsString(principal) // val file = this.javaClass.getResourceAsStream("/test.json") // val json = file.readBytes().toString(Charsets.UTF_8) // val map = readMap(json) val v = objectMapper.readValue(json, UsernamePasswordAuthenticationToken::class.java) assertEquals(principal.principal::class.java, v.principal::class.java) assertEquals(principal.credentials, principal.credentials) } }
0
Kotlin
0
5
31e1285b565ad35c2af8c870f2357fdefbd2b94a
2,768
infra-oauth2
Apache License 2.0
app/src/main/java/com/picassos/betamax/android/data/mapper/SeasonsMapper.kt
aelrahmanashraf
581,933,102
false
{"Kotlin": 768121}
package com.picassos.betamax.android.data.mapper import com.picassos.betamax.android.data.source.remote.dto.SeasonsDto import com.picassos.betamax.android.domain.model.Seasons fun SeasonsDto.toSeasons(): Seasons { return Seasons( seasons = seasons.map { season -> Seasons.Season( id = season.id, seasonId = season.seasonId, movieId = season.movieId, title = season.title, level = season.level) } ) }
0
Kotlin
0
0
004716ab1e75f18e85a88bed966078d439dd6e0a
517
betamax-android
MIT License
compiler-plugin/src/main/java/io/mths/kava/compiler/KavaClassId.kt
MerlinTHS
598,539,841
false
null
package io.mths.kava.compiler import org.jetbrains.kotlin.name.ClassId object KavaClassId { val Exception = ClassId.fromString("java/lang/Exception") }
0
Kotlin
0
0
5d038afd21c7099a47eb889422dbdb4b34926d0f
157
KavaCompilerPlugin
Apache License 2.0
app/src/main/java/com/challenge/bluelabsmovieapp/SplashScreen.kt
cdmejiam94
523,460,707
false
{"Kotlin": 20965}
package com.challenge.bluelabsmovieapp import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.view.View import android.widget.ImageView import android.widget.TextView import com.airbnb.lottie.LottieAnimationView import com.challenge.bluelabsmovieapp.ui.activity.ActivityMovie class SplashScreen : AppCompatActivity() { private val SPLASH_TIME_OUT: Long = 50 private val ANIMATION_TIME_OUT: Long = 3000 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.splash_screen) val animationView: LottieAnimationView = findViewById(R.id.movieImageView) animateSplashScreen(animationView, R.raw.hmm) } private fun animateSplashScreen(imageView: LottieAnimationView, animation: Int) { imageView.setAnimation(animation) imageView.playAnimation() imageView.animate() .alpha(1f) .setDuration(ANIMATION_TIME_OUT) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animator: Animator) { imageView.alpha = 0f changeActivity() } }) } private fun changeActivity() { Handler().postDelayed({ startActivity(Intent(this, ActivityMovie::class.java)) finish() },SPLASH_TIME_OUT) } }
0
Kotlin
0
0
575048b7ec3e1c409b01e8bbbcc815e8d53fe1cc
1,572
blue-labs-movie-app
MIT License
src/main/kotlin/de/shd/basis/kotlin/ui/media/MediaType.kt
shd-de
224,015,327
false
null
package de.shd.basis.kotlin.ui.media /** * Jeder Wert dieses Enums repräsentiert einen [Internet Media Type](https://de.wikipedia.org/wiki/Internet_Media_Type) (auch bekannt als "MIME Type" * oder "Content Type"), der u.a. dazu genutzt wird, um anzugeben, in was für einem Format Daten übertragen werden. Dies können sowohl textuelle als * auch Binärformate sein. * * @author Florian Steitz (fst) */ enum class MediaType(val type: String) { /** * Repräsentiert den Media Type `application/json`. */ APPLICATION_JSON("application/json") }
0
Kotlin
0
3
fafbe80d98f796fef34f7606aed92403b75d5460
563
powalin
Apache License 2.0
orb-kotlin-core/src/main/kotlin/com/withorb/api/services/blocking/AlertServiceImpl.kt
orbcorp
797,931,036
false
{"Kotlin": 10239831, "Shell": 3839, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package com.withorb.api.services.blocking import com.withorb.api.core.ClientOptions import com.withorb.api.core.RequestOptions import com.withorb.api.core.http.HttpMethod import com.withorb.api.core.http.HttpRequest import com.withorb.api.core.http.HttpResponse.Handler import com.withorb.api.errors.OrbError import com.withorb.api.models.Alert import com.withorb.api.models.AlertCreateForCustomerParams import com.withorb.api.models.AlertCreateForExternalCustomerParams import com.withorb.api.models.AlertCreateForSubscriptionParams import com.withorb.api.models.AlertDisableParams import com.withorb.api.models.AlertEnableParams import com.withorb.api.models.AlertListPage import com.withorb.api.models.AlertListParams import com.withorb.api.models.AlertRetrieveParams import com.withorb.api.services.errorHandler import com.withorb.api.services.json import com.withorb.api.services.jsonHandler import com.withorb.api.services.withErrorHandler class AlertServiceImpl constructor( private val clientOptions: ClientOptions, ) : AlertService { private val errorHandler: Handler<OrbError> = errorHandler(clientOptions.jsonMapper) private val retrieveHandler: Handler<Alert> = jsonHandler<Alert>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** This endpoint retrieves an alert by its ID. */ override fun retrieve(params: AlertRetrieveParams, requestOptions: RequestOptions): Alert { val request = HttpRequest.builder() .method(HttpMethod.GET) .addPathSegments("alerts", params.getPathParam(0)) .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { retrieveHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val listHandler: Handler<AlertListPage.Response> = jsonHandler<AlertListPage.Response>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** * This endpoint returns a list of alerts within Orb. * * The request must specify one of `customer_id`, `external_customer_id`, or `subscription_id`. * * If querying by subscripion_id, the endpoint will return the subscription level alerts as well * as the plan level alerts associated with the subscription. * * The list of alerts is ordered starting from the most recently created alert. This endpoint * follows Orb's [standardized pagination format](../reference/pagination). */ override fun list(params: AlertListParams, requestOptions: RequestOptions): AlertListPage { val request = HttpRequest.builder() .method(HttpMethod.GET) .addPathSegments("alerts") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { listHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } .let { AlertListPage.of(this, params, it) } } } private val createForCustomerHandler: Handler<Alert> = jsonHandler<Alert>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** * This endpoint creates a new alert to monitor a customer's credit balance. There are three * types of alerts that can be scoped to customers: `credit_balance_depleted`, * `credit_balance_dropped`, and `credit_balance_recovered`. Customers can have a maximum of one * of each type of alert per * [credit balance currency](https://docs.withorb.com/guides/product-catalog/prepurchase). * `credit_balance_dropped` alerts require a list of thresholds to be provided while * `credit_balance_depleted` and `credit_balance_recovered` alerts do not require thresholds. */ override fun createForCustomer( params: AlertCreateForCustomerParams, requestOptions: RequestOptions ): Alert { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("alerts", "customer_id", params.getPathParam(0)) .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .body(json(clientOptions.jsonMapper, params.getBody())) .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { createForCustomerHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val createForExternalCustomerHandler: Handler<Alert> = jsonHandler<Alert>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** * This endpoint creates a new alert to monitor a customer's credit balance. There are three * types of alerts that can be scoped to customers: `credit_balance_depleted`, * `credit_balance_dropped`, and `credit_balance_recovered`. Customers can have a maximum of one * of each type of alert per * [credit balance currency](https://docs.withorb.com/guides/product-catalog/prepurchase). * `credit_balance_dropped` alerts require a list of thresholds to be provided while * `credit_balance_depleted` and `credit_balance_recovered` alerts do not require thresholds. */ override fun createForExternalCustomer( params: AlertCreateForExternalCustomerParams, requestOptions: RequestOptions ): Alert { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("alerts", "external_customer_id", params.getPathParam(0)) .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .body(json(clientOptions.jsonMapper, params.getBody())) .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { createForExternalCustomerHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val createForSubscriptionHandler: Handler<Alert> = jsonHandler<Alert>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** * This endpoint is used to create alerts at the subscription level. * * Subscription level alerts can be one of two types: `usage_exceeded` or `cost_exceeded`. A * `usage_exceeded` alert is scoped to a particular metric and is triggered when the usage of * that metric exceeds predefined thresholds during the current billing cycle. A `cost_exceeded` * alert is triggered when the total amount due during the current billing cycle surpasses * predefined thresholds. `cost_exceeded` alerts do not include burndown of pre-purchase * credits. Each subscription can have one `cost_exceeded` alert and one `usage_exceeded` alert * per metric that is a part of the subscription. Alerts are triggered based on usage or cost * conditions met during the current billing cycle. */ override fun createForSubscription( params: AlertCreateForSubscriptionParams, requestOptions: RequestOptions ): Alert { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("alerts", "subscription_id", params.getPathParam(0)) .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .body(json(clientOptions.jsonMapper, params.getBody())) .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { createForSubscriptionHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val disableHandler: Handler<Alert> = jsonHandler<Alert>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** This endpoint can be used to disable an alert. */ override fun disable(params: AlertDisableParams, requestOptions: RequestOptions): Alert { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("alerts", params.getPathParam(0), "disable") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { disableHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val enableHandler: Handler<Alert> = jsonHandler<Alert>(clientOptions.jsonMapper).withErrorHandler(errorHandler) /** This endpoint can be used to enable an alert. */ override fun enable(params: AlertEnableParams, requestOptions: RequestOptions): Alert { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("alerts", params.getPathParam(0), "enable") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } .build() return clientOptions.httpClient.execute(request, requestOptions).let { response -> response .use { enableHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } }
1
Kotlin
0
0
d2ad23f9ba9b60d46900e154bf3c3ef1d7736222
11,475
orb-kotlin
Apache License 2.0
app/src/main/java/com/cocdetails/ui/nodels/home/Level.kt
iKhan1057
571,087,717
false
null
package com.cocdetails.ui.nodels.home data class Level( val id: String, val name: String, val th:String )
0
Kotlin
0
0
761228f09ea423a1745e556330c4c2b34fe0af38
118
cocinfo
Apache License 2.0
app/src/main/java/co/ello/android/ello/network/parsers/RegionParser.kt
ello
129,277,321
false
null
package co.ello.android.ello class RegionParser { companion object { fun graphQLRegions(jsonList: JSON, isRepostContent: Boolean = false): List<Regionable> { val regions = jsonList.list ?: return emptyList() return regions.flatMap(fun (json: JSON): List<Regionable> { val kind = json["kind"].string?.let { RegionKind.create(it) } ?: return emptyList() val regionable: Regionable? = when(kind) { RegionKind.Text -> textRegion(json) RegionKind.Image -> imageRegion(json) RegionKind.Embed -> embedRegion(json) } if (regionable != null) { regionable.isRepost = isRepostContent return listOf(regionable) } return emptyList() }) } private fun textRegion(json: JSON): TextRegion? { return TextRegion(content = json["data"].stringValue) } private fun imageRegion(json: JSON): ImageRegion? { val url = json["data"]["url"].url ?: return null val buyButtonURL = json["linkUrl"].url val imageRegion = ImageRegion(url = url, buyButtonURL = buyButtonURL) json["links"]["assets"].string?.let { id -> imageRegion.addLinkObject("assets", id = id, type = MappingType.AssetsType) } return imageRegion } private fun embedRegion(json: JSON): EmbedRegion? { val id = json["data"]["id"].string ?: return null val service = json["data"]["service"].string?.let { EmbedRegion.Service.create(it) } ?: return null val url = json["data"]["url"].url ?: return null val thumbnailLargeUrl = json["data"]["thumbnail_large_url"].url ?: json["data"]["thumbnailLargeUrl"].url return EmbedRegion( id = id, service = service, url = url, thumbnailLargeUrl = thumbnailLargeUrl ) } } }
0
Kotlin
0
2
489a1b9f0acf5c2b92bd65ada7e73b91fc8e2ff4
2,096
android
MIT License
xesar-connect/src/test/kotlin/com/open200/xesar/connect/it/command/AddZoneAuthorizationToMediumTest.kt
open200
684,928,079
false
{"Kotlin": 839009}
package com.open200.xesar.connect.command import com.open200.xesar.connect.Topics import com.open200.xesar.connect.XesarConnect import com.open200.xesar.connect.XesarMqttClient import com.open200.xesar.connect.extension.addZoneAuthorizationToMediumAsync import com.open200.xesar.connect.messages.command.AuthorizationData import com.open200.xesar.connect.messages.event.ApiEvent import com.open200.xesar.connect.messages.event.IndividualAuthorizationsAddedToMedium import com.open200.xesar.connect.messages.event.encodeEvent import com.open200.xesar.connect.testutils.MosquittoContainer import io.kotest.common.runBlocking import io.kotest.core.spec.style.FunSpec import io.kotest.extensions.testcontainers.perProject import io.kotest.matchers.equals.shouldBeEqual import io.mockk.coEvery import java.util.* import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.launch class AddZoneAuthorizationToMediumTest : FunSpec({ val container = MosquittoContainer.container() val config = MosquittoContainer.config(container) listener(container.perProject()) test("add installation point authorization to medium") { coEvery { config.uuidGenerator.generateId() } .returns(UUID.fromString("00000000-1281-40ae-89d7-5c541d77a757")) runBlocking { val simulatedBackendReady = CompletableDeferred<Unit>() val commandReceived = CompletableDeferred<String>() launch { XesarMqttClient.connectAsync(config).await().use { client -> client.subscribeAsync(arrayOf(Topics.ALL_TOPICS)).await() client.onMessage = { topic, payload -> when (topic) { Topics.Command.ADD_ZONE_AUTHORIZATION_TO_MEDIUM -> { commandReceived.complete(payload.decodeToString()) } } } simulatedBackendReady.complete(Unit) val commandContent = commandReceived.await() commandContent.shouldBeEqual( "{\"commandId\":\"00000000-1281-40ae-89d7-5c541d77a757\",\"id\":\"43edc7cf-80ab-4486-86db-41cda2c7a2cd\",\"authorization\":{\"authorizationName\":\"authorizationName\",\"authorizationProfileId\":\"2d52bd95-18ba-4e46-8f00-0fc4c1e3f9be\",\"timeProfileName\":\"timeProfileName\",\"authorizationId\":\"<KEY>\",\"installationPoint\":false,\"timeProfileId\":\"e9b31e62-8969-4794-a219-8c81ff10c91d\"},\"token\":\"<KEY>}") val apiEvent = ApiEvent( UUID.fromString("00000000-1281-40ae-89d7-5c541d77a757"), IndividualAuthorizationsAddedToMedium( UUID.fromString("43edc7cf-80ab-4486-86db-41cda2c7a2cd"))) client .publishAsync( Topics.Event.INDIVIDUAL_AUTHORIZATIONS_ADDED_TO_MEDIUM, encodeEvent(apiEvent)) .await() } } launch { simulatedBackendReady.await() val api = XesarConnect.connectAndLoginAsync(config).await() api.subscribeAsync( Topics(Topics.Event.INDIVIDUAL_AUTHORIZATIONS_ADDED_TO_MEDIUM)) .await() val authorizationData = AuthorizationData( "authorizationName", UUID.fromString("2d52bd95-18ba-4e46-8f00-0fc4c1e3f9be"), "timeProfileName", UUID.fromString("8c124504-8263-4201-8b17-f49a6c2f8671"), false, UUID.fromString("e9b31e62-8969-4794-a219-8c81ff10c91d")) val result = api.addZoneAuthorizationToMediumAsync( UUID.fromString("43edc7cf-80ab-4486-86db-41cda2c7a2cd"), authorizationData) .await() result.id.shouldBeEqual(UUID.fromString("43edc7cf-80ab-4486-86db-41cda2c7a2cd")) } } } })
18
Kotlin
1
10
c021a68d197bac5df431deafcdc83030c4cc635e
4,501
xesar-connect
Apache License 2.0