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
basick/src/main/java/com/mozhimen/basick/animk/builders/temps/ScaleType.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.animk.builder.temps import android.animation.* import android.view.View import android.view.animation.Animation import android.view.animation.ScaleAnimation import androidx.annotation.FloatRange import com.mozhimen.basick.animk.builder.bases.BaseAnimKType import com.mozhimen.basick.animk.builder.cons.EDirection import com.mozhimen.basick.animk.builder.mos.AnimKConfig /** * @ClassName ScaleConfig * @Description TODO * @Author mozhimen / <NAME> * @Date 2022/11/17 23:02 * @Version 1.0 */ open class ScaleType : BaseAnimKType<ScaleType>() { private var _scaleFromX = 0f private var _scaleToX = 1f private var _scaleFromY = 0f private var _scaleToY = 1f private var _isDismiss = false override lateinit var _animator: Animator init { setPivot(.5f, .5f) setPivot2(.5f, .5f) } fun fromDirection(vararg from: EDirection): ScaleType { if (from.isNotEmpty()) { var flag = 0 for (direction in from) { flag = flag or direction.flag } if (EDirection.isDirectionFlag(EDirection.LEFT, flag)) { _pivotX = 0f } if (EDirection.isDirectionFlag(EDirection.RIGHT, flag)) { _pivotX = 1f } if (EDirection.isDirectionFlag(EDirection.CENTER_HORIZONTAL, flag)) { _pivotX = 0.5f } if (EDirection.isDirectionFlag(EDirection.TOP, flag)) { _pivotY = 0f } if (EDirection.isDirectionFlag(EDirection.BOTTOM, flag)) { _pivotY = 1f } if (EDirection.isDirectionFlag(EDirection.CENTER_VERTICAL, flag)) { _pivotY = 0.5f } } return this } fun toDirection(vararg to: EDirection): ScaleType { if (to.isNotEmpty()) { var flag = 0 for (direction in to) { flag = flag or direction.flag } if (EDirection.isDirectionFlag(EDirection.LEFT, flag)) { _pivotX2 = 0f } if (EDirection.isDirectionFlag(EDirection.RIGHT, flag)) { _pivotX2 = 1f } if (EDirection.isDirectionFlag(EDirection.CENTER_HORIZONTAL, flag)) { _pivotX2 = 0.5f } if (EDirection.isDirectionFlag(EDirection.TOP, flag)) { _pivotY2 = 0f } if (EDirection.isDirectionFlag(EDirection.BOTTOM, flag)) { _pivotY2 = 1f } if (EDirection.isDirectionFlag(EDirection.CENTER_VERTICAL, flag)) { _pivotY2 = 0.5f } } return this } fun show(): ScaleType { _isDismiss = false return this } fun hide(): ScaleType { _isDismiss = true return this } fun scaleX(@FloatRange(from = 0.0, to = 1.0) fromVal: Float, @FloatRange(from = 0.0, to = 1.0) toVal: Float): ScaleType { _scaleFromX = fromVal _scaleToX = toVal return this } fun scaleY(@FloatRange(from = 0.0, to = 1.0) fromVal: Float, @FloatRange(from = 0.0, to = 1.0) toVal: Float): ScaleType { _scaleFromY = fromVal _scaleToY = toVal return this } fun scale(@FloatRange(from = 0.0, to = 1.0) fromVal: Float, @FloatRange(from = 0.0, to = 1.0) toVal: Float): ScaleType { scaleX(fromVal, toVal) scaleY(fromVal, toVal) return this } override fun buildAnimation(animKConfig: AnimKConfig): Animation { val values = genConfigs() val animation: Animation = ScaleAnimation( values[0], values[1], values[2], values[3], Animation.RELATIVE_TO_SELF, values[4], Animation.RELATIVE_TO_SELF, values[5] ) formatAnimation(animKConfig, animation) return animation } override fun buildAnimator(animKConfig: AnimKConfig): Animator { val values = genConfigs() _animator = AnimatorSet() val scaleX: Animator = ObjectAnimator.ofFloat(null, View.SCALE_X, values[0], values[1]) val scaleY: Animator = ObjectAnimator.ofFloat(null, View.SCALE_Y, values[2], values[3]) scaleX.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { val target = (animation as ObjectAnimator).target if (target is View) { target.pivotX = target.width * values[4] } } }) scaleY.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { val target = (animation as ObjectAnimator).target if (target is View) { target.pivotY = target.height * values[5] } } }) (_animator as AnimatorSet).playTogether(scaleX, scaleY) formatAnimator(animKConfig, _animator) return _animator } private fun genConfigs(): FloatArray { val result = FloatArray(6) result[0] = if (!_isDismiss) _scaleFromX else _scaleToX result[1] = if (!_isDismiss) _scaleToX else _scaleFromX result[2] = if (!_isDismiss) _scaleFromY else _scaleToY result[3] = if (!_isDismiss) _scaleToY else _scaleFromY result[4] = if (!_isDismiss) _pivotX else _pivotX2 result[5] = if (!_isDismiss) _pivotY else _pivotY2 return result } companion object { val LEFT_TO_RIGHT_SHOW = ScaleType().apply { fromDirection(EDirection.LEFT).toDirection(EDirection.RIGHT).show() } val LEFT_TO_RIGHT_HIDE = ScaleType().apply { fromDirection(EDirection.LEFT).toDirection(EDirection.RIGHT).hide() } val RIGHT_TO_LEFT_SHOW = ScaleType().apply { fromDirection(EDirection.RIGHT).toDirection(EDirection.LEFT).show() } val RIGHT_TO_LEFT_HIDE = ScaleType().apply { fromDirection(EDirection.RIGHT).toDirection(EDirection.LEFT).hide() } val TOP_TO_BOTTOM_SHOW = ScaleType().apply { fromDirection(EDirection.TOP).toDirection(EDirection.BOTTOM).show() } val TOP_TO_BOTTOM_HIDE = ScaleType().apply { fromDirection(EDirection.TOP).toDirection(EDirection.BOTTOM).hide() } val BOTTOM_TO_TOP_SHOW = ScaleType().apply { fromDirection(EDirection.BOTTOM).toDirection(EDirection.TOP).show() } val BOTTOM_TO_TOP_HIDE = ScaleType().apply { fromDirection(EDirection.BOTTOM).toDirection(EDirection.TOP).hide() } val CENTER_SHOW = ScaleType().apply { fromDirection(EDirection.CENTER).toDirection(EDirection.CENTER).show() } val CENTER_HIDE = ScaleType().apply { fromDirection(EDirection.CENTER).toDirection(EDirection.CENTER).hide() } } }
0
null
6
2
0b6d7642b1bd7c697d9107c4135c1f2592d4b9d5
7,058
SwiftKit
Apache License 2.0
mylib-file/mylib-file-doc/src/test/kotlin/com/zy/mylib/file/doc/DocUtilTest.kt
ismezy
140,005,112
false
null
/* * Copyright © 2020 ismezy (<EMAIL>) * * 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.zy.mylib.file.doc import fr.opensagres.xdocreport.document.images.ClassPathImageProvider import fr.opensagres.xdocreport.document.images.IImageProvider import org.junit.jupiter.api.Test import java.io.File import java.util.* import kotlin.collections.ArrayList class DocUtilTest { @Test fun genDoc() { val map = mutableMapOf<String, Any?>() val image: IImageProvider = ClassPathImageProvider(DocUtilTest::class.java.classLoader, "test.jpg", false) val image1: IImageProvider = ClassPathImageProvider(DocUtilTest::class.java.classLoader, "test1.png", false) map.put("swjgmc", "成都") map.put("wszg", "2023年02月23") map.put("logo", image) map.put("users", listOf( UserInfo().apply { name = "zy"; sex = "男"; age = 45; photo = image }, UserInfo().apply { name = "wbs"; sex = "男"; age = 35; photo = image1 }, UserInfo().apply { name = "czx"; sex = "男"; age = 30; photo = image }, // mapOf("name" to "zy", "sex" to "男", "age" to 45, "photo" to image), // mapOf("name" to "wbs", "sex" to "男", "age" to 35, "photo" to image), // mapOf("name" to "czx", "sex" to "男", "age" to 30, "photo" to image), )) val metaList = listOf( MetaInfo().apply { key = "users"; classes = UserInfo::class.java; list = true} ) ClassLoader.getSystemResourceAsStream("test.docx").use { val target = File.createTempFile("test_${Date().time}", ".docx") DocUtils.genDoc(map, it, target, metaList) println("---------------${target.path}") } } }
0
Kotlin
0
0
5c16d5d9b41628b4c9408df97d225ebea1d605e8
2,154
mylib
Apache License 2.0
app/src/main/java/com/duckduckgo/app/global/initialization/AppDataLoader.kt
tanujnotes
387,097,583
true
{"Kotlin": 2976206, "HTML": 42259, "Ruby": 7252, "JavaScript": 6544, "C++": 1820, "CMake": 1298, "Shell": 712}
/* * Copyright (c) 2019 DuckDuckGo * * 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.duckduckgo.app.global.initialization import com.duckduckgo.app.privacy.model.PrivacyPractices import com.duckduckgo.app.privacy.store.TermsOfServiceStore import timber.log.Timber import javax.inject.Inject class AppDataLoader @Inject constructor( private val termsOfServiceStore: TermsOfServiceStore, private val privacyPractices: PrivacyPractices ) { suspend fun loadData() { Timber.i("Started to load app data") termsOfServiceStore.loadData() privacyPractices.loadData() Timber.i("Finished loading app data") } }
0
Kotlin
0
10
0c48a2a934afee7df12e98b8e345a84f112d878a
1,177
DuckDuckPlus
Apache License 2.0
app/src/main/java/io/wax911/sample/extension/AppExt.kt
fossabot
223,555,788
true
{"Kotlin": 288406, "Java": 19109}
package io.wax911.sample.extension
0
Kotlin
0
0
50be1a136fc46fb0eaccc041ef40eca2f4c67771
36
support-arch
Apache License 2.0
billing/src/main/java/de/charlex/billing/BillingSecurity.kt
ch4rl3x
311,794,036
false
{"Kotlin": 20013}
package de.charlex.billing import android.text.TextUtils import android.util.Base64 import android.util.Log import java.io.IOException import java.security.InvalidKeyException import java.security.KeyFactory import java.security.NoSuchAlgorithmException import java.security.PublicKey import java.security.Signature import java.security.SignatureException import java.security.spec.InvalidKeySpecException import java.security.spec.X509EncodedKeySpec /** * BillingSecurity-related methods. For a secure implementation, all of this code should be implemented on * a server that communicates with the application on the device. */ object BillingSecurity { private const val KEY_FACTORY_ALGORITHM = "RSA" private const val SIGNATURE_ALGORITHM = "SHA1withRSA" /** * Verifies that the data was signed with the given signature, and returns the verified * purchase. * * Note: It's strongly recommended to perform such check on your backend since hackers can * replace this method with "constant true" if they decompile/rebuild your app. * * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key * @throws java.io.IOException if encoding algorithm is not supported or key specification * is invalid */ @Throws(IOException::class) fun verifyPurchase( base64PublicKey: String?, signedData: String, signature: String? ): Boolean { if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) || TextUtils.isEmpty(signature) ) { Log.d("BillingSecurity", "Purchase verification failed: missing data.") return false } val key = generatePublicKey(base64PublicKey) return verify(key, signedData, signature) } /** * Generates a PublicKey instance from a string containing the Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IOException if encoding algorithm is not supported or key specification * is invalid */ @Throws(IOException::class) private fun generatePublicKey(encodedPublicKey: String?): PublicKey { return try { val decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT) val keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM) keyFactory.generatePublic(X509EncodedKeySpec(decodedKey)) } catch (e: NoSuchAlgorithmException) { // "RSA" is guaranteed to be available. throw RuntimeException(e) } catch (e: InvalidKeySpecException) { val msg = "Invalid key specification: $e" Log.w("BillingSecurity", msg) throw IOException(msg) } } /** * Verifies that the signature from the server matches the computed signature on the data. * Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ private fun verify(publicKey: PublicKey?, signedData: String, signature: String?): Boolean { val signatureBytes: ByteArray = try { Base64.decode(signature, Base64.DEFAULT) } catch (e: IllegalArgumentException) { Log.w("BillingSecurity", "Base64 decoding failed.") return false } try { val signatureAlgorithm = Signature.getInstance(SIGNATURE_ALGORITHM) signatureAlgorithm.initVerify(publicKey) signatureAlgorithm.update(signedData.toByteArray()) if (!signatureAlgorithm.verify(signatureBytes)) { Log.w("BillingSecurity", "Signature verification failed.") return false } return true } catch (e: NoSuchAlgorithmException) { // "RSA" is guaranteed to be available. throw RuntimeException(e) } catch (e: InvalidKeyException) { Log.w("BillingSecurity", "Invalid key specification.") } catch (e: SignatureException) { Log.w("BillingSecurity", "Signature exception.") } return false } }
0
Kotlin
0
6
f840d8f53346b59f54d30b27b3039a55eec97ad4
4,433
billing-suspend
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/service/appointment/AppointmentCreateDomainService.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3213032, "Shell": 11230, "Dockerfile": 1490}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity import com.microsoft.applicationinsights.TelemetryClient import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.audit.AppointmentSeriesCreatedEvent import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AppointmentCancellationReasonRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AppointmentRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AppointmentSeriesRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.CANCELLED_APPOINTMENT_CANCELLATION_REASON_ID import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.findOrThrowNotFound import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.AuditService import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.TransactionHandler import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.events.OutboundEvent import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.events.OutboundEventsService import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.APPOINTMENT_COUNT_METRIC_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.APPOINTMENT_INSTANCE_COUNT_METRIC_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.APPOINTMENT_SERIES_ID_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.CATEGORY_CODE_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.CATEGORY_DESCRIPTION_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.CUSTOM_NAME_LENGTH_METRIC_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.END_TIME_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.EVENT_ORGANISER_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.EVENT_TIER_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.EVENT_TIME_MS_METRIC_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.EXTRA_INFORMATION_LENGTH_METRIC_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.FREQUENCY_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.HAS_CUSTOM_NAME_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.HAS_EXTRA_INFORMATION_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.INTERNAL_LOCATION_DESCRIPTION_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.INTERNAL_LOCATION_ID_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.IS_REPEAT_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.NUMBER_OF_APPOINTMENTS_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.PRISONER_COUNT_METRIC_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.PRISON_CODE_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.START_DATE_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.START_TIME_PROPERTY_KEY import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.TelemetryEvent import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.telemetry.USER_PROPERTY_KEY import java.time.LocalDate import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.AppointmentSeries as AppointmentSeriesModel @Service @Transactional class AppointmentCreateDomainService( private val appointmentSeriesRepository: AppointmentSeriesRepository, private val appointmentRepository: AppointmentRepository, private val appointmentCancellationReasonRepository: AppointmentCancellationReasonRepository, private val transactionHandler: TransactionHandler, private val outboundEventsService: OutboundEventsService, private val telemetryClient: TelemetryClient, private val auditService: AuditService, ) { fun createAppointments( appointmentSeriesId: Long, prisonNumberBookingIdMap: Map<String, Long>, startTimeInMs: Long, categoryDescription: String, locationDescription: String, ): AppointmentSeriesModel { val appointmentSeries = appointmentSeriesRepository.findOrThrowNotFound(appointmentSeriesId) return createAppointments( appointmentSeries = appointmentSeries, prisonNumberBookingIdMap = prisonNumberBookingIdMap, createFirstAppointmentOnly = false, isCancelled = false, categoryDescription = categoryDescription, locationDescription = locationDescription, startTimeInMs = startTimeInMs, trackEvent = true, auditEvent = true, ) } /** * Uses the appointment series as a blueprint to create all the appointments in the series and their attendees. * Will only create appointments and attendees not already created making it safe to use for the partial async create process. * * @param isCancelled specifies whether the appointments should be created in a cancelled state. Can only set to true for migrated appointments */ fun createAppointments( appointmentSeries: AppointmentSeries, prisonNumberBookingIdMap: Map<String, Long>, createFirstAppointmentOnly: Boolean = false, isCancelled: Boolean = false, startTimeInMs: Long = 0, categoryDescription: String = "", locationDescription: String = "", trackEvent: Boolean = false, auditEvent: Boolean = false, ): AppointmentSeriesModel { require(!isCancelled || appointmentSeries.isMigrated) { "Only migrated appointments can be created in a cancelled state" } val cancelledTime = if (isCancelled) appointmentSeries.updatedTime ?: appointmentSeries.createdTime else null val cancellationReason = if (isCancelled) appointmentCancellationReasonRepository.findOrThrowNotFound(CANCELLED_APPOINTMENT_CANCELLATION_REASON_ID) else null val cancelledBy = if (isCancelled) appointmentSeries.updatedBy ?: appointmentSeries.createdBy else null appointmentSeries.scheduleIterator().withIndex().forEach { indexedStartDate -> val sequenceNumber = indexedStartDate.index + 1 if (createFirstAppointmentOnly && sequenceNumber > 1) return@forEach if (appointmentSeries.appointments().none { it.sequenceNumber == sequenceNumber }) { transactionHandler.newSpringTransaction { appointmentRepository.saveAndFlush( appointmentSeries.createAndAddAppointment( sequenceNumber, indexedStartDate.value, ).apply { this.cancelledTime = cancelledTime this.cancellationReason = cancellationReason this.cancelledBy = cancelledBy prisonNumberBookingIdMap.forEach { addAttendee( AppointmentAttendee( appointment = this, prisonerNumber = it.key, bookingId = it.value, ), ) } }, ) }.also { if (!appointmentSeries.isMigrated) { it.attendees().forEach { outboundEventsService.send(OutboundEvent.APPOINTMENT_INSTANCE_CREATED, it.appointmentAttendeeId) } } } appointmentSeriesRepository.saveAndFlush(appointmentSeries) } } return appointmentSeries.toModel().also { if (trackEvent) it.logAppointmentSeriesCreatedMetric(prisonNumberBookingIdMap, startTimeInMs, categoryDescription, locationDescription) if (auditEvent) it.writeAppointmentCreatedAuditRecord(prisonNumberBookingIdMap) } } private fun AppointmentSeriesModel.logAppointmentSeriesCreatedMetric( prisonNumberBookingIdMap: Map<String, Long>, startTimeInMs: Long, categoryDescription: String, locationDescription: String, ) { val propertiesMap = mapOf( USER_PROPERTY_KEY to createdBy, PRISON_CODE_PROPERTY_KEY to prisonCode, APPOINTMENT_SERIES_ID_PROPERTY_KEY to id.toString(), CATEGORY_CODE_PROPERTY_KEY to categoryCode, CATEGORY_DESCRIPTION_PROPERTY_KEY to categoryDescription, HAS_CUSTOM_NAME_PROPERTY_KEY to (!customName.isNullOrEmpty()).toString(), INTERNAL_LOCATION_ID_PROPERTY_KEY to (if (this.inCell) "" else this.internalLocationId?.toString() ?: ""), INTERNAL_LOCATION_DESCRIPTION_PROPERTY_KEY to locationDescription, START_DATE_PROPERTY_KEY to startDate.toString(), START_TIME_PROPERTY_KEY to startTime.toString(), END_TIME_PROPERTY_KEY to endTime.toString(), IS_REPEAT_PROPERTY_KEY to (schedule != null).toString(), FREQUENCY_PROPERTY_KEY to (schedule?.frequency?.toString() ?: ""), NUMBER_OF_APPOINTMENTS_PROPERTY_KEY to (schedule?.numberOfAppointments?.toString() ?: ""), HAS_EXTRA_INFORMATION_PROPERTY_KEY to (extraInformation?.isNotEmpty() == true).toString(), EVENT_TIER_PROPERTY_KEY to (tier?.description ?: ""), EVENT_ORGANISER_PROPERTY_KEY to (organiser?.description ?: ""), ) val metricsMap = mapOf( PRISONER_COUNT_METRIC_KEY to prisonNumberBookingIdMap.size.toDouble(), APPOINTMENT_COUNT_METRIC_KEY to (schedule?.numberOfAppointments ?: 1).toDouble(), APPOINTMENT_INSTANCE_COUNT_METRIC_KEY to (prisonNumberBookingIdMap.size * (schedule?.numberOfAppointments ?: 1)).toDouble(), CUSTOM_NAME_LENGTH_METRIC_KEY to (customName?.length ?: 0).toDouble(), EXTRA_INFORMATION_LENGTH_METRIC_KEY to (extraInformation?.length ?: 0).toDouble(), EVENT_TIME_MS_METRIC_KEY to (System.currentTimeMillis() - startTimeInMs).toDouble(), ) telemetryClient.trackEvent(TelemetryEvent.APPOINTMENT_SERIES_CREATED.value, propertiesMap, metricsMap) } private fun AppointmentSeriesModel.writeAppointmentCreatedAuditRecord(prisonNumberBookingIdMap: Map<String, Long>) { auditService.logEvent( AppointmentSeriesCreatedEvent( appointmentSeriesId = id, prisonCode = prisonCode, categoryCode = categoryCode, hasCustomName = customName != null, internalLocationId = internalLocationId, startDate = startDate, startTime = startTime, endTime = endTime, isRepeat = schedule != null, frequency = schedule?.frequency, numberOfAppointments = schedule?.numberOfAppointments, hasExtraInformation = extraInformation?.isNotEmpty() == true, prisonerNumbers = prisonNumberBookingIdMap.keys.toList(), createdTime = createdTime, createdBy = createdBy, ), ) } } /** * Creates an appointment within an appointment series based on the series blueprint. * This function uses the parent appointment series' updatedTime and updatedBy values even though it's creating the * initial appointment data as migrated appointments can have these values set. When we migrate an appointment, we are * becoming the master record for that appointment so want to bring all the data we can over. When that appointment was * last updated and by whom is part of that data. */ fun AppointmentSeries.createAndAddAppointment(sequenceNumber: Int, startDate: LocalDate) = Appointment( appointmentSeries = this, sequenceNumber = sequenceNumber, prisonCode = this.prisonCode, categoryCode = this.categoryCode, customName = this.customName, appointmentTier = this.appointmentTier, internalLocationId = this.internalLocationId, customLocation = this.customLocation, inCell = this.inCell, onWing = this.onWing, offWing = this.offWing, startDate = startDate, startTime = this.startTime, endTime = this.endTime, unlockNotes = this.unlockNotes, extraInformation = this.extraInformation, createdTime = this.createdTime, createdBy = this.createdBy, updatedTime = this.updatedTime, updatedBy = this.updatedBy, ).also { it.appointmentOrganiser = this.appointmentOrganiser this.addAppointment(it) }
6
Kotlin
0
1
eae02fa4109011532d8b881a6338788d16e021ca
12,411
hmpps-activities-management-api
MIT License
samples/app/src/main/kotlin/com/bumble/appyx/app/composable/ScreenCenteredContent.kt
bumble-tech
493,334,393
false
null
package com.bumble.appyx.app.composable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable internal fun ScreenCenteredContent( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Box( modifier = modifier .fillMaxSize() ) { Box( modifier = Modifier.align(Alignment.Center) ) { content() } } }
68
Kotlin
45
754
1c13ab49fb3e2eb0bcd192332d597f8c05d3f6a9
574
appyx
Apache License 2.0
src/main/kotlin/spritz/builtin/companions/BooleanCompanion.kt
SpritzLanguage
606,570,819
false
null
package spritz.builtin.companions import spritz.value.bool.BooleanValue /** * @author surge * @since 26/03/2023 */ class BooleanCompanion(value: BooleanValue) : Companion(value) { fun binary() = if ((value as BooleanValue).value) 1 else 0 }
0
Kotlin
0
23
f50d81fa2d5aa7784ac4c76717603eea079c8db2
251
Spritz
The Unlicense
kotlin-jvm/src/main/kotlin/playground/Retrofit.kt
LouisCAD
295,134,297
false
null
@file:Suppress("PackageDirectoryMismatch") package playground.retrofit import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import playground.kotlinx.serialization.HttpBinGet import playground.shouldBe import retrofit2.Call import retrofit2.Retrofit import retrofit2.create import retrofit2.http.GET import retrofit2.http.QueryMap /** * square/retrofit - A type-safe HTTP client for Android and the JVM - [Website](https://square.github.io/retrofit/) - [GitHub square/retrofit](https://github.com/square/retrofit) - [CHANGELOG](https://github.com/square/retrofit/blob/master/CHANGELOG.md) - [Consuming APIs with Retrofit | CodePath Android Cliffnotes](https://guides.codepath.com/android/Consuming-APIs-with-Retrofit#references) */ fun main() { println() println("# square/retrofit - A type-safe HTTP client for Android and the JVM") val api: RetrofitHttpbinApi = Network.retrofit.create() val response = api.get(mapOf("hello" to "world")).execute() response.isSuccessful shouldBe true response.body()!!.run { args shouldBe mapOf("hello" to "world") url shouldBe "http://httpbin.org/get?hello=world" } } interface RetrofitHttpbinApi { @GET("get") fun get(@QueryMap params: Map<String, String>): Call<HttpBinGet> } object Network { var API_URL = "http://httpbin.org/" val okHttpClient = OkHttpClient.Builder() .addNetworkInterceptor(HttpLoggingInterceptor()) .build() val contentType = "application/json".toMediaType() @OptIn(ExperimentalSerializationApi::class) val retrofit = Retrofit.Builder() .client(okHttpClient) .baseUrl(API_URL) //.addCallAdapterFactory(CallAdapter.Factory) .addConverterFactory(Json.asConverterFactory(contentType)) .build() }
16
null
54
171
ff3ae6af7530d3b873b79486cf6e947f1ee53aa1
2,042
kotlin-libraries-playground
MIT License
utils/src/main/kotlin/com/aqrlei/open/utils/TransformType.kt
AqrLei
163,511,183
false
null
package com.aqrlei.open.utils import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream /** * @author aqrLei on 2018/4/24 */ @Suppress("unused") fun byteArrayToSequence(data: ByteArray): Any? { val result: Any? val arrayInputStream = ByteArrayInputStream(data) var inputStream: ObjectInputStream? = null try { inputStream = ObjectInputStream(arrayInputStream) result = inputStream.readObject() } finally { arrayInputStream.close() inputStream?.close() } return result } @Suppress("unused") fun sequenceToByteArray(data: Any): ByteArray? { val result: ByteArray? val arrayOutputStream = ByteArrayOutputStream() val objectOutputStream = ObjectOutputStream(arrayOutputStream) try { objectOutputStream.writeObject(data) objectOutputStream.flush() result = arrayOutputStream.toByteArray() } finally { arrayOutputStream.close() objectOutputStream.close() } return result } @Suppress("unused") fun byteArrayToBitmap(byte: ByteArray?, offset: Int = 0): Bitmap? { return byte?.let { BitmapFactory.decodeByteArray(it, offset, it.size) } } @Suppress("unused") fun bitmapToDrawable(bitmap: Bitmap?, res: Resources? = null): Drawable? { return bitmap?.let { BitmapDrawable(res, it) } } @Suppress("unused") fun byteArrayToDrawable(byte: ByteArray?, offset: Int = 0): Drawable? { return byte?.let { BitmapDrawable(null, BitmapFactory.decodeByteArray(it, offset, it.size)) } }
0
Kotlin
0
0
8f1fafab152404cee5ddc36d2747fc0e37c6c1fd
1,825
Utils
Apache License 2.0
domene/src/main/kotlin/no/nav/tiltakspenger/domene/behandling/BehandlingVilkårsvurdert.kt
navikt
487,246,438
false
{"Kotlin": 846627, "Dockerfile": 495, "Shell": 150, "HTML": 45}
package no.nav.tiltakspenger.domene.behandling import mu.KotlinLogging import no.nav.tiltakspenger.domene.saksopplysning.Saksopplysning import no.nav.tiltakspenger.domene.vilkår.Utfall import no.nav.tiltakspenger.domene.vilkår.Vilkår import no.nav.tiltakspenger.domene.vilkår.Vurdering import no.nav.tiltakspenger.felles.BehandlingId import no.nav.tiltakspenger.felles.Periode import no.nav.tiltakspenger.felles.SakId private val LOG = KotlinLogging.logger {} private val SECURELOG = KotlinLogging.logger("tjenestekall") sealed interface BehandlingVilkårsvurdert : Søknadsbehandling { val vilkårsvurderinger: List<Vurdering> override fun søknad(): Søknad { return søknader.maxBy { it.opprettet } } fun hentUtfallForVilkår(vilkår: Vilkår): Utfall { if (vilkårsvurderinger.any { it.vilkår == vilkår && it.utfall == Utfall.KREVER_MANUELL_VURDERING }) return Utfall.KREVER_MANUELL_VURDERING if (vilkårsvurderinger.any { it.vilkår == vilkår && it.utfall == Utfall.IKKE_OPPFYLT }) return Utfall.IKKE_OPPFYLT if (vilkårsvurderinger.filter { it.vilkår == vilkår }.all { it.utfall == Utfall.OPPFYLT }) return Utfall.OPPFYLT throw IllegalStateException("Kunne ikke finne utfall for vilkår $vilkår") } fun vurderPåNytt(): BehandlingVilkårsvurdert { return Søknadsbehandling.Opprettet( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, saksbehandler = saksbehandler, ).vilkårsvurder() } companion object { fun fromDb( id: BehandlingId, sakId: SakId, søknader: List<Søknad>, vurderingsperiode: Periode, saksopplysninger: List<Saksopplysning>, tiltak: List<Tiltak>, vilkårsvurderinger: List<Vurdering>, status: String, saksbehandler: String?, ): BehandlingVilkårsvurdert { when (status) { "Innvilget" -> return Innvilget( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = saksbehandler, ) "Avslag" -> return Avslag( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = saksbehandler, ) "Manuell" -> return Manuell( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = saksbehandler, ) else -> throw IllegalStateException("Ukjent BehandlingVilkårsvurdert $id med status $status") } } } data class Innvilget( override val id: BehandlingId, override val sakId: SakId, override val søknader: List<Søknad>, override val vurderingsperiode: Periode, override val saksopplysninger: List<Saksopplysning>, override val tiltak: List<Tiltak>, override val vilkårsvurderinger: List<Vurdering>, override val saksbehandler: String?, ) : BehandlingVilkårsvurdert { fun iverksett(): BehandlingIverksatt.Innvilget { return BehandlingIverksatt.Innvilget( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = "Automatisk", beslutter = "Automatisk", ) } fun tilBeslutting(): BehandlingTilBeslutter.Innvilget { return BehandlingTilBeslutter.Innvilget( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = checkNotNull(saksbehandler) { "Ikke lov å sende Behandling til Beslutter uten saksbehandler" }, beslutter = null, ) } override fun erÅpen() = true override fun leggTilSøknad(søknad: Søknad): BehandlingVilkårsvurdert { return Søknadsbehandling.Opprettet( id = id, sakId = sakId, søknader = søknader + søknad, vurderingsperiode = vurderingsperiode, saksopplysninger = lagFaktaAvSøknad(søknad).fold(saksopplysninger) { acc, saksopplysning -> acc.oppdaterSaksopplysninger(saksopplysning) }, tiltak = tiltak, saksbehandler = saksbehandler, ).vilkårsvurder() } override fun leggTilSaksopplysning(saksopplysning: Saksopplysning): LeggTilSaksopplysningRespons { val oppdatertSaksopplysningListe = saksopplysninger.oppdaterSaksopplysninger(saksopplysning) return if (oppdatertSaksopplysningListe == this.saksopplysninger) { LeggTilSaksopplysningRespons( behandling = this, erEndret = false, ) } else { LeggTilSaksopplysningRespons( behandling = this.copy(saksopplysninger = oppdatertSaksopplysningListe).vurderPåNytt(), erEndret = true, ) } } override fun oppdaterTiltak(tiltak: List<Tiltak>): Søknadsbehandling = this.copy( tiltak = tiltak, ) override fun startBehandling(saksbehandler: String): Søknadsbehandling = this.copy( saksbehandler = saksbehandler, ) override fun avbrytBehandling(): Søknadsbehandling = this.copy( saksbehandler = null, ) } data class Avslag( override val id: BehandlingId, override val sakId: SakId, override val søknader: List<Søknad>, override val vurderingsperiode: Periode, override val saksopplysninger: List<Saksopplysning>, override val tiltak: List<Tiltak>, override val vilkårsvurderinger: List<Vurdering>, override val saksbehandler: String?, ) : BehandlingVilkårsvurdert { fun iverksett(): BehandlingIverksatt.Avslag { return BehandlingIverksatt.Avslag( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = "Automatisk", beslutter = "Automatisk", ) } fun tilBeslutting(): BehandlingTilBeslutter.Avslag { return BehandlingTilBeslutter.Avslag( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vilkårsvurderinger, saksbehandler = checkNotNull(saksbehandler) { "Ikke lov å sende Behandling til Beslutter uten saksbehandler" }, beslutter = null, ) } override fun erÅpen() = true override fun leggTilSøknad(søknad: Søknad): BehandlingVilkårsvurdert { return Søknadsbehandling.Opprettet( id = id, sakId = sakId, søknader = søknader + søknad, vurderingsperiode = vurderingsperiode, saksopplysninger = lagFaktaAvSøknad(søknad).fold(saksopplysninger) { acc, saksopplysning -> acc.oppdaterSaksopplysninger(saksopplysning) }, tiltak = tiltak, saksbehandler = saksbehandler, ).vilkårsvurder() } override fun leggTilSaksopplysning(saksopplysning: Saksopplysning): LeggTilSaksopplysningRespons { val oppdatertSaksopplysningListe = saksopplysninger.oppdaterSaksopplysninger(saksopplysning) return if (oppdatertSaksopplysningListe == this.saksopplysninger) { LeggTilSaksopplysningRespons( behandling = this, erEndret = false, ) } else { LeggTilSaksopplysningRespons( behandling = this.copy(saksopplysninger = oppdatertSaksopplysningListe).vurderPåNytt(), erEndret = true, ) } } override fun oppdaterTiltak(tiltak: List<Tiltak>): Søknadsbehandling = this.copy( tiltak = tiltak, ) override fun startBehandling(saksbehandler: String): Søknadsbehandling = this.copy( saksbehandler = saksbehandler, ) override fun avbrytBehandling(): Søknadsbehandling = this.copy( saksbehandler = null, ) } data class Manuell( override val id: BehandlingId, override val sakId: SakId, override val søknader: List<Søknad>, override val vurderingsperiode: Periode, override val saksopplysninger: List<Saksopplysning>, override val tiltak: List<Tiltak>, override val vilkårsvurderinger: List<Vurdering>, override val saksbehandler: String?, ) : BehandlingVilkårsvurdert { override fun erÅpen() = true override fun leggTilSøknad(søknad: Søknad): BehandlingVilkårsvurdert { return Søknadsbehandling.Opprettet( id = id, sakId = sakId, søknader = søknader + søknad, vurderingsperiode = vurderingsperiode, saksopplysninger = lagFaktaAvSøknad(søknad).fold(saksopplysninger) { acc, saksopplysning -> acc.oppdaterSaksopplysninger(saksopplysning) }, tiltak = tiltak, saksbehandler = saksbehandler, ).vilkårsvurder() } override fun leggTilSaksopplysning(saksopplysning: Saksopplysning): LeggTilSaksopplysningRespons { val oppdatertSaksopplysningListe = saksopplysninger.oppdaterSaksopplysninger(saksopplysning) return if (oppdatertSaksopplysningListe == this.saksopplysninger) { LeggTilSaksopplysningRespons( behandling = this, erEndret = false, ) } else { LeggTilSaksopplysningRespons( behandling = this.copy(saksopplysninger = oppdatertSaksopplysningListe).vurderPåNytt(), erEndret = true, ) } } override fun oppdaterTiltak(tiltak: List<Tiltak>): Søknadsbehandling = this.copy( tiltak = tiltak, ) override fun startBehandling(saksbehandler: String): Søknadsbehandling = this.copy( saksbehandler = saksbehandler, ) override fun avbrytBehandling(): Søknadsbehandling = this.copy( saksbehandler = null, ) } }
3
Kotlin
0
2
a873372e114b2067022fb71a1d959568dc80c712
12,374
tiltakspenger-vedtak
MIT License
app/src/main/java/com/example/kotlinSub2Ara/api/SportDbRepository.kt
hantulautt
177,001,059
false
{"Kotlin": 20071}
package com.example.kotlinSub2Ara.Api import com.example.kotlinSub2Ara.BuildConfig import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object SportDbRepository { fun create(): SportDbService { val retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(BuildConfig.BASE_URL) .build() return retrofit.create(SportDbService::class.java) } }
0
Kotlin
0
0
feb81a6b7f327e8eba6628f800936fbdd117bd8f
462
kotlin-with-thesportdb-api
MIT License
app/src/main/java/com/prabhatpandey/otpcomposeapp/MainActivity.kt
prabhatsdp
752,274,865
false
{"Kotlin": 28309}
package com.prabhatpandey.otpcomposeapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.prabhatpandey.otpcompose.OTPTextField import com.prabhatpandey.otpcompose.OtpTextFieldDefaults import com.prabhatpandey.otpcomposeapp.ui.theme.OTPComposeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { var otp by rememberSaveable { mutableStateOf("") } OTPComposeTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding(32.dp) ) { Greeting("OTP Field") OTPTextField( value = otp, onTextChanged = { otp = it }, digitContainerStyle = OtpTextFieldDefaults.outlinedContainer( unfocusedBorderWidth = 2.dp, focusedBorderWidth = 4.dp, ), modifier = Modifier .fillMaxWidth() .padding(32.dp), isMasked = false, ) } } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { OTPComposeTheme { Greeting("Android") } }
0
Kotlin
0
2
78b4ee9d3da89475b4a60094aa82b87991052851
2,951
otp-compose
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/adjudications/AdjudicationTransformationTest.kt
ministryofjustice
452,734,022
false
{"Kotlin": 1281774, "Mustache": 1803, "Dockerfile": 1374}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.model.MigrateDamage.DamageType import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.model.MigrateEvidence.EvidenceCode import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.model.MigrateHearing import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.model.MigrateHearing.OicHearingType.GOV import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.model.MigrateHearing.OicHearingType.GOV_ADULT import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.model.MigrateWitness import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.AdjudicationCharge import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.AdjudicationChargeResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.AdjudicationIncident import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.AdjudicationOffence import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.CodeDescription import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.Evidence import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.Hearing import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.HearingNotification import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.HearingResult import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.HearingResultAward import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.InternalLocation import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.Investigation import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.Prisoner import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.Repair import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.Staff import java.math.BigDecimal import java.time.LocalDate import java.time.LocalTime import java.util.stream.Stream class AdjudicationTransformationTest { @Test fun `will copy core identifiers`() { val nomisAdjudication = nomisAdjudicationCharge(adjudicationNumber = 654321, chargeSequence = 2, adjudicationIncidentId = 45453) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.oicIncidentId).isEqualTo(654321) assertThat(dpsAdjudication.offenceSequence).isEqualTo(2) assertThat(dpsAdjudication.agencyIncidentId).isEqualTo(45453) } @Test fun `will user who created and reported the incident`() { val nomisAdjudication = nomisAdjudicationCharge(reportingStaffUsername = "F.LAST", createdByStaffUsername = "A.BEANS") val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.reportingOfficer.username).isEqualTo("F.LAST") assertThat(dpsAdjudication.createdByUsername).isEqualTo("A.BEANS") } @Test fun `will copy prisoner details`() { val nomisAdjudication = nomisAdjudicationCharge( offenderNo = "A1234AA", bookingId = 543231, genderCode = "F", currentPrison = CodeDescription("WWI", "Wandsworth (HMP)"), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.prisoner.prisonerNumber).isEqualTo("A1234AA") assertThat(dpsAdjudication.bookingId).isEqualTo(543231) assertThat(dpsAdjudication.prisoner.gender).isEqualTo("F") assertThat(dpsAdjudication.prisoner.currentAgencyId).isEqualTo("WWI") assertThat(nomisAdjudicationCharge(currentPrison = null).toAdjudication().prisoner.currentAgencyId).isNull() } @Test fun `will copy the incident location`() { val nomisAdjudication = nomisAdjudicationCharge(prisonId = "MDI", internalLocationId = 1234567) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.agencyId).isEqualTo("MDI") assertThat(dpsAdjudication.locationId).isEqualTo(1234567) } @Test fun `will copy incident dates`() { val nomisAdjudication = nomisAdjudicationCharge( incidentDate = LocalDate.parse("2020-12-25"), incidentTime = LocalTime.parse("12:34"), reportedDate = LocalDate.parse("2020-12-26"), reportedTime = LocalTime.parse("09:10"), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.reportedDateTime).isEqualTo("2020-12-26T09:10:00") assertThat(dpsAdjudication.incidentDateTime).isEqualTo("2020-12-25T12:34:00") } @Test fun `will copy the statement`() { val nomisAdjudication = nomisAdjudicationCharge(statementDetails = "Governor approximately 09:10 on the 23.07.2023 whilst completing enhanced AFC’s on cell K-02-25 dually occupied by Offender Bobby A9999DV and Simon A8888EK, whilst completing a rub down search of offender Marke A6543DV a small piece of paper was removed from his pocket along with a vape pen with paper on it was taken and placed in evidence bag M16824213. When these items were tested on the Rapiscan these tested positive for Spice 9. BWVC 655432 was active throughout, for this reason, I am placing Offender Bob on report.") val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.statement).isEqualTo("Governor approximately 09:10 on the 23.07.2023 whilst completing enhanced AFC’s on cell K-02-25 dually occupied by Offender Bobby A9999DV and Simon A8888EK, whilst completing a rub down search of offender Marke A6543DV a small piece of paper was removed from his pocket along with a vape pen with paper on it was taken and placed in evidence bag M16824213. When these items were tested on the Rapiscan these tested positive for Spice 9. BWVC 655432 was active throughout, for this reason, I am placing Offender Bob on report.") } @Nested inner class DamageRepairs { @Test fun `will copy multiple repairs`() { val nomisAdjudication = nomisAdjudicationCharge( repairs = listOf( Repair( type = CodeDescription(code = "PLUM", description = "Plumbing"), comment = "Broken toilet", createdByUsername = "A.BEANS", ), Repair( type = CodeDescription(code = "PLUM", description = "Plumbing"), comment = "Broken sink", createdByUsername = "B.STUFF", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.damages).hasSize(2) } @Test fun `will copy details`() { val nomisAdjudication = nomisAdjudicationCharge( repairs = listOf( Repair( type = CodeDescription(code = "PLUM", description = "Plumbing"), comment = "Broken toilet", createdByUsername = "A.BEANS", cost = BigDecimal("12.34"), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.damages).hasSize(1) assertThat(dpsAdjudication.damages[0].details).isEqualTo("Broken toilet") assertThat(dpsAdjudication.damages[0].createdBy).isEqualTo("A.BEANS") assertThat(dpsAdjudication.damages[0].repairCost).isEqualTo(BigDecimal("12.34")) } @Test fun `damage type is mapped`() { val nomisAdjudication = nomisAdjudicationCharge( repairs = listOf( Repair( type = CodeDescription(code = "ELEC", description = "Electrical"), createdByUsername = "A.BEANS", ), Repair(type = CodeDescription(code = "PLUM", description = "Plumbing"), createdByUsername = "A.BEANS"), Repair(type = CodeDescription(code = "DECO", description = "Re-Decoration"), createdByUsername = "A.BEANS"), Repair(type = CodeDescription(code = "FABR", description = "Fabric"), createdByUsername = "A.BEANS"), Repair(type = CodeDescription(code = "CLEA", description = "Cleaning"), createdByUsername = "A.BEANS"), Repair(type = CodeDescription(code = "LOCK", description = "Lock"), createdByUsername = "A.BEANS"), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.damages).hasSize(6) assertThat(dpsAdjudication.damages[0].damageType).isEqualTo(DamageType.ELECTRICAL_REPAIR) assertThat(dpsAdjudication.damages[1].damageType).isEqualTo(DamageType.PLUMBING_REPAIR) assertThat(dpsAdjudication.damages[2].damageType).isEqualTo(DamageType.REDECORATION) assertThat(dpsAdjudication.damages[3].damageType).isEqualTo(DamageType.FURNITURE_OR_FABRIC_REPAIR) assertThat(dpsAdjudication.damages[4].damageType).isEqualTo(DamageType.CLEANING) assertThat(dpsAdjudication.damages[5].damageType).isEqualTo(DamageType.LOCK_REPAIR) } } @Nested inner class InvestigationEvidence { @Test fun `will copy multiple evidence from multiple investigations`() { val nomisAdjudication = nomisAdjudicationCharge( investigations = listOf( Investigation( investigator = Staff( username = "J.SMITH", staffId = 1, firstName = "John", lastName = "Smith", createdByUsername = "B.BATTS", ), dateAssigned = LocalDate.parse("2020-12-25"), comment = "some comment", evidence = listOf( Evidence( type = CodeDescription(code = "BEHAV", description = "Behaviour Report"), date = LocalDate.parse("2020-12-25"), detail = "report detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "WITNESS", description = "Witness Statement"), date = LocalDate.parse("2020-12-26"), detail = "witness statement", createdByUsername = "A.BEANS", ), ), ), Investigation( investigator = Staff( username = "D.ABBOY", staffId = 67839, firstName = "DIKBLISNG", lastName = "ABBOY", createdByUsername = "B.BATTS", ), dateAssigned = LocalDate.parse("2023-08-07"), comment = "another comment", evidence = listOf( Evidence( type = CodeDescription(code = "BEHAV", description = "Behaviour Report"), date = LocalDate.parse("2021-12-25"), detail = "another behave report", createdByUsername = "A.BEANS", ), ), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.evidence).hasSize(3) } @Test fun `will copy evidence details`() { val nomisAdjudication = nomisAdjudicationCharge( investigations = listOf( Investigation( investigator = Staff( username = "J.SMITH", staffId = 1, firstName = "John", lastName = "Smith", createdByUsername = "B.BATTS", ), dateAssigned = LocalDate.parse("2020-12-25"), comment = "some comment", evidence = listOf( Evidence( type = CodeDescription(code = "BEHAV", description = "Behaviour Report"), date = LocalDate.parse("2020-12-25"), detail = "report detail", createdByUsername = "A.BEANS", ), ), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.evidence).hasSize(1) assertThat(dpsAdjudication.evidence[0].details).isEqualTo("report detail") assertThat(dpsAdjudication.evidence[0].reporter).isEqualTo("A.BEANS") assertThat(dpsAdjudication.evidence[0].dateAdded).isEqualTo("2020-12-25") } @Test fun `will map evidence type`() { val nomisAdjudication = nomisAdjudicationCharge( investigations = listOf( Investigation( investigator = Staff( username = "J.SMITH", staffId = 1, firstName = "John", lastName = "Smith", createdByUsername = "B.BATTS", ), dateAssigned = LocalDate.parse("2020-12-25"), comment = "some comment", evidence = listOf( Evidence( type = CodeDescription(code = "BEHAV", description = "Behaviour Report"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "WITNESS", description = "Witness Statement"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "VICTIM", description = "Victim Statement"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "WEAP", description = "Weapon"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "PHOTO", description = "Photographic Evidence"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "DRUGTEST", description = "Drug Test Report"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "EVI_BAG", description = "Evidence Bag"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), Evidence( type = CodeDescription(code = "OTHER", description = "Other"), date = LocalDate.now(), detail = "detail", createdByUsername = "A.BEANS", ), ), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.evidence).hasSize(8) assertThat(dpsAdjudication.evidence[0].evidenceCode).isEqualTo(EvidenceCode.OTHER) assertThat(dpsAdjudication.evidence[1].evidenceCode).isEqualTo(EvidenceCode.OTHER) assertThat(dpsAdjudication.evidence[2].evidenceCode).isEqualTo(EvidenceCode.OTHER) assertThat(dpsAdjudication.evidence[3].evidenceCode).isEqualTo(EvidenceCode.OTHER) assertThat(dpsAdjudication.evidence[4].evidenceCode).isEqualTo(EvidenceCode.PHOTO) assertThat(dpsAdjudication.evidence[5].evidenceCode).isEqualTo(EvidenceCode.OTHER) assertThat(dpsAdjudication.evidence[6].evidenceCode).isEqualTo(EvidenceCode.BAGGED_AND_TAGGED) assertThat(dpsAdjudication.evidence[7].evidenceCode).isEqualTo(EvidenceCode.OTHER) } @Test fun `will copy charge evidence details from charge details`() { val nomisAdjudication = nomisAdjudicationCharge( investigations = emptyList(), chargeEvidence = "Broken cup", chargeReportDetail = "Smashed to pieces", reportedDate = LocalDate.parse("2020-12-26"), reportingStaffUsername = "A.CHARGEBEANS", ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.evidence).hasSize(1) assertThat(dpsAdjudication.evidence[0].details).isEqualTo("Broken cup - Smashed to pieces") assertThat(dpsAdjudication.evidence[0].reporter).isEqualTo("A.CHARGEBEANS") assertThat(dpsAdjudication.evidence[0].dateAdded).isEqualTo("2020-12-26") assertThat(dpsAdjudication.evidence[0].evidenceCode).isEqualTo(EvidenceCode.OTHER) } @Test fun `will copy partial charge evidence details from charge details with evidence`() { val nomisAdjudication = nomisAdjudicationCharge( investigations = emptyList(), chargeEvidence = "Broken cup", chargeReportDetail = "", reportedDate = LocalDate.parse("2020-12-26"), reportingStaffUsername = "A.CHARGEBEANS", ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.evidence).hasSize(1) assertThat(dpsAdjudication.evidence[0].details).isEqualTo("Broken cup") assertThat(dpsAdjudication.evidence[0].reporter).isEqualTo("A.CHARGEBEANS") assertThat(dpsAdjudication.evidence[0].dateAdded).isEqualTo("2020-12-26") assertThat(dpsAdjudication.evidence[0].evidenceCode).isEqualTo(EvidenceCode.OTHER) } @Test fun `will copy partial charge evidence details from charge details with report deatils`() { val nomisAdjudication = nomisAdjudicationCharge( investigations = emptyList(), chargeEvidence = "", chargeReportDetail = "Smashed to pieces", reportedDate = LocalDate.parse("2020-12-26"), reportingStaffUsername = "A.CHARGEBEANS", ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.evidence).hasSize(1) assertThat(dpsAdjudication.evidence[0].details).isEqualTo("Smashed to pieces") assertThat(dpsAdjudication.evidence[0].reporter).isEqualTo("A.CHARGEBEANS") assertThat(dpsAdjudication.evidence[0].dateAdded).isEqualTo("2020-12-26") assertThat(dpsAdjudication.evidence[0].evidenceCode).isEqualTo(EvidenceCode.OTHER) } } @Test fun `will copy offence code`() { val nomisAdjudication = nomisAdjudicationCharge( offenceCode = "51:1J", offenceDescription = "Commits any assault - assault on prison officer", ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.offence.offenceCode).isEqualTo("51:1J") assertThat(dpsAdjudication.offence.offenceDescription).isEqualTo("Commits any assault - assault on prison officer") } @Nested @DisplayName("Witnesses and other parties") inner class Witnesses { @Test fun `staff witnesses are copied`() { val nomisAdjudication = nomisAdjudicationCharge( createdByStaffUsername = "A.BEANS", staffWitness = listOf( Staff( username = "J.SMITH", staffId = 1, firstName = "JOHN", lastName = "SMITH", createdByUsername = "B.BATTS", ), Staff( username = "K.KOFI", staffId = 2, firstName = "KWEKU", lastName = "KOFI", createdByUsername = "J.TOMS", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.witnesses).hasSize(2) assertThat(dpsAdjudication.witnesses[0].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[0].firstName).isEqualTo("JOHN") assertThat(dpsAdjudication.witnesses[0].lastName).isEqualTo("SMITH") assertThat(dpsAdjudication.witnesses[0].witnessType).isEqualTo(MigrateWitness.WitnessType.STAFF) assertThat(dpsAdjudication.witnesses[1].createdBy).isEqualTo("J.TOMS") assertThat(dpsAdjudication.witnesses[1].firstName).isEqualTo("KWEKU") assertThat(dpsAdjudication.witnesses[1].lastName).isEqualTo("KOFI") assertThat(dpsAdjudication.witnesses[1].witnessType).isEqualTo(MigrateWitness.WitnessType.STAFF) } @Test fun `prisoner witnesses are copied`() { val nomisAdjudication = nomisAdjudicationCharge( createdByStaffUsername = "A.BEANS", prisonerWitnesses = listOf( Prisoner( offenderNo = "A1234KK", firstName = "BOBBY", lastName = "BALLER", createdByUsername = "B.BATTS", dateAddedToIncident = LocalDate.parse("2020-12-25"), ), Prisoner( offenderNo = "A1234TT", firstName = "JANE", lastName = "MIKES", createdByUsername = "A.AMRK", dateAddedToIncident = LocalDate.parse("2020-12-26"), comment = "Saw everything", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.witnesses).hasSize(2) assertThat(dpsAdjudication.witnesses[0].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[0].firstName).isEqualTo("BOBBY") assertThat(dpsAdjudication.witnesses[0].lastName).isEqualTo("BALLER") assertThat(dpsAdjudication.witnesses[0].witnessType).isEqualTo(MigrateWitness.WitnessType.OTHER_PERSON) assertThat(dpsAdjudication.witnesses[0].dateAdded).isEqualTo("2020-12-25") assertThat(dpsAdjudication.witnesses[1].createdBy).isEqualTo("A.AMRK") assertThat(dpsAdjudication.witnesses[1].firstName).isEqualTo("JANE") assertThat(dpsAdjudication.witnesses[1].lastName).isEqualTo("MIKES") assertThat(dpsAdjudication.witnesses[1].witnessType).isEqualTo(MigrateWitness.WitnessType.OTHER_PERSON) assertThat(dpsAdjudication.witnesses[1].dateAdded).isEqualTo("2020-12-26") assertThat(dpsAdjudication.witnesses[1].comment).isEqualTo("Saw everything") } @Test fun `staff victims are copied`() { val nomisAdjudication = nomisAdjudicationCharge( staffVictims = listOf( Staff( username = "J.SMITH", staffId = 1, firstName = "JOHN", lastName = "SMITH", createdByUsername = "B.BATTS", ), Staff( username = "K.KOFI", staffId = 2, firstName = "KWEKU", lastName = "KOFI", createdByUsername = "B.BATTS", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.witnesses).hasSize(2) assertThat(dpsAdjudication.witnesses[0].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[0].firstName).isEqualTo("JOHN") assertThat(dpsAdjudication.witnesses[0].lastName).isEqualTo("SMITH") assertThat(dpsAdjudication.witnesses[0].witnessType).isEqualTo(MigrateWitness.WitnessType.VICTIM) assertThat(dpsAdjudication.witnesses[1].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[1].firstName).isEqualTo("KWEKU") assertThat(dpsAdjudication.witnesses[1].lastName).isEqualTo("KOFI") assertThat(dpsAdjudication.witnesses[1].witnessType).isEqualTo(MigrateWitness.WitnessType.VICTIM) } @Test fun `prisoner victims are copied`() { val nomisAdjudication = nomisAdjudicationCharge( prisonerVictims = listOf( Prisoner( offenderNo = "A1234KK", firstName = "BOBBY", lastName = "BALLER", createdByUsername = "B.BATTS", dateAddedToIncident = LocalDate.parse("2020-12-25"), ), Prisoner( offenderNo = "A1234TT", firstName = "JANE", lastName = "MIKES", createdByUsername = "B.BATTS", dateAddedToIncident = LocalDate.parse("2020-12-26"), comment = "Beaten up", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.witnesses).hasSize(2) assertThat(dpsAdjudication.witnesses[0].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[0].firstName).isEqualTo("BOBBY") assertThat(dpsAdjudication.witnesses[0].lastName).isEqualTo("BALLER") assertThat(dpsAdjudication.witnesses[0].witnessType).isEqualTo(MigrateWitness.WitnessType.VICTIM) assertThat(dpsAdjudication.witnesses[0].dateAdded).isEqualTo("2020-12-25") assertThat(dpsAdjudication.witnesses[1].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[1].firstName).isEqualTo("JANE") assertThat(dpsAdjudication.witnesses[1].lastName).isEqualTo("MIKES") assertThat(dpsAdjudication.witnesses[1].witnessType).isEqualTo(MigrateWitness.WitnessType.VICTIM) assertThat(dpsAdjudication.witnesses[1].dateAdded).isEqualTo("2020-12-26") assertThat(dpsAdjudication.witnesses[1].comment).isEqualTo("Beaten up") } @Test fun `other prisoner suspects are copied`() { val nomisAdjudication = nomisAdjudicationCharge( otherPrisonerInvolved = listOf( Prisoner( offenderNo = "A1234KK", firstName = "BOBBY", lastName = "BALLER", createdByUsername = "B.BATTS", dateAddedToIncident = LocalDate.parse("2020-12-25"), ), Prisoner( offenderNo = "A1234TT", firstName = "JANE", lastName = "MIKES", createdByUsername = "B.BATTS", dateAddedToIncident = LocalDate.parse("2020-12-26"), comment = "She joined in", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.witnesses).hasSize(2) assertThat(dpsAdjudication.witnesses[0].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[0].firstName).isEqualTo("BOBBY") assertThat(dpsAdjudication.witnesses[0].lastName).isEqualTo("BALLER") assertThat(dpsAdjudication.witnesses[0].witnessType).isEqualTo(MigrateWitness.WitnessType.PRISONER) assertThat(dpsAdjudication.witnesses[0].dateAdded).isEqualTo("2020-12-25") assertThat(dpsAdjudication.witnesses[1].createdBy).isEqualTo("B.BATTS") assertThat(dpsAdjudication.witnesses[1].firstName).isEqualTo("JANE") assertThat(dpsAdjudication.witnesses[1].lastName).isEqualTo("MIKES") assertThat(dpsAdjudication.witnesses[1].witnessType).isEqualTo(MigrateWitness.WitnessType.PRISONER) assertThat(dpsAdjudication.witnesses[1].dateAdded).isEqualTo("2020-12-26") assertThat(dpsAdjudication.witnesses[1].comment).isEqualTo("She joined in") } @Test fun `all other staff types copied`() { val nomisAdjudication = nomisAdjudicationCharge( reportingOfficers = listOf( Staff( username = "J.SMITH", staffId = 1, firstName = "JOHN", lastName = "SMITH", createdByUsername = "A.BEANS", ), Staff( username = "K.KOFI", staffId = 2, firstName = "KWEKU", lastName = "KOFI", createdByUsername = "A.BEANS", ), ), otherStaffInvolved = listOf( Staff( username = "J.BEEKS", staffId = 3, firstName = "JANE", lastName = "SEEKS", createdByUsername = "A.BEANS", ), Staff( username = "S.BIGHTS", staffId = 4, firstName = "SARAH", lastName = "BIGHTS", createdByUsername = "A.BEANS", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.witnesses).hasSize(4) assertThat(dpsAdjudication.witnesses[0].createdBy).isEqualTo("A.BEANS") assertThat(dpsAdjudication.witnesses[0].firstName).isEqualTo("JOHN") assertThat(dpsAdjudication.witnesses[0].lastName).isEqualTo("SMITH") assertThat(dpsAdjudication.witnesses[0].witnessType).isEqualTo(MigrateWitness.WitnessType.OTHER_PERSON) assertThat(dpsAdjudication.witnesses[1].createdBy).isEqualTo("A.BEANS") assertThat(dpsAdjudication.witnesses[1].firstName).isEqualTo("KWEKU") assertThat(dpsAdjudication.witnesses[1].lastName).isEqualTo("KOFI") assertThat(dpsAdjudication.witnesses[1].witnessType).isEqualTo(MigrateWitness.WitnessType.OTHER_PERSON) assertThat(dpsAdjudication.witnesses[2].createdBy).isEqualTo("A.BEANS") assertThat(dpsAdjudication.witnesses[2].firstName).isEqualTo("JANE") assertThat(dpsAdjudication.witnesses[2].lastName).isEqualTo("SEEKS") assertThat(dpsAdjudication.witnesses[2].witnessType).isEqualTo(MigrateWitness.WitnessType.OTHER_PERSON) assertThat(dpsAdjudication.witnesses[3].createdBy).isEqualTo("A.BEANS") assertThat(dpsAdjudication.witnesses[3].firstName).isEqualTo("SARAH") assertThat(dpsAdjudication.witnesses[3].lastName).isEqualTo("BIGHTS") assertThat(dpsAdjudication.witnesses[3].witnessType).isEqualTo(MigrateWitness.WitnessType.OTHER_PERSON) } } @Nested inner class Hearings { @Test fun `will copy core hearing details`() { val nomisAdjudication = nomisAdjudicationCharge( hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = emptyList(), scheduleDate = LocalDate.parse("2020-12-31"), scheduleTime = "11:00:00", comment = "Some comment", hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), representativeText = "JULIE BART", ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.hearings).containsExactly( MigrateHearing( oicHearingId = 54321, oicHearingType = GOV_ADULT, hearingDateTime = "2021-01-01T12:00:00", adjudicator = "A.JUDGE", commentText = "Some comment", locationId = 321, hearingResult = null, representative = "JULIE BART", ), ) } @Test fun `will copy scheduled hearing details`() { val nomisAdjudication = nomisAdjudicationCharge( hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", hearingResults = emptyList(), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.hearings).containsExactly( MigrateHearing( oicHearingId = 54321, oicHearingType = GOV, // TODO - we always have a NOMIS type so default to this until we have a decision hearingDateTime = "2021-01-01T12:00:00", adjudicator = null, commentText = null, locationId = 321, hearingResult = null, ), ) } @Nested inner class HearingResults { @Test fun `will copy results`() { val charge = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( chargeSequence = charge.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = listOf( HearingResult( charge = charge, offence = charge.offence, resultAwards = emptyList(), pleaFindingType = CodeDescription(code = "GUILTY", description = "Guilty"), findingType = CodeDescription(code = "S", description = "Suspended"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", ), ), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-30T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.hearings).hasSize(1) assertThat(dpsAdjudication.hearings[0].hearingResult).isNotNull assertThat(dpsAdjudication.hearings[0].hearingResult?.finding).isEqualTo("S") assertThat(dpsAdjudication.hearings[0].hearingResult?.plea).isEqualTo("GUILTY") assertThat(dpsAdjudication.hearings[0].hearingResult?.createdBy).isEqualTo("A.BEANS") assertThat(dpsAdjudication.hearings[0].hearingResult?.createdDateTime).isEqualTo("2020-12-31T10:00:00") } @Test fun `result can be null when not present`() { val charge = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( chargeSequence = charge.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = listOf(), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.hearings).hasSize(1) assertThat(dpsAdjudication.hearings[0].hearingResult).isNull() } } @Nested inner class HearingNotifications { @Test fun `will copy notifications`() { val charge = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( chargeSequence = charge.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-30T10:00:00", hearingResults = emptyList(), notifications = listOf( HearingNotification( deliveryDate = LocalDate.parse("2020-12-31"), deliveryTime = "11:00:00", comment = "You have been notified", notifiedStaff = Staff( username = "A.NOTIFY", staffId = 456, firstName = "A", lastName = "NOTIFY", createdByUsername = "A.BEANS", ), ), HearingNotification( deliveryDate = LocalDate.parse("2021-01-01"), deliveryTime = "10:30:00", notifiedStaff = Staff( username = "B.NOTIFY", staffId = 457, firstName = "B", lastName = "NOTIFY", createdByUsername = "A.BEANS", ), ), ), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.disIssued).hasSize(2) assertThat(dpsAdjudication.disIssued[0].issuingOfficer).isEqualTo("A.NOTIFY") assertThat(dpsAdjudication.disIssued[0].dateTimeOfIssue).isEqualTo("2020-12-31T11:00:00") assertThat(dpsAdjudication.disIssued[1].issuingOfficer).isEqualTo("B.NOTIFY") assertThat(dpsAdjudication.disIssued[1].dateTimeOfIssue).isEqualTo("2021-01-01T10:30:00") } @Test fun `result can be null when not present`() { val charge = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( chargeSequence = charge.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = listOf(), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.hearings).hasSize(1) assertThat(dpsAdjudication.hearings[0].hearingResult).isNull() } } @Nested inner class Punishments { @Test fun `will copy award for the charge punishment`() { val charge = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( chargeSequence = charge.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = listOf( HearingResult( charge = charge, offence = charge.offence, resultAwards = listOf( HearingResultAward( effectiveDate = LocalDate.parse("2021-01-01"), sanctionType = CodeDescription(code = "CC", description = "Cellular Confinement"), sanctionStatus = CodeDescription(code = "IMMEDIATE", description = "Immediate"), comment = "Remain in cell", statusDate = LocalDate.parse("2021-01-02"), sanctionDays = 2, sanctionMonths = null, compensationAmount = BigDecimal.valueOf(23.67), consecutiveAward = null, sequence = 23, chargeSequence = charge.chargeSequence, adjudicationNumber = 7654321, ), ), pleaFindingType = CodeDescription(code = "GUILTY", description = "Guilty"), findingType = CodeDescription(code = "S", description = "Suspended"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", ), ), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.punishments).hasSize(1) assertThat(dpsAdjudication.punishments[0].comment).isEqualTo("Remain in cell") assertThat(dpsAdjudication.punishments[0].compensationAmount).isEqualTo(BigDecimal.valueOf(23.67)) assertThat(dpsAdjudication.punishments[0].days).isEqualTo(2) assertThat(dpsAdjudication.punishments[0].effectiveDate).isEqualTo("2021-01-01") assertThat(dpsAdjudication.punishments[0].consecutiveChargeNumber).isNull() assertThat(dpsAdjudication.punishments[0].sanctionCode).isEqualTo("CC") assertThat(dpsAdjudication.punishments[0].sanctionSeq).isEqualTo(23) assertThat(dpsAdjudication.punishments[0].sanctionStatus).isEqualTo("IMMEDIATE") } @Test fun `will calculate the consecutiveChargeNumber when consecutive punishment is present`() { val charge1 = nomisAdjudicationCharge().charge.copy(chargeSequence = 1) val charge2 = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( adjudicationNumber = 12345, chargeSequence = charge2.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = listOf( HearingResult( charge = charge2, offence = charge2.offence, resultAwards = listOf( HearingResultAward( effectiveDate = LocalDate.parse("2021-01-01"), sanctionType = CodeDescription(code = "CC", description = "Cellular Confinement"), sanctionStatus = CodeDescription(code = "IMMEDIATE", description = "Immediate"), comment = "Remain in cell", statusDate = LocalDate.parse("2021-01-02"), sanctionDays = 2, sanctionMonths = null, compensationAmount = null, chargeSequence = charge2.chargeSequence, consecutiveAward = HearingResultAward( effectiveDate = LocalDate.parse("2021-01-01"), sanctionType = CodeDescription(code = "CC", description = "Cellular Confinement"), sanctionStatus = CodeDescription(code = "IMMEDIATE", description = "Immediate"), comment = "Remain in cell", statusDate = LocalDate.parse("2021-01-02"), sanctionDays = 2, sanctionMonths = null, compensationAmount = null, consecutiveAward = null, sequence = 24, chargeSequence = charge1.chargeSequence, adjudicationNumber = 7654321, ), sequence = 23, adjudicationNumber = 12345, ), ), pleaFindingType = CodeDescription(code = "GUILTY", description = "Guilty"), findingType = CodeDescription(code = "S", description = "Suspended"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", ), ), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.punishments).hasSize(1) assertThat(dpsAdjudication.punishments[0].comment).isEqualTo("Remain in cell") assertThat(dpsAdjudication.punishments[0].compensationAmount).isNull() assertThat(dpsAdjudication.punishments[0].days).isEqualTo(2) assertThat(dpsAdjudication.punishments[0].effectiveDate).isEqualTo("2021-01-01") assertThat(dpsAdjudication.punishments[0].sanctionCode).isEqualTo("CC") assertThat(dpsAdjudication.punishments[0].sanctionSeq).isEqualTo(23) assertThat(dpsAdjudication.punishments[0].sanctionStatus).isEqualTo("IMMEDIATE") assertThat(dpsAdjudication.punishments[0].consecutiveChargeNumber).isEqualTo("7654321-1") } @ParameterizedTest @MethodSource("uk.gov.justice.digital.hmpps.prisonerfromnomismigration.adjudications.AdjudicationTransformationTest#getAwardDayMonthData") fun `days and months are added together`( days: Int?, months: Int?, effectiveDate: String, calculatedDays: Int?, ) { val charge = nomisAdjudicationCharge().charge.copy(chargeSequence = 2) val nomisAdjudication = nomisAdjudicationCharge( chargeSequence = charge.chargeSequence, hearings = listOf( Hearing( hearingId = 54321, hearingDate = LocalDate.parse("2021-01-01"), hearingTime = "12:00:00", type = CodeDescription(code = "GOV_ADULT", description = "Governor's Hearing Adult"), hearingResults = listOf( HearingResult( charge = charge, offence = charge.offence, resultAwards = listOf( HearingResultAward( effectiveDate = LocalDate.parse(effectiveDate), sanctionType = CodeDescription(code = "CC", description = "Cellular Confinement"), sanctionStatus = CodeDescription(code = "IMMEDIATE", description = "Immediate"), comment = "Remain in cell", statusDate = LocalDate.parse("2021-01-02"), sanctionDays = days, sanctionMonths = months, compensationAmount = null, consecutiveAward = null, sequence = 23, chargeSequence = charge.chargeSequence, adjudicationNumber = 12345, ), ), pleaFindingType = CodeDescription(code = "GUILTY", description = "Guilty"), findingType = CodeDescription(code = "S", description = "Suspended"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", ), ), hearingStaff = Staff( username = "A.JUDGE", staffId = 123, firstName = "A", lastName = "JUDGE", createdByUsername = "A.BEANS", ), internalLocation = InternalLocation(321, "A-1-1", "MDI-A-1-1"), eventStatus = CodeDescription(code = "SCH", description = "Scheduled"), createdByUsername = "A.BEANS", createdDateTime = "2020-12-31T10:00:00", notifications = emptyList(), ), ), ) val dpsAdjudication = nomisAdjudication.toAdjudication() assertThat(dpsAdjudication.punishments).hasSize(1) assertThat(dpsAdjudication.punishments[0].days).isEqualTo(calculatedDays) } } } companion object { @JvmStatic fun getAwardDayMonthData(): Stream<Arguments> { // days, months, effect date and expected days return Stream.of( Arguments.of(null, null, "2020-01-01", null), Arguments.of(1, null, "2020-01-01", 1), Arguments.of(null, 1, "2020-01-01", 31), Arguments.of(null, 1, "2020-02-01", 29), // leap year Arguments.of(null, 1, "2021-02-01", 28), Arguments.of(10, 1, "2020-02-01", 39), Arguments.of(null, 6, "2020-01-01", 182), Arguments.of(null, 24, "2020-01-01", 731), Arguments.of(null, 24, "2021-01-01", 730), ) } } } private fun nomisAdjudicationCharge( adjudicationNumber: Long = 1234567, chargeSequence: Int = 1, offenderNo: String = "A1234AA", bookingId: Long = 543321, adjudicationIncidentId: Long = 8765432, incidentDate: LocalDate = LocalDate.now(), incidentTime: LocalTime = LocalTime.now(), reportedDate: LocalDate = LocalDate.now(), reportedTime: LocalTime = LocalTime.now(), internalLocationId: Long = 1234567, prisonId: String = "MDI", prisonerWitnesses: List<Prisoner> = emptyList(), prisonerVictims: List<Prisoner> = emptyList(), otherPrisonerInvolved: List<Prisoner> = emptyList(), reportingOfficers: List<Staff> = emptyList(), staffWitness: List<Staff> = emptyList(), staffVictims: List<Staff> = emptyList(), otherStaffInvolved: List<Staff> = emptyList(), repairs: List<Repair> = emptyList(), investigations: List<Investigation> = emptyList(), statementDetails: String = "Fight", offenceCode: String = "51:12A", offenceDescription: String = "Commits any assault - assault on prison officer", offenceType: String = "51", genderCode: String = "F", currentPrison: CodeDescription? = CodeDescription(prisonId, "HMP Prison"), reportingStaffUsername: String = "F.LAST", createdByStaffUsername: String = "A.BEANS", hearings: List<Hearing> = emptyList(), chargeEvidence: String? = null, chargeReportDetail: String? = null, ): AdjudicationChargeResponse { return AdjudicationChargeResponse( adjudicationSequence = chargeSequence, offenderNo = offenderNo, bookingId = bookingId, partyAddedDate = LocalDate.now(), gender = CodeDescription(genderCode, "Female"), currentPrison = currentPrison, incident = AdjudicationIncident( adjudicationIncidentId = adjudicationIncidentId, reportingStaff = Staff( username = reportingStaffUsername, staffId = 1, firstName = "stafffirstname", lastName = "stafflastname", createdByUsername = "A.BEANS", ), incidentDate = incidentDate, incidentTime = incidentTime.toString(), reportedDate = reportedDate, reportedTime = reportedTime.toString(), createdByUsername = createdByStaffUsername, createdDateTime = "2023-04-12T10:00:00", internalLocation = InternalLocation(internalLocationId, "GYM", "GYM"), prison = CodeDescription(prisonId, "HMP Prison"), prisonerWitnesses = prisonerWitnesses, prisonerVictims = prisonerVictims, incidentType = CodeDescription("GOV", "Governor's Report"), otherPrisonersInvolved = otherPrisonerInvolved, reportingOfficers = reportingOfficers, staffWitnesses = staffWitness, staffVictims = staffVictims, otherStaffInvolved = otherStaffInvolved, repairs = repairs, details = statementDetails, ), charge = AdjudicationCharge( chargeSequence = chargeSequence, evidence = chargeEvidence, reportDetail = chargeReportDetail, offenceId = "$adjudicationNumber/$chargeSequence", offence = AdjudicationOffence( code = offenceCode, description = offenceDescription, type = CodeDescription(offenceType, "Prison Rule $offenceType"), ), ), investigations = investigations, hearings = hearings, adjudicationNumber = adjudicationNumber, comment = "comment", ) }
1
Kotlin
0
2
c71ab77d1a2131357b360aa9165ea8ce50823ce4
54,372
hmpps-prisoner-from-nomis-migration
MIT License
utbot-framework-test/src/test/kotlin/org/utbot/examples/annotations/lombok/EnumWithAnnotationsTest.kt
UnitTestBot
480,810,501
false
null
package org.utbot.examples.annotations.lombok import org.junit.jupiter.api.Test import org.utbot.testcheckers.eq import org.utbot.testing.DoNotCalculate import org.utbot.testing.UtValueTestCaseChecker /** * Tests for Lombok annotations * * We do not calculate coverage here as Lombok always make it pure * (see, i.e. https://stackoverflow.com/questions/44584487/improve-lombok-data-code-coverage) * and Lombok code is considered to be already tested itself. */ internal class EnumWithAnnotationsTest : UtValueTestCaseChecker(testClass = EnumWithAnnotations::class) { @Test fun testGetterWithAnnotations() { check( EnumWithAnnotations::getConstant, eq(1), { r -> r == "Constant_1" }, coverage = DoNotCalculate, ) } }
396
Kotlin
31
91
ca7df7c1665cdab2a5d8bc2619611e02e761a228
799
UTBotJava
Apache License 2.0
swan-third-libs/shark-libs/shark-graph/src/main/java/shark/internal/ByteSubArray.kt
YoungTr
469,053,611
false
null
package kshark.internal /** * Provides read access to a sub part of a larger array. */ internal class ByteSubArray( private val array: ByteArray, private val rangeStart: Int, size: Int, private val longIdentifiers: Boolean ) { private val endInclusive = size - 1 private var currentIndex = 0 fun readByte(): Byte { val index = currentIndex currentIndex++ require(index in 0..endInclusive) { "Index $index should be between 0 and $endInclusive" } return array[rangeStart + index] } fun readId(): Long { return if (longIdentifiers) { readLong() } else { readInt().toLong() } } fun readInt(): Int { val index = currentIndex currentIndex += 4 require(index >= 0 && index <= endInclusive - 3) { "Index $index should be between 0 and ${endInclusive - 3}" } return array.readInt(rangeStart + index) } fun readTruncatedLong(byteCount: Int): Long { val index = currentIndex currentIndex += byteCount require(index >= 0 && index <= endInclusive - (byteCount - 1)) { "Index $index should be between 0 and ${endInclusive - (byteCount - 1)}" } var pos = rangeStart + index val array = array var value = 0L var shift = (byteCount - 1) * 8 while (shift >= 8) { value = value or (array[pos++] and 0xffL shl shift) shift -= 8 } value = value or (array[pos] and 0xffL) return value } fun readLong(): Long { val index = currentIndex currentIndex += 8 require(index >= 0 && index <= endInclusive - 7) { "Index $index should be between 0 and ${endInclusive - 7}" } return array.readLong(rangeStart + index) } } internal fun ByteArray.readShort(index: Int): Short { var pos = index val array = this val valueAsInt = array[pos++] and 0xff shl 8 or (array[pos] and 0xff) return valueAsInt.toShort() } internal fun ByteArray.readInt(index: Int): Int { var pos = index val array = this return (array[pos++] and 0xff shl 24 or (array[pos++] and 0xff shl 16) or (array[pos++] and 0xff shl 8) or (array[pos] and 0xff)) } internal fun ByteArray.readLong(index: Int): Long { var pos = index val array = this return (array[pos++] and 0xffL shl 56 or (array[pos++] and 0xffL shl 48) or (array[pos++] and 0xffL shl 40) or (array[pos++] and 0xffL shl 32) or (array[pos++] and 0xffL shl 24) or (array[pos++] and 0xffL shl 16) or (array[pos++] and 0xffL shl 8) or (array[pos] and 0xffL)) } @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. private inline infix fun Byte.and(other: Long): Long = toLong() and other @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. private inline infix fun Byte.and(other: Int): Int = toInt() and other
62
null
411
8
65169f46a5af9af3ce097d2cbb67b8f34e9df3f1
2,804
Swan
Apache License 2.0
detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/RuleExtensions.kt
niraj8
272,693,530
false
null
package io.gitlab.arturbosch.detekt.test import io.github.detekt.test.utils.KotlinScriptEngine import io.github.detekt.test.utils.KtTestCompiler import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.internal.BaseRule import org.intellij.lang.annotations.Language import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import java.nio.file.Path private val shouldCompileTestSnippets: Boolean = System.getProperty("compile-snippet-tests", "false")!!.toBoolean() fun BaseRule.compileAndLint(@Language("kotlin") content: String): List<Finding> { if (shouldCompileTestSnippets) { KotlinScriptEngine.compile(content) } return lint(content) } fun BaseRule.lint(@Language("kotlin") content: String): List<Finding> { val ktFile = KtTestCompiler.compileFromContent(content.trimIndent()) return findingsAfterVisit(ktFile) } fun BaseRule.lint(path: Path): List<Finding> { val ktFile = KtTestCompiler.compile(path) return findingsAfterVisit(ktFile) } fun BaseRule.compileAndLintWithContext( environment: KotlinCoreEnvironment, @Language("kotlin") content: String ): List<Finding> { if (shouldCompileTestSnippets) { KotlinScriptEngine.compile(content) } val ktFile = KtTestCompiler.compileFromContent(content.trimIndent()) val bindingContext = KtTestCompiler.getContextForPaths(environment, listOf(ktFile)) return findingsAfterVisit(ktFile, bindingContext) } fun BaseRule.lint(ktFile: KtFile) = findingsAfterVisit(ktFile) private fun BaseRule.findingsAfterVisit( ktFile: KtFile, bindingContext: BindingContext = BindingContext.EMPTY ): List<Finding> { this.visitFile(ktFile, bindingContext) return this.findings } fun Rule.format(@Language("kotlin") content: String): String { val ktFile = KtTestCompiler.compileFromContent(content.trimIndent()) return contentAfterVisit(ktFile) } fun Rule.format(path: Path): String { val ktFile = KtTestCompiler.compile(path) return contentAfterVisit(ktFile) } private fun Rule.contentAfterVisit(ktFile: KtFile): String { this.visit(ktFile) return ktFile.text }
0
null
0
1
8536e848ec2d4470c970442a8ea4579937b4b2d8
2,288
detekt
Apache License 2.0
app/src/main/java/br/com/alura/technews/ui/viewModel/VizualizaNoticiaViewModel.kt
Josue10599
204,558,088
false
null
package br.com.alura.technews.ui.viewModel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import br.com.alura.technews.model.Noticia import br.com.alura.technews.repository.NoticiaRepository import br.com.alura.technews.repository.Resource class VizualizaNoticiaViewModel( private val repository: NoticiaRepository ) : ViewModel() { fun remove(noticia: Noticia): LiveData<Resource<Void?>> = repository.remove(noticia) fun buscaPorId(noticiaId: Long): LiveData<Noticia?> = repository.buscaPorId(noticiaId) }
0
Kotlin
0
0
ae540ea41000ba26179ff0dcda79e8405d8ecaf3
545
TechNews-Kotlin
Apache License 2.0
core/src/main/java/com/github/corentinc/core/home/HomeInteractor.kt
corentin-c
235,539,306
false
null
package com.github.corentinc.core.home import com.github.corentinc.core.EditSearchInteractor import com.github.corentinc.core.SearchAdsPosition import com.github.corentinc.core.SearchAdsPostionDefaultSorter import com.github.corentinc.core.alarmManager.AlarmManagerInteractor import com.github.corentinc.core.repository.GlobalSharedPreferencesRepository import com.github.corentinc.core.repository.SharedPreferencesRepository import com.github.corentinc.core.repository.search.SearchPositionRepository import com.github.corentinc.core.repository.search.SearchRepository import com.github.corentinc.core.repository.searchAdsPosition.SearchAdsPositionRepository import com.github.corentinc.core.search.Search import com.github.corentinc.core.ui.home.HomePresenter import kotlinx.coroutines.* class HomeInteractor( val homePresenter: HomePresenter, private val alarmManagerInteractor: AlarmManagerInteractor, private val searchRepository: SearchRepository, private val searchPositionRepository: SearchPositionRepository, private val searchAdsPositionRepository: SearchAdsPositionRepository, private val sharedPreferencesRepository: SharedPreferencesRepository, private val globalSharedPreferencesRepository: GlobalSharedPreferencesRepository, private val searchAdsPostionDefaultSorter: SearchAdsPostionDefaultSorter ) { fun onStart( isBatteryWhiteListAlreadyGranted: Boolean, wasBatteryWhiteListDialogAlreadyShown: Boolean, shouldDisplaySpecialConstructorDialog: Boolean, id: Int, title: String, url: String ) { homePresenter.presentProgressBar() val shouldDisplayDefaultDialog = !isBatteryWhiteListAlreadyGranted if (sharedPreferencesRepository.shouldShowBatteryWhiteListDialog && !wasBatteryWhiteListDialogAlreadyShown && (shouldDisplaySpecialConstructorDialog || shouldDisplayDefaultDialog)) { homePresenter.presentBatteryWarningFragment(shouldDisplayDefaultDialog) } else { CoroutineScope(Dispatchers.IO).launch { var searchAdsPosition = searchAdsPositionRepository.getAllSortedSearchAdsPosition() searchAdsPosition = searchAdsPosition.sortedWith(searchAdsPostionDefaultSorter) withContext(Dispatchers.Main) { if (searchAdsPosition.isEmpty()) { homePresenter.presentEmptySearches() } else { homePresenter.presentSearches(searchAdsPosition.map { it.search } .toMutableList()) } } } alarmManagerInteractor.updateAlarm(globalSharedPreferencesRepository.alarmIntervalPreference) if (id != EditSearchInteractor.DEFAULT_ID) { homePresenter.presentUndoDeleteSearch(Search(id, title, url)) } } } fun onCreateAdButtonPressed() { homePresenter.presentEditSearchScreen() } fun onSearchDeleted(search: Search) { lateinit var searchAdsPositionList: List<SearchAdsPosition> runBlocking { CoroutineScope(Dispatchers.IO).launch { searchAdsPositionRepository.delete(search.id) searchAdsPositionList = searchAdsPositionRepository.getAllSortedSearchAdsPosition() searchAdsPositionList = searchAdsPositionList.sortedWith(searchAdsPostionDefaultSorter) }.join() if (searchAdsPositionList.isEmpty()) { homePresenter.presentEmptySearches() } } homePresenter.presentUndoDeleteSearch(search) } fun beforeFragmentPause(searchList: MutableList<Search>) { runBlocking { CoroutineScope(Dispatchers.IO).launch { searchList.forEachIndexed { index, search -> searchPositionRepository.updateSearchPosition(search.id, index) } }.join() } } fun onSearchClicked(search: Search) { homePresenter.presentAdListFragment(search) } fun onRestoreSearch(search: Search) { lateinit var searchAdsPosition: List<SearchAdsPosition> runBlocking { CoroutineScope(Dispatchers.IO).launch { searchRepository.addSearch(search) searchAdsPosition = searchAdsPositionRepository.getAllSortedSearchAdsPosition() searchAdsPosition = searchAdsPosition.sortedWith(searchAdsPostionDefaultSorter) }.join() } homePresenter.presentSearches(searchAdsPosition.map { it.search }.toMutableList()) } }
0
Kotlin
0
1
47ec5cbe754c9cae371546e08d74b43b20644cb0
4,676
notificoin
Apache License 2.0
src/main/kotlin/se/kth/spork/spoon/matching/ClassRepresentatives.kt
ASSERT-KTH
237,440,106
false
null
package se.kth.spork.spoon.matching import se.kth.spork.base3dm.Revision import se.kth.spork.spoon.wrappers.NodeFactory import se.kth.spork.spoon.wrappers.SpoonNode import spoon.reflect.declaration.CtElement import spoon.reflect.visitor.CtScanner import java.util.HashMap /** * Create the class representatives mapping. The class representatives for the different revisions are defined as: * * 1. A node NB in base is its own class representative. * 2. The class representative of a node NL in left is NB if there exists a tree matching NL -> NB in the baseLeft * matching. Otherwise it is NL. * 3. The class representative of a node NR in right is NB if there exists a tree matching NR -> NB in the baseRight * matching. If that is not the case, the class representative may be NL if there exists a tree matching * NL -> NR. The latter is referred to as an augmentation, and is done conservatively to avoid spurious * mappings between left and right revisions. See [ClassRepresentativeAugmenter] for more info. * * Put briefly, base nodes are always mapped to themselves, nodes in left are mapped to base nodes if they are * matched, and nodes in right are mapped to base nodes or left nodes if they are matched, with base matchings * having priority. * * @param base The base revision. * @param left The left revision. * @param right The right revision. * @param baseLeft A matching from base to left. * @param baseRight A matching from base to right. * @param leftRight A matching from left to right. * @return The class representatives map. */ fun createClassRepresentativesMapping( base: CtElement, left: CtElement, right: CtElement, baseLeft: SpoonMapping, baseRight: SpoonMapping, leftRight: SpoonMapping, ): Map<SpoonNode, SpoonNode> { val classRepMap = initializeClassRepresentatives(base) mapToClassRepresentatives(left, baseLeft, classRepMap, Revision.LEFT) mapToClassRepresentatives(right, baseRight, classRepMap, Revision.RIGHT) ClassRepresentativeAugmenter(classRepMap, leftRight).scan(left) return classRepMap } /** * Initialize the class representatives map by mapping each element in base to itself. * * @param base The base revision of the trees to be merged. * @return An initialized class representatives map. */ private fun initializeClassRepresentatives(base: CtElement): MutableMap<SpoonNode, SpoonNode> { val classRepMap: MutableMap<SpoonNode, SpoonNode> = HashMap() base.descendantIterator().forEach { NodeFactory.setRevisionIfUnset(it, Revision.BASE) val wrapped = NodeFactory.wrap(it) mapNodes(wrapped, wrapped, classRepMap) } // and finally the virtual root mapNodes(NodeFactory.virtualRoot, NodeFactory.virtualRoot, classRepMap) return classRepMap } /** * Map the nodes of a tree revision (left or right) to their corresponding class representatives. For example, if a * node NL in the left revision is matched to a node NB in the base revision, then the mapping NL -> NB is entered * into the class representatives map. * * This method also attaches the tree's revision to each node in the tree. * * TODO move attaching of the tree revision somewhere else, it's super obtuse to have here. * * @param tree A revision of the trees to be merged (left or right). * @param mappings A tree matching from the base revision to the provided tree. * @param classRepMap The class representatives map. * @param rev The provided tree's revision. */ private fun mapToClassRepresentatives(tree: CtElement, mappings: SpoonMapping, classRepMap: MutableMap<SpoonNode, SpoonNode>, rev: Revision) { val descIt = tree.descendantIterator() while (descIt.hasNext()) { val t = descIt.next() mapToClassRep(mappings, classRepMap, rev, t) } } private fun mapToClassRep(mappings: SpoonMapping, classRepMap: MutableMap<SpoonNode, SpoonNode>, rev: Revision, t: CtElement) { NodeFactory.setRevisionIfUnset(t, rev) val wrapped = NodeFactory.wrap(t) val classRep = mappings.getSrc(wrapped) if (classRep != null) { mapNodes(wrapped, classRep, classRepMap) } else { mapNodes(wrapped, wrapped, classRepMap) } } /** * Map from to to, including the associated virtual nodes. * * @param from A SpoonNode. * @param to A SpoonNode * @param classRepMap The class representatives map. */ private fun mapNodes(from: SpoonNode, to: SpoonNode, classRepMap: MutableMap<SpoonNode, SpoonNode>) { // map the real nodes classRepMap[from] = to // map the virtual nodes val fromVirtualNodes = from.virtualNodes val toVirtualNodes = to.virtualNodes for (i in fromVirtualNodes.indices) { val fromVirt = fromVirtualNodes[i] val toVirt = toVirtualNodes[i] if (fromVirt.isListEdge) { classRepMap[fromVirt] = toVirt } else { mapNodes(fromVirt, toVirt, classRepMap) } } } /** * A scanner that conservatively expands the class representatives mapping with matches from a left-to-right * tree matching. If a node in the left tree is not mapped to base (i.e. self-mapped in the class * representatives map), but it is matched with some node in right, then the node in right is mapped * to the node in left iff their parents are already mapped, and the node in right is also self-mapped. * The node in left remains self-mapped. * * This must be done by traversing the left tree top-down to allow augmenting mappings to propagate. For * example, if both the left and the right revision have added identical methods, then their declarations * will be mapped first, and then their contents will be mapped recursively (which is OK as the * declarations are now mapped). If one would have started with matches in the bodies of the methods, * then these would not be added to the class representatives map as the declarations (i.e. parents) * would not yet be mapped. * * The reason for this conservative use of the left-to-right matchings is that there is otherwise a high * probability of unwanted matches. For example, if the left revision adds a parameter to some method, * and the right revision adds an identical parameter to another method, then these may be matched, * even though they are not related. If that match is put into the class representatives map, there * may be some really strange effects on the merge process. * * @author <NAME> */ private class ClassRepresentativeAugmenter /** * @param classRepMap The class representatives map, initialized with left-to-base and right-to-base mappings. * @param leftRightMatch A tree matching between the left and right revisions, where the left revision is the * source and the right revision the destination. */(private val classRepMap: MutableMap<SpoonNode, SpoonNode>, private val leftRightMatch: SpoonMapping) : CtScanner() { private val forcedMappings: Map<String, SpoonNode>? = null /** * * @param element An element from the left revision. */ override fun scan(element: CtElement?) { if (element == null) return val left = NodeFactory.wrap(element) if (classRepMap[left] === left) { val right = leftRightMatch.getDst(left) if (right != null && classRepMap[right] === right) { val rightParentClassRep = classRepMap[right.parent] val leftParentClassRep = classRepMap[left.parent] if (leftParentClassRep === rightParentClassRep) { // map right to left mapNodes(right, left, classRepMap) } } } super.scan(element) } }
30
null
8
51
990397e537300ec3dd2687bc43e3766dd5baed73
7,719
spork
MIT License
plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/replaceSizeZeroCheckWithIsEmpty/string.kt
ingokegel
72,937,917
false
null
// WITH_STDLIB fun foo() { "123".length<caret> == 0 }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
58
intellij-community
Apache License 2.0
app/src/main/java/com/example/android/politicalpreparedness/network/CivicsHttpClient.kt
nawal-alghamdi
737,314,786
false
{"Kotlin": 40127}
package com.example.android.politicalpreparedness.network import com.example.android.politicalpreparedness.BuildConfig import okhttp3.OkHttpClient import com.facebook.stetho.okhttp3.StethoInterceptor import okhttp3.logging.HttpLoggingInterceptor class CivicsHttpClient: OkHttpClient() { companion object { //TODO: Place your API Key Here const val API_KEY = BuildConfig.API_KEY fun getClient(): OkHttpClient { return Builder() .addInterceptor { chain -> val original = chain.request() val url = original .url .newBuilder() .addQueryParameter("key", API_KEY) .build() val request = original .newBuilder() .url(url) .build() chain.proceed(request) } .addNetworkInterceptor(StethoInterceptor()) .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS)) .build() } } }
0
Kotlin
0
0
4cb9dd6afc89e08177a9e855a4c208265fd13ac8
1,262
PoliticalPreparedness
Apache License 2.0
src/main/kotlin/org/oso/core/services/DeviceType.kt
OSOSystem
156,911,157
false
null
package org.oso.core.services import org.oso.core.entities.DeviceType interface DeviceTypeService { fun findAll(): List<DeviceType> }
14
Kotlin
4
12
70473b0dca460ff313f5d839b7d166efdd11d0fb
139
oso-backend
Apache License 2.0
feature-staking-impl/src/main/java/com/dfinn/wallet/feature_staking_impl/presentation/mappers/Identity.kt
finn-exchange
500,972,990
false
null
package com.dfinn.wallet.feature_staking_impl.presentation.mappers import com.dfinn.wallet.feature_staking_api.domain.model.Identity import com.dfinn.wallet.feature_staking_impl.presentation.validators.details.model.IdentityModel import com.dfinn.wallet.feature_staking_impl.presentation.validators.parcel.IdentityParcelModel fun mapIdentityToIdentityParcelModel(identity: Identity): IdentityParcelModel { return with(identity) { IdentityParcelModel(display, legal, web, riot, email, pgpFingerprint, image, twitter) } } fun mapIdentityParcelModelToIdentityModel(identity: IdentityParcelModel): IdentityModel { return with(identity) { IdentityModel(display, legal, web, riot, email, pgpFingerprint, image, twitter) } }
0
Kotlin
0
0
6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d
753
dfinn-android-wallet
Apache License 2.0
src/test/kotlin/org/move/lang/resolve/ResolveStubOnlyTest.kt
pontem-network
279,299,159
false
null
package org.move.lang.resolve import org.move.utils.tests.resolve.ResolveProjectTestCase class ResolveStubOnlyTest : ResolveProjectTestCase() { fun `test stub resolve module import`() = stubOnlyResolve { namedMoveToml("MyPackage") sources { move( "module.move", """ module 0x1::Module {} //X """ ) move( "main.move", """ script { use 0x1::Module; //^ } """ ) } } fun `test stub resolve module ref`() = stubOnlyResolve { namedMoveToml("MyPackage") sources { move( "module.move", """ module 0x1::Module { //X public fun call() {} } """ ) move( "main.move", """ script { use 0x1::Module; fun main() { Module::call(); //^ } } """ ) } } // fun `test stub resolve module function`() = stubOnlyResolve { // namedMoveToml("MyPackage") // sources { // move( // "module.move", """ // module 0x1::Module { // public fun call() {} // //X // } // """ // ) // move( // "main.move", """ // script { // use 0x1::Module; // fun main() { // Module::call(); // //^ // } // } // """ // ) // } // } // fun `test stub resolve fq module function`() = stubOnlyResolve { // namedMoveToml("MyPackage") // sources { // move( // "module.move", """ // module 0x1::Module { // public fun call() {} // //X // } // """ // ) // move( // "main.move", """ // script { // fun main() { // 0x1::Module::call(); // //^ // } // } // """ // ) // } // } // fun `test stub resolve module struct`() = stubOnlyResolve { // namedMoveToml("MyPackage") // sources { // move( // "module.move", """ // module 0x1::Module { // struct S {} // //X // } // """ // ) // move( // "main.move", """ // script { // use 0x1::Module; // fun main(s: Module::S) { // //^ // } // } // """ // ) // } // } }
4
null
29
69
3420e175b388e503dbe796274939df4c84e329a8
3,078
intellij-move
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Snowmobile.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.Snowmobile: ImageVector get() { if (_snowmobile != null) { return _snowmobile!! } _snowmobile = Builder(name = "Snowmobile", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 21.5f) arcTo(2.5f, 2.5f, 0.0f, false, true, 9.5f, 24.0f) horizontalLineToRelative(-7.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, true, -0.572f, -4.928f) lineTo(0.0f, 15.0f) horizontalLineTo(3.192f) lineToRelative(1.661f, 3.38f) lineToRelative(1.952f, -3.167f) lineTo(3.884f, 13.5f) arcTo(3.5f, 3.5f, 0.0f, false, true, 2.37f, 8.83f) lineToRelative(0.1f, -0.174f) lineToRelative(1.24f, -1.822f) arcTo(3.5f, 3.5f, 0.0f, false, true, 8.354f, 5.37f) curveToRelative(0.67f, 0.335f, 4.657f, 2.861f, 5.45f, 3.364f) lineTo(12.2f, 11.267f) curveToRelative(-1.28f, -0.813f, -2.642f, -1.668f, -3.661f, -2.3f) lineTo(6.677f, 11.661f) lineToRelative(2.034f, 1.2f) arcToRelative(2.417f, 2.417f, 0.0f, false, true, 1.173f, 1.435f) arcTo(2.475f, 2.475f, 0.0f, false, true, 9.7f, 16.223f) lineTo(7.993f, 19.0f) horizontalLineTo(9.5f) arcTo(2.5f, 2.5f, 0.0f, false, true, 12.0f, 21.5f) close() moveTo(9.5f, 5.0f) arcTo(2.5f, 2.5f, 0.0f, true, false, 7.0f, 2.5f) arcTo(2.5f, 2.5f, 0.0f, false, false, 9.5f, 5.0f) close() moveTo(20.842f, 17.343f) lineTo(24.0f, 14.111f) verticalLineTo(10.405f) lineTo(14.529f, 2.829f) lineTo(12.655f, 5.172f) lineToRelative(2.482f, 1.985f) horizontalLineToRelative(0.0f) arcTo(3.873f, 3.873f, 0.0f, false, true, 16.5f, 8.936f) curveToRelative(0.0f, 1.369f, -0.832f, 2.064f, -2.473f, 2.064f) verticalLineToRelative(3.0f) curveToRelative(2.682f, 0.0f, 4.619f, -1.379f, 5.241f, -3.538f) lineTo(21.0f, 11.847f) verticalLineToRelative(1.042f) lineToRelative(-2.3f, 2.358f) arcTo(2.511f, 2.511f, 0.0f, false, true, 16.908f, 16.0f) horizontalLineTo(12.143f) lineToRelative(-1.734f, 3.0f) horizontalLineToRelative(4.664f) lineToRelative(1.0f, 2.0f) horizontalLineTo(14.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(5.5f) arcTo(4.5f, 4.5f, 0.0f, false, false, 24.0f, 19.5f) verticalLineTo(19.0f) horizontalLineTo(21.0f) verticalLineToRelative(0.5f) arcTo(1.5f, 1.5f, 0.0f, false, true, 19.5f, 21.0f) horizontalLineToRelative(-0.073f) lineToRelative(-1.105f, -2.211f) arcTo(5.5f, 5.5f, 0.0f, false, false, 20.842f, 17.343f) close() } } .build() return _snowmobile!! } private var _snowmobile: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,224
icons
MIT License
plugins/base/base-test-utils/src/main/kotlin/renderers/TestPage.kt
Kotlin
21,763,603
false
null
/* * Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package renderers import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.base.signatures.KotlinSignatureProvider import org.jetbrains.dokka.base.transformers.pages.comments.CommentsToContentConverter import org.jetbrains.dokka.base.translators.documentables.PageContentBuilder import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.doc.DocTag import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.utilities.DokkaConsoleLogger import org.jetbrains.dokka.utilities.LoggingLevel public fun testPage(callback: PageContentBuilder.DocumentableContentBuilder.() -> Unit): RawTestPage { val content = PageContentBuilder( EmptyCommentConverter, KotlinSignatureProvider(EmptyCommentConverter, DokkaConsoleLogger(LoggingLevel.DEBUG)), DokkaConsoleLogger(LoggingLevel.DEBUG) ).contentFor( DRI.topLevel, emptySet(), block = callback ) return RawTestPage(content) } public class RawTestPage( override val content: ContentNode, override val name: String = "testPage", override val dri: Set<DRI> = setOf(DRI.topLevel), override val embeddedResources: List<String> = emptyList(), override val children: List<PageNode> = emptyList(), ): RootPageNode(), ContentPage { override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ContentPage = this override fun modified(name: String, children: List<PageNode>): RootPageNode = this } internal object EmptyCommentConverter : CommentsToContentConverter { override fun buildContent( docTag: DocTag, dci: DCI, sourceSets: Set<DokkaConfiguration.DokkaSourceSet>, styles: Set<Style>, extras: PropertyContainer<ContentNode> ): List<ContentNode> = emptyList() }
421
Kotlin
388
3,010
97bccc0e12fdc8c3bd6d178e17fdfb57c3514489
2,063
dokka
Apache License 2.0
roboquant-server/src/test/kotlin/org/roboquant/server/WebServerTest.kt
neurallayer
406,929,056
false
null
/* * Copyright 2020-2023 Neural Layer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.roboquant.server import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.assertDoesNotThrow import org.roboquant.Roboquant import org.roboquant.common.Config import org.roboquant.common.Timeframe import org.roboquant.feeds.random.RandomWalkFeed import org.roboquant.loggers.MemoryLogger import org.roboquant.strategies.EMAStrategy import kotlin.test.Test class WebServerTest { @Test fun basic() { Config.getProperty("FULL_COVERAGE") ?: return val feed = RandomWalkFeed(Timeframe.fromYears(2000, 2001)) val rq = Roboquant(EMAStrategy(), logger = MemoryLogger(false)) assertDoesNotThrow { runBlocking { val ws = WebServer(port=8081) ws.runAsync(rq, feed, feed.timeframe) ws.stop() } } } }
18
Kotlin
30
228
e46bebffdd0aa845fa8c4a5051d35b64420e214f
1,442
roboquant
Apache License 2.0
sample/src/main/java/com/drake/net/sample/interceptor/RefreshTokenInterceptor.kt
liangjingkanji
370,593,764
false
null
package com.drake.net.sample.interceptor import com.drake.net.Net import com.drake.net.exception.ResponseException import com.drake.net.sample.constants.UserConfig import okhttp3.Interceptor import okhttp3.Response import org.json.JSONObject /** * 演示如何自动刷新token令牌 */ class RefreshTokenInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val response = chain.proceed(request) // 如果token失效 return synchronized(RefreshTokenInterceptor::class.java) { if (response.code == 401 && UserConfig.isLogin && !request.url.pathSegments.contains("token")) { val json = Net.get("token").execute<String>() // 同步刷新token val jsonObject = JSONObject(json) if (jsonObject.getBoolean("isExpired")) { // token刷新失败跳转到登录界面重新登录, 建议在错误处理器[NetErrorHandler]处理所有错误请求, 此处抛出异常即可 throw ResponseException(response, "登录状态失效") } else { UserConfig.token = jsonObject.optString("token") } chain.proceed(request) } else { response } } } }
1
Kotlin
3
38
ef866475ea0249d7be2672ad5e8864c841bbbd4b
1,221
Net-okhttp3
MIT License
src/main/kotlin/com/mitya1234/uuid/service/UuidService.kt
DmitriiTrifonov
274,063,153
false
null
package com.mitya1234.uuid.service import com.mitya1234.uuid.model.UuidList interface UuidService { fun generate(number: Int): UuidList }
0
Kotlin
0
0
86deb5c20d04a4c708953966405c1d28803d6f69
143
cbrf-uuid-service
Apache License 2.0
feature/main/src/main/java/com/t8rin/imagetoolboxlite/feature/main/presentation/components/ScreenBasedMaxBrightnessEnforcement.kt
T8RIN
767,600,774
false
null
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.feature.root.presentation.components import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.util.fastAny import ru.tech.imageresizershrinker.core.settings.presentation.provider.LocalSettingsState import ru.tech.imageresizershrinker.core.ui.utils.navigation.Screen @Composable internal fun ScreenBasedMaxBrightnessEnforcement( currentScreen: Screen? ) { val context = LocalContext.current as ComponentActivity val listToForceBrightness = LocalSettingsState.current.screenListWithMaxBrightnessEnforcement DisposableEffect(currentScreen) { if (listToForceBrightness.fastAny { it == currentScreen?.id }) { context.window.apply { attributes.apply { screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL } addFlags(WindowManager.LayoutParams.SCREEN_BRIGHTNESS_CHANGED) } } onDispose { context.window.apply { attributes.apply { screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE } addFlags(WindowManager.LayoutParams.SCREEN_BRIGHTNESS_CHANGED) } } } }
5
null
90
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
2,149
ImageToolboxLite
Apache License 2.0
buildSrc/src/main/kotlin/GradlePlugin.kt
vasilevungureanu
205,379,317
false
null
object GradlePlugin { const val android = "com.android.tools.build:gradle:3.4.2" const val versions = "com.github.ben-manes:gradle-versions-plugin:0.23.0" const val kotlin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Kotlin.version}" }
0
Kotlin
0
0
053e5d8d420a55963c5d88250fe8c3cdf8b5eea5
249
android-kata-template
MIT License
patient/src/main/kotlin/com/fiap/hackthon/healthmed/patient/domain/usecase/PatientUpdateUseCase.kt
fabianogoes
858,450,295
false
{"Kotlin": 146787, "HCL": 2976, "HTML": 774, "Dockerfile": 295, "Shell": 194}
package com.fiap.hackthon.healthmed.patient.domain.usecase import com.fiap.hackthon.healthmed.patient.domain.entity.Patient import com.fiap.hackthon.healthmed.patient.domain.exception.PatientNotFoundException import com.fiap.hackthon.healthmed.patient.ports.PatientPersistencePort import com.fiap.hackthon.healthmed.patient.ports.PatientUpdatePort import com.fiap.hackthon.healthmed.shared.Email import com.fiap.hackthon.healthmed.shared.logger import jakarta.inject.Named import java.util.UUID @Named class PatientUpdateUseCase( private val patientPersistencePort: PatientPersistencePort, ) : PatientUpdatePort { private val log = logger<PatientUpdateUseCase>() override fun doUpdate( id: UUID, name: String, email: String, ): Patient { log.info("Updating Patient id: $id, name: $name and email: $email") return patientPersistencePort .readOneById(id) ?.let { patientPersistencePort.update(it.copy(name = name, email = Email(email))) } ?: throw PatientNotFoundException(id.toString()) } }
0
Kotlin
0
0
57f2a072dbc1293d33a621405d5263b1d9f0a5fe
1,090
fiap-hackthon-health-med
MIT License
app/src/main/java/com/example/bookly/api/model/VolumeInfo.kt
glitterylungs
622,685,373
false
null
package com.example.bookly.api.model data class VolumeInfo( val authors: List<String?>? = null, val categories: List<String?>? = null, val description: String? = null, val imageLinks: ImageLinks? = null, val pageCount: Int? = null, val publishedDate: String? = null, val publisher: String? = null, val subtitle: String? = null, val title: String? = null )
0
Kotlin
0
0
e603067ed94e43378b9007a73ced0fe5ff37cc0b
392
Bookly
MIT License
src/main/kotlin/io/github/rybalkinsd/kohttp/dsl/context/BodyContext.kt
mlevesquedion
193,717,567
true
{"Kotlin": 70859}
package io.github.rybalkinsd.kohttp.dsl.context import io.github.rybalkinsd.kohttp.util.Form import io.github.rybalkinsd.kohttp.util.Json import okhttp3.MediaType import okhttp3.RequestBody import okhttp3.RequestBody.create import java.io.File /** * * @since 0.1.0 * @author sergey, alex */ @HttpDslMarker open class BodyContext(type: String?) { private val mediaType = type?.let { MediaType.get(it) } fun string(content: String): RequestBody = create(mediaType, content) fun file(content: File): RequestBody = create(mediaType, content) fun bytes(content: ByteArray): RequestBody = create(mediaType, content) fun json(content: String): RequestBody = create(JSON, content) fun form(content: String): RequestBody = create(FORM, content) fun json(init: Json.() -> Unit): RequestBody = create(JSON, Json().also(init).toString()) fun form(init: Form.() -> Unit): RequestBody = Form().also(init).makeBody() } private val JSON = MediaType.get("application/json") private val FORM = MediaType.get("application/x-www-form-urlencoded")
0
Kotlin
0
0
b7502e1c4b91376284caeeaceaafa69a5d23f038
1,070
kohttp
Apache License 2.0
sampleapp-kotlin/src/main/java/com/grab/partner/sdk/sampleapp/scheduleprovider/SchedulerProvider.kt
grab
157,938,313
false
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Proguard": 4, "XML": 46, "Kotlin": 83, "Java": 3}
/* * Copyright (c) Grab Taxi Holdings PTE LTD (GRAB) * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ package com.grab.partner.sdk.sampleappkotlin.wrapper.scheduleprovider import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers open class SchedulerProvider { open fun io() : Scheduler = Schedulers.io() open fun ui() : Scheduler = AndroidSchedulers.mainThread() } class TestSchedulerProvider : SchedulerProvider() { override fun io() : Scheduler = Schedulers.trampoline() override fun ui() : Scheduler = Schedulers.trampoline() }
1
Kotlin
7
22
cf4d95a8f2a1b553799c950b411d673d139a757e
715
grabplatform-sdk-android
MIT License
common/util/SystemUtil.kt
typedb
159,188,705
false
null
/* * Copyright (C) 2021 Vaticle * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.vaticle.bazel.distribution.common.util import com.vaticle.bazel.distribution.common.OS import com.vaticle.bazel.distribution.common.OS.LINUX import com.vaticle.bazel.distribution.common.OS.MAC import com.vaticle.bazel.distribution.common.OS.WINDOWS import java.util.Locale.ENGLISH object SystemUtil { val currentOS: OS get() { val osName = System.getProperty("os.name").lowercase(ENGLISH) return when { "mac" in osName || "darwin" in osName -> MAC "win" in osName -> WINDOWS else -> LINUX } } }
37
null
53
155
8bd47812bd957380d1f56ce1a5afb98ea2a3f788
1,423
bazel-distribution
Apache License 2.0
client/src/main/kotlin/ru/spb/kry127/netbench/client/net/Client.kt
kry127
328,053,995
false
null
package ru.spb.kry127.netbench.client.net import ru.spb.kry127.netbench.client.InputDataPoint import ru.spb.kry127.netbench.client.IntGenerator import ru.spb.kry127.netbench.client.MeanStatistics import ru.spb.kry127.netbench.client.MeanStatistics.Companion.mean import ru.spb.kry127.netbench.proto.ArraySorter import java.net.InetSocketAddress import java.nio.ByteBuffer import java.nio.channels.AsynchronousSocketChannel import java.nio.channels.CompletionHandler import java.util.concurrent.* /** * Client is something that should be able to receive InputDataPoint, * perform communication, and then give out mean statistics of the most interesting magnitudes */ interface Client { fun communicate(withParameters: InputDataPoint): MeanStatistics } /** * A stateless object of this class connects to the server and performs operation * of sorting some array. Should only know where to connect to give out info. * This client is based on asynchronous sockets. */ class ClientAsyncImpl(val connectTo: InetSocketAddress) : Client { override fun communicate(withParameters: InputDataPoint): MeanStatistics { return communicateAsync(withParameters).get() } private fun communicateAsync(withParameters: InputDataPoint): Future<MeanStatistics> { val completableFuture = CompletableFuture<MeanStatistics>() val asynchronousSocketChannel = AsynchronousSocketChannel.open() asynchronousSocketChannel.connect(connectTo, asynchronousSocketChannel, object : CompletionHandler<Void, AsynchronousSocketChannel> { override fun completed(result: Void?, channel: AsynchronousSocketChannel) { // A little bit artificial, but it should work AsyncHandler.completed( 0, AsyncHandlerAttachment( channel, completableFuture, withParameters, timeToLive = withParameters.x ) ) } override fun failed(exc: Throwable?, channel: AsynchronousSocketChannel) { completableFuture.completeExceptionally(exc) } }) return completableFuture } enum class ClientState { START_SENDING, SENDING, RECEIVING_SIZE, RECEIVING_MSG } data class AsyncHandlerAttachment( val channel: AsynchronousSocketChannel, val completableFuture: CompletableFuture<MeanStatistics>, val inputDataPoint: InputDataPoint, var timeToLive: Int, var state: ClientState = ClientState.START_SENDING, var buf: ByteBuffer = ByteBuffer.allocate(0), var msgSize: Int = 0, var startProcessingTime: Long = 0, val resultList: MutableList<MeanStatistics> = mutableListOf(), // for validation var toSort: List<Int> = listOf() ) object AsyncHandler : CompletionHandler<Int, AsyncHandlerAttachment> { override fun completed(result: Int, attachment: AsyncHandlerAttachment) { when (attachment.state) { ClientState.START_SENDING -> { attachment.startProcessingTime = System.currentTimeMillis() // we'd like to send some array val toSort = IntGenerator.generateUniformArray(attachment.inputDataPoint.n) attachment.toSort = toSort // TODO save for validation val msgBytes = ArraySorter.SortArray.newBuilder().addAllArray(toSort).build().toByteArray() val bigBuffer = ByteBuffer.allocate(4 + msgBytes.size) bigBuffer.putInt(msgBytes.size) bigBuffer.put(msgBytes) bigBuffer.flip() attachment.state = ClientState.SENDING attachment.channel.write( bigBuffer, attachment, AsyncHandler ) } ClientState.SENDING -> { attachment.state = ClientState.RECEIVING_SIZE attachment.buf = ByteBuffer.allocate(4) attachment.channel.read(attachment.buf, attachment, AsyncHandler) } ClientState.RECEIVING_SIZE -> { attachment.buf.flip() val sz = attachment.buf.getInt() // println("toSort.size=${attachment.toSort.size}, sz=$sz") // if (sz > 100000000) { // print(".") // } attachment.msgSize = sz attachment.buf = ByteBuffer.allocate(sz) attachment.state = ClientState.RECEIVING_MSG attachment.channel.read(attachment.buf, attachment, AsyncHandler) } ClientState.RECEIVING_MSG -> { if (attachment.buf.hasRemaining()) { // continue reading attachment.channel.read(attachment.buf, attachment, AsyncHandler) return } attachment.buf.flip() val rsp = ArraySorter.SortArrayRsp.parseFrom(attachment.buf) val meanResult = MeanStatistics( rsp.requestProcessingTime, rsp.clientProcessingTime, System.currentTimeMillis() - attachment.startProcessingTime ) // make some validation if(attachment.toSort.size != rsp.sortedArrayList.size) { error("Size of sorted list has changed!") } for((v1, v2) in attachment.toSort.sorted().zip(rsp.sortedArrayList)) { if (v1 != v2) { error("Sorted arrays not equal") } } attachment.resultList.add(meanResult) attachment.timeToLive-- if (attachment.timeToLive <= 0) { // That's all, lets provide the result! attachment.completableFuture.complete(attachment.resultList.mean()) // and also close connection attachment.channel.close() } else { // That's not all, start over again! But with delay of delta waitUntil(System.currentTimeMillis() + attachment.inputDataPoint.delta) attachment.state = ClientState.START_SENDING completed(0, attachment) } } } } private fun waitUntil(l: Long) { while(true) { val sleepFor = l - System.currentTimeMillis() if (sleepFor <= 0) break; try { Thread.sleep(sleepFor) } catch (ex : InterruptedException) { } } } override fun failed(exc: Throwable, attachment: AsyncHandlerAttachment) { attachment.completableFuture.completeExceptionally(exc) } } }
1
null
1
1
498b1f7063c2da7daf64ed3afe396442fe2079ef
7,344
JvmServerArchitectures
MIT License
backend/src/main/kotlin/io/github/katarem/domain/model/User.kt
katarem
857,288,553
false
{"Kotlin": 89540, "Dockerfile": 824, "Swift": 621}
package io.github.katarem.domain.model import kotlinx.datetime.LocalDateTime data class User( val id: Long, val username: String, val email: String, val password: String, val cards: List<Card>, val nextCard: LocalDateTime?, val role: Roles = Roles.USER ) enum class Roles{ ADMIN,USER }
0
Kotlin
0
0
bbe068561694292ac1ee8da518e79dfa0f188961
320
anime-card-trader
MIT License
app/src/main/java/com/dinaraparanid/prima/utils/web/youtube/json/YouTubeSearchResult.kt
dinaraparanid
365,311,683
false
null
package com.dinaraparanid.prima.utils.web.youtube.json import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName @Deprecated( "The YouTube API key is very limited in resources, " + "and it will not be enough for users from the Play Market" ) class YouTubeSearchResult( @Expose @JvmField val kind: String, @Expose @JvmField val etag: String, @Expose @JvmField @SerializedName("nextPageToken") val nextPageToken: String, @Expose @JvmField @SerializedName("regionCode") val regionCode: String, @Expose @JvmField @SerializedName("pageInfo") val pageInfo: PageInfo, @Expose @JvmField val items: Array<FoundVideo> )
0
Kotlin
0
6
c3b5bb93f515820862b04db199c9425fc03472e3
750
PrimaMobile
Apache License 2.0
app/src/unitTest/kotlin/batect/cli/CommandLineOptionsParserSpec.kt
uBuFun
221,905,828
true
{"Kotlin": 1851760, "Shell": 13393, "Groovy": 11432, "Python": 10433, "Dockerfile": 5030, "JavaScript": 4104, "Java": 1097, "HTML": 878}
/* Copyright 2017-2019 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.cli import batect.cli.options.defaultvalues.EnvironmentVariableDefaultValueProviderFactory import batect.docker.DockerHttpConfigDefaults import batect.os.PathResolutionResult import batect.os.PathResolver import batect.os.PathResolverFactory import batect.os.PathType import batect.testutils.equalTo import batect.testutils.given import batect.testutils.on import batect.ui.OutputStyle import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import com.natpryce.hamkrest.assertion.assertThat import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object CommandLineOptionsParserSpec : Spek({ describe("a command line interface") { val fileSystem = Jimfs.newFileSystem(Configuration.unix()) val pathResolver = mock<PathResolver> { on { resolve("somefile.log") } doReturn PathResolutionResult.Resolved("somefile.log", fileSystem.getPath("/resolved/somefile.log"), PathType.File) on { resolve("somefile.yml") } doReturn PathResolutionResult.Resolved("somefile.yml", fileSystem.getPath("/resolved/somefile.yml"), PathType.File) } val pathResolverFactory = mock<PathResolverFactory> { on { createResolverForCurrentDirectory() } doReturn pathResolver } val environmentVariableDefaultValueProviderFactory = EnvironmentVariableDefaultValueProviderFactory(emptyMap()) val defaultDockerHost = "http://some-docker-host" val dockerHttpConfigDefaults = mock<DockerHttpConfigDefaults> { on { this.defaultDockerHost } doReturn defaultDockerHost } given("no arguments") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(emptyList()) it("returns an error message") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Failed("No task name provided."))) } } } given("a single argument for the task name") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(listOf("some-task")) it("returns a set of options with just the task name populated") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Succeeded(CommandLineOptions( taskName = "some-task", dockerHost = defaultDockerHost )))) } } } given("multiple arguments without a '--' prefix") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(listOf("some-task", "some-extra-arg")) it("returns an error message") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Failed( "Too many arguments provided. The first extra argument is 'some-extra-arg'.\n" + "To pass additional arguments to the task command, prefix them with '--', for example, './batect my-task -- --extra-option-1 --extra-option-2 value'." ))) } } } given("multiple arguments with a '--' prefix") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(listOf("some-task", "--", "some-extra-arg")) it("returns a set of options with the task name and additional arguments populated") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Succeeded(CommandLineOptions( taskName = "some-task", additionalTaskCommandArguments = listOf("some-extra-arg"), dockerHost = defaultDockerHost )))) } } } given("a flag followed by a single argument") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(listOf("--no-color", "some-task")) it("returns a set of options with the task name populated and the flag set") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Succeeded(CommandLineOptions( disableColorOutput = true, taskName = "some-task", dockerHost = defaultDockerHost )))) } } } given("a flag followed by multiple arguments") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(listOf("--no-color", "some-task", "some-extra-arg")) it("returns an error message") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Failed( "Too many arguments provided. The first extra argument is 'some-extra-arg'.\n" + "To pass additional arguments to the task command, prefix them with '--', for example, './batect my-task -- --extra-option-1 --extra-option-2 value'." ))) } } } given("colour output has been disabled and fancy output mode has been selected") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(listOf("--no-color", "--output=fancy", "some-task", "some-extra-arg")) it("returns an error message") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Failed("Fancy output mode cannot be used when colored output has been disabled."))) } } } mapOf( listOf("--help") to CommandLineOptions(showHelp = true, dockerHost = defaultDockerHost), listOf("--help", "some-task") to CommandLineOptions(showHelp = true, dockerHost = defaultDockerHost), listOf("--version") to CommandLineOptions(showVersionInfo = true, dockerHost = defaultDockerHost), listOf("--version", "some-task") to CommandLineOptions(showVersionInfo = true, dockerHost = defaultDockerHost), listOf("--list-tasks") to CommandLineOptions(listTasks = true, dockerHost = defaultDockerHost), listOf("--list-tasks", "some-task") to CommandLineOptions(listTasks = true, dockerHost = defaultDockerHost), listOf("--upgrade") to CommandLineOptions(runUpgrade = true, dockerHost = defaultDockerHost), listOf("--upgrade", "some-task") to CommandLineOptions(runUpgrade = true, dockerHost = defaultDockerHost), listOf("-f=somefile.yml", "some-task") to CommandLineOptions(configurationFileName = fileSystem.getPath("/resolved/somefile.yml"), taskName = "some-task", dockerHost = defaultDockerHost), listOf("--config-file=somefile.yml", "some-task") to CommandLineOptions(configurationFileName = fileSystem.getPath("/resolved/somefile.yml"), taskName = "some-task", dockerHost = defaultDockerHost), listOf("--log-file=somefile.log", "some-task") to CommandLineOptions(logFileName = fileSystem.getPath("/resolved/somefile.log"), taskName = "some-task", dockerHost = defaultDockerHost), listOf("--output=simple", "some-task") to CommandLineOptions(requestedOutputStyle = OutputStyle.Simple, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--output=quiet", "some-task") to CommandLineOptions(requestedOutputStyle = OutputStyle.Quiet, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--output=fancy", "some-task") to CommandLineOptions(requestedOutputStyle = OutputStyle.Fancy, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--no-color", "some-task") to CommandLineOptions(disableColorOutput = true, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--no-update-notification", "some-task") to CommandLineOptions(disableUpdateNotification = true, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--no-cleanup-after-failure", "some-task") to CommandLineOptions(disableCleanupAfterFailure = true, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--no-cleanup-after-success", "some-task") to CommandLineOptions(disableCleanupAfterSuccess = true, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--no-cleanup", "some-task") to CommandLineOptions(disableCleanupAfterFailure = true, disableCleanupAfterSuccess = true, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--no-proxy-vars", "some-task") to CommandLineOptions(dontPropagateProxyEnvironmentVariables = true, taskName = "some-task", dockerHost = defaultDockerHost), listOf("--docker-host=some-host", "some-task") to CommandLineOptions(dockerHost = "some-host", taskName = "some-task") ).forEach { (args, expectedResult) -> given("the arguments $args") { on("parsing the command line") { val result = CommandLineOptionsParser(pathResolverFactory, environmentVariableDefaultValueProviderFactory, dockerHttpConfigDefaults).parse(args) it("returns a set of options with the expected options populated") { assertThat(result, equalTo(CommandLineOptionsParsingResult.Succeeded(expectedResult))) } } } } } })
4
Kotlin
1
1
e933116cad5b1c5c877233317534ba3e91e9475e
10,903
batect
Apache License 2.0
app/src/main/java/com/mhappening/gameclock/data/workManager/factory/RescheduleAlarmWorkerFactory.kt
Matt-Haywood
769,928,478
false
{"Kotlin": 276837}
package com.mhappening.gameclock.data.workManager.factory import android.content.Context import androidx.work.ListenableWorker import androidx.work.WorkerParameters import com.mhappening.gameclock.data.alarms.AlarmRepository import com.mhappening.gameclock.data.alarms.GameClockAlarmManager import com.mhappening.gameclock.data.workManager.WorkRequestManager import com.mhappening.gameclock.data.workManager.worker.RescheduleAlarmWorker import javax.inject.Inject class RescheduleAlarmWorkerFactory @Inject constructor( private val alarmRepository: AlarmRepository, private val scheduleAlarmManager: GameClockAlarmManager, private val workRequestManager: WorkRequestManager, ) : ChildWorkerFactory { override fun create(appContext: Context, params: WorkerParameters): ListenableWorker { return RescheduleAlarmWorker(alarmRepository, scheduleAlarmManager, workRequestManager, appContext, params) } }
0
Kotlin
0
1
96fab1ca52d9ddede722300c1c42fe6324c4110a
930
Game-Clock
Apache License 2.0
compiler/testData/codegen/box/ranges/stepped/unsigned/literal/downTo/illegalStepNonConst.kt
JetBrains
3,432,266
false
null
// Auto-generated by GenerateSteppedRangesCodegenTestData. Do not edit! // WITH_STDLIB // KT-34166: Translation of loop over literal completely removes the validation of step // DONT_TARGET_EXACT_BACKEND: JS import kotlin.test.* fun zero() = 0 fun box(): String { assertFailsWith<IllegalArgumentException> { for (i in 7u downTo 1u step zero()) { } } assertFailsWith<IllegalArgumentException> { for (i in 7uL downTo 1uL step zero().toLong()) { } } return "OK" }
179
null
5706
48,889
c46c3c26038158cf80a739431ac8807ac4bbbc0c
516
kotlin
Apache License 2.0
libs/ui-theme/src/main/kotlin/mono/ui/theme/ThemeManager.kt
tuanchauict
325,686,408
false
null
package mono.ui.theme import mono.livedata.LiveData import mono.livedata.MutableLiveData import mono.livedata.distinctUntilChange /** * A class for managing the theme of the app. */ class ThemeManager private constructor(initialThemeMode: ThemeMode) { private val themeModeMutableLiveData: MutableLiveData<ThemeMode> = MutableLiveData(initialThemeMode) val themeModeLiveData: LiveData<ThemeMode> = themeModeMutableLiveData.distinctUntilChange() /** * Gets color from [color] based on the current theme. * The return is the hex code of RGB or RGBA, the same to the hex code used in CSS. */ fun getColorCode(color: ThemeColor): String = when (themeModeLiveData.value) { ThemeMode.LIGHT -> color.lightColorCode ThemeMode.DARK -> color.darkColorCode } fun setTheme(themeMode: ThemeMode) { themeModeMutableLiveData.value = themeMode } companion object { private var instance: ThemeManager? = null fun getInstance(): ThemeManager { val nonNullInstance = instance ?: ThemeManager(ThemeMode.DARK) instance = nonNullInstance return nonNullInstance } } }
15
Kotlin
9
91
21cef26b45c984eee31ea2c3ba769dfe5eddd92e
1,197
MonoSketch
Apache License 2.0
src/main/java/test/AHSTUTest.kt
YZune
232,583,513
false
null
import java.io.File import java.util.Scanner import main.java.parser.AHSTUCourseProvider import main.java.parser.supwisdom.SupwisdomParser //获取课表html fun getCourseHTML() { val xuke = AHSTUCourseProvider() val img = xuke.getCaptchaImage() val _file = File("captcha.png") _file.writeBytes(img) println("获取验证码成功") println("输入验证码:") val sc = Scanner(System.`in`) val cap = sc.next() xuke.login("", "", cap) println("登录成功") val importOPT = xuke.getImportOption() val html = xuke.getCourseHtml(AHSTUCourseProvider.Semester(102, "", "")) val c = File("course.html") c.writeText(html) println("完成") } fun main() { val file = File("course.html").readText() SupwisdomParser(file).generateCourseList() }
0
Kotlin
119
96
2bc26e588f80cb7f9a1715b02309b653ba090454
765
CourseAdapter
MIT License
scan-engine/src/main/java/de/tillhub/scanengine/default/ui/GoogleScanningActivity.kt
tillhub
459,124,731
false
null
package de.tillhub.scanengine.default.ui import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.Camera import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.content.ContextCompat import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.viewbinding.ViewBinding import de.tillhub.scanengine.R import de.tillhub.scanengine.databinding.ActivityGoogleScanningBinding import kotlinx.coroutines.launch import java.util.concurrent.Executor class GoogleScanningActivity : AppCompatActivity() { private val viewModel: GoogleScanningViewModel by viewModels { GoogleScanningViewModel.Factory } private val binding by viewBinding(ActivityGoogleScanningBinding::inflate) private lateinit var camera: Camera private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted -> if (isGranted) { bindCamera() } else { Toast.makeText( baseContext, R.string.error_permission_not_granted, Toast.LENGTH_SHORT ).show() binding.requestPermission.isVisible = true } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.requestPermission.setOnClickListener { binding.requestPermission.isGone = true checkPermission() } lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) { viewModel.scanningState.collect { state -> when (state) { is ScanningState.CodeScanned -> { setResult( RESULT_OK, Intent().apply { putExtra(DATA_KEY, state.barcode) } ) finish() } ScanningState.Idle -> Unit } } } } checkPermission() } private fun checkPermission() { when (PackageManager.PERMISSION_GRANTED) { ContextCompat.checkSelfPermission( baseContext, Manifest.permission.CAMERA ) -> bindCamera() else -> requestPermissionLauncher.launch(Manifest.permission.CAMERA) } } private fun bindCamera() { val executor = ContextCompat.getMainExecutor(applicationContext) val cameraProviderFuture = ProcessCameraProvider.getInstance(applicationContext) cameraProviderFuture.addListener( { val cameraProvider = cameraProviderFuture.get() bindPreview(cameraProvider, executor) }, executor ) } private fun bindPreview(cameraProvider: ProcessCameraProvider, cameraExecutor: Executor) { val preview: Preview = Preview.Builder() .build() .also { it.setSurfaceProvider(binding.previewView.surfaceProvider) } val cameraSelector: CameraSelector = CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build() val imageAnalyzer = ImageAnalysis.Builder() .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .build() .also { it.setAnalyzer(cameraExecutor, viewModel.analyzer) } cameraProvider.unbindAll() camera = cameraProvider.bindToLifecycle( this as LifecycleOwner, cameraSelector, imageAnalyzer, preview ) } companion object { const val DATA_KEY = "scanned_data" } } inline fun <T : ViewBinding> AppCompatActivity.viewBinding( crossinline bindingInflater: (LayoutInflater) -> T, ) = lazy(LazyThreadSafetyMode.NONE) { bindingInflater.invoke(layoutInflater) }
0
null
0
2
2c0383d3e7f395d0fac179b5438b65f794c6c930
4,739
scan-engine
MIT License
app/src/main/java/com/maderix/bubblepickerdemo/BubbleFragment.kt
maderix
119,283,207
false
null
package com.maderix.bubblepickerdemo import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ToggleButton import com.github.debop.kodatimes.now import com.github.debop.kodatimes.toDateTime import com.github.debop.kodatimes.tomorrow import com.igalata.bubblelist.adapter.BubbleTaskData import kotlinx.android.synthetic.main.fragment_bubble.* import kotlinx.android.synthetic.main.fragment_bubble.view.* import org.joda.time.DateTime import java.util.* /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [BubbleFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [BubbleFragment.newInstance] factory method to * create an instance of this fragment. */ class BubbleFragment : DialogFragment() { // TODO: Rename and change types of parameters private var bubbleTaskName: String? = null private var bubbleTaskUrgent: Boolean = false private var bubbleTaskDueDate: DateTime? = null private var bubbleTaskColor:Int = 0 private var mListener: OnFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { bubbleTaskName = arguments!!.getString(BUBBLE_TASK_NAME) bubbleTaskDueDate = arguments!!.getString(BUBBLE_TASK_DUE_DATE).toDateTime() bubbleTaskColor = arguments!!.getString(BUBBLE_TASK_COLOR).toInt() bubbleTaskUrgent = arguments!!.getString(BUBBLE_TASK_URGENT).toBoolean() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment var rootView:View = inflater.inflate(R.layout.fragment_bubble, container, false) rootView.bt_add_bubble.setOnClickListener { var title:String = ed_task_title.text.toString() var urgent:Boolean = cb_urgent.isChecked var dateTime:DateTime = DateTime() if (tb_today.isChecked) dateTime = now() else if(tb_today.isChecked) dateTime = tomorrow() Random().let { var startColor: Int = it.nextInt(10) var endColor: Int = it.nextInt(10) onButtonPressed(BubbleTaskData(title, urgent, dateTime, startColor, endColor)) } dismiss() } rootView.tb_today.setOnCheckedChangeListener{buttonView, isChecked -> if (isChecked) buttonView.setBackgroundColor(resources.getColor(R.color.blueStart)) else buttonView.setBackgroundColor(resources.getColor(R.color.blueEnd)) rootView.tb_tomorrow.isChecked = false } rootView.tb_tomorrow.setOnCheckedChangeListener{ buttonView, isChecked -> if (isChecked) buttonView.setBackgroundColor(resources.getColor(R.color.blueStart)) else buttonView.setBackgroundColor(resources.getColor(R.color.blueEnd)) rootView.tb_today.isChecked = false } rootView.tb_someday.setOnClickListener{ mListener!!.onFragmentInteraction(true) dismiss() } return rootView } private fun onButtonPressed(bubbleTaskData: BubbleTaskData) { if (mListener != null) { mListener!!.onFragmentInteraction(bubbleTaskData) } } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mListener = context } else { throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnFragmentInteractionListener { // TODO: Update argument type and name fun onFragmentInteraction(bubbleTaskData: BubbleTaskData) fun onFragmentInteraction(enabled:Boolean) } companion object { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private val BUBBLE_TASK_NAME = "param1" private val BUBBLE_TASK_URGENT = "param2" private val BUBBLE_TASK_DUE_DATE = "param3" private val BUBBLE_TASK_COLOR = "param4" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BubbleFragment. */ // TODO: Rename and change types and number of parameters fun newInstance(bubbleTaskData: BubbleTaskData): BubbleFragment { val fragment = BubbleFragment() val args = Bundle().apply { this.putString(BUBBLE_TASK_NAME, bubbleTaskData.taskName) this.putString(BUBBLE_TASK_URGENT, bubbleTaskData.urgent.toString()) this.putString(BUBBLE_TASK_COLOR, bubbleTaskData.startColor.toString()) this.putString(BUBBLE_TASK_DUE_DATE, bubbleTaskData.taskDueDate.toString()) } fragment.arguments = args return fragment } } }// Required empty public constructor
0
Kotlin
0
0
e7d8a906a539064c0ff2c7c2e6df5a93b250fa0d
6,134
Bubble-Picker2
The Unlicense
ProjectService/app/src/main/java/me/liuqingwen/android/projectservice/APIService.kt
spkingr
99,180,956
false
null
package me.liuqingwen.android.projectservice import com.google.gson.annotations.SerializedName import io.reactivex.Observable import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query /** * Created by Qingwen on 2018-5-14, project: ProjectService. * * @Author: Qingwen * @DateTime: 2018-5-14 * @Package: me.liuqingwen.android.projectservice in project: ProjectService * * Notice: If you are using this class or file, check it and do some modification. */ private const val DOUBAN_BASE_URL = "https://api.douban.com/" object APIService { private val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(DOUBAN_BASE_URL) .build() private val movieService = this.retrofit.create(IMovieService::class.java) fun getTopObservable(start:Int = 0, count:Int = 20) = this.movieService.getTop250(start = start, count = count) fun getOnShowObservable(city: String) = this.movieService.getOnShowByCity(city = city) fun getComingSoonObservable(start: Int = 0, count: Int = 20) = this.movieService.getComingSoonOnes(start = start, count = count) } interface IMovieService { @GET("v2/movie/top250") fun getTop250(@Query("start") start:Int, @Query("count") count:Int): Observable<MovieResponse> @GET("/v2/movie/in_theaters") fun getOnShowByCity(@Query("city") city: String = "北京"): Observable<MovieResponse> @GET("/v2/movie/coming_soon") fun getComingSoonOnes(@Query("start") start: Int, @Query("count") count: Int): Observable<MovieResponse> } data class MovieResponse(val count: Int, val start: Int, val total: Int, val title: String, val subjects: List<Movie>) data class Movie(val id: String, val year: String, val images: SizedImage, val genres: List<String>, @SerializedName("original_title") val originalTitle: String, @SerializedName("title") val TranslationTitle: String, @SerializedName("alt") val webUrl: String, @SerializedName("casts") val movieStars: List<MovieStar>, @SerializedName("directors") val movieDirectors: List<MovieStar>) //aka: List<String>, ratings_count: Int, comments_count: Int, subtype: String, summary: String, current_season: Object, // collect_count: Int, countries: List<String>, episodes_count: Object, schedule_url: String, seasons_count: Object, share_url: String, do_count: Object, // , douban_site: String, wish_count: Int, reviews_count: Int, rating: Rating(val max:Int, val average:Int, val stars:String, val min:Int) data class MovieStar(val id: String, val name: String, @SerializedName("alt") val link: String, @SerializedName("avatars") val image: SizedImage) data class SizedImage(@SerializedName("small") val smallImage: String, @SerializedName("medium") val mediumImage: String, @SerializedName("large") val largeImage: String)
0
Kotlin
30
94
43756ad5107521e8156b0e5afa9e83fd0c20092a
3,187
50-android-kotlin-projects-in-100-days
MIT License
src/main/kotlin/cn/gionrose/facered/genshinDrawcard2/api/manager/CardManager.kt
13022631363
701,322,305
false
{"Kotlin": 95406}
package cn.gionrose.facered.genshinDrawcard2.api.manager import cn.gionrose.facered.genshinDrawcard2.api.card.Card import cn.gionrose.facered.genshinDrawcard2.api.card.CardStarGrade import com.skillw.pouvoir.api.manager.Manager import com.skillw.pouvoir.api.plugin.map.LowerKeyMap import org.bukkit.inventory.ItemStack /** * @description 卡片管理器 * @author facered * @date 2023/10/6 22:19 */ abstract class CardManager: LowerKeyMap<Card>(), Manager { /** * 注册卡片到管理器 * @param card 卡片 */ abstract fun registerCard (card: List<Card>) /** * 注册卡片到管理器 * @param card 卡片 */ abstract fun registerCard (card: Card) /** * 从管理器中注销卡片 (通过卡片名) * @param cardKeys 卡片名集合 */ abstract fun unregisterCard (cardKeys: List<String>) /** * 将管理器中的卡片全部清除 */ abstract fun releaseAllCards () /** * 从管理器中获取所有卡片 */ abstract fun getAllCards (): List<Card> /** * 通过卡片名 获取卡片 */ abstract fun getCard (cardName: String): Card? abstract fun createCard (key: String, source: ItemStack, isUp: Boolean = false, grade: CardStarGrade = CardStarGrade.THREE_STAR ): Card }
0
Kotlin
0
0
4caea9da4a398301c98a39de3867928ba6fb6757
1,258
GenshinDrawcard2
Apache License 2.0
app/src/main/java/com/duckduckgo/app/feedback/ui/negative/openended/ShareOpenEndedNegativeFeedbackViewModel.kt
Rachelmorrell
132,979,208
false
null
/* * Copyright (c) 2019 DuckDuckGo * * 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.duckduckgo.app.feedback.ui.negative.openended import androidx.lifecycle.ViewModel import com.duckduckgo.app.feedback.ui.negative.FeedbackType.MainReason import com.duckduckgo.app.feedback.ui.negative.FeedbackType.SubReason import com.duckduckgo.app.global.SingleLiveEvent import com.duckduckgo.app.global.plugins.view_model.ViewModelFactoryPlugin import com.duckduckgo.di.scopes.AppScope import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject class ShareOpenEndedNegativeFeedbackViewModel : ViewModel() { val command: SingleLiveEvent<Command> = SingleLiveEvent() fun userSubmittingPositiveFeedback(feedback: String) { command.value = Command.ExitAndSubmitPositiveFeedback(feedback) } fun userSubmittingNegativeFeedback(mainReason: MainReason, subReason: SubReason?, openEndedComment: String) { command.value = Command.ExitAndSubmitNegativeFeedback(mainReason, subReason, openEndedComment) } sealed class Command { data class ExitAndSubmitNegativeFeedback(val mainReason: MainReason, val subReason: SubReason?, val feedback: String) : Command() data class ExitAndSubmitPositiveFeedback(val feedback: String) : Command() object Exit : Command() } } @ContributesMultibinding(AppScope::class) class ShareOpenEndedNegativeFeedbackViewModelFactory @Inject constructor() : ViewModelFactoryPlugin { override fun <T : ViewModel?> create(modelClass: Class<T>): T? { with(modelClass) { return when { isAssignableFrom(ShareOpenEndedNegativeFeedbackViewModel::class.java) -> (ShareOpenEndedNegativeFeedbackViewModel() as T) else -> null } } } }
41
null
671
3
c03633f7faee192948e68c3897c526c323ee0f2e
2,332
Android
Apache License 2.0
app/src/main/kotlin/com/wiley/fordummies/androidsdk/tictactoe/ui/fragment/GameOptionsFragment.kt
acchampion
157,287,910
false
null
package com.wiley.fordummies.androidsdk.tictactoe.ui import android.content.Intent import android.os.Bundle import android.view.* import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.wiley.fordummies.androidsdk.tictactoe.* /** * Fragment that handles main user navigation in the app. * * Created by adamcchampion on 2017/08/05. */ class GameOptionsFragment : Fragment(), View.OnClickListener { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.fragment_game_options, container, false) val btnNewGame: Button = v.findViewById(R.id.buttonNewGame) btnNewGame.setOnClickListener(this) val btnAudio: Button = v.findViewById(R.id.buttonAudio) btnAudio.setOnClickListener(this) val btnVideo: Button = v.findViewById(R.id.buttonVideo) btnVideo.setOnClickListener(this) val btnImage: Button = v.findViewById(R.id.buttonImages) btnImage.setOnClickListener(this) val btnMaps: Button = v.findViewById(R.id.buttonMaps) btnMaps.setOnClickListener(this) val btnSettings: Button = v.findViewById(R.id.buttonSettings) btnSettings.setOnClickListener(this) val btnHelp: Button = v.findViewById(R.id.buttonHelp) btnHelp.setOnClickListener(this) val btnTestSensors: Button = v.findViewById(R.id.buttonSensors) btnTestSensors.setOnClickListener(this) val btnExit: Button = v.findViewById(R.id.buttonExit) btnExit.setOnClickListener(this) setHasOptionsMenu(true) return v } override fun onResume() { super.onResume() val activity = requireActivity() as AppCompatActivity activity.supportActionBar?.apply { subtitle = resources.getString(R.string.options) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val activity = requireActivity() when (item.itemId) { R.id.menu_settings -> { startActivity(Intent(activity.applicationContext, SettingsActivity::class.java)) return true } R.id.menu_help -> { startActivity(Intent(activity.applicationContext, HelpActivity::class.java)) return true } R.id.menu_exit -> { showQuitAppDialog() return true } R.id.menu_contacts -> { startActivity(Intent(activity.applicationContext, ContactsActivity::class.java)) return true } } return false } override fun onClick(v: View) { val activity = requireActivity() when (v.id) { R.id.buttonNewGame -> startActivity(Intent(activity.applicationContext, GameSessionActivity::class.java)) R.id.buttonAudio -> startActivity(Intent(activity.applicationContext, AudioActivity::class.java)) R.id.buttonVideo -> startActivity(Intent(activity.applicationContext, VideoActivity::class.java)) R.id.buttonImages -> startActivity(Intent(activity.applicationContext, ImagesActivity::class.java)) R.id.buttonMaps -> startActivity(Intent(activity.applicationContext, MapsActivity::class.java)) R.id.buttonSettings -> startActivity(Intent(activity.applicationContext, SettingsActivity::class.java)) R.id.buttonHelp -> startActivity(Intent(activity.applicationContext, HelpActivity::class.java)) R.id.buttonSensors -> startActivity(Intent(activity.applicationContext, SensorsActivity::class.java)) R.id.buttonExit -> { activity.stopService(Intent(activity.applicationContext, MediaPlaybackService::class.java)) showQuitAppDialog() } } } private fun showQuitAppDialog() { val manager = parentFragmentManager val fragment = QuitAppDialogFragment() fragment.show(manager, "quit_app") } }
0
Kotlin
2
1
bb4b953341d594d1401199d1cb8749a8ffadbfe0
4,284
TicTacToeKotlin
Apache License 2.0
exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectTests.kt
JetBrains
11,765,017
false
null
package org.jetbrains.exposed.sql.tests.shared.dml import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.tests.DatabaseTestsBase import org.jetbrains.exposed.sql.tests.TestDB import org.jetbrains.exposed.sql.tests.shared.assertEquals import org.junit.Test import kotlin.test.assertNull class SelectTests : DatabaseTestsBase() { // select expressions @Test fun testSelect() { withCitiesAndUsers { _, users, _ -> users.select { users.id.eq("andrey") }.forEach { val userId = it[users.id] val userName = it[users.name] when (userId) { "andrey" -> assertEquals("Andrey", userName) else -> error("Unexpected user $userId") } } } } @Test fun testSelectAnd() { withCitiesAndUsers { cities, users, userData -> users.select { users.id.eq("andrey") and users.name.eq("Andrey") }.forEach { val userId = it[users.id] val userName = it[users.name] when (userId) { "andrey" -> assertEquals("Andrey", userName) else -> error("Unexpected user $userId") } } } } @Test fun testSelectOr() { withCitiesAndUsers { cities, users, userData -> users.select { users.id.eq("andrey") or users.name.eq("Andrey") }.forEach { val userId = it[users.id] val userName = it[users.name] when (userId) { "andrey" -> assertEquals("Andrey", userName) else -> error("Unexpected user $userId") } } } } @Test fun testSelectNot() { withCitiesAndUsers { cities, users, userData -> users.select { org.jetbrains.exposed.sql.not(users.id.eq("andrey")) }.forEach { val userId = it[users.id] val userName = it[users.name] if (userId == "andrey") { error("Unexpected user $userId") } } } } @Test fun testSizedIterable() { withCitiesAndUsers { cities, users, userData -> assertEquals(false, cities.selectAll().empty()) assertEquals(true, cities.select { cities.name eq "Qwertt" }.empty()) assertEquals(0L, cities.select { cities.name eq "Qwertt" }.count()) assertEquals(3L, cities.selectAll().count()) } } @Test fun testInList01() { withCitiesAndUsers { cities, users, userData -> val r = users.select { users.id inList listOf("andrey", "alex") }.orderBy(users.name).toList() assertEquals(2, r.size) assertEquals("Alex", r[0][users.name]) assertEquals("Andrey", r[1][users.name]) } } @Test fun testInList02() { withCitiesAndUsers { cities, users, userData -> val cityIds = cities.selectAll().map { it[cities.id] }.take(2) val r = cities.select { cities.id inList cityIds } assertEquals(2L, r.count()) } } @Test fun testInList03() { withCitiesAndUsers(listOf(TestDB.SQLITE, TestDB.SQLSERVER)) { _, users, _ -> val r = users.select { users.id to users.name inList listOf("andrey" to "Andrey", "alex" to "Alex") }.orderBy(users.name).toList() assertEquals(2, r.size) assertEquals("Alex", r[0][users.name]) assertEquals("Andrey", r[1][users.name]) } } @Test fun testInList04() { withCitiesAndUsers(listOf(TestDB.SQLITE, TestDB.SQLSERVER)) { _, users, _ -> val r = users.select { users.id to users.name inList listOf("andrey" to "Andrey") }.toList() assertEquals(1, r.size) assertEquals("Andrey", r[0][users.name]) } } @Test fun testInList05() { withCitiesAndUsers(listOf(TestDB.SQLITE, TestDB.SQLSERVER)) { _, users, _ -> val r = users.select { users.id to users.name inList emptyList() }.toList() assertEquals(0, r.size) } } @Test fun testInList06() { withCitiesAndUsers(listOf(TestDB.SQLITE, TestDB.SQLSERVER)) { _, users, _ -> val r = users.select { users.id to users.name notInList emptyList() }.toList() assertEquals(users.selectAll().count().toInt(), r.size) } } @Test fun testInList07() { withCitiesAndUsers(listOf(TestDB.SQLITE, TestDB.SQLSERVER)) { _, users, _ -> val r = users.select { Triple(users.id, users.name, users.cityId) notInList listOf(Triple("alex", "Alex", null)) }.toList() assertEquals(users.selectAll().count().toInt() - 1, r.size) } } @Test fun testInSubQuery01() { withCitiesAndUsers { cities, _, _ -> val r = cities.select { cities.id inSubQuery cities.slice(cities.id).select { cities.id eq 2 } } assertEquals(1L, r.count()) } } @Test fun testNotInSubQueryNoData() { withCitiesAndUsers { cities, _, _ -> val r = cities.select { cities.id notInSubQuery cities.slice(cities.id).selectAll() } // no data since all ids are selected assertEquals(0L, r.count()) } } @Test fun testNotInSubQuery() { withCitiesAndUsers { cities, _, _ -> val cityId = 2 val r = cities.select { cities.id notInSubQuery cities.slice(cities.id).select { cities.id eq cityId } }.map { it[cities.id] }.sorted() assertEquals(2, r.size) // only 2 cities with id 1 and 2 respectively assertEquals(1, r[0]) assertEquals(3, r[1]) // there is no city with id=2 assertNull(r.find { it == cityId }) } } @Test fun testSelectDistinct() { val tbl = DMLTestsData.Cities withTables(tbl) { tbl.insert { it[tbl.name] = "test" } tbl.insert { it[tbl.name] = "test" } assertEquals(2L, tbl.selectAll().count()) assertEquals(2L, tbl.selectAll().withDistinct().count()) assertEquals(1L, tbl.slice(tbl.name).selectAll().withDistinct().count()) assertEquals("test", tbl.slice(tbl.name).selectAll().withDistinct().single()[tbl.name]) } } @Test fun testCompoundOp() { withCitiesAndUsers { _, users, _ -> val allUsers = setOf( "Andrey", "Sergey", "Eugene", "Alex", "Something" ) val orOp = allUsers.map { Op.build { users.name eq it } }.compoundOr() val userNamesOr = users.select(orOp).map { it[users.name] }.toSet() assertEquals(allUsers, userNamesOr) val andOp = allUsers.map { Op.build { users.name eq it } }.compoundAnd() assertEquals(0L, users.select(andOp).count()) } } @Test fun `test select on nullable reference column`() { val firstTable = object : IntIdTable("first") {} val secondTable = object : IntIdTable("second") { val firstOpt = optReference("first", firstTable) } withTables(firstTable, secondTable) { val firstId = firstTable.insertAndGetId { } secondTable.insert { it[firstOpt] = firstId } secondTable.insert { } assertEquals(2L, secondTable.selectAll().count()) val secondEntries = secondTable.select { secondTable.firstOpt eq firstId.value }.toList() assertEquals(1, secondEntries.size) } } @Test fun `test that column length check is not affects select queries`() { val stringTable = object : IntIdTable("StringTable") { val name = varchar("name", 10) } withTables(stringTable) { stringTable.insert { it[name] = "TestName" } assertEquals(1, stringTable.select { stringTable.name eq "TestName" }.count()) val veryLongString = "1".repeat(255) assertEquals(0, stringTable.select { stringTable.name eq veryLongString }.count()) } } }
301
null
480
5,838
eb6e68abc152b7ee1cc73dd05a3827df6938a4b8
8,564
Exposed
Apache License 2.0
app/src/main/java/com/example/musicplayer/localModule/LocalMusicListAdapter.kt
Mimosa0w0
631,589,917
false
null
package com.example.musicplayer.localModule import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.constraintlayout.utils.widget.ImageFilterView import androidx.recyclerview.widget.RecyclerView import com.example.musicplayer.R import com.example.musicplayer.MyViewModel class LocalMusicListAdapter( private val musicList: List<LocalMusic>, private val viewModel: MyViewModel, ) : RecyclerView.Adapter<LocalMusicListAdapter.ViewHolder>() { inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val cover: ImageFilterView = view.findViewById(R.id.cover) val musicName: TextView = view.findViewById(R.id.musicName) val artist: TextView = view.findViewById(R.id.artist) val index: TextView = view.findViewById(R.id.index) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_music, parent, false) val holder = ViewHolder(view) holder.itemView.setOnClickListener { if (viewModel.controllerBinder.musicListLocal.isEmpty()) { viewModel.controllerBinder.musicListLocal.addAll(viewModel.musicListLocal) } val index = holder.index.text.toString().toInt() viewModel.run { Log.d("Mimosa", "Adapter Play") controllerBinder.startMusicLocal(index) upDateCurrentPlay(index, "LocalMusic") } } return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val music = musicList[position] holder.run { musicName.text = music.title artist.text = music.author index.text = position.toString() cover.setImageBitmap(music.pic) } } override fun getItemCount() = musicList.size }
0
Kotlin
0
0
07c6661adbccf2500c16209aaa807a41c599fa07
2,010
MusicPlayer
Apache License 2.0
app/src/main/java/com/twilio/video/app/ui/room/RoomViewEvent.kt
gershire
261,673,245
false
null
package com.twilio.video.app.ui.room import com.twilio.audioswitch.selection.AudioDevice sealed class RoomViewEvent { object ScreenLoad : RoomViewEvent() data class SelectAudioDevice(val device: AudioDevice) : RoomViewEvent() object ActivateAudioDevice : RoomViewEvent() object DeactivateAudioDevice : RoomViewEvent() data class Connect( val identity: String, val roomName: String, val isNetworkQualityEnabled: Boolean ) : RoomViewEvent() data class PinParticipant(val sid: String) : RoomViewEvent() data class ToggleLocalVideo(val sid: String) : RoomViewEvent() data class VideoTrackRemoved(val sid: String) : RoomViewEvent() data class ScreenTrackRemoved(val sid: String) : RoomViewEvent() object Disconnect : RoomViewEvent() }
0
null
0
1
0b6a4d1fed3d7874884a5c44e15bcfb0a2b45d3e
800
twilio-video-app-android
Apache License 2.0
app/src/main/kotlin/com/sbgapps/scoreit/app/ui/edition/universal/UniversalEditionViewModel.kt
StephaneBg
16,022,770
false
null
/* * Copyright 2019 Stéphane Baiget * * 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.sbgapps.scoreit.app.ui.edition.universal import com.sbgapps.scoreit.core.ext.replace import com.sbgapps.scoreit.core.ui.BaseViewModel import com.sbgapps.scoreit.data.interactor.GameUseCase import com.sbgapps.scoreit.data.model.Player import com.sbgapps.scoreit.data.model.UniversalLap import io.uniflow.core.flow.UIState class UniversalEditionViewModel(private val useCase: GameUseCase) : BaseViewModel() { private val editedLap get() = useCase.getEditedLap() as UniversalLap fun loadContent() { setState { getContent() } } fun incrementScore(increment: Int, position: Int) { setState { val oldPoints = editedLap.points val newScore = oldPoints[position] + increment val newPoints = oldPoints.replace(position, newScore) useCase.updateEdition(UniversalLap(newPoints)) getContent() } } fun setScore(position: Int, score: Int) { setState { val newPoints = editedLap.points.replace(position, score) useCase.updateEdition(UniversalLap(newPoints)) getContent() } } fun cancelEdition() { setState { useCase.cancelEdition() UniversalEditionState.Completed } } fun completeEdition() { setState { useCase.completeEdition() UniversalEditionState.Completed } } private fun getContent(): UniversalEditionState.Content = UniversalEditionState.Content( useCase.getPlayers(), editedLap.points ) } sealed class UniversalEditionState : UIState() { data class Content(val players: List<Player>, val results: List<Int>) : UniversalEditionState() object Completed : UniversalEditionState() }
1
null
11
37
7684d40c56c3293b1e9b06158efcbefa51693f7a
2,410
ScoreIt
Apache License 2.0
EuSouDaltonico_app/app/src/main/java/tads/eaj/ufrn/eusoudaltonico_app/ui/model/Desafio.kt
EuNetu
541,246,366
false
null
package tads.eaj.ufrn.eusoudaltonico_app.ui.model class Desafio( var resposta1: String, var resposta2: String, var resposta3: String ) { fun resultadoDoTeste(): String { if (this.resposta1.equals("") || this.resposta2.equals("") || this.resposta3.equals("")) { return "Você deixou algum desafio em branco" } if (this.resposta1.equals("10") && this.resposta2.equals("57") && this.resposta3.equals("7")) { return "Você não é daltônico" } return "Vá a um oftalmologista" } }
0
Kotlin
0
0
bc38e195ca4f1727f1de7a6cb4d6f85779b30256
556
daltonico_teste_app
MIT License
data/src/main/java/com/udacity/political/preparedness/data/util/Constant.kt
RicardoBravoA
321,486,289
false
null
package com.udacity.political.preparedness.data.util object Constant { const val BASE_URL = "https://civicinfo.googleapis.com/civicinfo/v2/" const val GEOCODE_URL = "https://maps.googleapis.com/maps/api/geocode/json" const val DURATION = 10L const val SPACE = " " const val EMPTY = "" }
0
Kotlin
0
1
7b04440ba25aa12ada732603283ea06e35fb4e54
309
PoliticalPreparedness
Apache License 2.0
ArchitectureLib/network/src/main/java/com/notrace/network/mvvm/LiveDataListDataSourceFactory.kt
messnoTrace
179,020,296
false
{"Java": 104721, "Kotlin": 104083}
package com.notrace.network.mvvm import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.paging.DataSource import com.notrace.network.mvvm.base.ApiResponse class LiveDataListDataSourceFactory<T>( val dataSource: (page: Int) -> LiveData<ApiResponse<List<T>>> ) : DataSource.Factory<Int, T>() { val listDataSource = MutableLiveData<LiveDataListDataSource<T>>() override fun create(): DataSource<Int, T> { val designDataSource = LiveDataListDataSource(dataSource) listDataSource.postValue(designDataSource) return designDataSource } }
1
Java
1
2
6c6de7092018309dda5d4c4d4f14f4bf5163ea28
615
Architecture
Apache License 2.0
favorite/favoritedb/src/main/java/com/example/favoritedb/db/FavoritesDatabase.kt
prdp89
391,939,601
false
null
package com.example.favoritedb.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.core.domain.ParameterizedSingleton import com.example.core.entity.FavoriteRepoEntity const val FAVORITES_DB_NAME = "favorites-db" @Database(entities = [FavoriteRepoEntity::class], version = 1, exportSchema = false) abstract class FavoritesDatabase : RoomDatabase() { abstract fun dao(): FavoritesDAO companion object : ParameterizedSingleton<FavoritesDatabase, Context>({ Room.databaseBuilder(it, FavoritesDatabase::class.java, FAVORITES_DB_NAME) .build() }) }
0
Kotlin
0
1
651bd0b582f4b8844181c253cd7a5018d096a648
671
Trending-Git
MIT License
core/src/main/kotlin/fr/xgouchet/elmyr/regex/node/BackReferenceNode.kt
cybernetics
365,665,131
true
{"Kotlin": 447545, "Java": 19634}
package fr.xgouchet.elmyr.regex.node import fr.xgouchet.elmyr.Forge /** * Describe a back reference to a previously captured group. * e.g.: ```/(a*)bc\1/``` */ internal class BackReferenceNode( internal val groupReference: Int, private val parentNode: ParentNode ) : ChildNode { internal lateinit var referencedGroup: GroupNode // region ChildNode override fun getParent(): ParentNode = parentNode // endregion // region Node override fun build(forge: Forge, builder: StringBuilder) { builder.append(referencedGroup.referenceValue) } // endregion }
0
null
0
0
1d4bc5176784fe678a4befdab8f29a15f7756000
609
Elmyr
MIT License
src/main/kotlin/dev/moru3/compsql/datatype/types/numeric/SMALLINT.kt
moruch4nn
386,672,322
false
{"Kotlin": 107931, "Java": 2738}
package dev.moru3.compsql.datatype.types.numeric import dev.moru3.compsql.datatype.BaseDataType import java.sql.PreparedStatement import java.sql.ResultSet import java.sql.Types /** * SmallInt -32768 から 32767 までの整数を格納できるSQLの型です。 * これ以上大きな型が必要な場合は INTEGER, UINTEGER を使用します。 * Unsigned: USMALLINT, Non-Unsigned: SMALLINT * 注意: numeric系のプロパティは"最大数"ではなく"最大桁数"なのでお間違えなく。 */ open class SMALLINT(property: Byte): SmallIntBase<Short>(property) { override val from: Class<Short> = Short::class.javaObjectType override fun get(resultSet: ResultSet, id: String): Short? = resultSet.getShort(id) } abstract class SmallIntBase<F>(val property: Byte): BaseDataType<F, Short> { final override val typeName: String = "SMALLINT" final override val type: Class<Short> = Short::class.javaObjectType final override val sqlType: Int = Types.SMALLINT final override val allowPrimaryKey: Boolean = true final override val allowNotNull: Boolean = true final override val allowUnique: Boolean = true final override val isUnsigned: Boolean = false final override val allowZeroFill: Boolean = true final override val allowAutoIncrement: Boolean = true override val allowDefault: Boolean = true override val defaultProperty: String = "$property" override val priority: Int = 10 override fun set(ps: PreparedStatement, index: Int, any: Any?) { check(any is Number?) { "The type of \"${if(any!=null) any::class.javaObjectType.simpleName else "null"}\" is different from \"Number\"." } super.set(ps, index, any?.toShort()) } }
0
Kotlin
0
2
9c354863cd5ef504adf73f40e7a9993b175e4c38
1,585
CompSQL
MIT License
core/android/src/main/java/com/pilinhas/android/core/android/viewstateholder/ViewStateHolder.kt
pilinhasapp
587,541,347
false
null
package com.pilinhas.android.core.android.viewstateholder import kotlinx.coroutines.flow.StateFlow interface ViewStateHolder<T> { val viewState: StateFlow<T> }
0
Kotlin
0
0
075edd796b36203b4950567aecd303e22a330b43
166
Android
MIT License
dlock-core/src/main/kotlin/com/dlock/core/SimpleLocalKeyLock.kt
pmalirz
166,285,922
false
{"Kotlin": 40973, "Groovy": 6221, "Java": 1584}
package com.dlock.core import com.dlock.core.expiration.LocalLockExpirationPolicy import com.dlock.core.handle.LockHandleUUIDIdGenerator import com.dlock.core.repository.LocalLockRepository import com.dlock.core.util.time.DateTimeProvider /** * Local, memory-based key lock (uses LocalLockRepository). * * @author <NAME> */ object SimpleLocalKeyLock: SimpleKeyLock( LocalLockRepository(), LockHandleUUIDIdGenerator(), LocalLockExpirationPolicy(DateTimeProvider), DateTimeProvider)
0
Kotlin
0
0
f6df7935ce9207432f2d545b50efc321e60d4ed5
518
dlock
MIT License
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/messages/objects/KeyboardReturned.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "SpellCheckingInspection") package name.anton3.vkapi.generated.messages.objects import com.fasterxml.jackson.databind.annotation.JsonDeserialize /** * Keyboard from a received message object * * @property authorId Community or bot, which set this keyboard * @property oneTime Should this keyboard disappear on first use * @property buttons No description * @property inline Should this keyboard be attached to a message instead of a conversation */ @JsonDeserialize(`as` = Void::class) data class KeyboardReturned( val authorId: Long, override val oneTime: Boolean, override val buttons: List<List<KeyboardButton>>, override val inline: Boolean? = null ) : Keyboard
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
717
kotlin-vk-api
MIT License
app/src/main/java/dev/marcosfarias/pokedex/ui/dashboard/DashboardFragment.kt
zsmb13
232,301,179
false
null
package dev.marcosfarias.pokedex.ui.dashboard import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.bumptech.glide.Glide import dev.marcosfarias.pokedex.R import dev.marcosfarias.pokedex.utils.PokemonColorUtil import kotlinx.android.synthetic.main.fragment_dashboard.* class DashboardFragment : Fragment() { private lateinit var dashboardViewModel: DashboardViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel::class.java) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_dashboard, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val id = checkNotNull(arguments?.getString("id")) dashboardViewModel.getPokemonById(id).observe(viewLifecycleOwner, Observer { pokemonValue -> pokemonValue?.let { pokemon -> textViewID.text = pokemon.id textViewName.text = pokemon.name val color = PokemonColorUtil(view.context).getPokemonColor(pokemon.typeofpokemon) app_bar.background.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP) toolbar_layout.contentScrim?.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP) activity?.window?.statusBarColor = PokemonColorUtil(view.context).getPokemonColor(pokemon.typeofpokemon) pokemon.typeofpokemon?.getOrNull(0).let { firstType -> textViewType3.text = firstType textViewType3.isVisible = firstType != null } pokemon.typeofpokemon?.getOrNull(1).let { secondType -> textViewType2.text = secondType textViewType2.isVisible = secondType != null } pokemon.typeofpokemon?.getOrNull(2).let { thirdType -> textViewType1.text = thirdType textViewType1.isVisible = thirdType != null } Glide.with(view.context) .load(pokemon.imageurl) .placeholder(android.R.color.transparent) .into(imageView) val pager = viewPager val tabs = tabs pager.adapter = ViewPagerAdapter(requireFragmentManager(), requireContext(), pokemon.id!!) tabs.setupWithViewPager(pager) } }) } }
0
null
8
48
a2ab162c1de76700e16ba521b1193c503b6b3f84
3,140
Kotlin-Pokedex
MIT License
profilers-android/src/com/android/tools/idea/profilers/AndroidProfilerToolWindow.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.profilers import com.android.ddmlib.IDevice import com.android.tools.adtui.model.AspectObserver import com.android.tools.idea.IdeInfo import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.model.StudioAndroidModuleInfo import com.android.tools.idea.run.AndroidRunConfiguration import com.android.tools.idea.run.deployment.DeviceAndSnapshotComboBoxTargetProvider import com.android.tools.idea.transport.TransportService import com.android.tools.idea.transport.TransportServiceProxy.Companion.getDeviceManufacturer import com.android.tools.idea.transport.TransportServiceProxy.Companion.getDeviceModel import com.android.tools.nativeSymbolizer.ProjectSymbolSource import com.android.tools.nativeSymbolizer.SymbolFilesLocator import com.android.tools.nativeSymbolizer.SymbolSource import com.android.tools.profiler.proto.Common import com.android.tools.profilers.IdeProfilerComponents import com.android.tools.profilers.Notification import com.android.tools.profilers.ProfilerAspect import com.android.tools.profilers.ProfilerClient import com.android.tools.profilers.StudioProfilers import com.android.tools.profilers.taskbased.common.icons.TaskIconUtils import com.android.tools.profilers.taskbased.home.selections.deviceprocesses.ProcessListModel.ToolbarDeviceSelection import com.android.tools.profilers.tasks.ProfilerTaskTabs import com.android.tools.profilers.tasks.ProfilerTaskType import com.android.tools.profilers.tasks.args.TaskArgs import com.android.tools.profilers.tasks.taskhandlers.ProfilerTaskHandler import com.android.tools.profilers.tasks.taskhandlers.ProfilerTaskHandlerFactory import com.intellij.execution.RunManager import com.intellij.openapi.Disposable import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindow import com.intellij.ui.content.Content import org.jetbrains.annotations.VisibleForTesting import java.awt.BorderLayout import java.io.File import java.util.function.Supplier import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel class AndroidProfilerToolWindow(private val window: ToolWindowWrapper, private val project: Project) : AspectObserver(), Disposable { private val ideProfilerServices: IntellijProfilerServices private val ideProfilerComponents: IdeProfilerComponents val profilers: StudioProfilers private var currentTaskHandler: ProfilerTaskHandler? = null private val taskHandlers = HashMap<ProfilerTaskType, ProfilerTaskHandler>() private lateinit var homeTab: StudioProfilersHomeTab private lateinit var homePanel: JPanel private lateinit var pastRecordingsTab: StudioProfilersPastRecordingsTab private lateinit var pastRecordingsPanel: JPanel private lateinit var profilersTab: StudioProfilersTab lateinit var profilersPanel: JPanel private set init { val symbolSource: SymbolSource = ProjectSymbolSource(project) val symbolLocator = SymbolFilesLocator(symbolSource) ideProfilerServices = IntellijProfilerServices(project, symbolLocator) Disposer.register(this, ideProfilerServices) // Ensures the transport service is initialized. TransportService.getInstance() val client = ProfilerClient(TransportService.channelName) profilers = StudioProfilers(client, ideProfilerServices, taskHandlers, { taskType, args -> ProfilerTaskTabs.create(project, taskType, args) }, { ProfilerTaskTabs.open(project) }, { getToolbarDeviceSelections(project) }, { getPreferredProcessName(project) }) val navigator = ideProfilerServices.codeNavigator // CPU ABI architecture, when needed by the code navigator, should be retrieved from StudioProfiler selected session. navigator.cpuArchSource = Supplier { profilers.sessionsManager.selectedSessionMetaData.processAbi } profilers.addDependency(this).onChange(ProfilerAspect.STAGE) { stageChanged() } // Attempt to find the last-run process and start profiling it. This covers the case where the user presses "Run" (without profiling), // but then opens the profiling window manually. val processInfo = project.getUserData(LAST_RUN_APP_INFO) if (processInfo != null) { profilers.setPreferredProcess(processInfo.deviceName, processInfo.processName) { p: Common.Process? -> processInfo.processFilter.invoke(p!!) } project.putUserData(LAST_RUN_APP_INFO, null) } else if (!IdeInfo.getInstance().isGameTools){ StartupManager.getInstance(project).runWhenProjectIsInitialized { profilers.preferredProcessName = getPreferredProcessName(project) } } ideProfilerComponents = IntellijProfilerComponents(project, this, ideProfilerServices.featureTracker) // Create and store the task handlers in a map. initializeTaskHandlers() if (ideProfilerServices.featureConfig.isTaskBasedUxEnabled) { // Initialize the two static/un-closable tabs: home and past recordings tabs. homeTab = StudioProfilersHomeTab(profilers, ideProfilerComponents) homePanel = JPanel(BorderLayout()) homePanel.removeAll() homePanel.add(homeTab.view.panel) homePanel.revalidate() homePanel.repaint() pastRecordingsTab = StudioProfilersPastRecordingsTab(profilers, ideProfilerComponents) pastRecordingsPanel = JPanel(BorderLayout()) pastRecordingsPanel.removeAll() pastRecordingsPanel.add(pastRecordingsTab.view.panel) pastRecordingsPanel.revalidate() pastRecordingsPanel.repaint() } // The Profiler tab is initialized here with the home tab so that the view bindings will be ready in the case the user imports a file // from a fresh/un-opened Profiler tool window state. While entering a stage from an uninitialized Profiler state after importing is // not a possible flow in the Task-Based UX, the initialization of the Profiler tab logic is used for both the Sessions-based Profiler // tab and the Task-Based UX Profiler tab, so it must be called in a place that accommodates both tabs. initializeProfilerTab() } private fun getToolbarDeviceSelections(project: Project): List<ToolbarDeviceSelection> { val devices = DeviceAndSnapshotComboBoxTargetProvider.getInstance().getDeployTarget(project).getAndroidDevices(project) try { val selections = devices.map { ToolbarDeviceSelection(it.name, it.version.featureLevel, it.isRunning, if (it.isRunning) it.launchedDevice.get().serialNumber else "", it.icon) } return selections } catch (e: Exception) { return listOf() } } private fun initializeTaskHandlers() { taskHandlers.clear() taskHandlers.putAll(ProfilerTaskHandlerFactory.createTaskHandlers(profilers.sessionsManager)) } @VisibleForTesting fun createNewTab(component: JComponent, tabName: String, isCloseable: Boolean, icon: Icon? = null) { val contentManager = window.getContentManager() val content = contentManager.factory.createContent(component, tabName, false).also { content -> content.isCloseable = isCloseable icon?.let { content.icon = it content.putUserData(ToolWindow.SHOW_CONTENT_ICON, true) } } contentManager.addContent(content) contentManager.setSelectedContent(content) } private fun findHomeTab(): Content? { val contentManager = window.getContentManager() return if (contentManager.contentCount == 0) null else contentManager.getContent(0) } private fun findPastRecordingsTab(): Content? { val contentManager = window.getContentManager() return if (contentManager.contentCount <= 1) null else contentManager.getContent(1) } private fun findTaskTab(): Content? { val contentManager = window.getContentManager() return when (contentManager.contentCount) { 0 -> null 1 -> null 2 -> null 3 -> contentManager.getContent(2) else -> throw RuntimeException("Profiler window has more than 3 tabs") } } private fun initializeProfilerTab() { profilersTab = if (ideProfilerServices.featureConfig.isTaskBasedUxEnabled) StudioProfilersTaskTab(profilers, ideProfilerComponents) else StudioProfilersSessionTab(profilers, window, ideProfilerComponents, project) Disposer.register(this, profilersTab) profilersPanel = JPanel(BorderLayout()) profilersPanel.removeAll() profilersPanel.add(profilersTab.view.component) profilersPanel.revalidate() profilersPanel.repaint() } fun openHomeTab() { val homeTab = findHomeTab() if (homeTab != null) { window.getContentManager().setSelectedContent(homeTab) } else { createNewTab(homePanel, PROFILER_HOME_TAB_NAME, false) } } fun openPastRecordingsTab() { val pastRecordingsTab = findPastRecordingsTab() if (pastRecordingsTab != null) { window.getContentManager().setSelectedContent(pastRecordingsTab) } else { createNewTab(pastRecordingsPanel, PROFILER_PAST_RECORDINGS_TAB_NAME, false) } } /** * Creates and opens a Profiler task tab for a specified task type. If a task tab has been opened beforehand, the existing tab is reused. */ fun createTaskTab(taskType: ProfilerTaskType, taskArgs: TaskArgs) { val taskTab = findTaskTab() val taskName = taskHandlers[taskType]?.getTaskName() ?: "Task Not Supported Yet" val taskIcon = TaskIconUtils.getTaskIcon(taskType) if (taskTab != null) { taskTab.displayName = taskName window.getContentManager().setSelectedContent(taskTab) window.getContentManager().selectedContent!!.icon = taskIcon } else { createNewTab(profilersPanel, taskName, true, taskIcon) } currentTaskHandler?.exit() currentTaskHandler = taskHandlers[taskType] currentTaskHandler?.let { taskHandler -> val enterSuccessful = taskHandler.enter(taskArgs) } } /** * Opens an existing Profiler task tab. There is at most one existing task tab at any time that can be opened. */ fun openTaskTab() { val taskTab = findTaskTab() if (taskTab != null) { window.getContentManager().setSelectedContent(taskTab) } } /** Sets the profiler's auto-profiling process in case it has been unset. */ fun profile(processInfo: PreferredProcessInfo) { profilers.setPreferredProcess(processInfo.deviceName, processInfo.processName) { p: Common.Process? -> processInfo.processFilter.invoke(p!!) } } /** * Disables auto device+process selection. * See: [StudioProfilers.setAutoProfilingEnabled] */ fun disableAutoProfiling() { profilers.autoProfilingEnabled = false } /** * Tries to import a file into an imported session of the profilers and shows an error balloon if it fails to do so. */ fun openFile(file: VirtualFile) { if (!profilers.sessionsManager.importSessionFromFile(File(file.path))) { ideProfilerServices.showNotification(OPEN_FILE_FAILURE_NOTIFICATION) } } override fun dispose() { profilers.stop() } private fun stageChanged() { if (profilers.isStopped) { window.removeContent() } } companion object { private const val PROFILER_HOME_TAB_NAME = "Home" private const val PROFILER_PAST_RECORDINGS_TAB_NAME = "Past Recordings" /** * Key for storing the last app that was run when the profiler window was not opened. This allows the Profilers to start auto-profiling * that app when the user opens the window at a later time. */ @JvmField val LAST_RUN_APP_INFO = Key.create<PreferredProcessInfo>("Profiler.Last.Run.App") private val OPEN_FILE_FAILURE_NOTIFICATION = Notification( Notification.Severity.ERROR, "Failed to open file", "The profiler was unable to open the selected file. Please try opening it " + "again or select a different file.", null) /** * Analogous to [StudioProfilers.buildDeviceName] but works with an [IDevice] instead. * * @return A string of the format: {Manufacturer Model}. */ @JvmStatic fun getDeviceDisplayName(device: IDevice): String { val manufacturer = getDeviceManufacturer(device) val model = getDeviceModel(device) val serial = device.serialNumber return getDeviceDisplayName(manufacturer, model, serial) } /** * Gets the display name of a device with the given manufacturer, model, and serial string. */ fun getDeviceDisplayName(manufacturer: String, model: String, serial: String): String { var deviceModel = model val deviceNameBuilder = StringBuilder() val suffix = String.format("-%s", serial) if (deviceModel.endsWith(suffix)) { deviceModel = deviceModel.substring(0, deviceModel.length - suffix.length) } if (!StringUtil.isEmpty(manufacturer) && !deviceModel.uppercase().startsWith(manufacturer.uppercase())) { deviceNameBuilder.append(manufacturer) deviceNameBuilder.append(" ") } deviceNameBuilder.append(deviceModel) return deviceNameBuilder.toString() } private fun getPreferredProcessName(project: Project): String? { if (StudioFlags.PROFILER_TASK_BASED_UX.get()) { // There can only be up to one Android app module per selected configuration as the call to getModules can only return up to one // module per AndroidRunConfiguration. return (RunManager.getInstance(project).selectedConfiguration?.configuration as? AndroidRunConfiguration)?.modules?.map { StudioAndroidModuleInfo.getInstance(it) }?.map { it?.packageName }?.firstOrNull() } else { for (module in ModuleManager.getInstance(project).modules) { val moduleName = getModuleName(module) if (moduleName != null) { return moduleName } } return null } } private fun getModuleName(module: Module): String? { val moduleInfo = StudioAndroidModuleInfo.getInstance(module) if (moduleInfo != null) { val pkg = moduleInfo.packageName if (pkg != null) { return pkg } } return null } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
15,159
android
Apache License 2.0
app/src/main/java/com/funs/eye/logic/network/api/MainPageService.kt
hhhcan
507,734,165
false
null
package com.funs.eye.logic.network.api import com.funs.eye.logic.model.* import com.funs.eye.logic.network.ServiceCreator import retrofit2.http.GET import retrofit2.http.Url /** * 主页界面,主要包含:(首页,社区,通知,我的)对应的 API 接口。 * * @author can */ interface MainPageService { /** * 首页-发现列表 */ @GET suspend fun getDiscovery(@Url url: String): Discovery /** * 首页-日报列表 */ @GET suspend fun getDaily(@Url url: String): Daily /** * 社区-推荐列表 */ @GET suspend fun getCommunityRecommend(@Url url: String): CommunityRecommend /** * 社区-关注列表 */ @GET suspend fun gethFollow(@Url url: String): Follow /** * 通知-推送列表 */ @GET suspend fun getPushMessage(@Url url: String): PushMessage companion object { /** * 首页-发现列表 */ const val DISCOVERY_URL = "${ServiceCreator.BASE_URL}api/v7/index/tab/discovery" /** * 首页-日报列表 */ const val DAILY_URL = "${ServiceCreator.BASE_URL}api/v5/index/tab/feed" /** * 社区-推荐列表 */ const val COMMUNITY_RECOMMEND_URL = "${ServiceCreator.BASE_URL}api/v7/community/tab/rec" /** * 社区-关注列表 */ const val FOLLOW_URL = "${ServiceCreator.BASE_URL}api/v6/community/tab/follow" /** * 通知-推送列表 */ const val PUSHMESSAGE_URL = "${ServiceCreator.BASE_URL}api/v3/messages" } }
0
Kotlin
0
0
a127a42d98aa6e8d0d793d74d057f1ac3d5c2799
1,458
FunsEye
Apache License 2.0
airin-gradle-android/src/main/kotlin/io/morfly/airin/feature/AndroidToolchainFeature.kt
Morfly
368,910,388
false
null
package io.morfly.airin.feature import io.morfly.airin.FeatureContext import io.morfly.airin.FeatureComponent import io.morfly.airin.GradleModule import io.morfly.airin.module.RootModule import io.morfly.airin.property import io.morfly.pendant.starlark.android_sdk_repository import io.morfly.pendant.starlark.define_kt_toolchain import io.morfly.pendant.starlark.http_archive import io.morfly.pendant.starlark.kotlin_repositories import io.morfly.pendant.starlark.kotlinc_version import io.morfly.pendant.starlark.lang.context.BuildContext import io.morfly.pendant.starlark.lang.context.WorkspaceContext import io.morfly.pendant.starlark.lang.onContext import io.morfly.pendant.starlark.lang.type.ListType import io.morfly.pendant.starlark.lang.type.StringType import io.morfly.pendant.starlark.maven_install import io.morfly.pendant.starlark.register_toolchains import io.morfly.pendant.starlark.rules_java_dependencies import io.morfly.pendant.starlark.rules_java_toolchains import io.morfly.pendant.starlark.rules_jvm_external_deps import io.morfly.pendant.starlark.rules_jvm_external_setup import org.gradle.api.Project abstract class AndroidToolsFeature : FeatureComponent() { var kotlinToolchainVersion by property("1.8") var kotlinJvmTarget by property("11") var androidApiVersion by property(34) var androidBuildToolsVersion by property("34.0.0") var kotlincVersion by property("1.8.21") var kotlincSha by property("6e43c5569ad067492d04d92c28cdf8095673699d81ce460bd7270443297e8fd7") var rulesJavaVersion by property("6.5.0") var rulesJavaSha by property("160d1ebf33763124766fb35316329d907ca67f733238aa47624a8e3ff3cf2ef4") var rulesJvmExternalVersion by property("4.5") var rulesJvmExternalSha by property("b17d7388feb9bfa7f2fa09031b32707df529f26c91ab9e5d909eb1676badd9a6") var rulesKotlinVersion by property("1.8.1") var rulesKotlinSha by property("a630cda9fdb4f56cf2dc20a4bf873765c41cf00e9379e8d59cd07b24730f4fde") var rulesAndroidVersion by property("0.1.1") var rulesAndroidSha by property("cd06d15dd8bb59926e4d65f9003bfc20f9da4b2519985c27e190cddc8b7a7806") var allowedRepositories by property( mutableListOf( "https://maven.google.com", "https://repo1.maven.org/maven2", ) ) override fun canProcess(target: Project): Boolean = target.plugins.hasPlugin("io.morfly.airin.android") override fun FeatureContext.onInvoke(module: GradleModule) { onContext<BuildContext>(id = RootModule.ID_BUILD) { load("@io_bazel_rules_kotlin//kotlin:core.bzl", "define_kt_toolchain") val KOTLIN_VERSION by kotlinToolchainVersion val JAVA_VERSION by kotlinJvmTarget define_kt_toolchain( name = "kotlin_toolchain", api_version = KOTLIN_VERSION, jvm_target = JAVA_VERSION, language_version = KOTLIN_VERSION, ) } onContext<BuildContext>(id = RootModule.ID_THIRD_PARTY_BUILD) { } onContext<WorkspaceContext>(id = RootModule.ID_WORKSPACE) { comment { "Java" } val RULES_JAVA_VERSION by rulesJavaVersion val RULES_JAVA_SHA by rulesJavaSha http_archive( name = "rules_java", sha256 = RULES_JAVA_SHA, urls = list[ "https://github.com/bazelbuild/rules_java/releases/download/{v}/rules_java-{v}.tar.gz".format { "v" `=` RULES_JAVA_VERSION } ], ) load( "@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains" ) rules_java_dependencies() rules_java_toolchains() comment { "Kotlin" } val RULES_KOTLIN_VERSION by rulesKotlinVersion val RULES_KOTLIN_SHA by rulesKotlinSha http_archive( name = "io_bazel_rules_kotlin", sha256 = RULES_KOTLIN_SHA, urls = list["https://github.com/bazelbuild/rules_kotlin/releases/download/v%s/rules_kotlin_release.tgz" `%` RULES_KOTLIN_VERSION], ) load( "@io_bazel_rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories", "kotlinc_version", ) kotlin_repositories( compiler_release = kotlinc_version( release = kotlincVersion, sha256 = kotlincSha, ), ) register_toolchains("//:kotlin_toolchain") comment { "Android" } val RULES_ANDROID_VERSION by rulesAndroidVersion val RULES_ANDROID_SHA by rulesAndroidSha http_archive( name = "rules_android", sha256 = RULES_ANDROID_SHA, strip_prefix = "rules_android-%s" `%` RULES_ANDROID_VERSION, urls = list["https://github.com/bazelbuild/rules_android/archive/v%s.zip" `%` RULES_ANDROID_VERSION], ) load("@rules_android//android:rules.bzl", "android_sdk_repository") android_sdk_repository( name = "androidsdk", api_level = androidApiVersion, build_tools_version = androidBuildToolsVersion, ) _checkpoint(CHECKPOINT_BEFORE_JVM_EXTERNAL) comment { "JVM External" } val RULES_JVM_EXTERNAL_VERSION by rulesJvmExternalVersion val RULES_JVM_EXTERNAL_SHA by rulesJvmExternalSha http_archive( name = "rules_jvm_external", sha256 = RULES_JVM_EXTERNAL_SHA, strip_prefix = "rules_jvm_external-%s" `%` RULES_JVM_EXTERNAL_VERSION, url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" `%` RULES_JVM_EXTERNAL_VERSION, ) load("@rules_jvm_external//:repositories.bzl", "rules_jvm_external_deps") rules_jvm_external_deps() load("@rules_jvm_external//:setup.bzl", "rules_jvm_external_setup") rules_jvm_external_setup() val MAVEN_ARTIFACTS = load( "//third_party:maven_dependencies.bzl", "MAVEN_ARTIFACTS" ).of<ListType<StringType>>() load("@rules_jvm_external//:defs.bzl", "maven_install") maven_install { _id = ID_MAVEN_INSTALL artifacts = MAVEN_ARTIFACTS repositories = allowedRepositories version_conflict_policy = "pinned" } } } companion object { const val ID_MAVEN_INSTALL = "android_tools_maven_install" const val CHECKPOINT_BEFORE_JVM_EXTERNAL = "checkpoint_before_jvm_external" } }
1
null
5
34
7ba3fada7a1e0e73a758d37447a42ef7f54d338f
6,894
airin
Apache License 2.0
sample/src/main/java/ru/tinkoff/acquiring/sample/ui/AboutActivity.kt
TinkoffCreditSystems
268,528,392
false
null
/* * Copyright © 2020 Tinkoff Bank * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.tinkoff.acquiring.sample.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import ru.tinkoff.acquiring.sample.BuildConfig import ru.tinkoff.acquiring.sample.R /** * @author <NAME> */ class AboutActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) supportActionBar?.setDisplayHomeAsUpEnabled(true) val textViewVersion = findViewById<TextView>(R.id.tv_version) val version = getString(R.string.version, BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE) textViewVersion.text = version } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } companion object { fun start(context: Context) { context.startActivity(Intent(context, AboutActivity::class.java)) } } }
26
null
16
23
6deb46fa37a41292e8065a3d7b944acb2e3eac26
1,803
AcquiringSdkAndroid
Apache License 2.0
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/PrescriptionSolid.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineawesomeicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.LineAwesomeIcons public val LineAwesomeIcons.PrescriptionSolid: ImageVector get() { if (_prescriptionSolid != null) { return _prescriptionSolid!! } _prescriptionSolid = Builder(name = "PrescriptionSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.0f, 3.0f) lineTo(6.0f, 13.0f) lineTo(6.0f, 19.0f) lineTo(8.0f, 19.0f) lineTo(8.0f, 13.0f) lineTo(12.994f, 13.0f) lineTo(17.77f, 21.828f) lineTo(13.107f, 29.0f) lineTo(15.492f, 29.0f) lineTo(19.393f, 23.0f) lineTo(19.607f, 23.0f) lineTo(23.508f, 29.0f) lineTo(25.893f, 29.0f) lineTo(21.244f, 21.852f) lineTo(25.24f, 15.0f) lineTo(22.926f, 15.0f) lineTo(19.514f, 20.85f) lineTo(15.031f, 12.561f) curveTo(16.777f, 11.78f, 18.0f, 10.033f, 18.0f, 8.0f) curveTo(18.0f, 5.243f, 15.757f, 3.0f, 13.0f, 3.0f) lineTo(8.0f, 3.0f) lineTo(6.0f, 3.0f) close() moveTo(8.0f, 5.0f) lineTo(13.0f, 5.0f) curveTo(14.654f, 5.0f, 16.0f, 6.346f, 16.0f, 8.0f) curveTo(16.0f, 9.654f, 14.654f, 11.0f, 13.0f, 11.0f) lineTo(8.0f, 11.0f) lineTo(8.0f, 5.0f) close() } } .build() return _prescriptionSolid!! } private var _prescriptionSolid: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,498
compose-icons
MIT License
ktor-network/jvm/src/io/ktor/network/sockets/CIOWriter.kt
ktorio
40,136,600
false
null
package io.ktor.network.sockets import io.ktor.network.selector.* import kotlinx.coroutines.* import kotlinx.coroutines.io.* import kotlinx.coroutines.io.ByteChannel import kotlinx.io.pool.* import java.nio.* import java.nio.channels.* import kotlin.coroutines.* internal fun CoroutineScope.attachForWritingImpl( channel: ByteChannel, nioChannel: WritableByteChannel, selectable: Selectable, selector: SelectorManager, pool: ObjectPool<ByteBuffer> ): ReaderJob { val buffer = pool.borrow() return reader(Dispatchers.Unconfined, channel) { try { while (true) { buffer.clear() if (channel.readAvailable(buffer) == -1) { break } buffer.flip() while (buffer.hasRemaining()) { val rc = nioChannel.write(buffer) if (rc == 0) { selectable.interestOp(SelectInterest.WRITE, true) selector.select(selectable, SelectInterest.WRITE) } else { selectable.interestOp(SelectInterest.WRITE, false) } } } } finally { pool.recycle(buffer) if (nioChannel is SocketChannel) { try { nioChannel.shutdownOutput() } catch (ignore: ClosedChannelException) { } } } } } internal fun CoroutineScope.attachForWritingDirectImpl( channel: ByteChannel, nioChannel: WritableByteChannel, selectable: Selectable, selector: SelectorManager ): ReaderJob { return reader(Dispatchers.Unconfined, channel) { selectable.interestOp(SelectInterest.WRITE, false) try { channel.lookAheadSuspend { while (true) { val buffer = request(0, 1) if (buffer == null) { // if (channel.isClosedForRead) break if (!awaitAtLeast(1)) break continue } while (buffer.hasRemaining()) { val r = nioChannel.write(buffer) if (r == 0) { selectable.interestOp(SelectInterest.WRITE, true) selector.select(selectable, SelectInterest.WRITE) } else { consumed(r) } } } } } finally { selectable.interestOp(SelectInterest.WRITE, false) if (nioChannel is SocketChannel) { try { nioChannel.shutdownOutput() } catch (ignore: ClosedChannelException) { } } } } }
303
null
958
9,709
9e0eb99aa2a0a6bc095f162328525be1a76edb21
2,910
ktor
Apache License 2.0
app/src/main/java/com/nightwalker/runnersstopwatch/fragments/splash/SplashFragment.kt
mihailolukic
393,330,102
false
null
package com.nightwalker.runnersstopwatch.fragments.splash import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.Navigation import com.nightwalker.runnersstopwatch.R import com.nightwalker.runnersstopwatch.databinding.FragmentSplashBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class SplashFragment : Fragment() { private val viewModel: SplashViewModel by viewModels() private lateinit var binding: FragmentSplashBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentSplashBinding.inflate(inflater, container, false) binding.proceedOnNextScreen.setOnClickListener( Navigation.createNavigateOnClickListener(R.id.action_splashFragment_to_stopwatchFragment) ) return binding.root } }
0
Kotlin
0
0
7017939fd9b0a6edb715cb804a5d25b8d7f25287
1,118
RunnersStopwatch
Apache License 2.0
models/src/commonMain/kotlin/com/revenuecat/purchases/kmp/models/PurchasingData.kt
RevenueCat
758,647,648
false
{"Kotlin": 339864, "Ruby": 17314, "Swift": 594}
package com.revenuecat.purchases.kmp.models import com.revenuecat.purchases.kmp.ProductType /** * Data connected to a purchase. */ public expect interface PurchasingData { public val productId: String public val productType: ProductType }
6
Kotlin
2
68
7c60a7131a5b7aa0476078ea7a86f7e6dd59de84
251
purchases-kmp
MIT License
app/src/test/java/com/balocco/androidcomponents/feature/toprated/viewmodel/TopRatedViewModelTest.kt
AlexBalo
285,021,731
false
null
package com.balocco.androidcomponents.feature.toprated.viewmodel import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.balocco.androidcomponents.R import com.balocco.androidcomponents.TestUtils import com.balocco.androidcomponents.common.navigation.Navigator import com.balocco.androidcomponents.common.scheduler.TestSchedulerProvider import com.balocco.androidcomponents.common.viewmodel.State import com.balocco.androidcomponents.data.model.Movie import com.balocco.androidcomponents.data.model.MoviesPage import com.balocco.androidcomponents.feature.toprated.domain.FetchTopRatedMoviesUseCase import com.balocco.androidcomponents.feature.toprated.domain.LoadTopRatedMoviesUseCase import com.nhaarman.mockito_kotlin.* import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Single import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mock import org.mockito.MockitoAnnotations class TopRatedViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() private lateinit var viewModel: TopRatedViewModel @Captor private lateinit var moviesCaptor: ArgumentCaptor<TopRatedState> @Mock private lateinit var navigator: Navigator @Mock private lateinit var observer: Observer<TopRatedState> @Mock private lateinit var topRatedPaginator: TopRatedPaginator @Mock private lateinit var fetchTopRatedMoviesUseCase: FetchTopRatedMoviesUseCase @Mock private lateinit var loadTopRatedMoviesUseCase: LoadTopRatedMoviesUseCase @Before fun setUp() { MockitoAnnotations.initMocks(this) viewModel = TopRatedViewModel( TestSchedulerProvider(), topRatedPaginator, fetchTopRatedMoviesUseCase, loadTopRatedMoviesUseCase ) viewModel.topRatedState().observeForever(observer) } @Test fun `When started no movies locally, updates observers with loading state`() { val movies = listOf(TestUtils.createMovie("1"), TestUtils.createMovie("2")) val moviesPage = createMoviePage(movies) whenever(loadTopRatedMoviesUseCase()).thenReturn(Flowable.just(emptyList())) whenever(fetchTopRatedMoviesUseCase()).thenReturn(Single.just(moviesPage)) viewModel.start() verify(observer).onChanged(moviesCaptor.capture()) val loadingState = moviesCaptor.value assertEquals(State.LOADING, loadingState.state) assertTrue(loadingState.results.isEmpty()) assertEquals(0, loadingState.errorMessage) verify(fetchTopRatedMoviesUseCase)(1) } @Test fun `When started and movies already available, updates observers with success state`() { val movies = mutableListOf(TestUtils.createMovie("11"), TestUtils.createMovie("12")) whenever(loadTopRatedMoviesUseCase()).thenReturn(Flowable.just(movies)) viewModel.start() verify(observer, times(1)).onChanged(moviesCaptor.capture()) val successState = moviesCaptor.value assertEquals(State.SUCCESS, successState.state) assertEquals(movies, successState.results) assertEquals(0, successState.errorMessage) verify(fetchTopRatedMoviesUseCase, never())(1) } @Test fun `When started and movies fetched with error, updates observers with error state`() { whenever(fetchTopRatedMoviesUseCase()).thenReturn(Single.error(Throwable())) whenever(loadTopRatedMoviesUseCase()).thenReturn(Flowable.just(emptyList())) viewModel.start() // We get invokation for the loading state and error when fetching data verify(observer, times(2)).onChanged(moviesCaptor.capture()) val loadingState = moviesCaptor.allValues[1] assertEquals(State.ERROR, loadingState.state) assertTrue(loadingState.results.isEmpty()) assertEquals(R.string.error_loading_movies, loadingState.errorMessage) } @Test fun `When movies fetched with error, notifies paginator`() { whenever(fetchTopRatedMoviesUseCase()).thenReturn(Single.error(Throwable())) whenever(loadTopRatedMoviesUseCase()).thenReturn(Flowable.just(emptyList())) viewModel.start() verify(topRatedPaginator).pageError() } @Test fun `When movie selected, navigates to detail view`() { val movie = TestUtils.createMovie("12") viewModel.setNavigator(navigator) viewModel.onMovieSelected(movie) verify(navigator).goToDetail(movie.id) } @Test fun `When list scrolled no pagination, does not fetch new page`() { whenever(topRatedPaginator.canPaginate(5)).thenReturn(false) viewModel.onListScrolled(5) verify(fetchTopRatedMoviesUseCase, never())(any()) } @Test fun `When list scrolled pagination possible, fetches next page`() { val movies = mutableListOf(TestUtils.createMovie("11"), TestUtils.createMovie("12")) val moviesPage = createMoviePage(movies) whenever(fetchTopRatedMoviesUseCase(6)).thenReturn(Single.just(moviesPage)) whenever(topRatedPaginator.canPaginate(5)).thenReturn(true) whenever(topRatedPaginator.nextPage()).thenReturn(6) viewModel.onListScrolled(5) verify(fetchTopRatedMoviesUseCase)(6) } private fun createMoviePage(movies: List<Movie>): MoviesPage = MoviesPage( page = 1, totalPages = 10, totalResults = 1000, results = movies ) }
0
Kotlin
0
0
8c6909841af60db6d3370793a4383d6bdacf2d42
5,711
AndroidComponents
Apache License 2.0
src/main/kotlin/com/dp/advancedgunnerycontrol/combatgui/buttongroups/CreateSimpleButtons.kt
DesperatePeter
361,380,141
false
null
package com.dp.advancedgunnerycontrol.combatgui.buttongroups /** * Simple implementation of CreateButtonsAction interface that creates * a button for each entry in names. * @param names list of display names of buttons. Must not be null and defines the number of buttons created * @param data list of data that buttons shall contain. If null or too short, button names will be used as data. * @param tooltips list of tooltips to use for buttons. If null or too short, no tooltip will be used. */ class CreateSimpleButtons( private val names: List<String>, private val data: List<Any>?, private val tooltips: List<String>? ) : CreateButtonsAction { override fun createButtons(group: DataButtonGroup) { names.forEachIndexed { index, s -> val d = data?.getOrNull(index) ?: s val tt = tooltips?.getOrNull(index) ?: "" group.addButton(s, d, tt, false) } } }
2
Kotlin
3
9
514c3a1b9bd3f16ad6d0c602c9d9bdd9b50fb9fb
931
starsector-advanced-weapon-control
MIT License
v_shared_packages/v_chat_media_editor/media_example/android/app/src/main/kotlin/com/example/media_example/MainActivity.kt
hatemragab
388,805,542
false
null
package com.example.media_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
20
42
efa20b4b2e1426404c2f50020d08975d572f0d19
130
v_chat_sdk
MIT License
page/src/main/java/dev/entao/keb/page/bootstrap/BootImage.kt
yangentao
213,028,942
false
null
package dev.entao.keb.page.bootstrap import dev.entao.keb.page.tag.* fun Tag.imgFluid(vararg kv: HKeyValue, block: TagCallback): Tag { return this.tag("img", class_ to _img_fluid, *kv, block = block) } fun Tag.imgThumbnail(vararg kv: HKeyValue, block: TagCallback): Tag { return this.tag("img", class_ to _img_thumbnail, *kv, block = block) } fun Tag.figure(vararg kv: HKeyValue, block: TagCallback): Tag { return this.tag("figure", class_ to _figure, *kv, block = block) } fun Tag.figureCaption(vararg kv: HKeyValue, block: TagCallback): Tag { return this.tag("figcaption", class_ to _figure_caption, *kv, block = block) } fun Tag.figureImage(vararg kv: HKeyValue, block: TagCallback): Tag { return this.tag("img", class_ to _figure_img.._img_fluid.._rounded, *kv, block = block) }
0
Kotlin
0
0
f428379568e33c3f63d6fe9b2f1bf794271d0a2a
793
KebPage
MIT License
src/main/kotlin/cn/yiiguxing/plugin/figlet/TestAllFontsDialog.kt
YiiGuxing
167,921,297
false
null
package cn.yiiguxing.plugin.figlet import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.ex.DocumentEx import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.ui.CollectionListModel import com.intellij.ui.JBColor import com.intellij.ui.SingleSelectionModel import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import org.slf4j.LoggerFactory import java.awt.Component import javax.swing.* class TestAllFontsDialog(project: Project, parent: Component) : DialogWrapper(parent, false) { private val testModel = CollectionListModel<TestItem>(ArrayList(NUMBER_OF_FONTS)) private val testList = JBList<TestItem>(testModel) private var disposed = false init { init() title = "Fonts" setOKButtonText("Use Font") isOKActionEnabled = false initList(project) runTestTask(project) } private fun initList(project: Project) = with(testList) { setPaintBusy(true) selectionModel = SingleSelectionModel() background = JBColor(0xE8E8E8, 0x4C5052) addListSelectionListener { isOKActionEnabled = testList.selectedValue != null } val viewer = Previews.createPreviewViewer(project).apply { settings.isLineNumbersShown = false setBorder(JBEmptyBorder(JBUI.insets(10))) component.border = JBEmptyBorder(2) } Disposer.register(disposable, Disposable { Previews.releasePreviewViewer(viewer) }) val title = JLabel().apply { border = JBEmptyBorder(JBUI.insets(8)) } val item = BorderLayoutPanel().apply { isOpaque = true addToTop(title) addToCenter(viewer.component) } cellRenderer = object : ListCellRenderer<TestItem> { override fun getListCellRendererComponent( list: JList<out TestItem>, value: TestItem, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { title.text = value.fontName WriteCommandAction.runWriteCommandAction(project) { (viewer.document as DocumentEx).apply { setReadOnly(false) replaceString(0, textLength, value.effectText) clearLineModificationFlags() setReadOnly(true) } } if (isSelected) { val foreground = list.selectionForeground title.foreground = foreground item.foreground = foreground val background = list.selectionBackground item.background = background viewer.component.background = background } else { val foreground = list.foreground title.foreground = foreground item.foreground = foreground val background = list.background item.background = background viewer.component.background = background } item.revalidate() return item } } } private fun runTestTask(project: Project) { val task = TestTask(project) val indicator = BackgroundableProcessIndicator(task) Disposer.register(disposable, indicator) ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, indicator) } override fun createActions(): Array<Action> = arrayOf(okAction, cancelAction) override fun createCenterPanel(): JComponent { return JBScrollPane(testList) .apply { preferredSize = JBDimension(600, 750) } } fun showAndGetResult(): String? { val isOk = showAndGet() return testList.selectedValue?.takeIf { isOk }?.fontName } override fun dispose() { super.dispose() disposed = true } companion object { private val NUMBER_OF_FONTS = FIGlet.fonts.size private val LOGGER = LoggerFactory.getLogger(TestAllFontsDialog::class.java) } private data class TestItem(val fontName: String, val effectText: String) private inner class TestTask(project: Project?) : Task.Backgroundable(project, "FIGlet") { override fun run(indicator: ProgressIndicator) { val fonts = FIGlet.fonts for (i in fonts.indices) { val fontName = fonts[i] indicator.checkCanceled() indicator.text = "Testing $fontName..." try { onTestFont(fontName) } catch (error: Throwable) { onThrowable(IllegalStateException("Test failed: $fontName.", error)) } indicator.fraction = (i + 1.0) / NUMBER_OF_FONTS } finish() } private fun onTestFont(fontName: String) { val font = FIGlet.getFigFont(fontName) val artText = FIGlet.generate(fontName, font) val effectText = FIGlet.trimArtText(artText) val testItem = TestItem(fontName, effectText) ApplicationManager.getApplication().invokeAndWait({ if (!disposed) { testModel.add(testItem) } }, ModalityState.any()) } override fun onThrowable(error: Throwable) { LOGGER.error("Some fault occurred.", error) } private fun finish() { ApplicationManager.getApplication().invokeLater({ if (!disposed) { testList.setPaintBusy(false) } }, ModalityState.any()) } } }
0
Kotlin
5
35
e4d9a915d8f7f65137d22bad70539b1e072ed9e3
6,550
intellij-figlet
MIT License
plugins/kotlin/idea/tests/testData/refactoring/bindToElement/extensionProperty/SafeAccess.kt
JetBrains
2,489,216
false
null
// BIND_TO test.barFoo package test fun foo() { val x: Any? = null x?.<caret>fooBar } val Any?.fooBar: Any? = null val Any?.barFoo: Any? = null
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
154
intellij-community
Apache License 2.0
chat-core/src/main/java/com/fzm/chat/core/session/UserDataSource.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.core.session import com.fzm.chat.core.data.bean.Field import com.fzm.chat.core.data.bean.ChatQuery import com.fzm.chat.core.data.bean.ServerGroupInfo import com.zjy.architecture.data.Result /** * @author zhengjy * @since 2020/12/04 * Description: */ interface UserDataSource { /** * 获取用户自己的信息 */ suspend fun getUserInfo(address: String, publicKey: String, query: ChatQuery): Result<UserInfo> /** * 退出登录清空用户信息 */ suspend fun logout(address: String) /** * 设置用户信息 */ suspend fun setUserInfo(fields: List<Field>): Result<String> /** * 修改分组列表信息 * * @param groupInfo 分组信息 */ suspend fun modifyServerGroup(groupInfo: List<ServerGroupInfo>): Result<String> }
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
765
ChatPro-Android
MIT License
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/logos/BxlWhatsappSquare.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.boxicons.boxicons.logos import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.boxicons.boxicons.LogosGroup public val LogosGroup.BxlWhatsappSquare: ImageVector get() { if (_bxlWhatsappSquare != null) { return _bxlWhatsappSquare!! } _bxlWhatsappSquare = Builder(name = "BxlWhatsappSquare", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.043f, 6.925f) arcToRelative(4.985f, 4.985f, 0.0f, false, false, -4.98f, 4.979f) curveToRelative(-0.001f, 0.94f, 0.263f, 1.856f, 0.761f, 2.649f) lineToRelative(0.118f, 0.188f) lineToRelative(-0.503f, 1.837f) lineToRelative(1.885f, -0.494f) lineToRelative(0.181f, 0.108f) arcToRelative(4.97f, 4.97f, 0.0f, false, false, 2.535f, 0.693f) horizontalLineToRelative(0.001f) arcToRelative(4.986f, 4.986f, 0.0f, false, false, 4.979f, -4.978f) arcToRelative(4.946f, 4.946f, 0.0f, false, false, -1.456f, -3.522f) arcToRelative(4.946f, 4.946f, 0.0f, false, false, -3.521f, -1.46f) close() moveTo(14.971f, 14.043f) curveToRelative(-0.125f, 0.35f, -0.723f, 0.668f, -1.01f, 0.711f) arcToRelative(2.044f, 2.044f, 0.0f, false, true, -0.943f, -0.059f) arcToRelative(8.51f, 8.51f, 0.0f, false, true, -0.853f, -0.315f) curveToRelative(-1.502f, -0.648f, -2.482f, -2.159f, -2.558f, -2.26f) curveToRelative(-0.074f, -0.1f, -0.61f, -0.812f, -0.61f, -1.548f) curveToRelative(0.0f, -0.737f, 0.386f, -1.099f, 0.523f, -1.249f) arcToRelative(0.552f, 0.552f, 0.0f, false, true, 0.4f, -0.186f) curveToRelative(0.1f, 0.0f, 0.199f, 0.001f, 0.287f, 0.005f) curveToRelative(0.092f, 0.004f, 0.215f, -0.035f, 0.336f, 0.257f) curveToRelative(0.125f, 0.3f, 0.425f, 1.036f, 0.462f, 1.111f) curveToRelative(0.037f, 0.074f, 0.062f, 0.162f, 0.013f, 0.262f) curveToRelative(-0.05f, 0.101f, -0.074f, 0.162f, -0.15f, 0.25f) curveToRelative(-0.074f, 0.088f, -0.157f, 0.195f, -0.224f, 0.263f) curveToRelative(-0.075f, 0.074f, -0.153f, 0.155f, -0.066f, 0.305f) curveToRelative(0.088f, 0.149f, 0.388f, 0.64f, 0.832f, 1.037f) curveToRelative(0.572f, 0.51f, 1.055f, 0.667f, 1.204f, 0.743f) curveToRelative(0.15f, 0.074f, 0.237f, 0.063f, 0.325f, -0.038f) curveToRelative(0.087f, -0.101f, 0.374f, -0.437f, 0.474f, -0.586f) curveToRelative(0.1f, -0.15f, 0.199f, -0.125f, 0.337f, -0.076f) curveToRelative(0.137f, 0.051f, 0.873f, 0.412f, 1.022f, 0.487f) curveToRelative(0.148f, 0.074f, 0.249f, 0.112f, 0.287f, 0.175f) curveToRelative(0.036f, 0.062f, 0.036f, 0.361f, -0.088f, 0.711f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 3.0f) lineTo(4.0f, 3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, 1.0f) verticalLineToRelative(16.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f) horizontalLineToRelative(16.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f) lineTo(21.0f, 4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f) close() moveTo(12.04f, 17.896f) horizontalLineToRelative(-0.002f) arcToRelative(5.98f, 5.98f, 0.0f, false, true, -2.862f, -0.729f) lineTo(6.0f, 18.0f) lineToRelative(0.85f, -3.104f) arcToRelative(5.991f, 5.991f, 0.0f, false, true, 5.19f, -8.983f) arcToRelative(5.95f, 5.95f, 0.0f, false, true, 4.238f, 1.757f) arcToRelative(5.95f, 5.95f, 0.0f, false, true, 1.751f, 4.237f) arcToRelative(5.998f, 5.998f, 0.0f, false, true, -5.989f, 5.989f) close() } } .build() return _bxlWhatsappSquare!! } private var _bxlWhatsappSquare: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
5,477
compose-icon-collections
MIT License
Squadris/src/main/java/com/squadris/squadris/compose/components/CustomPullRefresh.kt
JacobCube
683,485,839
false
null
package com.squadris.squadris.compose.components import android.app.Activity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.pullrefresh.PullRefreshState import androidx.compose.material.pullrefresh.pullRefreshIndicatorTransform 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.platform.LocalConfiguration import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.squadris.squadris.R import com.squadris.squadris.compose.theme.Colors import com.squadris.squadris.ext.isTablet private const val REFRESH_WIDTH_PERCENTILE_PHONE = 0.25 private const val REFRESH_WIDTH_PERCENTILE_TABLET = 0.175 const val REFRESH_RETURN_ANIMATION_LENGTH = 600L @OptIn(ExperimentalMaterialApi::class) @Composable fun CustomPullRefresh( modifier: Modifier = Modifier, isRefreshing: Boolean, state: PullRefreshState, content: @Composable (isRefreshing: Boolean) -> Unit = { } ) { Box( modifier = modifier .fillMaxWidth() .pullRefreshIndicatorTransform(state), contentAlignment = Alignment.BottomCenter ) { content(isRefreshing) } } @Composable fun getDefaultPullRefreshSize(isTablet: Boolean): Dp { return (LocalConfiguration.current.screenWidthDp).times(if(isTablet) { REFRESH_WIDTH_PERCENTILE_TABLET }else REFRESH_WIDTH_PERCENTILE_PHONE).dp } /** Gives random loading lottie animation */ val randomLoadingLottieAnim: Pair<Int, Color> get() = listOf( R.raw.loading_animation_3a3a3a to Colors.LOADING_ANIMATION_3a3a3a, R.raw.loading_animation_45ddd2 to Colors.LOADING_ANIMATION_45ddd2, R.raw.loading_animation_755334 to Colors.LOADING_ANIMATION_755334, R.raw.loading_animation_798c8e to Colors.LOADING_ANIMATION_798c8e, R.raw.loading_animation_88fcac to Colors.LOADING_ANIMATION_88fcac, R.raw.loading_animation_a6dfff to Colors.LOADING_ANIMATION_a6dfff, R.raw.loading_animation_a87b2a to Colors.LOADING_ANIMATION_a87b2a, R.raw.loading_animation_aa7d2e to Colors.LOADING_ANIMATION_aa7d2e, R.raw.loading_animation_bcd8cb to Colors.LOADING_ANIMATION_bcd8cb, R.raw.loading_animation_c0e0ed to Colors.LOADING_ANIMATION_c0e0ed, R.raw.loading_animation_c0f3ff to Colors.LOADING_ANIMATION_c0f3ff, R.raw.loading_animation_c19a2d to Colors.LOADING_ANIMATION_c19a2d, R.raw.loading_animation_c1a58e to Colors.LOADING_ANIMATION_c1a58e, R.raw.loading_animation_c5eae8 to Colors.LOADING_ANIMATION_c5eae8, R.raw.loading_animation_cebb8e to Colors.LOADING_ANIMATION_cebb8e, R.raw.loading_animation_d5edef to Colors.LOADING_ANIMATION_d5edef, R.raw.loading_animation_e2c888 to Colors.LOADING_ANIMATION_e2c888, R.raw.loading_animation_e51749 to Colors.LOADING_ANIMATION_e51749, R.raw.loading_animation_e8e1cf to Colors.LOADING_ANIMATION_e8e1cf, R.raw.loading_animation_efc6f7 to Colors.LOADING_ANIMATION_efc6f7, R.raw.loading_animation_f27d2f to Colors.LOADING_ANIMATION_f27d2f, R.raw.loading_animation_f8ffb6 to Colors.LOADING_ANIMATION_f8ffb6, R.raw.loading_animation_fcc0de to Colors.LOADING_ANIMATION_fcc0de, R.raw.loading_animation_ff0000 to Colors.LOADING_ANIMATION_ff0000, R.raw.loading_animation_ffb6ae to Colors.LOADING_ANIMATION_ffb6ae, R.raw.loading_animation_ffdbc0 to Colors.LOADING_ANIMATION_ffdbc0, R.raw.loading_animation_fff4c0 to Colors.LOADING_ANIMATION_fff4c0, ).random()
0
Kotlin
0
0
ff06694f062c3b9a5c648ce1705ce2b26121eda2
3,769
Study-me-please
Apache License 2.0
android/app/src/test/java/com/yubico/authenticator/device/InfoTest.kt
Yubico
16,949,032
false
{"Dart": 1512777, "Kotlin": 295587, "Python": 119028, "C++": 26701, "CMake": 19488, "Shell": 12660, "Swift": 1903, "C": 1425, "Ruby": 1330, "PowerShell": 1243, "Batchfile": 1008}
/* * Copyright (C) 2023 Yubico. * * 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.yubico.authenticator.device import com.yubico.yubikit.core.Transport import com.yubico.yubikit.core.Version import com.yubico.yubikit.management.DeviceInfo import com.yubico.yubikit.management.FormFactor import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import org.mockito.Mockito.`when` class InfoTest { @Test fun construction() { val deviceInfo = deviceInfoMock `when`(deviceInfo.serialNumber).thenReturn(1234) `when`(deviceInfo.version).thenReturn(Version(1, 2, 3)) `when`(deviceInfo.formFactor).thenReturn(FormFactor.USB_C_KEYCHAIN) `when`(deviceInfo.isLocked).thenReturn(true) `when`(deviceInfo.isSky).thenReturn(false) `when`(deviceInfo.isFips).thenReturn(true) `when`(deviceInfo.hasTransport(Transport.NFC)).thenReturn(true) `when`(deviceInfo.hasTransport(Transport.USB)).thenReturn(true) `when`(deviceInfo.getSupportedCapabilities(Transport.USB)).thenReturn(456) `when`(deviceInfo.getSupportedCapabilities(Transport.NFC)).thenReturn(789) val info = Info(name = "TestD", isNfc = true, usbPid = null, deviceInfo = deviceInfo) assertEquals(Config(deviceConfigMock), info.config) assertEquals(1234, info.serialNumber) assertEquals(Version(1, 2, 3).major, info.version.major) assertEquals(Version(1, 2, 3).minor, info.version.minor) assertEquals(Version(1, 2, 3).micro, info.version.micro) assertEquals(FormFactor.USB_C_KEYCHAIN.value, info.formFactor) assertTrue(info.isLocked) assertFalse(info.isSky) assertTrue(info.isFips) assertEquals(456, info.supportedCapabilities.usb) assertEquals(789, info.supportedCapabilities.nfc) assertEquals("TestD", info.name) assertTrue(info.isNfc) assertNull(info.usbPid) } private fun DeviceInfo.withTransport(transport: Transport, capabilities : Int = 0) : DeviceInfo { `when`(hasTransport(transport)).thenReturn(true) `when`(getSupportedCapabilities(transport)).thenReturn(capabilities) return this } private fun DeviceInfo.withoutTransport(transport: Transport) : DeviceInfo { `when`(hasTransport(transport)).thenReturn(false) return this } @Test fun withNfcCapabilities() { val deviceInfo = deviceInfoMock.withTransport(Transport.NFC, 123) val info = Info(name = "TestD", isNfc = false, usbPid = null, deviceInfo = deviceInfo) assertEquals(123, info.supportedCapabilities.nfc) } @Test fun withoutNfcCapabilities() { val deviceInfo = deviceInfoMock.withoutTransport(Transport.NFC) val info = Info(name = "TestD", isNfc = false, usbPid = null, deviceInfo = deviceInfo) assertNull(info.supportedCapabilities.nfc) } @Test fun withUsbCapabilities() { val deviceInfo = deviceInfoMock.withTransport(Transport.USB, 454) val info = Info(name = "TestD", isNfc = false, usbPid = null, deviceInfo = deviceInfo) assertEquals(454, info.supportedCapabilities.usb) } @Test fun withoutUsbCapabilities() { val deviceInfo = deviceInfoMock.withoutTransport(Transport.USB) val info = Info(name = "TestD", isNfc = false, usbPid = null, deviceInfo = deviceInfo) assertNull(info.supportedCapabilities.usb) } }
55
Dart
136
999
353766bc01c24909d55384354f87bad71c170516
4,085
yubioath-flutter
Apache License 2.0
src/main/kotlin/nobility/downloader/ui/views/SettingsView.kt
NobilityDeviant
836,259,311
false
null
package nobility.downloader.ui.views import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.darkrockstudios.libraries.mpfilepicker.DirectoryPicker import com.darkrockstudios.libraries.mpfilepicker.FilePicker import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import nobility.downloader.core.BoxHelper import nobility.downloader.core.BoxHelper.Companion.boolean import nobility.downloader.core.BoxHelper.Companion.intString import nobility.downloader.core.BoxHelper.Companion.string import nobility.downloader.core.BoxHelper.Companion.update import nobility.downloader.core.Core import nobility.downloader.core.settings.Defaults import nobility.downloader.core.settings.Quality import nobility.downloader.ui.components.* import nobility.downloader.ui.components.dialog.DialogHelper import nobility.downloader.ui.windows.utils.AppWindowScope import nobility.downloader.ui.windows.utils.ApplicationState import nobility.downloader.utils.Constants.maxThreads import nobility.downloader.utils.Constants.maxTimeout import nobility.downloader.utils.Constants.minThreads import nobility.downloader.utils.Constants.minTimeout import nobility.downloader.utils.FrogLog import nobility.downloader.utils.Tools import nobility.downloader.utils.fileExists import nobility.downloader.utils.tone import org.jsoup.Jsoup import java.util.regex.Matcher import java.util.regex.Pattern class SettingsView { private var threads by mutableStateOf( Defaults.DOWNLOAD_THREADS.intString() ) private var timeout by mutableStateOf( Defaults.TIMEOUT.intString() ) private var saveFolder by mutableStateOf( Defaults.SAVE_FOLDER.string() ) private var proxy by mutableStateOf( Defaults.PROXY.string() ) private var wcoDomain by mutableStateOf( Defaults.WCO_DOMAIN.string() ) private var wcoExtension by mutableStateOf( Defaults.WCO_EXTENSION.string() ) private var chromePath by mutableStateOf( Defaults.CHROME_BROWSER_PATH.string() ) private var chromeDriverPath by mutableStateOf( Defaults.CHROME_DRIVER_PATH.string() ) private var quality by mutableStateOf( Defaults.QUALITY.string() ) private var proxyEnabled = mutableStateOf(false) private var debugMessages = mutableStateOf( Defaults.SHOW_DEBUG_MESSAGES.boolean() ) private var bypassDiskSpace = mutableStateOf( Defaults.BYPASS_DISK_SPACE.boolean() ) private var showTooltips = mutableStateOf( Defaults.SHOW_TOOLTIPS.boolean() ) private var consoleOnTop = mutableStateOf( Defaults.CONSOLE_ON_TOP.boolean() ) private var headlessMode = mutableStateOf( Defaults.HEADLESS_MODE.boolean() ) private var separateSeasons = mutableStateOf( Defaults.SEPARATE_SEASONS.boolean() ) private var autoScrollConsoles = mutableStateOf( Defaults.AUTO_SCROLL_CONSOLES.boolean() ) private var ctrlForHotKeys = mutableStateOf( Defaults.CTRL_FOR_HOTKEYS.boolean() ) private var disableUserAgentsUpdate = mutableStateOf( Defaults.DISABLE_USER_AGENTS_UPDATE.boolean() ) private var disableWcoUrlsUpdate = mutableStateOf( Defaults.DISABLE_WCO_URLS_UPDATE.boolean() ) private var disableDubbedUpdate = mutableStateOf( Defaults.DISABLE_DUBBED_UPDATE.boolean() ) private var disableSubbedUpdate = mutableStateOf( Defaults.DISABLE_SUBBED_UPDATE.boolean() ) private var disableCartoonUpdate = mutableStateOf( Defaults.DISABLE_CARTOON_UPDATE.boolean() ) private var disableMoviesUpdate = mutableStateOf( Defaults.DISABLE_MOVIES_UPDATE.boolean() ) private var disableWcoSeriesLinksUpdate = mutableStateOf( Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE.boolean() ) private var disableWcoDataUpdate = mutableStateOf( Defaults.DISABLE_WCO_DATA_UPDATE.boolean() ) private var saveButtonEnabled = mutableStateOf(false) private lateinit var windowScope: AppWindowScope @OptIn(ExperimentalLayoutApi::class) @Composable fun settingsUi(windowScope: AppWindowScope) { this.windowScope = windowScope Scaffold( bottomBar = { Column( modifier = Modifier.fillMaxWidth() ) { HorizontalDivider() Row( modifier = Modifier.align(Alignment.CenterHorizontally) .padding(10.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically ) { defaultButton( "Update Options", width = 150.dp, height = 40.dp ) { openCheckBoxWindow() } defaultButton( "Reset Settings", width = 150.dp, height = 40.dp ) { DialogHelper.showConfirm( "Are you sure you want to reset your settings to the default ones?", "Reset Settings" ) { BoxHelper.resetSettings() updateValues() windowScope.showToast("Settings have been reset.") } } defaultButton( "Save Settings", enabled = saveButtonEnabled, width = 150.dp, height = 40.dp ) { saveSettings() } } } } ) { val scrollState = rememberScrollState(0) Box( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier.padding( bottom = it.calculateBottomPadding(), end = 12.dp ).fillMaxWidth().verticalScroll(scrollState) ) { fieldRow(Defaults.DOWNLOAD_THREADS) fieldRow(Defaults.TIMEOUT) fieldRow(Defaults.SAVE_FOLDER) fieldRow(Defaults.CHROME_BROWSER_PATH) fieldRow(Defaults.CHROME_DRIVER_PATH) //fieldRow(Defaults.PROXY) fieldDropdown(Defaults.QUALITY) FlowRow( verticalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp), maxItemsInEachRow = 4 ) { Defaults.checkBoxes.forEach { fieldCheckbox(it) } } fieldWcoDomain() Box( modifier = Modifier.fillMaxWidth() ) { Text( "Error Console", modifier = Modifier.align(Alignment.Center) .padding(top = 5.dp, bottom = 5.dp), textAlign = TextAlign.Center, fontSize = 16.sp ) defaultButton( "Copy Console Text", height = 35.dp, modifier = Modifier.align(Alignment.CenterEnd) ) { Tools.clipboardString = Core.errorConsole.text windowScope.showToast("Copied") } } Core.errorConsole.textField() } VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd) .background(MaterialTheme.colorScheme.surface.tone(20.0)) .fillMaxHeight() .padding(top = 3.dp, bottom = 3.dp), style = ScrollbarStyle( minimalHeight = 16.dp, thickness = 10.dp, shape = RoundedCornerShape(10.dp), hoverDurationMillis = 300, unhoverColor = MaterialTheme.colorScheme.surface.tone(50.0).copy(alpha = 0.70f), hoverColor = MaterialTheme.colorScheme.surface.tone(50.0).copy(alpha = 0.90f) ), adapter = rememberScrollbarAdapter( scrollState = scrollState ) ) } } } @OptIn(ExperimentalLayoutApi::class) private fun openCheckBoxWindow() { ApplicationState.newWindow( "Update Options", undecorated = true, transparent = true, alwaysOnTop = true, size = DpSize(500.dp, 300.dp) ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(5.dp), modifier = Modifier.fillMaxSize() .padding(10.dp) .background( color = MaterialTheme.colorScheme.background, shape = RoundedCornerShape(10.dp) ).border( 1.dp, color = MaterialTheme.colorScheme.primary, shape = RoundedCornerShape(10.dp) ) ) { FlowRow( verticalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp), maxItemsInEachRow = 3 ) { Defaults.updateCheckBoxes.forEach { fieldCheckbox(it) } } Row( modifier = Modifier.align(Alignment.CenterHorizontally), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically ) { if ( disableUserAgentsUpdate.value || disableWcoUrlsUpdate.value || disableWcoDataUpdate.value || disableWcoSeriesLinksUpdate.value || disableDubbedUpdate.value || disableSubbedUpdate.value || disableMoviesUpdate.value || disableCartoonUpdate.value ) { defaultButton( "Enable All Updates", width = 150.dp, height = 35.dp ) { disableUserAgentsUpdate.value = false disableWcoUrlsUpdate.value = false disableWcoDataUpdate.value = false disableWcoSeriesLinksUpdate.value = false disableDubbedUpdate.value = false disableSubbedUpdate.value = false disableMoviesUpdate.value = false disableCartoonUpdate.value = false updateSaveButton() } } else { defaultButton( "Disable All Updates", width = 150.dp, height = 35.dp ) { disableUserAgentsUpdate.value = true disableWcoUrlsUpdate.value = true disableWcoDataUpdate.value = true disableWcoSeriesLinksUpdate.value = true disableDubbedUpdate.value = true disableSubbedUpdate.value = true disableMoviesUpdate.value = true disableCartoonUpdate.value = true updateSaveButton() } } defaultButton( "Close", width = 150.dp, height = 35.dp ) { closeWindow() } } } } } @OptIn(ExperimentalFoundationApi::class) @Composable private fun fieldRow( setting: Defaults ) { val title = when (setting) { Defaults.DOWNLOAD_THREADS -> "Download Threads" Defaults.TIMEOUT -> "Network Timeout" Defaults.SAVE_FOLDER -> "Download Folder" Defaults.PROXY -> "Proxy" Defaults.CHROME_BROWSER_PATH -> "Chrome Browser Path" Defaults.CHROME_DRIVER_PATH -> "Chrome Driver Path" else -> "" } Row( horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(10.dp) ) { tooltip(setting.description) { Text( "$title:", style = MaterialTheme.typography.labelMedium ) } when (setting) { Defaults.DOWNLOAD_THREADS -> { defaultSettingsTextField( threads, { text -> if (text.isNotEmpty()) { threads = textToDigits(FieldType.THREADS, text) updateSaveButton() } else { if (threads.isNotEmpty()) { threads = "" } } }, numbersOnly = true, ) } Defaults.TIMEOUT -> { defaultSettingsTextField( timeout, { text -> if (text.isNotEmpty()) { timeout = textToDigits(FieldType.TIMEOUT, text) updateSaveButton() } else { if (timeout.isNotEmpty()) { timeout = "" } } }, numbersOnly = true, ) } Defaults.SAVE_FOLDER -> { defaultSettingsTextField( saveFolder, { text -> if (text.isNotEmpty()) { saveFolder = text updateSaveButton() } else { if (saveFolder.isNotEmpty()) { saveFolder = "" } } }, modifier = Modifier.height(30.dp).width(300.dp), ) var showFilePicker by remember { mutableStateOf(false) } DirectoryPicker( show = showFilePicker, initialDirectory = saveFolder, title = "Choose Save Folder" ) { if (it != null) { saveFolder = it updateSaveButton() } showFilePicker = false } defaultButton( "Set Folder", height = 30.dp, width = 80.dp ) { showFilePicker = true } } Defaults.CHROME_BROWSER_PATH -> { defaultSettingsTextField( chromePath, { text -> if (text.isNotEmpty()) { chromePath = text updateSaveButton() } else { if (chromePath.isNotEmpty()) { chromePath = "" } } }, modifier = Modifier.height(30.dp).width(300.dp), ) var showFilePicker by remember { mutableStateOf(false) } FilePicker( show = showFilePicker, initialDirectory = Defaults.SAVE_FOLDER.value.toString(), title = "Choose Chrome Browser File" ) { if (it != null) { chromePath = it.path updateSaveButton() } showFilePicker = false } defaultButton( "Set File", height = 30.dp, width = 80.dp ) { showFilePicker = true } } Defaults.CHROME_DRIVER_PATH -> { defaultSettingsTextField( chromeDriverPath, { text -> if (text.isNotEmpty()) { chromeDriverPath = text updateSaveButton() } else { if (chromeDriverPath.isNotEmpty()) { chromeDriverPath = "" } } }, modifier = Modifier.height(30.dp).width(300.dp), ) var showFilePicker by remember { mutableStateOf(false) } FilePicker( show = showFilePicker, initialDirectory = Defaults.SAVE_FOLDER.value.toString(), title = "Choose Chrome Driver FIle" ) { if (it != null) { chromeDriverPath = it.path updateSaveButton() } showFilePicker = false } defaultButton( "Set File", height = 30.dp, width = 80.dp ) { showFilePicker = true } } Defaults.PROXY -> { defaultSettingsTextField( proxy, { text -> if (text.isNotEmpty()) { proxy = text.trim() updateSaveButton() } else { if (proxy.isNotEmpty()) { proxy = "" } } }, enabled = proxyEnabled, modifier = Modifier.height(30.dp).width(180.dp), ) defaultButton( "Test Proxy", enabled = proxyEnabled, modifier = Modifier.height(30.dp) ) { if (!isValidProxy()) { return@defaultButton } val timeout = [email protected]() windowScope.showToast("Testing proxy with timeout: $timeout") Core.child.taskScope.launch(Dispatchers.IO) { val website = "https://google.com" try { val split = proxy.split(":") val response = Jsoup.connect(website) .proxy(split[0], split[1].toInt()) .followRedirects(true) .timeout(timeout * 1000) .execute() withContext(Dispatchers.Main) { if (response.statusCode() == 200) { windowScope.showToast("Proxy successfully connected to $website") } else { windowScope.showToast("Proxy failed to connect with status code: ${response.statusCode()}") } } } catch (e: Exception) { DialogHelper.showError( "Failed to connect to $website with proxy.", e ) } } } defaultCheckbox( proxyEnabled, modifier = Modifier.height(30.dp) ) { proxyEnabled.value = it updateSaveButton() } Text( "Enable Proxy", fontSize = 12.sp, modifier = Modifier.onClick { proxyEnabled.value = proxyEnabled.value.not() updateSaveButton() } ) } else -> {} } } } @Suppress("warnings") @Composable private fun fieldDropdown( setting: Defaults ) { val title = when (setting) { Defaults.QUALITY -> "Video Download Quality" else -> "" } Row( horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(10.dp) ) { tooltip(setting.description) { Text( "$title:", style = MaterialTheme.typography.labelMedium ) } if (setting == Defaults.QUALITY) { var expanded by remember { mutableStateOf(false) } val options = Quality.entries.map { DropdownOption(it.tag) { expanded = false quality = it.tag updateSaveButton() } } tooltip(setting.description) { defaultDropdown( quality, expanded, options, onTextClick = { expanded = true } ) { expanded = false } } } } } @OptIn(ExperimentalFoundationApi::class) @Composable private fun fieldCheckbox( setting: Defaults ) { val title = when (setting) { Defaults.SHOW_DEBUG_MESSAGES -> "Show Debug Messages" Defaults.BYPASS_DISK_SPACE -> "Bypass Storage Space Check" Defaults.SHOW_TOOLTIPS -> "Show Tooltips" Defaults.CONSOLE_ON_TOP -> "Popout Console Window Always On Top" Defaults.HEADLESS_MODE -> "Headless Mode" Defaults.SEPARATE_SEASONS -> "Separate Seasons Into Folders" Defaults.AUTO_SCROLL_CONSOLES -> "Auto Scroll Consoles" Defaults.DISABLE_USER_AGENTS_UPDATE -> "Disable User Agents Updates" Defaults.DISABLE_WCO_URLS_UPDATE -> "Disable WcoUrls Updates" Defaults.DISABLE_DUBBED_UPDATE -> "Disable Dubbed Updates" Defaults.DISABLE_SUBBED_UPDATE -> "Disable Subbed Updates" Defaults.DISABLE_CARTOON_UPDATE -> "Disable Cartoon Updates" Defaults.DISABLE_MOVIES_UPDATE -> "Disable Movies Updates" Defaults.DISABLE_WCO_DATA_UPDATE -> "Disable WcoData Updates" Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE -> "Disable Wco Series Links Updates" Defaults.CTRL_FOR_HOTKEYS -> "CTRL For Hotkeys" else -> "Not Implemented" } Row( horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(10.dp) ) { tooltip(setting.description) { Text( "$title:", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.onClick { when (setting) { Defaults.SHOW_DEBUG_MESSAGES -> { debugMessages.value = debugMessages.value.not() } Defaults.BYPASS_DISK_SPACE -> { bypassDiskSpace.value = bypassDiskSpace.value.not() } Defaults.SHOW_TOOLTIPS -> { showTooltips.value = showTooltips.value.not() } Defaults.CONSOLE_ON_TOP -> { consoleOnTop.value = consoleOnTop.value.not() } Defaults.HEADLESS_MODE -> { headlessMode.value = headlessMode.value.not() } Defaults.SEPARATE_SEASONS -> { separateSeasons.value = separateSeasons.value.not() } Defaults.AUTO_SCROLL_CONSOLES -> { autoScrollConsoles.value = autoScrollConsoles.value.not() } Defaults.DISABLE_USER_AGENTS_UPDATE -> { disableUserAgentsUpdate.value = disableUserAgentsUpdate.value.not() } Defaults.DISABLE_WCO_URLS_UPDATE -> { disableWcoUrlsUpdate.value = disableWcoUrlsUpdate.value.not() } Defaults.DISABLE_DUBBED_UPDATE -> { disableDubbedUpdate.value = disableDubbedUpdate.value.not() } Defaults.DISABLE_SUBBED_UPDATE -> { disableSubbedUpdate.value = disableSubbedUpdate.value.not() } Defaults.DISABLE_CARTOON_UPDATE -> { disableCartoonUpdate.value = disableCartoonUpdate.value.not() } Defaults.DISABLE_MOVIES_UPDATE -> { disableMoviesUpdate.value = disableMoviesUpdate.value.not() } Defaults.DISABLE_WCO_DATA_UPDATE -> { disableWcoDataUpdate.value = disableWcoDataUpdate.value.not() } Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE -> { disableWcoSeriesLinksUpdate.value = disableWcoSeriesLinksUpdate.value.not() } else -> {} } } ) } when (setting) { Defaults.SHOW_DEBUG_MESSAGES -> { tooltip(setting.description) { defaultCheckbox( debugMessages, modifier = Modifier.height(30.dp) ) { debugMessages.value = it updateSaveButton() } } } Defaults.BYPASS_DISK_SPACE -> { tooltip(setting.description) { defaultCheckbox( bypassDiskSpace, modifier = Modifier.height(30.dp) ) { bypassDiskSpace.value = it updateSaveButton() } } } Defaults.SHOW_TOOLTIPS -> { tooltip(setting.description) { defaultCheckbox( showTooltips, modifier = Modifier.height(30.dp) ) { showTooltips.value = it updateSaveButton() } } } Defaults.CONSOLE_ON_TOP -> { tooltip(setting.description) { defaultCheckbox( consoleOnTop, modifier = Modifier.height(30.dp) ) { consoleOnTop.value = it updateSaveButton() } } } Defaults.HEADLESS_MODE -> { tooltip(setting.description) { defaultCheckbox( headlessMode, modifier = Modifier.height(30.dp) ) { headlessMode.value = it updateSaveButton() } } } Defaults.SEPARATE_SEASONS -> { tooltip(setting.description) { defaultCheckbox( separateSeasons, modifier = Modifier.height(30.dp) ) { separateSeasons.value = it updateSaveButton() } } } Defaults.AUTO_SCROLL_CONSOLES -> { tooltip(setting.description) { defaultCheckbox( autoScrollConsoles, modifier = Modifier.height(30.dp) ) { autoScrollConsoles.value = it updateSaveButton() } } } Defaults.CTRL_FOR_HOTKEYS -> { tooltip(setting.description) { defaultCheckbox( ctrlForHotKeys, modifier = Modifier.height(30.dp) ) { ctrlForHotKeys.value = it updateSaveButton() } } } Defaults.DISABLE_USER_AGENTS_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableUserAgentsUpdate, modifier = Modifier.height(30.dp) ) { disableUserAgentsUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_WCO_URLS_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableWcoUrlsUpdate, modifier = Modifier.height(30.dp) ) { disableWcoUrlsUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_DUBBED_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableDubbedUpdate, modifier = Modifier.height(30.dp) ) { disableDubbedUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_SUBBED_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableSubbedUpdate, modifier = Modifier.height(30.dp) ) { disableSubbedUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_CARTOON_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableCartoonUpdate, modifier = Modifier.height(30.dp) ) { disableCartoonUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_MOVIES_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableMoviesUpdate, modifier = Modifier.height(30.dp) ) { disableMoviesUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_WCO_DATA_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableWcoDataUpdate, modifier = Modifier.height(30.dp) ) { disableWcoDataUpdate.value = it updateSaveButton() } } } Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE -> { tooltip(setting.description) { defaultCheckbox( disableWcoSeriesLinksUpdate, modifier = Modifier.height(30.dp) ) { disableWcoSeriesLinksUpdate.value = it updateSaveButton() } } } else -> {} } } } @Composable private fun fieldWcoDomain() { Row( horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(10.dp) ) { val tooltipText = """ Wcofun changes their domain a lot. This is used for the slug system to keep all wcofun links updated. Only use this option if you're having trouble connecting to wcofun. These values auto update everytime the app starts. """.trimIndent() tooltip(tooltipText) { Text( "Wcofun Domain:", style = MaterialTheme.typography.labelMedium ) } tooltip(tooltipText) { Text( "https://", style = MaterialTheme.typography.labelSmall ) } defaultSettingsTextField( wcoDomain, { wcoDomain = it updateSaveButton() }, modifier = Modifier.width(100.dp).height(30.dp) ) Text( ".", style = MaterialTheme.typography.labelSmall ) defaultSettingsTextField( wcoExtension, { wcoExtension = it updateSaveButton() }, modifier = Modifier.width(40.dp).height(30.dp) ) tooltip( """ Executes the auto update function that happens everytime the app starts. The auto update function checks the links found in the text file and follows them to the latest redirect. """.trimIndent() ) { defaultButton( "Auto Update", height = 30.dp, width = 80.dp ) { windowScope.showToast("[TODO]") } } } } private enum class FieldType { THREADS, TIMEOUT; } private fun textToDigits( type: FieldType, text: String ): String { var mText = text.filter { it.isDigit() } val num = mText.toIntOrNull() if (num != null) { if (type == FieldType.THREADS) { if (num < minThreads) { mText = minThreads.toString() } else if (num > maxThreads) { mText = maxThreads.toString() } } else if (type == FieldType.TIMEOUT) { if (num < minTimeout) { if (mText.length > 1) { mText = minTimeout.toString() } } else if (num > maxTimeout) { mText = maxTimeout.toString() } } } return mText } private fun updateSaveButton() { saveButtonEnabled.value = settingsChanged() } fun updateValues() { Defaults.entries.forEach { when (it) { Defaults.DOWNLOAD_THREADS -> { threads = it.intString() } Defaults.TIMEOUT -> { timeout = it.intString() } Defaults.SAVE_FOLDER -> { saveFolder = it.string() } Defaults.CHROME_BROWSER_PATH -> { chromePath = it.string() } Defaults.CHROME_DRIVER_PATH -> { chromeDriverPath = it.string() } Defaults.PROXY -> { proxy = it.string() } Defaults.ENABLE_PROXY -> { proxyEnabled.value = it.boolean() } Defaults.QUALITY -> { quality = it.string() } Defaults.SHOW_DEBUG_MESSAGES -> { debugMessages.value = it.boolean() } Defaults.BYPASS_DISK_SPACE -> { bypassDiskSpace.value = it.boolean() } Defaults.WCO_DOMAIN -> { wcoDomain = it.string() } Defaults.WCO_EXTENSION -> { wcoExtension = it.string() } Defaults.SHOW_TOOLTIPS -> { showTooltips.value = it.boolean() } Defaults.CONSOLE_ON_TOP -> { consoleOnTop.value = it.boolean() } Defaults.HEADLESS_MODE -> { headlessMode.value = it.boolean() } Defaults.SEPARATE_SEASONS -> { separateSeasons.value = it.boolean() } Defaults.AUTO_SCROLL_CONSOLES -> { autoScrollConsoles.value = it.boolean() } Defaults.CTRL_FOR_HOTKEYS -> { ctrlForHotKeys.value = it.boolean() } Defaults.DISABLE_USER_AGENTS_UPDATE -> { disableUserAgentsUpdate.value = it.boolean() } Defaults.DISABLE_WCO_URLS_UPDATE -> { disableWcoUrlsUpdate.value = it.boolean() } Defaults.DISABLE_DUBBED_UPDATE -> { disableDubbedUpdate.value = it.boolean() } Defaults.DISABLE_SUBBED_UPDATE -> { disableSubbedUpdate.value = it.boolean() } Defaults.DISABLE_CARTOON_UPDATE -> { disableCartoonUpdate.value = it.boolean() } Defaults.DISABLE_MOVIES_UPDATE -> { disableMoviesUpdate.value = it.boolean() } Defaults.DISABLE_WCO_DATA_UPDATE -> { disableWcoDataUpdate.value = it.boolean() } Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE -> { disableWcoSeriesLinksUpdate.value = it.boolean() } else -> {} } } saveButtonEnabled.value = false } private fun isValidProxy(): Boolean { if (proxy.isEmpty()) { windowScope.showToast("Please enter a proxy first.") return false } val split = try { proxy.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() } catch (e: Exception) { windowScope.showToast("Failed to parse proxy.") return false } val ip: String val port: Int? try { if (split.size > 2) { windowScope.showToast("Kotlin doesn't support Username & Password Authentication.") return false } else if (split.size < 2) { windowScope.showToast("Please enter a valid proxy.") return false } ip = split[0] val regex = "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$" val pattern: Pattern = Pattern.compile(regex) val matcher: Matcher = pattern.matcher(ip) if (!matcher.matches()) { windowScope.showToast("The proxy ip isn't valid.") return false } port = split[1].toIntOrNull() if (port != null) { if (port < 1 || port > 65535) { windowScope.showToast("The proxy port can only be 1-65535.") return false } } else { windowScope.showToast("The proxy port needs to be numbers only.") return false } } catch (e: Exception) { windowScope.showToast("Something wen't wrong checking the proxy format. Look at the console for more info.") FrogLog.logError( "Failed to check the proxy in settings." + "\nGo to Settings and scroll to the bottom for the entire exception.", e ) return false } return true } fun saveSettings(): Boolean { if (threads.isEmpty()) { threads = Defaults.DOWNLOAD_THREADS.intString() } val threadsValue = threads.toIntOrNull() if (threadsValue == null || threadsValue < minThreads || threadsValue > maxThreads) { windowScope.showToast("You must enter a Download Threads value of $minThreads-$maxThreads.") return false } if (timeout.isEmpty()) { timeout = Defaults.SAVE_FOLDER.string() } val timeoutValue = timeout.toIntOrNull() if (timeoutValue == null || timeoutValue < minTimeout || timeoutValue > maxTimeout) { windowScope.showToast("You must enter a Network Timeout value of $minTimeout-$maxTimeout.") return false } if (saveFolder.isEmpty()) { saveFolder = Defaults.SAVE_FOLDER.string() } if (!saveFolder.fileExists()) { windowScope.showToast("The download folder doesn't exist.") return false } if (chromePath.isNotEmpty()) { if (!chromePath.fileExists()) { windowScope.showToast("The chrome browser path doesn't exist.") return false } } if (chromeDriverPath.isNotEmpty()) { if (!chromeDriverPath.fileExists()) { windowScope.showToast("The chrome driver path doesn't exist.") return false } } if (chromePath.isNotEmpty() && chromeDriverPath.isEmpty()) { windowScope.showToast("Both Chrome Browser and Chrome Driver paths need to be set.") return false } if (chromeDriverPath.isNotEmpty() && chromePath.isEmpty()) { windowScope.showToast("Both Chrome Browser and Chrome Driver paths need to be set.") return false } val proxyEnabledValue = proxyEnabled.value if (proxy.isEmpty() && proxyEnabledValue) { proxyEnabled.value = false } else if (proxy.isNotEmpty() && proxyEnabledValue) { if (!isValidProxy()) { return false } } if (wcoExtension.isNotEmpty()) { val acceptedDomains = listOf( "org", "net", "tv", "com", "io", "to", ) wcoExtension = wcoExtension.replace("[^a-zA-Z]".toRegex(), "").lowercase() if (!acceptedDomains.contains(wcoExtension)) { DialogHelper.showError( "Your domain extension $wcoExtension isn't allowed. Please use any of these:" + "\n$acceptedDomains" ) return false } } Defaults.DOWNLOAD_THREADS.update(threadsValue) Defaults.TIMEOUT.update(timeoutValue) Defaults.SAVE_FOLDER.update(saveFolder) Defaults.CHROME_BROWSER_PATH.update(chromePath) Defaults.CHROME_DRIVER_PATH.update(chromeDriverPath) Core.child.refreshDownloadsProgress() Defaults.PROXY.update(proxy) Defaults.ENABLE_PROXY.update(proxyEnabledValue) Defaults.QUALITY.update(quality) Defaults.SHOW_DEBUG_MESSAGES.update(debugMessages.value) Defaults.BYPASS_DISK_SPACE.update(bypassDiskSpace.value) Defaults.WCO_DOMAIN.update(wcoDomain) Defaults.WCO_EXTENSION.update(wcoExtension) Defaults.SHOW_TOOLTIPS.update(showTooltips.value) Defaults.CONSOLE_ON_TOP.update(consoleOnTop.value) Defaults.HEADLESS_MODE.update(headlessMode.value) Defaults.SEPARATE_SEASONS.update(separateSeasons.value) Defaults.AUTO_SCROLL_CONSOLES.update(autoScrollConsoles.value) Defaults.CTRL_FOR_HOTKEYS.update(ctrlForHotKeys.value) Defaults.DISABLE_USER_AGENTS_UPDATE.update(disableUserAgentsUpdate.value) Defaults.DISABLE_WCO_URLS_UPDATE.update(disableWcoUrlsUpdate.value) Defaults.DISABLE_DUBBED_UPDATE.update(disableDubbedUpdate.value) Defaults.DISABLE_SUBBED_UPDATE.update(disableSubbedUpdate.value) Defaults.DISABLE_CARTOON_UPDATE.update(disableCartoonUpdate.value) Defaults.DISABLE_MOVIES_UPDATE.update(disableMoviesUpdate.value) Defaults.DISABLE_WCO_DATA_UPDATE.update(disableWcoDataUpdate.value) Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE.update(disableWcoSeriesLinksUpdate.value) updateValues() windowScope.showToast("Settings successfully saved.") return true } fun settingsChanged(): Boolean { return Defaults.TIMEOUT.intString() != timeout || Defaults.DOWNLOAD_THREADS.intString() != threads || Defaults.SAVE_FOLDER.string() != saveFolder || Defaults.CHROME_BROWSER_PATH.string() != chromePath || Defaults.CHROME_DRIVER_PATH.string() != chromeDriverPath || Defaults.PROXY.string() != proxy || Defaults.ENABLE_PROXY.boolean() != proxyEnabled.value || Defaults.QUALITY.string() != quality || Defaults.SHOW_DEBUG_MESSAGES.boolean() != debugMessages.value || Defaults.BYPASS_DISK_SPACE.boolean() != bypassDiskSpace.value || Defaults.WCO_DOMAIN.string() != wcoDomain || Defaults.WCO_EXTENSION.string() != wcoExtension || Defaults.SHOW_TOOLTIPS.boolean() != showTooltips.value || Defaults.CONSOLE_ON_TOP.boolean() != consoleOnTop.value || Defaults.HEADLESS_MODE.boolean() != headlessMode.value || Defaults.SEPARATE_SEASONS.boolean() != separateSeasons.value || Defaults.AUTO_SCROLL_CONSOLES.boolean() != autoScrollConsoles.value || Defaults.CTRL_FOR_HOTKEYS.boolean() != ctrlForHotKeys.value || Defaults.DISABLE_USER_AGENTS_UPDATE.boolean() != disableUserAgentsUpdate.value || Defaults.DISABLE_WCO_URLS_UPDATE.boolean() != disableWcoUrlsUpdate.value || Defaults.DISABLE_DUBBED_UPDATE.boolean() != disableDubbedUpdate.value || Defaults.DISABLE_SUBBED_UPDATE.boolean() != disableSubbedUpdate.value || Defaults.DISABLE_CARTOON_UPDATE.boolean() != disableCartoonUpdate.value || Defaults.DISABLE_MOVIES_UPDATE.boolean() != disableMoviesUpdate.value || Defaults.DISABLE_WCO_DATA_UPDATE.boolean() != disableWcoDataUpdate.value || Defaults.DISABLE_WCO_SERIES_LINKS_UPDATE.boolean() != disableWcoSeriesLinksUpdate.value } }
4
null
0
9
cf9790e125c977646f63e800a0ee949b5f806ec4
51,952
ZenDownloader
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Speaker.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup public val OutlineGroup.Speaker: ImageVector get() { if (_speaker != null) { return _speaker!! } _speaker = Builder(name = "Speaker", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 22.75f) horizontalLineTo(9.0f) curveTo(5.58f, 22.75f, 4.25f, 21.42f, 4.25f, 18.0f) verticalLineTo(6.0f) curveTo(4.25f, 2.58f, 5.58f, 1.25f, 9.0f, 1.25f) horizontalLineTo(15.0f) curveTo(18.42f, 1.25f, 19.75f, 2.58f, 19.75f, 6.0f) verticalLineTo(18.0f) curveTo(19.75f, 21.42f, 18.42f, 22.75f, 15.0f, 22.75f) close() moveTo(9.0f, 2.75f) curveTo(6.42f, 2.75f, 5.75f, 3.42f, 5.75f, 6.0f) verticalLineTo(18.0f) curveTo(5.75f, 20.58f, 6.42f, 21.25f, 9.0f, 21.25f) horizontalLineTo(15.0f) curveTo(17.58f, 21.25f, 18.25f, 20.58f, 18.25f, 18.0f) verticalLineTo(6.0f) curveTo(18.25f, 3.42f, 17.58f, 2.75f, 15.0f, 2.75f) horizontalLineTo(9.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 18.75f) curveTo(9.93f, 18.75f, 8.25f, 17.07f, 8.25f, 15.0f) curveTo(8.25f, 12.93f, 9.93f, 11.25f, 12.0f, 11.25f) curveTo(14.07f, 11.25f, 15.75f, 12.93f, 15.75f, 15.0f) curveTo(15.75f, 17.07f, 14.07f, 18.75f, 12.0f, 18.75f) close() moveTo(12.0f, 12.75f) curveTo(10.76f, 12.75f, 9.75f, 13.76f, 9.75f, 15.0f) curveTo(9.75f, 16.24f, 10.76f, 17.25f, 12.0f, 17.25f) curveTo(13.24f, 17.25f, 14.25f, 16.24f, 14.25f, 15.0f) curveTo(14.25f, 13.76f, 13.24f, 12.75f, 12.0f, 12.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 9.75f) curveTo(10.76f, 9.75f, 9.75f, 8.74f, 9.75f, 7.5f) curveTo(9.75f, 6.26f, 10.76f, 5.25f, 12.0f, 5.25f) curveTo(13.24f, 5.25f, 14.25f, 6.26f, 14.25f, 7.5f) curveTo(14.25f, 8.74f, 13.24f, 9.75f, 12.0f, 9.75f) close() moveTo(12.0f, 6.75f) curveTo(11.59f, 6.75f, 11.25f, 7.09f, 11.25f, 7.5f) curveTo(11.25f, 7.91f, 11.59f, 8.25f, 12.0f, 8.25f) curveTo(12.41f, 8.25f, 12.75f, 7.91f, 12.75f, 7.5f) curveTo(12.75f, 7.09f, 12.41f, 6.75f, 12.0f, 6.75f) close() } } .build() return _speaker!! } private var _speaker: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,184
VuesaxIcons
MIT License
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/HankealueEntity.kt
City-of-Helsinki
300,534,352
false
null
package fi.hel.haitaton.hanke import fi.hel.haitaton.hanke.domain.HasId import java.time.LocalDate import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.Table @Entity @Table(name = "hankealue") class HankealueEntity : HasId<Int> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) override var id: Int? = null @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "hankeid") var hanke: HankeEntity? = null // NOTE: This should be changed to an entity // Refers to HankeGeometria. var geometriat: Int? = null var haittaAlkuPvm: LocalDate? = null var haittaLoppuPvm: LocalDate? = null var kaistaHaitta: TodennakoinenHaittaPaaAjoRatojenKaistajarjestelyihin? = null var kaistaPituusHaitta: KaistajarjestelynPituus? = null var meluHaitta: Haitta13? = null var polyHaitta: Haitta13? = null var tarinaHaitta: Haitta13? = null var nimi: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as HankealueEntity if (id != other.id) return false if (hanke != other.hanke) return false if (haittaAlkuPvm != other.haittaAlkuPvm) return false if (haittaLoppuPvm != other.haittaLoppuPvm) return false if (kaistaHaitta != other.kaistaHaitta) return false if (kaistaPituusHaitta != other.kaistaPituusHaitta) return false if (meluHaitta != other.meluHaitta) return false if (polyHaitta != other.polyHaitta) return false if (tarinaHaitta != other.tarinaHaitta) return false if (nimi != other.nimi) return false return true } override fun hashCode(): Int { var result = id ?: 0 result = 31 * result + (hanke?.hashCode() ?: 0) result = 31 * result + (haittaAlkuPvm?.hashCode() ?: 0) result = 31 * result + (haittaLoppuPvm?.hashCode() ?: 0) result = 31 * result + (kaistaHaitta?.hashCode() ?: 0) result = 31 * result + (kaistaPituusHaitta?.hashCode() ?: 0) result = 31 * result + (meluHaitta?.hashCode() ?: 0) result = 31 * result + (polyHaitta?.hashCode() ?: 0) result = 31 * result + (tarinaHaitta?.hashCode() ?: 0) result = 31 * result + (nimi?.hashCode() ?: 0) return result } }
6
Kotlin
5
2
970a4d9fb82acb48541e5fac9a357dd28cf39acc
2,555
haitaton-backend
MIT License
ktor-io/js/src/io/ktor/utils/io/ConditionJS.kt
ktorio
40,136,600
false
null
package kotlinx.coroutines.io import kotlin.coroutines.* internal actual class Condition actual constructor(val predicate: () -> Boolean) { private var cont: Continuation<Unit>? = null actual fun check(): Boolean { return predicate() } actual fun signal() { val cont = cont if (cont != null && predicate()) { this.cont = null cont.resume(Unit) } } actual suspend fun await(block: () -> Unit) { if (predicate()) return return suspendCoroutine { c -> cont = c block() } } actual suspend fun await() { if (predicate()) return return suspendCoroutine { c -> cont = c } } }
302
null
774
9,308
9244f9a4a406f3eca06dc05d9ca0f7d7ec74a314
752
ktor
Apache License 2.0
app/src/main/java/io/github/sdwfqin/quickseed/di/AppModule.kt
sdwfqin
119,345,649
false
null
package io.github.sdwfqin.app_kt.di import android.util.Log import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import io.github.sdwfqin.app_kt.BuildConfig import io.github.sdwfqin.app_kt.data.remote.WeatherService import io.github.sdwfqin.samplecommonlibrary.base.Constants import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import javax.inject.Singleton /** * 描述:Retrofit封装 * * @author 张钦 * @date 2017/9/25 */ @Module @InstallIn(ApplicationComponent::class) object AppModule { @Provides fun provideWeatherService(retrofit: Retrofit): WeatherService = retrofit.create(WeatherService::class.java) @Singleton @Provides fun provideRetrofit(okHttp: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(Constants.BASE_URL) // 设置OkHttpclient .client(okHttp) // RxJava2 .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) // 字符串 .addConverterFactory(ScalarsConverterFactory.create()) // Gson .addConverterFactory(GsonConverterFactory.create()) .build() } @Provides fun provideOkHttpClient(): OkHttpClient { val builder = OkHttpClient.Builder() if (BuildConfig.DEBUG) { // OkHttp日志拦截器 builder.addInterceptor(HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { override fun log(message: String) { val strLength: Int = message.length var start = 0 var end = 2000 for (i in 0..99) { //剩下的文本还是大于规定长度则继续重复截取并输出 if (strLength > end) { Log.d("okhttp", message.substring(start, end)) start = end end += 2000 } else { Log.d("okhttp", message.substring(start, strLength)) break } } } }).setLevel(HttpLoggingInterceptor.Level.BODY)) } return builder.build() } }
1
null
166
850
b4741e22d20b137342282219d41d2533b55d5b69
2,457
AndroidQuick
Apache License 2.0
compiler/testData/codegen/box/inlineClasses/boxImplDoesNotExecuteInSecondaryConstructorGeneric.kt
JetBrains
3,432,266
false
null
// WITH_STDLIB // WORKS_WHEN_VALUE_CLASS // LANGUAGE: +ValueClasses, +GenericInlineClassParameter OPTIONAL_JVM_INLINE_ANNOTATION value class IC<T: Int> private constructor(val i: T) { @Suppress("SECONDARY_CONSTRUCTOR_WITH_BODY_INSIDE_VALUE_CLASS") constructor() : this(0 as T) { counter += 1 } } var counter = 0 fun <T> id(t: T) = t fun box(): String { val ic = IC<Int>() if (counter != 1) return "FAIL 1: $counter" counter = 0 id(ic) if (counter != 0) return "FAIL 2: $counter" return "OK" }
34
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
543
kotlin
Apache License 2.0
build-logic/convention/src/main/kotlin/AndroidLibraryComposeConventionPlugin.kt
kamerok
192,063,678
false
{"Kotlin": 200991}
import com.android.build.gradle.LibraryExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure class AndroidLibraryComposeConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("easydone.android.library") apply("org.jetbrains.kotlin.android") apply("org.jetbrains.kotlin.plugin.compose") } extensions.configure<LibraryExtension> { buildFeatures { compose = true } } } } }
0
Kotlin
0
4
55b69474c7cc421c084bba5896b31d38eee0bc24
662
EasyDone
Apache License 2.0
netflix-graph/src/main/kotlin/uy/klutter/graph/netflix/internal/Building.kt
kohesive
40,305,456
false
null
package uy.klutter.graph.netflix.internal import com.netflix.nfgraph.build.NFBuildGraph import com.netflix.nfgraph.spec.NFGraphSpec import com.netflix.nfgraph.spec.NFNodeSpec import com.netflix.nfgraph.spec.NFPropertySpec import uy.klutter.graph.netflix.* import java.io.DataOutputStream import java.io.OutputStream class CompiledGraphSchema<N : Enum<N>, R : Enum<R>>(val schema: GraphSchemaBuilder<N, R>) { internal val nodeTypes: Set<N> = schema.nodeTypes internal val relationTypes: Set<R> = schema.relationTypes internal val nodeTypeEnum: Class<N> = schema.nodeTypeEnum internal val relationTypeEnum: Class<R> = schema.relationTypeEnum // when have a relationship of a->R->b and a->R->c need to change to a->R.b->b and a->R.c->c but later find both if someone asks for R again during querying // ok, take the schema, render out both the NFGraphSpec and also our version of this that we can serialize // Ours includes: // outbound relationships for a given node type // relationship groups that disambiguate any collisions // relationship mirrors that automatically apply the reverse relationship when the opposite is added internal val relationshipGroups: MutableMap<RelationshipPairKey<N, R>, MutableSet<RelationshipTrippleKey<N, R>>> = hashMapOf() internal val relationshipMirrors = hashMapOf<RelationshipTrippleKey<N, R>, RelationshipTrippleKey<N, R>>() internal val graphSpec = NFGraphSpec() init { val relationshipFlags = hashMapOf<RelationshipTrippleKey<N, R>, Int>() fun createRelation(fromNode: N, relationship: R, toNode: N, relationOptions: GraphRelationOptions, modelScope: String? = null): RelationshipTrippleKey<N, R> { val trippleKey = RelationshipTrippleKey(fromNode, relationship, toNode) val oldFlags = relationshipFlags.get(trippleKey) if (oldFlags != null && oldFlags != relationOptions.flags) { throw RuntimeException("Repeated definition of a relationship must have the same flags: ${trippleKey} with old ${oldFlags} new ${relationOptions.flags}") } val pairKey = RelationshipPairKey(fromNode, relationship) val relationGroup = relationshipGroups.getOrPut(pairKey, { hashSetOf() }) relationGroup.add(trippleKey) relationshipFlags.put(trippleKey, relationOptions.flags) return trippleKey } schema.relations.forEach { r -> val modelScope = if (r.scopeAs == RelationScope.GLOBAL) null else r.modelScopeName val forward = createRelation(r.fromNode, r.forwardRelation, r.toNode, r.forwardFlags, modelScope) if (r.backwardRelation != null) { val backward = createRelation(r.toNode, r.backwardRelation!!, r.fromNode, r.backwardFlags, modelScope) val oldForwardMirror = relationshipMirrors.get(forward) val oldBackwardMirror = relationshipMirrors.get(backward) if (oldForwardMirror != null && oldBackwardMirror != null && oldForwardMirror != backward && oldBackwardMirror != forward) { throw RuntimeException("Repeated definition of a relationship mirrors must have the same mirror relationships: ${forward} and ${backward} have differing mirrors ${oldBackwardMirror} and ${oldForwardMirror}") } relationshipMirrors.put(forward, backward) relationshipMirrors.put(backward, forward) } } val relationshipGroupsPerNodeType = relationshipGroups.keys.groupBy { it.fromNode } nodeTypes.forEach { node -> val nodeRelationGroups = relationshipGroupsPerNodeType.get(node) ?: listOf() val propSpecs = arrayListOf<NFPropertySpec>() if (nodeRelationGroups.isNotEmpty()) { nodeRelationGroups.forEach { pairKey -> val groupMembers = relationshipGroups.getOrElse(pairKey, { hashSetOf() }) if (groupMembers.isNotEmpty()) { val fullyQualify = groupMembers.size > 1 groupMembers.forEach { trippleKey -> val relateName = if (fullyQualify) "${trippleKey.relationship.name}.${trippleKey.toNode.name}" else trippleKey.relationship.name propSpecs.add(NFPropertySpec(relateName, trippleKey.toNode.name, relationshipFlags.get(trippleKey) ?: 0)) } } } graphSpec.addNodeSpec(NFNodeSpec(node.name, *(propSpecs.toTypedArray()))) } } } } class GraphBuilderTempStep1<N : Enum<N>, R : Enum<R>>(val fromNodeWithOrd: NodeAndOrd<N>, val completr: (NodeAndOrd<N>, R, NodeAndOrd<N>)->Unit) { fun edge(relation: R): GraphBuilderTempStep2<N,R> { return GraphBuilderTempStep2<N, R>(fromNodeWithOrd, relation, completr) } } class GraphBuilderTempStep2<N : Enum<N>, R : Enum<R>>(val fromNodeWithOrd: NodeAndOrd<N>, val relation: R, val completr: (NodeAndOrd<N>,R,NodeAndOrd<N>)->Unit) { fun to(toNodeWithOrd: NodeAndOrd<N>): Unit { completr(fromNodeWithOrd, relation, toNodeWithOrd) } } class GraphBuilder<N : Enum<N>, R : Enum<R>>(val schema: CompiledGraphSchema<N, R>) : GraphOrdinalContainer<N>(false) { private val graphBuilder = NFBuildGraph(schema.graphSpec) fun connect(fromNodeWithOrd: NodeAndOrd<N>): GraphBuilderTempStep1<N,R> { return GraphBuilderTempStep1<N,R>(fromNodeWithOrd, { f,r,t -> connect(f,r,t) }) } fun connect(fromNodeWithId: NodeAndId<N>, relation: R, toNodeWithId: NodeAndId<N>) { connect(fromNodeWithId.toNord(), relation, toNodeWithId.toNord()) } fun connect(fromNodeWithOrd: NodeAndOrd<N>, relation: R, toNodeWithOrd: NodeAndOrd<N>) { val forward = connectInternal(fromNodeWithOrd, relation, toNodeWithOrd) val mirrorRelation = schema.relationshipMirrors.get(forward) if (mirrorRelation != null) { connectInternal(toNodeWithOrd, mirrorRelation.relationship, fromNodeWithOrd) } } // TODO: support new methods getNodes(), getOrCreateNote(), addConnection(node, spec, ...) which are more efficient // also addConnectionModel returning int can be used to speed things up // also getPropertySpec returning NFPropertySpec can be used in the new add methods // ... see: https://github.com/Netflix/netflix-graph/commit/2f297cf584bb83361d8ca7f1ecdfe84f11731031 // this may not be in release yet, could be 1.6 or later, have to check... private fun connectInternal(fromNodeWithOrd: NodeAndOrd<N>, relation: R, toNodeWithOrd: NodeAndOrd<N>): RelationshipTrippleKey<N,R> { val pairKey = RelationshipPairKey(fromNodeWithOrd.nodeType, relation) val trippleKey = RelationshipTrippleKey(fromNodeWithOrd.nodeType, relation, toNodeWithOrd.nodeType) val nodeRelations = schema.relationshipGroups.getOrElse(pairKey, { setOf<RelationshipTrippleKey<N,R>>() }) if (nodeRelations.isNotEmpty()) { val fullyQualify = nodeRelations.size > 1 val matchingRelation = nodeRelations.filter { it == trippleKey }.firstOrNull() if (matchingRelation != null) { val relateName = if (fullyQualify) "${trippleKey.relationship.name}.${trippleKey.toNode.name}" else trippleKey.relationship.name graphBuilder.addConnection(matchingRelation.fromNode.name, fromNodeWithOrd.ord, relateName, toNodeWithOrd.ord) return trippleKey } else { throw RuntimeException("No relationship for ${trippleKey} exists, cannot connect these nodes!") } } else { throw RuntimeException("No relationship for ${pairKey} exists, cannot connect it to anything!") } } fun serialize(output: OutputStream) { DataOutputStream(output).use { dataStream -> // Header: // "**KOTLIN-NFGRAPH**" // version as number // Partial Schema: (only unidirectional relations, no mirrors) // "**SCHEMA**" // number of nodeType // [foreach nodeType] // - name of nodeType // number of relation groups // [foreach relation group] // - nodeType name // - relation name // - number of targets // [foreach target] // - target nodeType name // number of mirrors // [foreach mirror] // - forward nodeType name // - forward relation name // - forward target nodeType name // - backward nodeType name // - backward relation name // - backward target nodeType name // // Ordinals: // "**ORDINALS**" // number of ordinal maps // [foreach ordinal map] // - name of nodeType // - count N of ordinals // - 0..N of ordinals // // Graph: // "**GRAPH**" // compressed graph serialized // Header dataStream.writeUTF(GRAPH_MARKERS_HEADER) dataStream.writeInt(1) // Partial Schema: dataStream.writeUTF(GRAPH_MARKERS_SCHEMA_HEADER) val values = schema.nodeTypes dataStream.writeInt(values.size) values.forEach { nodeType -> dataStream.writeUTF(nodeType.name) } val groups = schema.relationshipGroups dataStream.writeInt(groups.size) groups.entries.forEach { groupEntry -> dataStream.writeUTF(groupEntry.key.fromNode.name) dataStream.writeUTF(groupEntry.key.relationship.name) dataStream.writeInt(groupEntry.value.size) groupEntry.value.forEach { target -> dataStream.writeUTF(target.toNode.name) } } val mirrors = schema.relationshipMirrors dataStream.writeInt(mirrors.size) mirrors.entries.forEach { mirrorEntry -> dataStream.writeUTF(mirrorEntry.key.fromNode.name) dataStream.writeUTF(mirrorEntry.key.relationship.name) dataStream.writeUTF(mirrorEntry.key.toNode.name) dataStream.writeUTF(mirrorEntry.value.fromNode.name) dataStream.writeUTF(mirrorEntry.value.relationship.name) dataStream.writeUTF(mirrorEntry.value.toNode.name) } // Ordinals: dataStream.writeUTF(GRAPH_MARKERS_ORDINAL_HEADER) dataStream.writeInt(ordinalsByType.size) ordinalsByType.forEach { entry -> dataStream.writeUTF(entry.key.name) dataStream.writeInt(entry.value.size()) entry.value.asSequence().forEach { ordValue -> dataStream.writeUTF(ordValue) } } // Graph: dataStream.writeUTF(GRAPH_MARKERS_GRAPH_HEADER) val compressed = graphBuilder.compress() compressed.writeTo(dataStream) } } }
1
null
8
142
f93e32817aac31aa7b4b40ee6ed69c885b65e44f
11,433
klutter
MIT License
Aulas/Aula_2023_03_03/Aula2_continuacao.kt
brlpdiniz
615,543,194
false
null
fun main( print("Digite uma frase: ") val texto = readLine() println(text) )
0
Kotlin
0
1
51eddb2f15efd67e6795214fc857ac4a2f66e6cf
88
programacao-mobile-1
MIT License
medium/kotlin/c0169_338_counting-bits/00_leetcode_0169.kt
drunkwater
127,843,545
false
{"Text": 2, "Shell": 7, "Markdown": 3, "Perl": 12, "HTML": 3645, "C": 2246, "Java": 738, "Swift": 738, "Go": 738, "C#": 750, "Microsoft Visual Studio Solution": 4, "XML": 8, "Makefile": 1476, "Python": 1476, "Kotlin": 738, "Ruby": 738, "JavaScript": 738, "Scala": 738, "C++": 1484}
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //338. Counting Bits //Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. //Example: //For num = 5 you should return [0,1,1,2,1,2]. //Follow up: //It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? //Space complexity should be O(n). //Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. //Credits: //Special thanks to @ syedee for adding this problem and creating all test cases. //class Solution { // fun countBits(num: Int): IntArray { // } //} // Time Is Money
1
null
1
1
8cc4a07763e71efbaedb523015f0c1eff2927f60
931
leetcode
Ruby License
codelabs/updating-ui/app/src/main/java/com/facebook/litho/codelab/RootComponentSpec.kt
facebook
80,179,724
false
null
/* * Copyright 2019-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.codelab import com.facebook.litho.annotations.Prop import com.facebook.litho.annotations.State import com.facebook.litho.ClickEvent import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Row import com.facebook.litho.annotations.LayoutSpec import com.facebook.litho.annotations.OnCreateInitialState import com.facebook.litho.annotations.OnCreateLayout import com.facebook.litho.annotations.OnEvent import com.facebook.litho.annotations.OnUpdateState import com.facebook.litho.StateValue import com.facebook.litho.widget.Text import com.facebook.yoga.YogaEdge @Suppress("MagicNumber") @LayoutSpec object RootComponentSpec { @OnCreateInitialState fun onCreateInitialState(c: ComponentContext, toggleState: StateValue<Boolean>) { toggleState.set(true) } @OnCreateLayout fun onCreateLayout(c: ComponentContext, @Prop labelText: String, @State toggleState: Boolean): Component { return Column.create(c) .child(Text.create(c).textSizeSp(20f).text(labelText)) .child( Row.create(c) .child( Text.create(c) .textSizeSp(20f) .text("Toggle state: ") .marginPx(YogaEdge.RIGHT, 30) .clickHandler(RootComponent.onClick(c))) .child(Text.create(c).textSizeSp(20f).text(toggleState.toString()))) .build() } @OnEvent(ClickEvent::class) fun onClick(c: ComponentContext) { RootComponent.updateToggle(c) } @OnUpdateState fun updateToggle(toggleState: StateValue<Boolean>) { val toggleStateVal: Boolean? = toggleState.get() if (toggleStateVal == true) { toggleState.set(false) } else { toggleState.set(true) } } }
88
null
765
7,703
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
2,460
litho
Apache License 2.0
app/src/main/java/com/demo/app/TextFragment.kt
czy1121
874,719,761
false
{"Kotlin": 39557}
package com.demo.app import android.content.res.Resources import android.graphics.BlurMaskFilter import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.text.method.LinkMovementMethod import android.text.style.MaskFilterSpan import android.view.View import android.widget.TextView import android.widget.Toast import androidx.core.text.buildSpannedString import androidx.fragment.app.Fragment import me.reezy.cosmo.span.bold import me.reezy.cosmo.span.br import me.reezy.cosmo.span.clickable import me.reezy.cosmo.span.color import me.reezy.cosmo.span.paragraph import me.reezy.cosmo.span.scale import me.reezy.cosmo.span.strike import me.reezy.cosmo.span.text import me.reezy.cosmo.span.underline class TextFragment : Fragment(R.layout.fragment_text) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val tv = requireView() as TextView tv.movementMethod = LinkMovementMethod.getInstance() tv.text = buildSpannedString { paragraph(lineHeight = 30f.dp) { text("text no style") br() text("text Typeface.BOLD", style = Typeface.BOLD) br() text("text Typeface.ITALIC", style = Typeface.ITALIC) br() text("text relative size x 2", scale = 2f) br() text("text foreground color", color = Color.RED) br() text("text background color", bgColor = Color.RED) br() text("text underline", underline) br() text("text strike", strike) br() clickable("text clickable") { Toast.makeText(requireContext(), "text clickable clicked", Toast.LENGTH_SHORT).show() } br() text("text multiple style", color(Color.RED), bold, underline, strike, scale(1.5f), clickable { Toast.makeText(requireContext(), "text multiple style clicked", Toast.LENGTH_SHORT).show() }) } br() paragraph { text("Blur.NORMAL", color(Color.RED), MaskFilterSpan(BlurMaskFilter(1f.dp.toFloat(), BlurMaskFilter.Blur.NORMAL))) br() text("Blur.SOLID", color(Color.RED), MaskFilterSpan(BlurMaskFilter(1f.dp.toFloat(), BlurMaskFilter.Blur.SOLID))) br() text("Blur.OUTER", color(Color.RED), MaskFilterSpan(BlurMaskFilter(1f.dp.toFloat(), BlurMaskFilter.Blur.OUTER))) br() text("Blur.INNER", color(Color.RED), MaskFilterSpan(BlurMaskFilter(1f.dp.toFloat(), BlurMaskFilter.Blur.INNER))) } } } private val Float.dp: Int get() = (Resources.getSystem().displayMetrics.density * this).toInt() }
0
Kotlin
0
3
dded0412663cca0a0ef2cf665d7f0d45655f4466
2,950
span
Apache License 2.0
src/main/kotlin/net/fabricmc/example/items/Stable_creeper.kt
nikjust
394,595,634
false
null
package net.fabricmc.example.items import net.fabricmc.fabric.api.item.v1.FabricItemSettings import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.FoodComponent import net.minecraft.item.Item import net.minecraft.item.ItemGroup import net.minecraft.item.ItemStack import net.minecraft.util.Hand import net.minecraft.util.TypedActionResult import net.minecraft.world.World public class stable_creeper_instance(settings: Settings?) : Item(settings) { override fun use(world: World?, user: PlayerEntity?, hand: Hand?): TypedActionResult<ItemStack> { println("food used") return super.use(world, user, hand) } } class stable_creeper { // an instance of our new item companion object { val stableCreeper = stable_creeper_instance(FabricItemSettings().group(ItemGroup.MISC)) } }
0
Kotlin
0
0
7519111c9087bf338101652f3f2251b0bf570208
843
Rituality-fabric
Creative Commons Zero v1.0 Universal
stream-video-android-ui-xml/src/main/kotlin/io/getstream/video/android/xml/widget/participant/internal/CallParticipantsListView.kt
GetStream
505,572,267
false
{"Kotlin": 2549850, "MDX": 279508, "Python": 18285, "Shell": 4455, "JavaScript": 1112, "PureBasic": 107}
/* * Copyright (c) 2014-2023 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-video-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.video.android.xml.widget.participant.internal import android.content.Context import android.graphics.Color import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RectShape import android.util.AttributeSet import android.widget.HorizontalScrollView import android.widget.LinearLayout import androidx.annotation.Px import io.getstream.video.android.core.ParticipantState import io.getstream.video.android.xml.utils.extensions.createStreamThemeWrapper import io.getstream.video.android.xml.widget.participant.CallParticipantView import io.getstream.video.android.xml.widget.participant.RendererInitializer import io.getstream.video.android.xml.widget.renderer.VideoRenderer import io.getstream.video.android.xml.widget.view.JobHolder import kotlinx.coroutines.Job internal class CallParticipantsListView : HorizontalScrollView, VideoRenderer, JobHolder { internal var buildParticipantView: () -> CallParticipantView = { CallParticipantView(context) } private val childList: MutableList<CallParticipantView> = mutableListOf() override val runningJobs: MutableList<Job> = mutableListOf() private var rendererInitializer: RendererInitializer? = null private val participantsList: LinearLayout by lazy { LinearLayout(context).apply { [email protected](this) layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT) showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE } } /** * Sets the [RendererInitializer] handler. * * @param rendererInitializer Handler for initializing the renderer. */ override fun setRendererInitializer(rendererInitializer: RendererInitializer) { this.rendererInitializer = rendererInitializer childList.forEach { it.setRendererInitializer(rendererInitializer) } } internal constructor(context: Context) : this(context, null) internal constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) internal constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(context, attrs, defStyleAttr, 0) internal constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super( context.createStreamThemeWrapper(), attrs, defStyleAttr, defStyleRes, ) /** * Set the margin between participant views in the list. * * @param size The size of the divider. */ internal fun setItemMargin(@Px size: Int) { participantsList.dividerDrawable = ShapeDrawable(RectShape()).apply { intrinsicWidth = size intrinsicHeight = size paint.color = Color.TRANSPARENT } } /** * Updates the participants list. If there are more or less views than participants, the views will be added or * removed from the view. * * @param participants The list of participants to show on the screen. */ internal fun updateParticipants(participants: List<ParticipantState>) { when { childList.size > participants.size -> { val diff = childList.size - participants.size for (index in 0 until diff) { val view = childList.last() participantsList.removeView(view) childList.remove(view) } } childList.size < participants.size -> { val diff = participants.size - childList.size for (index in 0 until diff) { val view = buildParticipantView().apply { rendererInitializer?.let { setRendererInitializer(it) } } childList.add(view) participantsList.addView(view) } } } childList.forEachIndexed { index, view -> val participant = participants[index] view.setParticipant(participant) view.tag = participant.sessionId } } /** * Updates the current primary speaker and shows a border around the primary speaker. * * @param participant The call participant marked as a primary speaker. */ internal fun updatePrimarySpeaker(participant: ParticipantState?) { childList.forEach { it.setActive(it.tag == participant?.sessionId) } } override fun onDetachedFromWindow() { stopAllJobs() super.onDetachedFromWindow() } }
3
Kotlin
30
308
1c67906e4c01e480ab180f30b39f341675bc147e
5,237
stream-video-android
FSF All Permissive License
scripts/src/main/java/io/github/fate_grand_automata/scripts/models/battle/RunState.kt
Fate-Grand-Automata
245,391,245
false
null
package com.mathewsachin.fategrandautomata.scripts.models.battle import kotlin.time.TimeSource class RunState { private val timestamp = TimeSource.Monotonic.markNow() val runTime get() = timestamp.elapsedNow() var totalTurns = 0 private set var stage = -1 private set(value) { field = value stageState.stageCountSnaphot?.close() stageState = StageState() turn = -1 } var stageState = StageState() private set var turn = -1 private set(value) { field = value if (value != -1) { ++totalTurns } turnState = TurnState() } var turnState = TurnState() private set fun nextStage() = ++stage fun nextTurn() = ++turn }
25
null
187
993
eb630b8efcdb56782f796de2e17b36fdf9e19f3b
823
FGA
MIT License
compiler/testData/codegen/bytecodeListing/tailcall/tailSuspendUnitFun.kt
JakeWharton
99,388,807
false
null
suspend fun empty() {} suspend fun withoutReturn() { empty() } suspend fun withReturn() { return empty() } suspend fun notTailCall() { empty(); empty() } suspend fun lambdaAsParameter(c: suspend ()->Unit) { c() } suspend fun lambdaAsParameterNotTailCall(c: suspend ()->Unit) { c(); c() } suspend fun lambdaAsParameterReturn(c: suspend ()->Unit) { return c() } suspend fun returnsInt() = 42 // This should not be tail-call, since the caller should push Unit.INSTANCE on stack suspend fun callsIntNotTailCall() { returnsInt() } suspend fun multipleExitPoints(b: Boolean) { if (b) empty() else withoutReturn() } suspend fun multipleExitPointsNotTailCall(b: Boolean) { if (b) empty() else returnsInt() } fun ordinary() = 1 inline fun ordinaryInline() { ordinary() } suspend fun multipleExitPointsWithOrdinaryInline(b: Boolean) { if (b) empty() else ordinaryInline() } suspend fun multipleExitPointsWhen(i: Int) { when(i) { 1 -> empty() 2 -> withReturn() 3 -> withoutReturn() else -> lambdaAsParameter {} } } suspend fun <T> generic(): T = TODO() suspend fun useGenericReturningUnit() { generic<Unit>() } class Generic<T> { suspend fun foo(): T = TODO() } suspend fun useGenericClass(g: Generic<Unit>) { g.foo() } suspend fun <T> genericInferType(c: () -> T): T = TODO() suspend fun useGenericIngerType() { genericInferType {} } suspend fun nullableUnit(): Unit? = null suspend fun useNullableUnit() { nullableUnit() } suspend fun useRunRunRunRunRun() { run { run { run { run { run { empty() } } } } } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
1,710
kotlin
Apache License 2.0
src/main/java/org/samoxive/safetyjim/discord/DiscordBot.kt
SosiskaDBMG
195,842,972
true
{"Kotlin": 191650, "Python": 1253, "Dockerfile": 414}
package org.samoxive.safetyjim.discord import com.uchuhimo.konf.Config import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.dv8tion.jda.core.EmbedBuilder import net.dv8tion.jda.core.MessageBuilder import net.dv8tion.jda.core.Permission import net.dv8tion.jda.core.entities.Guild import net.dv8tion.jda.core.utils.SessionControllerAdapter import org.samoxive.safetyjim.config.JimConfig import org.samoxive.safetyjim.database.* import org.samoxive.safetyjim.database.SettingsTable.getGuildSettings import org.samoxive.safetyjim.discord.commands.* import org.samoxive.safetyjim.discord.processors.InviteLink import org.samoxive.safetyjim.discord.processors.MessageStats import org.samoxive.safetyjim.tryhard import org.samoxive.safetyjim.tryhardAsync import org.slf4j.LoggerFactory import java.awt.Color import java.util.* import kotlin.collections.ArrayList class DiscordBot(val config: Config) { private val log = LoggerFactory.getLogger(DiscordBot::class.java) val shards = ArrayList<DiscordShard>() val commands = mapOf( "ping" to Ping(), "unmute" to Unmute(), "invite" to Invite(), "ban" to Ban(), "kick" to Kick(), "mute" to Mute(), "warn" to Warn(), "help" to Help(), "clean" to Clean(), "tag" to Tag(), "remind" to Remind(), "info" to Info(), "settings" to Settings(), "softban" to Softban(), "unban" to Unban(), "server" to Server(), "iam" to Iam(), "role" to RoleCommand(), "hardban" to Hardban(), "melo" to Melo(), "xkcd" to Xkcd() ) val deleteCommands = arrayOf("ban", "kick", "mute", "softban", "warn", "hardban") val processors = listOf(InviteLink(), MessageStats()) val startTime = Date() val guildCount: Long get() = shards.asSequence().map { shard -> shard.jda } .map { shard -> shard.guildCache.size() } .sum() init { val sessionController = SessionControllerAdapter() for (i in 0 until config[JimConfig.shard_count]) { val shard = DiscordShard(this, i, sessionController) shards.add(shard) } scheduleJob(10, 5, "allowUsers") { allowUsers() } scheduleJob(10, 10, "unmuteUsers") { unmuteUsers() } scheduleJob(10, 30, "unbanUsers") { unbanUsers() } scheduleJob(10, 5, "remindReminders") { remindReminders() } val inviteLink = shards[0].jda.asBot().getInviteUrl( Permission.KICK_MEMBERS, Permission.BAN_MEMBERS, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_MANAGE, Permission.MANAGE_ROLES ) log.info("All shards ready.") log.info("Bot invite link: $inviteLink") } private fun scheduleJob(delaySeconds: Int, intervalSeconds: Int, jobName: String, job: suspend () -> Unit) { GlobalScope.launch { delay(delaySeconds * 1000L) while (true) { try { job() } catch (e: Throwable) { log.error("Exception occured in $jobName", e) } delay(intervalSeconds * 1000L) } } } fun getGuildFromBot(guildId: String): Guild? { val guildIdLong = tryhard { guildId.toLong() } ?: return null val shardId = getShardIdFromGuildId(guildIdLong, shards.size) return shards[shardId].jda.getGuildById(guildId) } private suspend fun allowUsers() { val usersToBeAllowed = JoinsTable.fetchExpiredJoins() for (user in usersToBeAllowed) { val guildId = user.guildId val shardId = getShardIdFromGuildId(guildId, config[JimConfig.shard_count]) val shard = shards[shardId] val shardClient = shard.jda val guild = shardClient.getGuildById(guildId) if (guild == null) { JoinsTable.updateJoin(user.copy(allowed = true)) continue } val guildSettings = getGuildSettings(guild, config) val enabled = guildSettings.holdingRoom if (enabled) { val guildUser = shard.jda.retrieveUserById(user.userId).await() val member = guild.getMember(guildUser) val roleId = guildSettings.holdingRoomRoleId val role = if (roleId != null) guild.getRoleById(roleId) else null val controller = guild.controller if (role == null) { SettingsTable.updateSettings(guildSettings.copy(holdingRoom = false)) continue } tryhardAsync { controller.addSingleRoleToMember(member, role).await() } } JoinsTable.updateJoin(user.copy(allowed = true)) } } private suspend fun unbanUsers() { val usersToBeUnbanned = BansTable.fetchExpiredBans() for (user in usersToBeUnbanned) { val guildId = user.guildId val shardId = getShardIdFromGuildId(guildId, config[JimConfig.shard_count]) val shard = shards[shardId] val shardClient = shard.jda val guild = shardClient.getGuildById(guildId) if (guild == null) { BansTable.updateBan(user.copy(unbanned = true)) continue } val guildUser = shard.jda.retrieveUserById(user.userId).await() val controller = guild.controller if (!guild.selfMember.hasPermission(Permission.BAN_MEMBERS)) { BansTable.updateBan(user.copy(unbanned = true)) continue } val banRecord = tryhardAsync { guild.banList.await() } ?.firstOrNull { ban -> ban.user.id == guildUser.id } if (banRecord == null) { BansTable.updateBan(user.copy(unbanned = true)) continue } tryhardAsync { controller.unban(guildUser).await() } BansTable.updateBan(user.copy(unbanned = true)) } } private suspend fun unmuteUsers() { val usersToBeUnmuted = MutesTable.fetchExpiredMutes() for (user in usersToBeUnmuted) { val guildId = user.guildId val shardId = getShardIdFromGuildId(guildId, config[JimConfig.shard_count]) val shard = shards[shardId] val shardClient = shard.jda val guild = shardClient.getGuildById(guildId) if (guild == null) { MutesTable.updateMute(user.copy(unmuted = true)) continue } val guildUser = shard.jda.retrieveUserById(user.userId).await() val member = guild.getMember(guildUser) if (member == null) { MutesTable.updateMute(user.copy(unmuted = true)) continue } val mutedRoles = guild.getRolesByName("Muted", false) val role = if (mutedRoles.isEmpty()) { tryhardAsync { Mute.setupMutedRole(guild) } } else { mutedRoles[0] } if (role == null) { MutesTable.updateMute(user.copy(unmuted = true)) continue } val controller = guild.controller tryhardAsync { controller.removeSingleRoleFromMember(member, role).await() } MutesTable.updateMute(user.copy(unmuted = true)) } } private suspend fun remindReminders() { val reminders = RemindersTable.fetchExpiredReminders() for (reminder in reminders) { val guildId = reminder.guildId val channelId = reminder.channelId val userId = reminder.userId val shardId = getShardIdFromGuildId(guildId, config[JimConfig.shard_count]) val shard = shards[shardId].jda val guild = shard.getGuildById(guildId) val user = shard.retrieveUserById(userId).await() if (guild == null) { RemindersTable.updateReminder(reminder.copy(reminded = true)) continue } val channel = guild.getTextChannelById(channelId) val member = guild.getMember(user) val embed = EmbedBuilder() embed.setTitle("Reminder - #${reminder.id}") embed.setDescription(reminder.message) embed.setAuthor("Safety Jim", null, shard.selfUser.avatarUrl) embed.setFooter("Reminder set on", null) embed.setTimestamp(Date(reminder.createTime * 1000).toInstant()) embed.setColor(Color(0x4286F4)) if (channel == null || member == null) { user.trySendMessage(embed.build()) } else { try { val builder = MessageBuilder() builder.append(user.asMention) builder.setEmbed(embed.build()) channel.sendMessage(builder.build()).await() } catch (e: Exception) { user.trySendMessage(embed.build()) } } RemindersTable.updateReminder(reminder.copy(reminded = true)) } } }
0
Kotlin
0
0
c585de5f5b66f7d5275fed094076b593fddc72ed
9,600
SafetyJim
MIT License