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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/zibook/feature_book/domain/model/EpubManifestModel.kt | flgsercan | 609,108,096 | false | {"Kotlin": 151068} | package com.example.zibook.feature_book.domain.model
/**
* Epub manifest model. Contains exhaustive list of all publication resources.
*
* @property resources List of all resources available in publication.
*/
data class EpubManifestModel(val resources: List<EpubResourceModel>?) {
fun getById(id: String?): EpubResourceModel? {
return resources?.firstOrNull {
it.id == id
}
}
}
/**
* Model of single publication resource.
*
* @property id Id of the resource
* @property href Location of the resource
* @property mediaType Type and format of the resource
* @property properties Set of property values
*/
data class EpubResourceModel(
val id: String? = null,
val href: String? = null,
val mediaType: String? = null,
val properties: HashSet<String>? = null,
val byteArray: ByteArray?=null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as EpubResourceModel
if (id != other.id) return false
if (href != other.href) return false
if (mediaType != other.mediaType) return false
if (properties != other.properties) return false
if (byteArray != null) {
if (other.byteArray == null) return false
if (!byteArray.contentEquals(other.byteArray)) return false
} else if (other.byteArray != null) return false
return true
}
override fun hashCode(): Int {
var result = id?.hashCode() ?: 0
result = 31 * result + (href?.hashCode() ?: 0)
result = 31 * result + (mediaType?.hashCode() ?: 0)
result = 31 * result + (properties?.hashCode() ?: 0)
result = 31 * result + (byteArray?.contentHashCode() ?: 0)
return result
}
} | 0 | Kotlin | 0 | 0 | 33d264760f07dd189ab4ef70117030bfe8ef0be0 | 1,832 | EbookProject | MIT License |
later-core/src/jsMain/kotlin/later/Later.kt | aSoft-Ltd | 322,250,962 | false | null | package later
import kotlin.js.Promise
actual open class Later<T> actual constructor(executor: ((resolve: (T) -> Unit, reject: ((Throwable) -> Unit)) -> Unit)?) : BaseLater<T>(executor) {
actual companion object {
actual fun <T> resolve(value: T) = Later<T> { resolve, _ -> resolve(value) }
actual fun reject(error: Throwable) = Later<Nothing> { _, reject -> reject(error) }
}
@JsName("asPromise")
fun asPromise(): Promise<T> = asDynamic().promise ?: Promise { resolve, reject ->
then(onResolved = { resolve(it) }, onRejected = { reject(it) })
}
} | 1 | Kotlin | 1 | 3 | 1dda3e0a6c712092bee4174d18b906bf42e79f50 | 595 | later | MIT License |
web/src/main/kotlin/com/theone/web/WebApplication.kt | snailflying | 158,662,297 | false | {"Gradle": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 47, "INI": 1, "Java": 2, "YAML": 1} | package com.theone.web
import com.theone.web.service.WxNettyService
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class WebApplication
fun main(args: Array<String>) {
// runApplication<WebApplication>(*args)
val context = runApplication<WebApplication>(*args)
val nettyServer = context.getBean(WxNettyService::class.java)
nettyServer.run()
}
| 1 | null | 1 | 1 | b43726776c4de373e918bd9f2522435189a3fd9f | 454 | SpringBootCore | Apache License 2.0 |
lithic-java-core/src/test/kotlin/com/lithic/api/models/ThreeDSDecisioningRotateSecretParamsTest.kt | lithic-com | 592,386,416 | false | {"Kotlin": 3278563, "Java": 3600, "Shell": 1249} | package com.lithic.api.models
import com.lithic.api.models.*
import org.junit.jupiter.api.Test
class ThreeDSDecisioningRotateSecretParamsTest {
@Test
fun createThreeDSDecisioningRotateSecretParams() {
ThreeDSDecisioningRotateSecretParams.builder().build()
}
}
| 0 | Kotlin | 0 | 14 | d4b5f3297e08aeb1bdbb3705731aef6a70912c7b | 283 | lithic-java | Apache License 2.0 |
src/main/kotlin/nl/kute/hashing/Hashing.kt | JanHendrikVanHeusden | 454,323,023 | false | {"Kotlin": 733032, "Java": 31861} | @file:JvmName("Hashing")
package nl.kute.hashing
import nl.kute.exception.handleWithReturn
import nl.kute.exception.throwableAsString
import nl.kute.hashing.DigestMethod.CRC32C
import nl.kute.hashing.DigestMethod.JAVA_HASHCODE
import nl.kute.logging.logWithCaller
import nl.kute.reflection.util.simplifyClassName
import nl.kute.util.asHexString
import nl.kute.util.byteArrayToHex
import java.nio.charset.Charset
import java.security.MessageDigest
import java.util.zip.CRC32C as JavaUtilCRC32C
/**
* Create a hex String based on the [input] object's [hashCode] method using `CRC32C`
* @param input The [String] object to create as hash String for
* @param charset The [Charset] of the [input] String
* @return The [input]'s [hashCode] as a hexadecimal String, consisting of characters `0..9`, `a..f`
*/
private fun JavaUtilCRC32C.hashCrc32C(input: String, charset: Charset): String {
this.update(input.toByteArray(charset))
val result = this.value.asHexString
return if (result == "") "0" else result
}
/**
* Create a hex String based on the [input] object's [hashCode] method using the receiver [MessageDigest]
* @param input The [String] object to create as hash String for
* @param charset The [Charset] of the [input] String
* @return The [input]'s [hashCode] as a hexadecimal String, consisting of characters `0..9`, `a..f`
*/
private fun MessageDigest.hashByAlgorithm(input: String, charset: Charset): String {
this.update(input.toByteArray(charset))
return this.digest().byteArrayToHex()
}
/**
* Create a hash String for the given [input] String
* @param input The [String] to create as hash for
* @param digestMethod The [DigestMethod] to create the hash with
* @param charset The [Charset] of the input [String]; default is [Charset.defaultCharset].
* @return The hash String as a hexadecimal String, consisting of characters `0..9`, `a..f`
* @see [nl.kute.asstring.annotation.modify.AsStringHash]
*/
@JvmSynthetic // avoid access from external Java code
internal fun hashString(input: String?, digestMethod: DigestMethod, charset: Charset = Charset.defaultCharset()): String? {
return if (input == null) null
else try {
when (digestMethod) {
JAVA_HASHCODE -> input.hashCode().asHexString
CRC32C -> (CRC32C.instanceProvider!!.invoke() as JavaUtilCRC32C).hashCrc32C(input, charset)
else -> (digestMethod.instanceProvider!!.invoke() as MessageDigest).hashByAlgorithm(input, charset)
}
} catch (e: Exception) {
return handleWithReturn(e, null) {
// The property's value is probably sensitive, so make sure not to use the value in the error message
logWithCaller(
"Hashing.hashString()",
"${e.javaClass.name.simplifyClassName()} occurred when hashing with digestMethod $digestMethod; exception: [${e.throwableAsString()}]"
)
}
}
}
| 0 | Kotlin | 0 | 1 | 6d83ba7e801cdd4dc27e321c9048ead4c365766c | 2,931 | Kute | MIT License |
app/src/main/kotlin/com/ne1c/gitteroid/events/RefreshMessagesRoomEvent.kt | fullstackenviormentss | 131,682,557 | true | {"Kotlin": 222987} | package com.ne1c.gitteroid.events
import com.ne1c.gitteroid.models.view.RoomViewModel
class RefreshMessagesRoomEvent(val roomModel: RoomViewModel)
| 0 | Kotlin | 0 | 0 | bf1af85eae715a168668ab472b406b8997c3c1c4 | 149 | GitterClient | Apache License 2.0 |
src/main/kotlin/com/theapache64/ghmm/util/JsonUtils.kt | theapache64 | 330,988,608 | false | null | package com.theapache64.ghmm.util
import kotlinx.serialization.json.Json
object JsonUtils {
val json = Json {
ignoreUnknownKeys = true
}
} | 25 | Kotlin | 3 | 52 | 439e52157669365a7431d30c1b6383a602c3f060 | 156 | gh-meme-maker | Apache License 2.0 |
ulyp-ui/src/main/kotlin/com/ulyp/ui/settings/RecordedCallWeightType.kt | 0xaa4eb | 393,146,539 | false | null | package com.ulyp.ui.settings
/**
* Every call in a call tree has weight. It's drawn as a rectangle in a background.
* It represents how much time/calls current call's subtree has in comparison to other calls. Currently, weight can
* be either time spent or call count.
*/
enum class RecordedCallWeightType {
TIME,
CALLS
} | 6 | null | 2 | 16 | f97e5c6a2b206c641a158288d7a2cdc4e24afde1 | 334 | ulyp | Apache License 2.0 |
apache-avro/apache-avro-producer-v2/src/main/kotlin/com/example/apacheavro/Application.kt | luramarchanjo | 241,752,765 | false | {"Java": 7994, "Kotlin": 7915} | package com.example.apacheavro
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableScheduling
@SpringBootApplication
@EnableScheduling
class ApacheAvroApplication
fun main(args: Array<String>) {
runApplication<ApacheAvroApplication>(*args)
}
| 1 | null | 1 | 1 | 70a1d1838e4ec8a756956a32c559fcb60ca5e533 | 364 | poc-kafka | Apache License 2.0 |
net.akehurst.language/agl-processor/src/jvm8Test/kotlin/processor/java8/test_Java8Agl_BlocksAndStatements.kt | dhakehurst | 197,245,665 | false | {"Kotlin": 3541898, "ANTLR": 64742, "Rascal": 17698, "Java": 14313, "PEG.js": 6866, "JavaScript": 5287, "BASIC": 22} | /**
* Copyright (C) 2020 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* 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 net.akehurst.language.agl.processor.java8
import net.akehurst.language.agl.grammar.grammar.AglGrammarSemanticAnalyser
import net.akehurst.language.agl.processor.Agl
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@RunWith(Parameterized::class)
class test_Java8Agl_BlocksAndStatements(val data: Data) {
private companion object {
private val grammarStr = this::class.java.getResource("/java8/Java8AglOptm.agl").readText()
val processor by lazy {
Agl.processorFromString(
grammarStr,
Agl.configuration(Agl.configurationDefault()) { targetGrammarName("BlocksAndStatements"); defaultGoalRuleName("Block") },
aglOptions = Agl.options {
semanticAnalysis {
// switch off ambiguity analysis for performance
option(AglGrammarSemanticAnalyser.OPTIONS_KEY_AMBIGUITY_ANALYSIS, false)
}
}
).processor!!
}
var sourceFiles = arrayOf(
"/java8/sentences/blocks-valid.txt"
)
@JvmStatic
@Parameters(name = "{0}")
fun data(): Collection<Array<Any>> {
val col = ArrayList<Array<Any>>()
for (sourceFile in sourceFiles) {
val inps = test_Java8Agl_BlocksAndStatements::class.java.getResourceAsStream(sourceFile)
val br = BufferedReader(InputStreamReader(inps))
var line: String? = br.readLine()
while (null != line) {
line = line.trim { it <= ' ' }
if (line.isEmpty()) {
// blank line
line = br.readLine()
} else if (line.startsWith("//")) {
// comment
line = br.readLine()
} else {
col.add(arrayOf(Data(sourceFile, line)))
line = br.readLine()
}
}
}
return col
}
}
class Data(val file: String, val text: String) {
// --- Object ---
override fun toString(): String {
return "${this.file} | ${this.text}"
}
}
@Test(timeout = 5000)
fun parse() {
val result = processor.parse(this.data.text)
assertNotNull(result.sppt)
assertTrue(result.issues.errors.isEmpty())
val resultStr = result.sppt!!.asString
assertEquals(this.data.text, resultStr)
assertEquals(1, result.sppt!!.maxNumHeads)
}
@Test(timeout = 5000)
fun process() {
val result = processor.process(this.data.text)
assertNotNull(result.asm)
assertTrue(result.issues.errors.isEmpty())
val resultStr = result.asm!!.asString(" ", "")
//assertEquals(this.data.text, resultStr)
assertEquals(1, result.asm?.rootElements?.size)
}
}
| 3 | Kotlin | 7 | 45 | 177abcb60c51efcfc2432174f5d6620a7db89928 | 3,871 | net.akehurst.language | Apache License 2.0 |
widgetssdk/src/main/java/com/glia/widgets/core/dialog/DialogController.kt | salemove | 312,288,713 | false | {"Kotlin": 1723271, "Java": 469744, "Shell": 1802} | package com.glia.widgets.core.dialog
import com.glia.androidsdk.comms.MediaUpgradeOffer
import com.glia.widgets.core.dialog.domain.SetEnableCallNotificationChannelDialogShownUseCase
import com.glia.widgets.core.dialog.model.DialogState
import com.glia.widgets.core.dialog.model.MediaUpgradeMode
import com.glia.widgets.helper.Logger
private const val TAG = "DialogController"
internal interface DialogContract {
interface Controller {
val isShowingUnexpectedErrorDialog: Boolean
val isEnableScreenSharingNotificationsAndStartSharingDialogShown: Boolean
fun dismissCurrentDialog()
fun dismissDialogs()
fun showExitQueueDialog()
fun showExitChatDialog()
fun showUpgradeAudioDialog(mediaUpgradeOffer: MediaUpgradeOffer, operatorName: String?)
fun showUpgradeVideoDialog2Way(mediaUpgradeOffer: MediaUpgradeOffer, operatorName: String?)
fun showUpgradeVideoDialog1Way(mediaUpgradeOffer: MediaUpgradeOffer, operatorName: String?)
fun showVisitorCodeDialog()
fun dismissVisitorCodeDialog()
fun showUnexpectedErrorDialog()
fun showOverlayPermissionsDialog()
fun dismissOverlayPermissionsDialog()
fun dismissMessageCenterUnavailableDialog()
fun showStartScreenSharingDialog(operatorName: String?)
fun showEnableCallNotificationChannelDialog()
fun showEnableScreenSharingNotificationsAndStartSharingDialog()
fun showMessageCenterUnavailableDialog()
fun showUnauthenticatedDialog()
fun showEngagementConfirmationDialog()
fun addCallback(callback: Callback)
fun removeCallback(callback: Callback)
fun interface Callback {
fun emitDialogState(dialogState: DialogState)
}
}
}
internal class DialogController(
private val setEnableCallNotificationChannelDialogShownUseCase: SetEnableCallNotificationChannelDialogShownUseCase
) : DialogContract.Controller {
private val viewCallbacks: MutableSet<DialogContract.Controller.Callback> = HashSet()
private val dialogManager: DialogManager by lazy { DialogManager(::emitDialogState) }
override val isShowingUnexpectedErrorDialog: Boolean
get() = dialogManager.currentDialogState is DialogState.UnexpectedError
override val isEnableScreenSharingNotificationsAndStartSharingDialogShown: Boolean
get() = DialogState.EnableScreenSharingNotificationsAndStartSharing == dialogManager.currentDialogState
private val isOverlayDialogShown: Boolean
get() = DialogState.OverlayPermission == dialogManager.currentDialogState
override fun dismissCurrentDialog() {
Logger.d(TAG, "Dismiss current dialog")
dialogManager.dismissCurrent()
}
override fun dismissDialogs() {
Logger.d(TAG, "Dismiss dialogs")
dialogManager.dismissAll()
}
private fun emitDialogState(dialogState: DialogState) {
Logger.d(TAG, "Emit dialog state:\n$dialogState")
viewCallbacks.forEach { it.emitDialogState(dialogState) }
}
override fun showExitQueueDialog() {
Logger.i(TAG, "Show Exit Queue Dialog")
dialogManager.addAndEmit(DialogState.ExitQueue)
}
override fun showExitChatDialog() {
Logger.i(TAG, "Show End Engagement Dialog")
dialogManager.addAndEmit(DialogState.EndEngagement)
}
override fun showUpgradeAudioDialog(mediaUpgradeOffer: MediaUpgradeOffer, operatorName: String?) {
Logger.i(TAG, "Show Upgrade Audio Dialog")
dialogManager.addAndEmit(DialogState.MediaUpgrade(mediaUpgradeOffer, operatorName, MediaUpgradeMode.AUDIO))
}
override fun showUpgradeVideoDialog2Way(mediaUpgradeOffer: MediaUpgradeOffer, operatorName: String?) {
Logger.i(TAG, "Show Upgrade 2WayVideo Dialog")
dialogManager.addAndEmit(DialogState.MediaUpgrade(mediaUpgradeOffer, operatorName, MediaUpgradeMode.VIDEO_TWO_WAY))
}
override fun showUpgradeVideoDialog1Way(mediaUpgradeOffer: MediaUpgradeOffer, operatorName: String?) {
Logger.i(TAG, "Show Upgrade 1WayVideo Dialog")
dialogManager.addAndEmit(DialogState.MediaUpgrade(mediaUpgradeOffer, operatorName, MediaUpgradeMode.VIDEO_ONE_WAY))
}
override fun showVisitorCodeDialog() {
Logger.i(TAG, "Show Visitor Code Dialog")
if (isOverlayDialogShown) {
dialogManager.add(DialogState.VisitorCode)
} else {
dialogManager.addAndEmit(DialogState.VisitorCode)
}
}
override fun dismissVisitorCodeDialog() {
Logger.i(TAG, "Dismiss Visitor Code Dialog")
dialogManager.remove(DialogState.VisitorCode)
}
override fun showUnexpectedErrorDialog() {
// Prioritise this error as it is engagement fatal error indicator
// (e.g., GliaException:{"details":"Queue is closed","error":"Unprocessable entity"}) for example
Logger.i(TAG, "Show Unexpected error Dialog")
dialogManager.addAndEmit(DialogState.UnexpectedError)
}
override fun showOverlayPermissionsDialog() {
Logger.i(TAG, "Show Overlay permissions Dialog")
dialogManager.addAndEmit(DialogState.OverlayPermission)
}
override fun dismissOverlayPermissionsDialog() {
Logger.d(TAG, "Dismiss Overlay Permissions Dialog")
dialogManager.remove(DialogState.OverlayPermission)
}
override fun dismissMessageCenterUnavailableDialog() {
Logger.d(TAG, "Dismiss Message Center Unavailable Dialog")
dialogManager.remove(DialogState.MessageCenterUnavailable)
}
override fun showStartScreenSharingDialog(operatorName: String?) {
Logger.i(TAG, "Show Start Screen Sharing Dialog")
dialogManager.addAndEmit(DialogState.StartScreenSharing(operatorName))
}
override fun showEnableCallNotificationChannelDialog() {
Logger.i(TAG, "Show Enable Call Notification Channel Dialog")
setEnableCallNotificationChannelDialogShownUseCase.execute()
dialogManager.addAndEmit(DialogState.EnableNotificationChannel)
}
override fun showEnableScreenSharingNotificationsAndStartSharingDialog() {
Logger.i(TAG, "Show Enable Screen Sharing Notifications And Start Screen Sharing Dialog")
dialogManager.addAndEmit(DialogState.EnableScreenSharingNotificationsAndStartSharing)
}
override fun showMessageCenterUnavailableDialog() {
Logger.i(TAG, "Show Message Center Unavailable Dialog")
dialogManager.addAndEmit(DialogState.MessageCenterUnavailable)
}
override fun showUnauthenticatedDialog() {
Logger.i(TAG, "Show Unauthenticated Dialog")
dialogManager.addAndEmit(DialogState.Unauthenticated)
}
override fun showEngagementConfirmationDialog() {
Logger.d(TAG, "Show Live Observation Opt In Dialog")
if (isOverlayDialogShown) {
dialogManager.add(DialogState.Confirmation)
} else {
dialogManager.addAndEmit(DialogState.Confirmation)
}
}
override fun addCallback(callback: DialogContract.Controller.Callback) {
Logger.d(TAG, "addCallback")
viewCallbacks.add(callback)
if (viewCallbacks.size == 1) {
dialogManager.showNext()
}
}
override fun removeCallback(callback: DialogContract.Controller.Callback) {
Logger.d(TAG, "removeCallback")
viewCallbacks.remove(callback)
}
}
| 5 | Kotlin | 1 | 5 | 12707c2b09cec76796cf06c8ee54c9a7c71e4034 | 7,440 | android-sdk-widgets | MIT License |
app/src/main/java/eventcalendar/jeeon/co/utility/EventListAdapter.kt | farhadssj | 154,870,832 | false | null | package eventcalendar.jeeon.co.utility
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import eventcalendar.jeeon.co.eventcalendar.R
import kotlinx.android.synthetic.main.each_event_item.view.*
class EventListAdapter internal constructor(
context: Context, val clickListener: (Event) -> Unit
) : RecyclerView.Adapter<EventListAdapter.EventViewHolder>() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private var events = emptyList<Event>()
private var allEvents = emptyList<Event>()
inner class EventViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val eventTitleTextView: TextView = itemView.findViewById(R.id.eventTitleTextView)
val eventDetailsTextView: TextView = itemView.findViewById(R.id.eventDetailsTextView)
fun bind(event: Event, clickListener: (Event) -> Unit) {
itemView.eventTitleTextView.text = event.title
itemView.eventDetailsTextView.text = event.details
itemView.setOnClickListener { clickListener(event)}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventViewHolder {
val itemView = inflater.inflate(R.layout.each_event_item, parent, false)
return EventViewHolder(itemView)
}
override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
holder.bind(events[position], clickListener)
}
internal fun setEvents(events: List<Event>, selectedTime : Long?) {
//filter with selected time
var selectedDateEventList = arrayListOf<Event>()
for (event: Event in events){
Log.e("Live Refresh", "EventTime: "+ event.event_date+ " selected Time: "+selectedTime)
if (event.event_date == selectedTime){
Log.e("Live Refresh", "Match")
selectedDateEventList.add(event)
}
}
this.allEvents = events
this.events = selectedDateEventList
notifyDataSetChanged()
}
internal fun loadSelectedDayEvents(selectedTime : Long?) {
//filter with selected time
var selectedDateEventList = arrayListOf<Event>()
for (event: Event in this.allEvents){
Log.e("Manual Refresh", "EventTime: "+ event.event_date+ " selected Time: "+selectedTime)
if (event.event_date == selectedTime){
Log.e("Manual Refresh", "Match")
selectedDateEventList.add(event)
}
}
this.events = selectedDateEventList
notifyDataSetChanged()
}
override fun getItemCount() = events.size
} | 0 | Kotlin | 1 | 0 | aef992651bbb4b7de17c62b7587337b366b95c95 | 2,797 | Event-Calendar | MIT License |
lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/AndroidDetectorTest.kt | MaTriXy | 116,227,290 | true | {"Kotlin": 177642, "Java": 43098, "Shell": 1027} | package com.vanniktech.lintrules.android
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import com.vanniktech.lintrules.android.AndroidDetector.ISSUE_RESOURCES_GET_COLOR
import com.vanniktech.lintrules.android.AndroidDetector.ISSUE_RESOURCES_GET_COLOR_STATE_LIST
import com.vanniktech.lintrules.android.AndroidDetector.ISSUE_RESOURCES_GET_DRAWABLE
import org.junit.Test
class AndroidDetectorTest {
private val resourcesStub = java("""
|package android.content.res;
|public class Resources {
| public void getDrawable(int id) {}
| public void getColor(int id) {}
| public void getColorStateList(int id) {}
|}""".trimMargin())
@Test fun callingGetDrawable() {
lint()
.files(resourcesStub, java("""
|package foo;
|import android.content.res.Resources;
|class Example {
| public void foo() {
| Resources resources = null;
| resources.getDrawable(0);
| }
|}""".trimMargin()))
.issues(ISSUE_RESOURCES_GET_DRAWABLE)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using deprecated getDrawable() [ResourcesGetDrawable]
| resources.getDrawable(0);
| ~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
}
@Test fun callingGetColor() {
lint()
.files(resourcesStub, java("""
|package foo;
|import android.content.res.Resources;
|class Example {
| public void foo() {
| Resources resources = null;
| resources.getColor(0);
| }
|}""".trimMargin()))
.issues(ISSUE_RESOURCES_GET_COLOR)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using deprecated getColor() [ResourcesGetColor]
| resources.getColor(0);
| ~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
}
@Test fun callingGetColorStateList() {
lint()
.files(resourcesStub, java("""
|package foo;
|import android.content.res.Resources;
|class Example {
| public void foo() {
| Resources resources = null;
| resources.getColorStateList(0);
| }
|}""".trimMargin()))
.issues(ISSUE_RESOURCES_GET_COLOR_STATE_LIST)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using deprecated getColorStateList() [ResourcesGetColorStateList]
| resources.getColorStateList(0);
| ~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
}
}
| 0 | Kotlin | 0 | 0 | 06cf052b352bfcba7010b2f0e285f0ac327c332e | 2,736 | lint-rules | Apache License 2.0 |
app/src/main/java/com/playground/redux/repository/Specification.kt | petnagy | 127,631,057 | false | null | package com.playground.redux.repository
interface Specification | 0 | Kotlin | 0 | 2 | bc1ed41d8b9cf404417229fde24571e3b667e587 | 64 | redux_playground | MIT License |
app/src/main/java/com/wx/compose/plugin/activity/CollapsableActivity.kt | wgllss | 872,242,948 | false | {"Kotlin": 220285, "Java": 1033} | package com.wx.compose.plugin.activity
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
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.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.lifecycleScope
import com.wx.compose.plugin.R
import com.wx.compose.plugin.viewmodel.ComposeViewModel
import com.wx.compose1.ui.composable.baseUI
import com.wx.compose1.ui.theme.WXComposePlugin
import kotlinx.coroutines.launch
import me.onebone.toolbar.CollapsingToolbarScaffold
import me.onebone.toolbar.ExperimentalToolbarApi
import me.onebone.toolbar.ScrollStrategy
import me.onebone.toolbar.rememberCollapsingToolbarScaffoldState
class CollapsableActivity : ComponentActivity() {
val viewModel by viewModels<ComposeViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
lifecycleScope.launch {
setContent {
WXComposePlugin {
// Surface(color = MaterialTheme.colorScheme.background) {
// ParallaxEffect()
// }
MainScreen()
// ParallaxEffect()
}
}
}
}
}
@Composable
fun MainScreen() {
val state = rememberCollapsingToolbarScaffoldState()
CollapsingToolbarScaffold(modifier = Modifier.fillMaxSize(), state = state, scrollStrategy = ScrollStrategy.ExitUntilCollapsed, toolbar = {
val textSize = (18 + (30 - 18) * state.toolbarState.progress).sp
Box(
modifier = Modifier
.background(MaterialTheme.colorScheme.primary)
.fillMaxWidth()
.height(150.dp)
.pin()
)
Image(
modifier = Modifier
.parallax(0.5f)
.height(300.dp)
.fillMaxWidth()
.pin()
// .padding(16.dp)
.graphicsLayer {
// change alpha of Image as the toolbar expands
alpha = state.toolbarState.progress
}, contentScale = ContentScale.Crop, painter = painterResource(id = R.drawable.ava2), contentDescription = null
)
Text(
text = "Title", modifier = Modifier
// .height(81.dp)
.road(Alignment.CenterStart, Alignment.BottomEnd)
.padding(60.dp, 36.dp, 16.dp, 16.dp), textAlign = TextAlign.Center, color = Color.White, fontSize = textSize
)
}) {
LazyColumn(
modifier = Modifier.fillMaxWidth()
) {
items(100) {
Text(
text = "Item $it", modifier = Modifier.padding(8.dp)
)
}
}
// Box(modifier = Modifier
// .fillMaxWidth()
// .alpha(0.5f)
//// .background(MaterialTheme.colorScheme.secondary)
// .graphicsLayer {
// // change alpha of Image as the toolbar expands
// alpha = state.toolbarState.progress
// }
// .height(40.dp))
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ParallaxEffect() {
val state = rememberCollapsingToolbarScaffoldState()
var enabled by remember { mutableStateOf(true) }
Box {
CollapsingToolbarScaffold(modifier = Modifier.fillMaxSize(), state = state, scrollStrategy = ScrollStrategy.ExitUntilCollapsed, toolbarModifier = Modifier.background(MaterialTheme.colorScheme.primary), enabled = enabled, toolbar = {
// Collapsing toolbar collapses its size as small as the that of
// a smallest child. To make the toolbar collapse to 50dp, we create
// a dummy Spacer composable.
// You may replace it with TopAppBar or other preferred composable.
Spacer(
modifier = Modifier
.fillMaxWidth()
.background(Color.Red)
.height(50.dp)
)
Image(
painter = painterResource(id = R.drawable.ava2), modifier = Modifier
.parallax(0.5f)
.height(300.dp)
.fillMaxWidth()
.graphicsLayer {
// change alpha of Image as the toolbar expands
alpha = state.toolbarState.progress
}, contentScale = ContentScale.Crop, contentDescription = null
)
}) {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
stickyHeader {
Text(
modifier = Modifier
.fillMaxWidth()
.height(81.dp)
.align(Alignment.Center)
// .background(Color.Red)
, text = "吸顶标题栏", fontWeight = FontWeight.Bold
)
}
items(List(100) { "Hello World!! $it" }) {
Text(
text = it, modifier = Modifier
.fillMaxWidth()
.padding(4.dp)
)
}
}
@OptIn(ExperimentalToolbarApi::class) Button(modifier = Modifier
.padding(16.dp)
.align(Alignment.BottomEnd), onClick = { }) {
Text(text = "Floating Button!")
}
}
// Row(
// verticalAlignment = Alignment.CenterVertically
// ) {
//// Checkbox(checked = enabled, onCheckedChange = { enabled = !enabled })
//
// Text(
// modifier = Modifier
// .fillMaxWidth()
// .height(50.dp)
// .align(Alignment.CenterVertically)
//// .background(Color.Red)
// , text = "Enable collapse/expand", fontWeight = FontWeight.Bold
// )
// }
}
}
| 0 | Kotlin | 0 | 6 | d290b4bbd412aabc33fa66b61c3e7f082724f4bd | 7,963 | WX-Compose-Plugin | Mulan Permissive Software License, Version 2 |
idea/tests/testData/indentationOnNewline/controlFlowConstructions/IfBeforeCondition.kt | JetBrains | 278,369,660 | false | null | fun some() {
if <caret>(3 > 5) {
}
}
| 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 46 | intellij-kotlin | Apache License 2.0 |
src/common/src/main/kotlin/org/icpclive/util/FileChangesWatcher.kt | icpc | 447,849,919 | false | null | package org.icpclive.util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchEvent
import java.util.concurrent.TimeUnit
import org.slf4j.Logger
import kotlin.io.path.inputStream
import kotlin.io.path.listDirectoryEntries
import kotlin.time.Duration.Companion.seconds
fun directoryChangesFlow(path: Path) =
flow {
while (currentCoroutineContext().isActive) {
path.fileSystem.newWatchService().use { watcher ->
path.register(
watcher,
arrayOf(StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY)
)
path.listDirectoryEntries().forEach { emit(it.fileName) }
while (currentCoroutineContext().isActive) {
val key = watcher.poll(100, TimeUnit.MILLISECONDS) ?: continue
for (event in key.pollEvents()) {
val kind = event.kind()
if (kind === StandardWatchEventKinds.OVERFLOW) {
path.listDirectoryEntries().forEach { emit(it) }
continue
}
@Suppress("UNCHECKED_CAST")
emit((event as WatchEvent<Path>).context())
}
if (!key.reset()) {
break
}
}
}
}
}.map { path.resolve(it).toAbsolutePath() }
.flowOn(Dispatchers.IO)
fun fileChangesFlow(path: Path) = directoryChangesFlow(path.parent.toAbsolutePath())
.filter { it.endsWith(path.fileName) }
@OptIn(ExperimentalSerializationApi::class)
inline fun <reified T> fileJsonContentFlow(path: Path, logger: Logger) = fileChangesFlow(path).map {
logger.info("Reloaded ${path.fileName}")
path.inputStream().use {
Json.decodeFromStream<T>(it)
}
}.flowOn(Dispatchers.IO)
.logAndRetryWithDelay(5.seconds) {
logger.error("Failed to reload ${path.fileName}", it)
} | 14 | Kotlin | 7 | 28 | 8d3469e8507227f17bda28c5ac0652411a8d09dc | 2,320 | live-v3 | MIT License |
plugins/kotlin-plugin/src/main/kotlin/io/github/gmazzo/codeowners/CodeOwnersKotlinTargetExtension.kt | gmazzo | 575,122,672 | false | {"Kotlin": 107229, "Java": 3485} | package io.github.gmazzo.codeowners
import org.gradle.api.provider.Property
interface CodeOwnersKotlinTargetExtension {
/**
* If it should compute the code owners for this compilation target
*/
val enabled: Property<Boolean>
}
| 2 | Kotlin | 0 | 4 | 527ac59020a95094f0041cbce8e2aaa8b131556e | 249 | gradle-codeowners-plugin | MIT License |
app/src/main/java/com/faldez/shachi/data/model/TagDetail.kt | faldez | 457,580,136 | false | null | package com.faldez.shachi.data.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
enum class Modifier(val symbol: String) {
Minus("-"),
Tilde("~"),
Wildcard("*"),
}
const val modifierRegex = "^[-~*\\{]|\\}\$"
/*
Tag with post count and excluded status, only to be used in search
*/
@Parcelize
data class TagDetail(
val name: String,
val count: Int? = null,
val type: Category = Category.Unknown,
val modifier: Modifier? = null,
) : Parcelable {
override fun toString(): String {
return when (modifier) {
null -> name
else -> "${modifier.symbol}$name"
}
}
companion object {
fun fromName(name: String): TagDetail {
val tag = name.replaceFirst(Regex(modifierRegex), "")
val modifier = when (name.firstOrNull()) {
'~' -> Modifier.Tilde
'-' -> Modifier.Minus
'*' -> Modifier.Wildcard
null -> throw IllegalAccessException()
else -> null
}
return TagDetail(name = tag, modifier = modifier)
}
fun fromTag(tag: Tag): TagDetail {
return fromName(tag.name).copy(type = tag.type)
}
}
}
fun List<Tag>.mapToTagDetails(): List<TagDetail> = this.map {
TagDetail(name = it.name, type = it.type)
}
fun List<TagDetail>.mapToTags(serverId: Int): List<Tag> =
this.map { Tag(name = it.name, type = it.type, serverId = serverId) } | 8 | Java | 1 | 20 | 6491f53f06ae2aeb6cd786fb9f4fe7cb21958540 | 1,499 | shachi | Apache License 2.0 |
app/src/main/java/io/github/fornewid/dagger/hilt/example/ExampleViewModel.kt | fornewid | 675,553,168 | false | null | package io.github.fornewid.dagger.hilt.example
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.fornewid.feature.bar.Bar
import javax.inject.Inject
@HiltViewModel
class ExampleViewModel @Inject constructor(
private val bar: Bar,
) : ViewModel() {
fun doSomething() {
bar.toString()
}
}
| 1 | Kotlin | 0 | 2 | cef3bf6ba621fb9f5eb8ac6e3421b31caa975646 | 364 | dagger-hilt-example | Apache License 2.0 |
as2f/src/main/kotlin/dev/vishna/as2f/DartResolver.kt | eyeem | 411,635,250 | true | {"Kotlin": 35634, "Dart": 6383} | package dev.vishna.as2f
import dev.vishna.as2f.LangResolver
import dev.vishna.stringcode.smartCamelize
import java.lang.IllegalStateException
class DartResolver : LangResolver() {
override fun className(model: Model): String = model.name.smartCamelize()
override fun memberType(field: Field): String {
return when(field) {
is StringField -> "String"
is IntField -> "int"
is DateField -> "DateTime"
is FloatField -> "double"
is LongField -> "int"
is BooleanField -> "bool"
is ArrayField -> "List<${memberType(field.field)}>"
is CustomField -> field.customType.smartCamelize()
}
}
fun dynamicType(field: Field) : String {
return with(field.info) {
when (field) {
is CustomField -> """${field.customType.smartCamelize()}"""
is DateField -> """DateTime"""
is ArrayField -> """List<${memberType(field.field)}>"""
else -> """dynamic"""
}
}
}
fun ctor1(field: Field) : String {
if (!field.info.serializable) { // means it isn't part of json
return "null"
}
return with(field.info) {
when (field) {
is CustomField -> """${field.customType.smartCamelize()}.fromJson(json['$nameUnescaped'])"""
is DateField -> """DateTime.parse(json['$nameUnescaped'])"""
is ArrayField -> """json['$nameUnescaped']?.map((it) => ${arrayCtor(field.field)})?.toList()${arrayCast(field.field)}"""
is FloatField -> "json['$nameUnescaped']?.toDouble()"
is StringField -> "json['$nameUnescaped']?.toString()"
else -> """json['$nameUnescaped']"""
}
}
}
private fun arrayCtor(innerField: Field) : String {
return when (innerField) {
is FloatField -> "it?.toDouble()"
is LongField,
is BooleanField,
is StringField,
is DateField,
is IntField -> "it"
is CustomField -> """${innerField.customType.smartCamelize()}?.fromJson(it)"""
is ArrayField -> throw IllegalStateException("nested arrays unsupported because developer is lazy.")
}
}
private fun arrayCast(innerField: Field) : String {
return when (innerField) {
is FloatField,
is LongField,
is BooleanField,
is StringField,
is DateField,
is IntField -> """?.cast<${memberType(innerField)}>()"""
is CustomField -> """?.cast<${innerField.customType.smartCamelize()}>()"""
is ArrayField -> throw IllegalStateException("nested arrays unsupported because developer is lazy.")
}
}
private fun arrayMap(innerField: Field) : String {
return when (innerField) {
is FloatField,
is LongField,
is BooleanField,
is StringField,
is DateField,
is IntField -> "it"
is CustomField -> """it?.copyWith()"""
is ArrayField -> throw IllegalStateException("nested arrays unsupported because developer is lazy.")
}
}
fun copyWith(field: Field) : String {
return with(field.info) {
when (field) {
is FloatField,
is LongField,
is BooleanField,
is StringField,
is DateField,
is IntField -> """${field.info.name} ?? this.${field.info.name}"""
is CustomField -> """${field.info.name} ?? this.${field.info.name}?.copyWith()"""
is ArrayField -> """${field.info.name} ?? this.${field.info.name}?.map((it) => ${arrayMap(innerField = field.field)} )?.toList()"""
}
}
}
fun dtor(field: Field) : String {
if (!field.info.serializable) {
return "null"
}
return with(field.info) {
when (field) {
is FloatField,
is LongField,
is BooleanField,
is StringField,
is IntField -> name
is DateField -> """$name?.toIso8601String()"""
is CustomField -> """$name?.toJson()"""
is ArrayField -> """$name?.map((it) => ${arrayDtor(field.field)})?.toList()"""
}
}
}
fun arrayDtor(field: Field) : String {
return when (field) {
is FloatField,
is LongField,
is BooleanField,
is StringField,
is IntField -> "it"
is DateField -> """it?.toIso8601String()"""
is CustomField -> """it?.toJson()"""
is ArrayField -> throw IllegalStateException("nested arrays unsupported because developer is lazy.")
}
}
fun objectId(model: Model) : String {
val hasIdField = model.fields.find { it is StringField && it.info.name == "id" } != null
if (hasIdField) {
return """"${className(model)}#${'$'}{id}";"""
} else {
return "null; // id field not recognized by generator"
}
}
override val specialNames: List<String>
get() = listOf("new", "do", "with", "other")
} | 0 | null | 0 | 0 | ebd5fec61b2934ded8b19732894938e21636c6de | 5,365 | as2f | Apache License 2.0 |
idea/testData/codeInsight/overrideImplement/overridePrimitiveProperty.kt | JakeWharton | 99,388,807 | true | null | interface T {
val a1: Byte
val a2: Short
val a3: Int
val a4: Long
val a5: Float
val a6: Double
val a7: Char
val a8: Boolean
}
class C : T {<caret>
} | 0 | Kotlin | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 181 | kotlin | Apache License 2.0 |
kotlin-html/src/commonTest/kotlin/dev/scottpierce/html/style/StyleTest.kt | kpgalligan | 219,295,211 | true | {"Kotlin": 346305, "Shell": 456, "JavaScript": 103} | package dev.scottpierce.html
import dev.scottpierce.html.style.style
import dev.scottpierce.html.util.assertEquals
import dev.scottpierce.html.util.writeStyle
import dev.scottpierce.html.write.WriteOptions
import kotlin.test.Test
class StyleTest {
@Test
fun basic() {
writeStyle {
properties["blah"] = "blah"
} assertEquals {
"blah: blah;"
}
}
@Test
fun basicMinified() {
writeStyle(options = WriteOptions(minifyStyles = true)) {
properties["blah"] = "blah"
} assertEquals {
"blah:blah;"
}
}
@Test
fun addStyle() {
writeStyle {
properties["blah"] = "blah"
+style {
properties["blah2"] = "blah2"
}
} assertEquals {
"""
blah: blah;
blah2: blah2;
""".trimIndent()
}
}
} | 0 | Kotlin | 0 | 0 | e3dc01e8396a115ca5bcf405e8eb1c032d739afe | 926 | kotlin-html | Apache License 2.0 |
features/jumps/domain/src/main/java/com/fredprojects/features/jumps/domain/useCases/crud/GetJDUseCase.kt | FredNekrasov | 832,214,231 | false | {"Kotlin": 204897} | package com.fredprojects.features.jumps.domain.useCases.crud
import com.fredprojects.features.jumps.domain.repositories.IJDRepository
import com.fredprojects.features.jumps.domain.utils.SortType
import kotlinx.coroutines.flow.map
/**
* GetJDUseCase is used to get data from the database
* @param repository the repository used to get data from the database
*/
class GetJDUseCase(
private val repository: IJDRepository
) {
/**
* invoke is used to get data from the database
* @param sortType the type of sorting
* @return the flow of data received from the database sorted by date in ascending or descending order
*/
operator fun invoke(sortType: SortType) = repository.getData().map { jumpDataList ->
when(sortType) {
SortType.Ascending -> jumpDataList.sortedBy { it.date }
SortType.Descending -> jumpDataList.sortedByDescending { it.date }
}
}
} | 0 | Kotlin | 0 | 1 | 121509e94bf25e341b7187fe86f75a310638cc30 | 927 | jetpack-compose-projects | MIT License |
app/src/main/java/com/koma/video/data/source/VideoDataSource.kt | komamj | 135,701,576 | false | {"Kotlin": 177378} | package com.koma.video.data.source
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.provider.MediaStore
import com.koma.video.data.enities.BucketEntry
import com.koma.video.data.enities.VideoEntryDetail
import com.koma.video.data.enities.VideoEntry
import com.koma.video.util.LogUtils
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import java.io.FileNotFoundException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class VideoDataSource @Inject constructor(private val context: Context) : IVideoDataSource {
private val resolver: ContentResolver by lazy<ContentResolver> {
context.contentResolver
}
override fun getVideoEntries(): Flowable<List<VideoEntry>> {
return Flowable.create({
val entries = ArrayList<VideoEntry>()
val projection = arrayOf(
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION
)
val cursor =
resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
SORT_ORDER
)
cursor?.use {
if (cursor.count > 0) {
it.moveToFirst()
do {
val entry = VideoEntry(it.getLong(0), it.getString(1), it.getInt(2))
entries.add(entry)
} while (it.moveToNext())
}
}
it.onNext(entries)
it.onComplete()
}, BackpressureStrategy.LATEST)
}
override fun getBucketEntries(): Flowable<List<BucketEntry>> {
return Flowable.create({
val entries = ArrayList<BucketEntry>()
val projection = arrayOf(
MediaStore.Video.VideoColumns.BUCKET_ID,
MediaStore.Video.VideoColumns.BUCKET_DISPLAY_NAME,
MediaStore.Video.Media.DATE_TAKEN
)
val selection = "1) GROUP BY (1"
val cursor = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection,
selection, null, null
)
cursor?.use {
if (cursor.count > 0) {
it.moveToFirst()
do {
val bucketId = it.getInt(0)
val dateTaken = it.getInt(2)
val entry = BucketEntry(bucketId, it.getString(1))
entry.dateTaken = dateTaken
val cur = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Video.Media._ID),
MediaStore.Video.Media.BUCKET_ID + " = ?",
arrayOf(bucketId.toString()), SORT_ORDER
)
cur?.use {
if (cur.count > 0) {
cur.moveToFirst()
entry.uri = ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
cur.getLong(0)
)
entry.count = cur.count
entries.add(entry)
}
}
} while (it.moveToNext())
}
}
it.onNext(entries)
it.onComplete()
}, BackpressureStrategy.LATEST)
}
override fun getVideoEntries(bucketId: Int): Flowable<List<VideoEntry>> {
return Flowable.create({
val entries = ArrayList<VideoEntry>()
val projection = arrayOf(
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION
)
val selection = MediaStore.Video.Media.BUCKET_ID + " = ?"
val cursor =
resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
arrayOf(bucketId.toString()),
SORT_ORDER
)
cursor?.use {
if (cursor.count > 0) {
it.moveToFirst()
do {
val entry = VideoEntry(it.getLong(0), it.getString(1), it.getInt(2))
entries.add(entry)
} while (it.moveToNext())
}
}
it.onNext(entries)
it.onComplete()
}, BackpressureStrategy.LATEST)
}
override fun getVideoDetailEntry(mediaId: Long): Flowable<VideoEntryDetail> {
return Flowable.create({
val projection = arrayOf(
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.DATE_TAKEN,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATA
)
val selection = MediaStore.Video.Media._ID + " = ?"
val cursor =
resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
arrayOf(mediaId.toString()),
null
)
if (cursor == null || cursor.count <= 0) {
it.onError(FileNotFoundException("the media id $mediaId is not existed"))
} else {
val entry = cursor.use {
it.moveToFirst()
VideoEntryDetail(
it.getString(0),
it.getInt(1),
it.getLong(2),
it.getLong(3),
it.getString(4)
)
}
it.onNext(entry)
it.onComplete()
}
}, BackpressureStrategy.LATEST)
}
override fun getTitle(mediaId: Long): Flowable<String> {
return Flowable.create(
{
var title = ""
val cursor =
resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE),
MediaStore.Video.Media._ID + " = ?",
arrayOf(mediaId.toString()),
null
)
cursor?.use {
it.moveToFirst()
title = it.getString(1)
}
it.onNext(title)
it.onComplete()
}, BackpressureStrategy.LATEST
)
}
override fun getVideoEntries(keyword: String): Flowable<List<VideoEntry>> {
return Flowable.create({
val entries = ArrayList<VideoEntry>()
val projection = arrayOf(
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION
)
val selection = MediaStore.Video.Media.DISPLAY_NAME + " LIKE '%$keyword%'"
LogUtils.d(TAG, "selection $selection")
val cursor =
resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
SORT_ORDER
)
cursor?.use {
if (cursor.count > 0) {
it.moveToFirst()
do {
val entry = VideoEntry(it.getLong(0), it.getString(1), it.getInt(2))
entries.add(entry)
} while (it.moveToNext())
}
}
it.onNext(entries)
it.onComplete()
}, BackpressureStrategy.LATEST)
}
companion object {
private const val TAG = "VideoDataSource"
private const val SORT_ORDER = MediaStore.Video.Media.DATE_TAKEN + " DESC"
}
} | 0 | Kotlin | 1 | 1 | be4142c9126b0e74cd1d8d1dcaae5285505294d8 | 8,515 | Video | Apache License 2.0 |
core-starter/src/main/kotlin/com/labijie/application/data/pojo/LocalizationMessage.kt | hongque-pro | 309,874,586 | false | {"Kotlin": 1051745, "Java": 72766} | @file:Suppress("RedundantVisibilityModifier")
package com.labijie.application.`data`.pojo
import kotlin.String
/**
* POJO for LocalizationMessageTable
*
* This class made by a code generation tool (https://github.com/hongque-pro/infra-orm).
*
* Don't modify these codes !!
*
* Origin Exposed Table:
* @see com.labijie.application.data.LocalizationMessageTable
*/
public open class LocalizationMessage {
public var locale: String = ""
public var code: String = ""
public var message: String = ""
}
| 0 | Kotlin | 0 | 8 | 9e2b1f76bbb239ae9029bd27cda2d17f96b13326 | 517 | application-framework | Apache License 2.0 |
src/main/kotlin/com/pandus/leetcode/solutions/daily/KthSmallestInLexicographicalOrder.kt | bodyangug | 740,204,714 | false | {"Kotlin": 294942} | package com.pandus.leetcode.solutions.daily
// Reference: https://leetcode.com/problems/k-th-smallest-in-lexicographical-order
class KthSmallestInLexicographicalOrder {
fun findKthNumber(n: Int, k: Int): Int {
var remainingK = k - 1L
var current = 1L
while (remainingK > 0) {
val steps = calculateSteps(n.toLong(), current, current + 1)
if (steps <= remainingK) {
current += 1
remainingK -= steps
} else {
current *= 10
remainingK -= 1
}
}
return current.toInt()
}
private fun calculateSteps(n: Long, firstPrefix: Long, nextPrefix: Long): Long {
var steps = 0L
var first = firstPrefix
var last = nextPrefix
while (first <= n) {
steps += minOf(n + 1, last) - first
first *= 10
last *= 10
}
return steps
}
}
| 0 | Kotlin | 0 | 1 | 95f90c3703faf4bebf54b5901ea2bab41431b8b0 | 963 | leetcode-solutions | MIT License |
app/src/main/java/io/github/cnpog/gamingview/ui/gamingview/TabAdapter.kt | cnpog | 877,409,789 | false | {"Kotlin": 36356} | package io.github.cnpog.gamingview.ui.gamingview
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import io.github.cnpog.gamingview.settings.Mode
import io.github.cnpog.gamingview.settings.Position
class TabAdapter(
fragmentActivity: FragmentActivity,
private val mode: Mode?,
private val appPosition: Position?
) : FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int = 3
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> TabMobaFragment().apply {
arguments = Bundle().apply {
putSerializable("mode", mode)
putSerializable("position", [email protected])
}
}
1 -> TabShooterFragment().apply {
arguments = Bundle().apply {
putSerializable("mode", mode)
putSerializable("position", [email protected])
}
}
2 -> TabVerticalFragment().apply {
arguments = Bundle().apply {
putSerializable("mode", mode)
putSerializable("position", [email protected])
}
}
else -> throw IllegalStateException("Invalid position")
}
}
}
| 0 | Kotlin | 0 | 2 | 432af67578826207c712424787e8915cdea8f629 | 1,458 | ZuiAdvancedGamingView | MIT License |
data-login/api/src/main/java/com/mukul/jan/primer/data/login/api/repo/LoginRepo.kt | Mukuljangir372 | 600,396,968 | false | null | package com.mukul.jan.primer.data.login.api.repo
import com.mukul.jan.primer.data.login.api.repo.model.RegisterUserActionDataModel
import com.mukul.jan.primer.data.login.api.repo.model.UserModel
import kotlinx.coroutines.flow.Flow
interface LoginRepo {
suspend fun signIn(key: String, password: String): Flow<UserModel>
suspend fun signUp(model: RegisterUserActionDataModel): Flow<UserModel>
suspend fun isLoggedIn(): Flow<Boolean>
} | 0 | Kotlin | 4 | 8 | 5135cc81e1bca2c380460694779d5c343de4ea18 | 447 | Primer-Android | Apache License 2.0 |
1442.Count Triplets That Can Form Two Arrays of Equal XOR.kt | sarvex | 842,260,390 | false | {"Kotlin": 1775678, "PowerShell": 418} | internal class Solution {
fun countTriplets(arr: IntArray): Int {
val n = arr.size
val pre = IntArray(n + 1)
for (i in 0 until n) {
pre[i + 1] = pre[i] xor arr[i]
}
var ans = 0
for (i in 0 until n - 1) {
for (j in i + 1 until n) {
for (k in j until n) {
val a = pre[j] xor pre[i]
val b = pre[k + 1] xor pre[j]
if (a == b) {
++ans
}
}
}
}
return ans
}
}
| 0 | Kotlin | 0 | 0 | 71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48 | 475 | kotlin-leetcode | MIT License |
kalendar/src/main/java/com/himanshoe/kalendar/component/day/KalendarDay.kt | yogeshpaliyal | 472,848,577 | true | {"Kotlin": 84961} | package com.himanshoe.kalendar.endlos.component.day
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.himanshoe.kalendar.endlos.component.day.config.KalendarDayColors
import com.himanshoe.kalendar.endlos.component.day.config.KalendarDayState
import com.himanshoe.kalendar.endlos.component.text.KalendarNormalText
import com.himanshoe.kalendar.endlos.model.KalendarDay
import com.himanshoe.kalendar.endlos.model.KalendarEvent
import kotlinx.datetime.LocalDate
@Composable
fun KalendarDay(
kalendarDay: KalendarDay,
modifier: Modifier = Modifier,
size: Dp = 56.dp,
textSize: TextUnit = 16.sp,
kalendarEvents: List<KalendarEvent> = emptyList(),
isCurrentDay: Boolean = false,
onCurrentDayClick: (KalendarDay, List<KalendarEvent>) -> Unit = { _, _ -> },
selectedKalendarDay: LocalDate,
kalendarDayColors: KalendarDayColors,
dotColor: Color,
dayBackgroundColor: Color,
) {
val kalendarDayState = getKalendarDayState(selectedKalendarDay, kalendarDay.localDate)
val bgColor = getBackgroundColor(kalendarDayState, dayBackgroundColor)
val textColor = getTextColor(kalendarDayState, kalendarDayColors)
val weight = getTextWeight(kalendarDayState)
val border = getBorder(isCurrentDay)
Column(
modifier = modifier
.border(border = border, shape = CircleShape)
.clip(shape = CircleShape)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = true)
) { onCurrentDayClick(kalendarDay, kalendarEvents) }
.size(size = size)
.background(color = bgColor),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
KalendarNormalText(
text = kalendarDay.localDate.dayOfMonth.toString(),
modifier = Modifier,
fontWeight = weight,
color = textColor,
textSize = textSize,
)
Row(
modifier = Modifier
.padding(top = 4.dp)
.fillMaxWidth()
.align(Alignment.CenterHorizontally),
horizontalArrangement = Arrangement.Center
) {
if (kalendarEvents.isNotEmpty()) {
kalendarEvents.take(3).forEachIndexed { index, _ ->
KalendarDots(
modifier = Modifier,
index = index,
size = size,
color = dotColor
)
}
}
}
}
}
@Composable
fun EmptyKalendarDay(
modifier: Modifier = Modifier,
size: Dp = 56.dp,
background: Color,
) {
Box(
modifier = modifier
.clip(shape = RectangleShape)
.size(size = size)
.background(
color = background
),
)
}
@Composable
fun KalendarDots(
modifier: Modifier = Modifier,
index: Int,
size: Dp,
color: Color
) {
Box(
modifier = modifier
.padding(horizontal = 1.dp)
.clip(shape = CircleShape)
.background(
color = color
.copy(alpha = index.plus(1) * 0.3F)
)
.size(size = size.div(12))
)
}
private fun getKalendarDayState(selectedDate: LocalDate, currentDay: LocalDate) =
when (selectedDate) {
currentDay -> KalendarDayState.KalendarDaySelected
else -> KalendarDayState.KalendarDayDefault
}
private fun getBorder(isCurrentDay: Boolean) =
BorderStroke(
width = if (isCurrentDay) 1.dp else 0.dp,
color = if (isCurrentDay) Color.Black else Color.Transparent,
)
private fun getTextWeight(kalendarDayState: KalendarDayState) =
if (kalendarDayState is KalendarDayState.KalendarDaySelected) {
FontWeight.Bold
} else {
FontWeight.SemiBold
}
private fun getBackgroundColor(
kalendarDayState: KalendarDayState,
backgroundColor: Color,
) = if (kalendarDayState is KalendarDayState.KalendarDaySelected) {
backgroundColor
} else {
Color.Transparent
}
private fun getTextColor(
kalendarDayState: KalendarDayState,
kalendarDayColors: KalendarDayColors,
): Color = if (kalendarDayState is KalendarDayState.KalendarDaySelected) {
kalendarDayColors.selectedTextColor
} else {
kalendarDayColors.textColor
}
@Preview
@Composable
private fun KalendarDayPreview() {
// KalendarDay(
// kalendarDay = KalendarDay(localDate = Clock.System.todayIn(TimeZone.currentSystemDefault())),
// kalendarDayConfig = KalendarDayDefaults.kalendarDayConfig(),
// selectedKalendarDate = mutableStateOf<LocalDate>()
// )
}
| 0 | Kotlin | 0 | 1 | 158330e93eb50a639abb52e032925b47b9d539f4 | 5,996 | Kalendar | Apache License 2.0 |
presentation/src/main/java/com/yapp/bol/presentation/utils/KeyboardManager.kt | YAPP-Github | 634,125,431 | false | {"Kotlin": 369447} | package com.yapp.bol.presentation.utils
import android.app.Activity
import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
class KeyboardManager(
private val activity: Activity,
) {
private val inputManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
fun hideKeyboard() {
if (activity.currentFocus == null) return
inputManager.hideSoftInputFromWindow(activity.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
fun showKeyboard(editText: EditText) {
if (activity.currentFocus == null) return
inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}
}
| 1 | Kotlin | 2 | 14 | 4b5efbf0d68d5d2b03d4afd5a08e73e5bb67bd9b | 735 | onboard-aos | Apache License 2.0 |
app/src/main/java/com/fjbg/weather/data/mapper/Mapper.kt | franciscobarrios | 393,943,102 | false | null | package com.fjbg.weather.data.mapper
import com.fjbg.weather.data.local.AqiEntity
import com.fjbg.weather.data.local.CityEntity
import com.fjbg.weather.data.local.CityWeatherEntity
import com.fjbg.weather.data.local.WeatherEntity
import com.fjbg.weather.data.model.AqiDto
import com.fjbg.weather.data.model.CityDto
import com.fjbg.weather.data.model.CityWeatherDto
import com.fjbg.weather.data.model.WeatherDto
import com.fjbg.weather.data.remote.AqiResponse
import com.fjbg.weather.data.remote.CityResponse
import com.fjbg.weather.data.remote.WeatherResponse
// Weather
fun weatherResponseToEntity(response: WeatherResponse): WeatherEntity = WeatherEntity(
id = 0,
longitude = response.coord.lon,
latitude = response.coord.lat,
currentTemp = response.main.temp,
weatherDescription = response.weather[0].description,
weatherMain = response.weather[0].main,
weatherIcon = response.weather[0].icon,
weatherIconId = response.weather[0].id,
feelsLike = response.main.feels_like,
tempMax = response.main.temp_max,
tempMin = response.main.temp_min,
pressure = response.main.pressure,
humidity = response.main.humidity,
windSpeed = response.wind.speed,
windDirection = response.wind.deg,
windGust = response.wind.gust,
cloud = if (response.clouds == null) 0 else response.clouds.all,
timezone = response.timezone,
cityName = response.name,
dt = response.dt,
country = response.sys.country,
sunrise = response.sys.sunrise,
sunset = response.sys.sunset,
visibility = response.visibility
)
fun weatherEntityToDomain(entity: WeatherEntity): WeatherDto {
return WeatherDto(
longitude = entity.longitude,
latitude = entity.latitude,
currentTemp = entity.currentTemp,
feelsLike = entity.feelsLike,
tempMax = entity.tempMax,
tempMin = entity.tempMin,
pressure = entity.pressure,
humidity = entity.humidity,
windSpeed = entity.windSpeed,
windDirection = entity.windDirection,
windGust = entity.windGust,
cloud = entity.cloud,
timezone = entity.timezone,
name = entity.cityName,
dt = entity.dt,
country = entity.country,
sunrise = entity.sunrise,
sunset = entity.sunset,
visibility = entity.visibility,
weatherIcon = entity.weatherIcon,
weatherIconId = entity.weatherIconId,
weatherMain = entity.weatherMain,
weatherDescription = entity.weatherDescription
)
}
fun aqiResponseToEntity(response: AqiResponse): AqiEntity = AqiEntity(
id = 0,
aqi = response.data?.aqi ?: 0,
)
fun aqiEntityToDomain(entity: AqiEntity): AqiDto = AqiDto(
id = entity.id,
aqi = entity.aqi
)
// City
fun mapToEntity(response: CityResponse): CityEntity =
CityEntity(
id = 0,
name = response.name,
country = response.country,
lat = response.lat,
lon = response.lon
)
fun mapEntityToDomain(entity: CityEntity): CityDto =
CityDto(
id = entity.id,
name = entity.name,
country = entity.country,
lat = entity.lat,
lon = entity.lon
)
fun CityDto.mapToEntity(): CityEntity =
CityEntity(
id = 0,
name = this.name,
country = this.country,
lat = this.lat,
lon = this.lon
)
fun citiResponseMapToDomain(response: CityResponse): CityDto {
return CityDto(
id = -1,
name = response.name,
country = response.country,
lat = response.lat,
lon = response.lon
)
}
fun cityResponseListMapToEntities(list: List<CityResponse>): List<CityEntity> =
list.map(::mapToEntity)
fun cityEntityListMapToDomain(list: List<CityEntity>): List<CityDto> =
list.map(::mapEntityToDomain)
fun cityResponseListMapToDomain(list: List<CityResponse>): List<CityDto> =
list.map(::citiResponseMapToDomain)
fun cityWeatherDomainToEntity(cityWeather: CityWeatherDto): CityWeatherEntity {
return CityWeatherEntity(
id = 0,
city = cityWeather.city,
country = cityWeather.country,
temperature = cityWeather.temperature,
humidity = cityWeather.humidity,
wind = cityWeather.wind,
icon = cityWeather.icon,
active = cityWeather.active,
isFavorite = cityWeather.isFavorite
)
}
fun cityWeatherDtoToEntity(cityWeather: CityWeatherDto): CityWeatherEntity =
CityWeatherEntity(
id = 0,
city = cityWeather.city,
country = cityWeather.country,
temperature = cityWeather.temperature,
humidity = cityWeather.humidity,
wind = cityWeather.wind,
icon = cityWeather.icon,
active = cityWeather.active,
isFavorite = cityWeather.isFavorite
)
fun cityWeatherEntityToDomain(entity: CityWeatherEntity): CityWeatherDto =
CityWeatherDto(
id = entity.id,
city = entity.city,
country = entity.country,
temperature = entity.temperature,
humidity = entity.humidity,
wind = entity.wind,
icon = entity.icon,
active = entity.active,
isFavorite = entity.isFavorite
)
fun cityWeatherEntitiesToDomain(list: List<CityWeatherEntity>): List<CityWeatherDto> =
list.map(::cityWeatherEntityToDomain)
| 0 | Kotlin | 0 | 2 | f054002f3303722d9d128101d8c53d388d57460d | 5,331 | Weather | MIT License |
src/main/kotlin/org/pathcheck/intellij/cql/psi/scopes/Query.kt | Path-Check | 543,746,466 | false | null | package org.pathcheck.intellij.cql.psi.scopes
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.lang.ASTNode
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.isAncestor
import org.antlr.intellij.adaptor.psi.ScopeNode
import org.hl7.cql.model.DataType
import org.pathcheck.intellij.cql.psi.DeclaringIdentifiers
import org.pathcheck.intellij.cql.psi.HasResultType
import org.pathcheck.intellij.cql.psi.LookupProvider
import org.pathcheck.intellij.cql.psi.antlr.BasePsiNode
import org.pathcheck.intellij.cql.psi.expressions.Expression
import org.pathcheck.intellij.cql.psi.expressions.ExpressionTerm
import org.pathcheck.intellij.cql.psi.expressions.Quantity
import org.pathcheck.intellij.cql.psi.expressions.SimpleLiteral
import org.pathcheck.intellij.cql.psi.references.Identifier
import org.pathcheck.intellij.cql.utils.LookupHelper
import org.pathcheck.intellij.cql.utils.cleanText
/** A subtree associated with a query.
* Its scope is the set of arguments.
*/
class Query(node: ASTNode) : BasePsiNode(node), ScopeNode, DeclaringIdentifiers, LookupProvider, HasResultType {
fun sourceClause(): SourceClause? {
return getRule(SourceClause::class.java, 0)
}
fun letClause(): LetClause? {
return getRule(LetClause::class.java, 0)
}
fun queryInclusionClause(): List<QueryInclusionClause>? {
return getRules(QueryInclusionClause::class.java)
}
fun queryInclusionClause(i: Int): QueryInclusionClause? {
return getRule(QueryInclusionClause::class.java, i)
}
fun whereClause(): WhereClause? {
return getRule(WhereClause::class.java, 0)
}
fun aggregateClause(): AggregateClause? {
return getRule(AggregateClause::class.java, 0)
}
fun returnClause(): ReturnClause? {
return getRule(ReturnClause::class.java, 0)
}
fun sortClause(): SortClause? {
return getRule(SortClause::class.java, 0)
}
/**
* User clicked in the [element]. This function tries to find the definition token related to the [element]
* inside this subtree and return it.
*/
override fun resolve(element: PsiNamedElement): PsiElement? {
sourceClause()?.aliasedQuerySource()?.forEach {
// If it is a QuerySource, the element was defined outside this tree.
if (it.querySource().isAncestor(element)) {
thisLogger().debug("Query Resolve ${element.text}. Part of QuerySource, sending to Parent")
return context?.resolve(element)
}
}
// Finds the aliases that were defined under this subtree and checks if the element is one of these aliases.
visibleIdentifiers().firstOrNull() {
it.text == element.text
}?.let {
thisLogger().debug("Query Resolve ${element.text} to ${it.parent.parent.parent}/${it.parent.parent}")
return it.parent
}
thisLogger().debug("Query Resolve ${element.text} -> Not part of the Identifying set")
// sends to parent scope.
return context?.resolve(element)
}
override fun visibleIdentifiers(): List<PsiElement> {
return sourceClause()?.aliasedQuerySource()?.map {
it.alias()?.identifier()?.all() ?: emptyList()
}?.flatten() ?: emptyList()
}
fun getAliasName(): PsiElement? {
return visibleIdentifiers().first()
}
override fun lookup(): List<LookupElementBuilder> {
return listOfNotNull(
LookupHelper.build(
getAliasName()?.cleanText(),
AllIcons.Nodes.Variable,
null,
null
)
)
}
override fun getResultType(): DataType? {
return aggregateClause()?.getResultType()
?: returnClause()?.getResultType()
?: sourceClause()?.getResultType()
}
}
class QuerySource(node: ASTNode) : BasePsiNode(node), HasResultType {
fun retrieve(): Retrieve? {
return getRule(Retrieve::class.java, 0)
}
fun qualifiedIdentifierExpression(): QualifiedIdentifierExpression? {
return getRule(QualifiedIdentifierExpression::class.java, 0)
}
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
override fun getResultType(): DataType? {
return retrieve()?.getResultType()
?: expression()?.getResultType()
?: qualifiedIdentifierExpression()?.getResultType()
}
}
class AliasedQuerySource(node: ASTNode) : BasePsiNode(node), HasResultType {
fun querySource(): QuerySource? {
return getRule(QuerySource::class.java, 0)
}
fun alias(): Alias? {
return getRule(Alias::class.java, 0)
}
override fun getResultType() = querySource()?.getResultType()
}
class Alias(node: ASTNode) : BasePsiNode(node) {
fun identifier(): Identifier? {
return getRule(Identifier::class.java, 0)
}
}
class LetClause(node: ASTNode) : BasePsiNode(node), HasResultType {
fun letClauseItem(): List<LetClauseItem>? {
return getRules(LetClauseItem::class.java)
}
fun letClauseItem(i: Int): LetClauseItem? {
return getRule(LetClauseItem::class.java, i)
}
override fun getResultType() = letClauseItem(0)?.getResultType()
}
class LetClauseItem(node: ASTNode) : BasePsiNode(node), HasResultType {
fun identifier(): Identifier? {
return getRule(Identifier::class.java, 0)
}
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
override fun getResultType() = expression()?.getResultType()
}
class SourceClause(node: ASTNode) : BasePsiNode(node), HasResultType {
fun aliasedQuerySource(): List<AliasedQuerySource>? {
return getRules(AliasedQuerySource::class.java)
}
fun aliasedQuerySource(i: Int): AliasedQuerySource? {
return getRule(AliasedQuerySource::class.java, i)
}
override fun getResultType() = aliasedQuerySource(0)?.getResultType()
}
class QueryInclusionClause(node: ASTNode) : BasePsiNode(node) {
fun withClause(): WithClause? {
return getRule(WithClause::class.java, 0)
}
fun withoutClause(): WithoutClause? {
return getRule(WithoutClause::class.java, 0)
}
}
class WithClause(node: ASTNode) : BasePsiNode(node) {
fun aliasedQuerySource(): AliasedQuerySource? {
return getRule(AliasedQuerySource::class.java, 0)
}
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
}
class WithoutClause(node: ASTNode) : BasePsiNode(node) {
fun aliasedQuerySource(): AliasedQuerySource? {
return getRule(AliasedQuerySource::class.java, 0)
}
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
}
class WhereClause(node: ASTNode) : BasePsiNode(node) {
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
}
class AggregateClause(node: ASTNode) : BasePsiNode(node), ScopeNode, DeclaringIdentifiers, LookupProvider, HasResultType {
fun identifier(): Identifier? {
return getRule(Identifier::class.java, 0)
}
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
fun startingClause(): StartingClause? {
return getRule(StartingClause::class.java, 0)
}
override fun resolve(element: PsiNamedElement): PsiElement? {
identifier()?.all()?.firstOrNull() {
it.text == element.text
}?.let {
return it.parent
}
// sends to parent scope.
return context?.resolve(element)
}
override fun visibleIdentifiers(): List<PsiElement> {
return identifier()?.all() ?: emptyList()
}
override fun lookup(): List<LookupElementBuilder> {
return listOfNotNull(
LookupHelper.build(
identifier()?.cleanText(),
AllIcons.Nodes.Parameter,
null,
null
)
)
}
override fun getResultType() = startingClause()?.getResultType() ?: resolveTypeName("System", "Any")
}
class StartingClause(node: ASTNode) : BasePsiNode(node), HasResultType {
fun simpleLiteral(): SimpleLiteral? {
return getRule(SimpleLiteral::class.java, 0)
}
fun quantity(): Quantity? {
return getRule(Quantity::class.java, 0)
}
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
override fun getResultType(): DataType? {
return simpleLiteral()?.getResultType() ?:
quantity()?.getResultType() ?:
expression()?.getResultType()
}
}
class ReturnClause(node: ASTNode) : BasePsiNode(node), HasResultType {
fun expression(): Expression? {
return getRule(Expression::class.java, 0)
}
override fun getResultType() = expression()?.getResultType()
}
class SortClause(node: ASTNode) : BasePsiNode(node) {
fun sortDirection(): SortDirection? {
return getRule(SortDirection::class.java, 0)
}
fun sortByItem(): List<SortByItem>? {
return getRules(SortByItem::class.java)
}
fun sortByItem(i: Int): SortByItem? {
return getRule(SortByItem::class.java, i)
}
}
class SortDirection(node: ASTNode) : BasePsiNode(node)
class SortByItem(node: ASTNode) : BasePsiNode(node), HasResultType {
fun expressionTerm(): ExpressionTerm? {
return getRule(ExpressionTerm::class.java, 0)
}
fun sortDirection(): SortDirection? {
return getRule(SortDirection::class.java, 0)
}
override fun getResultType() = expressionTerm()?.getResultType()
} | 0 | Kotlin | 0 | 4 | 898e712a21992c79afe8be698a72e16eb9463620 | 9,851 | intellij-cql | Apache License 2.0 |
app/src/main/java/ir/rahmani/githubproject/ui/theme/Color.kt | MahdiRahmani80 | 614,581,339 | false | null | package ir.rahmani.githubproject.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val primaryDark = Color(0xFF211031)
val secondaryDark = Color(0xFF4254b6)
val primaryLight = Color(0xFF579BB1)
val secondaryLight = Color(0xFFFFFBAC)
| 0 | Kotlin | 0 | 0 | 72fb0ba1a9946786194a0f80f4dd6db137bb057c | 441 | GitHubUsers | MIT License |
src/main/java/ru/hollowhorizon/hollowengine/client/screen/widget/dialogue/FadeInLabelWidget.kt | HollowHorizon | 586,593,959 | false | null | package ru.hollowhorizon.hollowengine.client.screen.widget.dialogue
import com.mojang.blaze3d.matrix.MatrixStack
import net.minecraft.util.text.ITextComponent
import net.minecraft.util.text.StringTextComponent
import ru.hollowhorizon.hc.client.screens.widget.HollowWidget
import ru.hollowhorizon.hc.client.utils.GuiAnimator
import ru.hollowhorizon.hc.client.utils.ScissorUtil
import ru.hollowhorizon.hc.client.utils.math.Interpolation
class FadeInLabelWidget(x: Int, y: Int, width: Int, height: Int) : HollowWidget(x, y, width, height, StringTextComponent("")) {
private var text: ITextComponent = StringTextComponent("")
private var onFadeInComplete: Runnable? = null
private var animator: GuiAnimator? = null
private var isUpdated = false
override fun init() {
super.init()
animator = GuiAnimator.Single(0, width, 1f, Interpolation::easeOutSine)
}
fun setText(text: ITextComponent) {
this.text = text
}
fun setText(text: String) {
setText(StringTextComponent(text))
}
fun reset() {
animator?.reset()
}
fun onFadeInComplete(onFadeInComplete: Runnable) {
this.onFadeInComplete = onFadeInComplete
}
override fun renderButton(stack: MatrixStack, mouseX: Int, mouseY: Int, ticks: Float) {
super.renderButton(stack, mouseX, mouseY, ticks)
ScissorUtil.start(x, y, animator!!.value, height)
stack.pushPose()
stack.translate(0.0, 0.0, 500.0)
font.drawShadow(stack, text, x.toFloat(), y + height / 2f - font.lineHeight / 2f, 0xFFFFFF)
stack.popPose()
ScissorUtil.stop()
}
override fun tick() {
if (animator?.isFinished() == true && !isUpdated) {
onFadeInComplete?.run()
isUpdated = true
}
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
return false
}
val isComplete: Boolean
get() = animator!!.isFinished()
fun complete() {
animator!!.setTime(1.0f)
}
fun getText(): String {
return text.string
}
}
| 0 | null | 5 | 7 | 129e9b0704381a9207dcdc7262b2689c691eee21 | 2,116 | HollowEngine | MIT License |
cookiebar3/src/main/java/com/inlacou/cookiebar3/interpolators/easetypes/EaseOutSine.kt | inlacou | 188,406,196 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 4, "XML": 14, "Kotlin": 42} | package com.inlacou.cookiebar3.interpolators.easetypes
import com.inlacou.cookiebar3.interpolators.CubicBezier
/**
* Created by Weiping on 2016/3/3.
*/
class EaseOutSine : CubicBezier() {
init {
init(0.39, 0.575, 0.565, 1.0)
}
} | 0 | Kotlin | 0 | 0 | ccba27512eb7a6ec355c5128833ab5a39ac3699b | 236 | CookieBar3 | Apache License 2.0 |
spotlight/src/main/kotlin/no/nav/helse/kafka/Meldingssender.kt | navikt | 767,438,587 | false | {"Kotlin": 61012, "Dockerfile": 118} | package no.nav.helse.kafka
import no.nav.helse.db.KommandokjedeFraDatabase
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.RapidsConnection
internal class Meldingssender(private val rapidsConnection: RapidsConnection) {
internal fun påminnKommandokjeder(
kommandokjeder: List<KommandokjedeFraDatabase>
): List<KommandokjedeFraDatabase> =
kommandokjeder.onEach { (commandContextId, meldingId) ->
rapidsConnection.publish(
JsonMessage.newMessage(
"kommandokjede_påminnelse",
mapOf(
"commandContextId" to commandContextId,
"meldingId" to meldingId
)
).toJson()
)
}
} | 0 | Kotlin | 0 | 0 | 642d1e061f0bef233c5a49a95677ce889a023bb6 | 795 | helse-spotlight | MIT License |
data/profile-impl/src/main/java/com/mldz/profile_impl/usecase/GetUserProfileUseCaseImpl.kt | MaximZubarev | 729,033,741 | false | {"Kotlin": 158696} | package com.mldz.profile_impl.usecase
import com.mldz.photo_api.repository.PhotoRepository
import com.mldz.profile_api.models.Profile
import com.mldz.profile_api.usecase.GetUserProfileUseCase
import com.mldz.profile_impl.repository.ProfileRepository
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import org.koin.core.annotation.Factory
@Factory
class GetUserProfileUseCaseImpl(
private val profileRepository: ProfileRepository,
private val photoRepository: PhotoRepository
) : GetUserProfileUseCase {
override suspend fun invoke(username: String): Profile {
return coroutineScope {
val profile = async {
profileRepository.getUserProfile(username = username)
}
val photos = async {
photoRepository.getUserPhotos(username = username)
}
profile.await().copy(photosFlow = photos.await())
}
}
} | 0 | Kotlin | 0 | 0 | 81fe998593361581c232e3d9d33661268f6bd25b | 944 | unsplash_app | The Unlicense |
kandy-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/kandy/letsplot/layers/context/aes/WithMiddle.kt | Kotlin | 502,039,936 | false | null | /*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.kandy.letsplot.layers.context.aes
import org.jetbrains.kotlinx.dataframe.DataColumn
import org.jetbrains.kotlinx.dataframe.columns.ColumnReference
import org.jetbrains.kotlinx.kandy.dsl.internal.BindingContext
import org.jetbrains.kotlinx.kandy.ir.bindings.PositionalMapping
import org.jetbrains.kotlinx.kandy.letsplot.internal.MIDDLE
import kotlin.reflect.KProperty
public interface WithMiddle : BindingContext {
public val middle: ConstantSetter
get() = ConstantSetter(MIDDLE, bindingCollector)
/*
public fun <T> middle(value: T): PositionalSetting<T> {
return addPositionalSetting(MIDDLE, value)
}
*/
public fun <T> middle(
column: ColumnReference<T>,
): PositionalMapping<T> {
return addPositionalMapping<T>(MIDDLE, column.name(), null)
}
public fun <T> middle(
column: KProperty<T>,
): PositionalMapping<T> {
return addPositionalMapping<T>(MIDDLE, column.name, null)
}
public fun <T> middle(
column: String,
): PositionalMapping<T> {
return addPositionalMapping<T>(MIDDLE, column, null)
}
public fun <T> middle(
values: Iterable<T>,
): PositionalMapping<T> {
return addPositionalMapping<T>(
MIDDLE,
values.toList(),
null,
null
)
}
public fun <T> middle(
values: DataColumn<T>,
): PositionalMapping<T> {
return addPositionalMapping<T>(
MIDDLE,
values,
null
)
}
} | 78 | Kotlin | 0 | 98 | 0e54a419c188b5e6dbee8a95af5213c7ac978bb6 | 1,691 | kandy | Apache License 2.0 |
news/src/main/java/com/ricknout/rugbyranker/news/ui/TextArticlesViewModel.kt | Anhmike | 215,666,476 | true | {"Kotlin": 262314} | package com.ricknout.rugbyranker.news.ui
import com.ricknout.rugbyranker.news.repository.ArticlesRepository
import com.ricknout.rugbyranker.news.vo.ArticleType
import com.ricknout.rugbyranker.news.work.ArticlesWorkManager
import javax.inject.Inject
class TextArticlesViewModel @Inject constructor(
articlesRepository: ArticlesRepository,
articlesWorkManager: ArticlesWorkManager
) : ArticlesViewModel(ArticleType.TEXT, articlesRepository, articlesWorkManager)
| 0 | null | 0 | 1 | 53c1889a127ff797c4df9b7651ddc2ddf58546c0 | 470 | rugby-ranker | Apache License 2.0 |
app/src/main/java/com/keelim/cnubus/ui/content/Content3ViewModel.kt | keelim | 202,127,420 | false | null | /*
* Designed and developed by 2021 keelim (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.keelim.cnubus.ui.content
import androidx.lifecycle.viewModelScope
import com.keelim.cnubus.data.model.Event
import com.keelim.common.base.BaseViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class Content3ViewModel : BaseViewModel() {
private val _viewEvent: MutableStateFlow<Event<String>> = MutableStateFlow(Event(""))
val viewEvent: StateFlow<Event<String>> get() = _viewEvent
fun start1() = viewModelScope.launch {
_viewEvent.emit(Event(VIEW_1))
}
companion object {
const val VIEW_1 = "homepage"
}
}
| 6 | Kotlin | 0 | 1 | 836c7fca6793ed74249f9430c798466b1a7aaa27 | 1,255 | project_cnuBus | Apache License 2.0 |
library/generator/src/main/java/io/mehow/laboratory/generator/Supervisor.kt | boguszpawlowski | 387,763,435 | true | {"Kotlin": 324311, "Shell": 2768, "HTML": 261, "CSS": 188} | package io.mehow.laboratory.generator
import arrow.core.Either
public class Supervisor internal constructor(
internal val featureFlag: FeatureFlagModel,
internal val option: FeatureFlagOption,
) {
public data class Builder(
private val featureFlag: FeatureFlagModel,
private val option: FeatureFlagOption,
) {
internal fun build(): Either<GenerationFailure, Supervisor> = Either.cond(
test = featureFlag.options.map(FeatureFlagOption::name).contains(option.name),
ifTrue = { Supervisor(featureFlag, option) },
ifFalse = { NoMatchingOptionFound(featureFlag.toString(), option.name) }
)
}
}
| 0 | null | 0 | 0 | 08e0d941c8bb4bc6d137eba4151c49376e3f9578 | 641 | laboratory | Apache License 2.0 |
kdoctor/src/jvmTest/kotlin/VerifyCompatibilityJson.kt | Kotlin | 448,964,171 | false | {"Kotlin": 147695, "Batchfile": 2673} | import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.jetbrains.kotlin.doctor.entity.Compatibility
import org.jetbrains.kotlin.doctor.entity.EnvironmentPiece
import org.jetbrains.kotlin.doctor.entity.Version
import org.junit.Test
class VerifyCompatibilityJson {
@Test
fun verify() {
val compatibilityJson = javaClass.getResource("compatibility.json")?.readText().orEmpty()
val compatibility = Json.decodeFromString<Compatibility>(compatibilityJson)
val knownEnvNames = EnvironmentPiece.allNames
compatibility.problems.flatMap { problem ->
problem.matrix.map { it.name }
}.forEach { jsonEnvName ->
if (!knownEnvNames.contains(jsonEnvName) && !jsonEnvName.startsWith("GradlePlugin(")) {
error("Unknown env name: $jsonEnvName")
}
}
val invalidVersions = mutableListOf<String>()
compatibility.problems.forEach { problem ->
problem.matrix.forEach { range ->
range.from?.let { str ->
val version = Version(str)
if (version.semVersion == null) {
invalidVersions.add(str)
}
}
range.fixedIn?.let { str ->
val version = Version(str)
if (version.semVersion == null) {
invalidVersions.add(str)
}
}
}
}
if (invalidVersions.isNotEmpty()) {
error("Invalid semantic versions: $invalidVersions")
}
println(compatibility.problems.joinToString("\n") { it.url })
}
} | 7 | Kotlin | 21 | 543 | e07d16ac6b5a411e3212a7c7681fd64877095b36 | 1,721 | kdoctor | Apache License 2.0 |
src/main/kotlin/sim.kt | retinaburn | 115,067,884 | false | null | package moynes.spacesim.sim
import kotlinx.coroutines.experimental.*
val oneG = 9.8 //m/s2
val acceleration = oneG
fun main(args: Array<String>){
var positionV = Vector2d(0.0,0.0)
var accelerationV = Vector2d(acceleration, 0.0)
var ship1 = Ship(position = positionV, acceleration = accelerationV)
println("Acceleration: ${ship1.acceleration}(m/s2) - Give er....")
for (elapsedTime in 0..10){
ship1.calc(1)
println("Elapsed: $elapsedTime(s), Velocity: ${ship1.velocity}(m/s) Position: ${ship1.position}")
}
ship1.acceleration = Vector2d(0.0, 0.0)
println()
println("Acceleration: ${ship1.acceleration}(m/s2) - On the float...")
for (elapsedTime in 0..10){
ship1.calc(1)
println("Elapsed: $elapsedTime(s), Velocity: ${ship1.velocity}(m/s) Position: ${ship1.position}")
}
//add a little sideways momentun
ship1.acceleration = Vector2d(0.0, 5.0)
println()
println("Acceleration: ${ship1.acceleration}(m/s2) - dodge")
for (elapsedTime in 0..10){
ship1.calc(1)
println("Elapsed: $elapsedTime(s), Velocity: ${ship1.velocity}(m/s) Position: ${ship1.position}")
}
//flip and burn
ship1.acceleration = Vector2d(-acceleration, 0.0)
println()
println("Acceleration: ${ship1.acceleration}(m/s2) - Flip and burn...")
for (elapsedTime in 0..10){
ship1.calc(1)
println("Elapsed: $elapsedTime(s), Velocity: ${ship1.velocity}(m/s) Position: ${ship1.position}")
}
}
data class Vector2d(val x: Double, val y: Double)
data class Ship(var position: Vector2d, var acceleration: Vector2d, var velocity: Vector2d = Vector2d(0.0,0.0)){
fun calc(changeInTime: Int){
val newX = velocity.x + acceleration.x * changeInTime
val newY = velocity.y + acceleration.y * changeInTime
velocity = Vector2d(newX, newY)
calcPosition(changeInTime)
}
fun calc(changeInTime: Double){
val newX = velocity.x + acceleration.x * changeInTime
val newY = velocity.y + acceleration.y * changeInTime
velocity = Vector2d(newX, newY)
calcPosition(changeInTime)
}
private fun calcPosition(changeInTime: Int): Vector2d{
val newX = position.x + velocity.x * changeInTime
val newY = position.y + velocity.y * changeInTime
position = Vector2d(newX, newY)
return position
}
private fun calcPosition(changeInTime: Double): Vector2d{
val newX = position.x + velocity.x * changeInTime
val newY = position.y + velocity.y * changeInTime
position = Vector2d(newX, newY)
return position
}
}
| 0 | Kotlin | 0 | 0 | c0b9efea63f75104677af9c9c7cd21ea6a5c0775 | 2,460 | spacesim | MIT License |
analysis/analysis-api-fe10/src/org/jetbrains/kotlin/analysis/api/descriptors/Fe10AnalysisFacade.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.descriptors
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbolOrigin
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.results.OverloadingConflictResolver
import org.jetbrains.kotlin.resolve.calls.tower.KotlinToResolvedCallTransformer
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
interface Fe10AnalysisFacade {
companion object {
fun getInstance(project: Project): Fe10AnalysisFacade {
return project.getService(Fe10AnalysisFacade::class.java)
}
}
fun getResolveSession(element: KtElement): ResolveSession
fun getDeprecationResolver(element: KtElement): DeprecationResolver
fun getCallResolver(element: KtElement): CallResolver
fun getKotlinToResolvedCallTransformer(element: KtElement): KotlinToResolvedCallTransformer
fun getOverloadingConflictResolver(element: KtElement): OverloadingConflictResolver<ResolvedCall<*>>
fun getKotlinTypeRefiner(element: KtElement): KotlinTypeRefiner
fun analyze(element: KtElement, mode: AnalysisMode = AnalysisMode.FULL): BindingContext
fun getOrigin(file: VirtualFile): KtSymbolOrigin
enum class AnalysisMode {
FULL,
PARTIAL_WITH_DIAGNOSTICS,
PARTIAL
}
}
class Fe10AnalysisContext(
facade: Fe10AnalysisFacade,
val contextElement: KtElement,
val token: KtLifetimeToken
) : Fe10AnalysisFacade by facade {
val resolveSession: ResolveSession = getResolveSession(contextElement)
val deprecationResolver: DeprecationResolver = getDeprecationResolver(contextElement)
val callResolver: CallResolver = getCallResolver(contextElement)
val kotlinToResolvedCallTransformer: KotlinToResolvedCallTransformer = getKotlinToResolvedCallTransformer(contextElement)
val overloadingConflictResolver: OverloadingConflictResolver<ResolvedCall<*>> = getOverloadingConflictResolver(contextElement)
val kotlinTypeRefiner: KotlinTypeRefiner = getKotlinTypeRefiner(contextElement)
val builtIns: KotlinBuiltIns
get() = resolveSession.moduleDescriptor.builtIns
val languageVersionSettings: LanguageVersionSettings
get() = resolveSession.languageVersionSettings
}
| 4 | null | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 3,004 | kotlin | Apache License 2.0 |
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/runtime/data/TimeImpl.kt | Double-O-Seven | 142,487,686 | false | null | package ch.leadrian.samp.kamp.core.runtime.data
import ch.leadrian.samp.kamp.core.api.data.MutableTime
import ch.leadrian.samp.kamp.core.api.data.Time
internal data class TimeImpl(
override val hour: Int,
override val minute: Int
) : Time {
override fun toTime(): Time = this
override fun toMutableTime(): MutableTime = MutableTimeImpl(
hour = hour,
minute = minute
)
} | 1 | null | 1 | 7 | af07b6048210ed6990e8b430b3a091dc6f64c6d9 | 425 | kamp | Apache License 2.0 |
app/src/test/java/me/hufman/androidautoidrive/AppSettingsTest.kt | BimmerGestalt | 164,273,785 | false | {"Kotlin": 1839646, "Python": 4131, "HTML": 3912, "Shell": 1732} | package me.hufman.androidautoidrive
import android.content.Context
import android.content.SharedPreferences
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nhaarman.mockito_kotlin.*
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
class AppSettingsTest {
@Rule
@JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun testBooleanSettingRead() {
val context = mock<Context>()
val setting = BooleanLiveSetting(context, AppSettings.KEYS.ENABLED_NOTIFICATIONS)
// it can read the AppSettings
AppSettings.tempSetSetting(setting.key, "true")
assertEquals("$setting is true", true, setting.value)
AppSettings.tempSetSetting(setting.key, "false")
assertEquals("$setting is false" , false, setting.value)
}
@Test
fun testBooleanSettingWrite() {
val preferences = mock<SharedPreferences> {
on { edit() } doReturn mock<SharedPreferences.Editor>()
}
val context = mock<Context> {
on {getSharedPreferences(any(), any())} doReturn preferences
}
val setting = BooleanLiveSetting(context, AppSettings.KEYS.ENABLED_NOTIFICATIONS)
// it can write the AppSettings
AppSettings.tempSetSetting(setting.key, "false")
setting.setValue(true)
assertEquals("$setting is true", "true", AppSettings[setting.key])
setting.setValue(false)
assertEquals("$setting is true", "false", AppSettings[setting.key])
}
@Test
fun testStringSettingRead() {
val context = mock<Context>()
val setting = StringLiveSetting(context, AppSettings.KEYS.GMAPS_STYLE)
// it can read the AppSettings
AppSettings.tempSetSetting(setting.key, "night")
assertEquals("night", setting.value)
AppSettings.tempSetSetting(setting.key, "auto")
assertEquals("auto", setting.value)
}
@Test
fun testStringSettingWrite() {
val preferences = mock<SharedPreferences> {
on { edit() } doReturn mock<SharedPreferences.Editor>()
}
val context = mock<Context> {
on {getSharedPreferences(any(), any())} doReturn preferences
}
val setting = StringLiveSetting(context, AppSettings.KEYS.GMAPS_STYLE)
// it can write the AppSettings
AppSettings.tempSetSetting(setting.key, "auto")
setting.setValue("night")
assertEquals("night", AppSettings[setting.key])
setting.setValue("auto")
assertEquals("auto", AppSettings[setting.key])
}
@Test
fun testStoredSet() {
val settings = MockAppSettings(AppSettings.KEYS.HIDDEN_MUSIC_APPS to "a,b")
val storedSet = StoredSet(settings, AppSettings.KEYS.HIDDEN_MUSIC_APPS)
// tests the mass set functionality
val expected = setOf("a", "b")
assertEquals(expected, storedSet.getAll())
storedSet.setAll(setOf("1", "2"))
assertEquals("[\"1\",\"2\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
storedSet.setAll(setOf("a", "b"))
val foundItems = mutableSetOf<String>()
storedSet.withSet {
foundItems.addAll(this)
}
assertEquals(expected, foundItems)
// set functionality
assertEquals("a,b", storedSet.iterator().asSequence().joinToString(","))
assertEquals(setOf("a", "b"), storedSet)
assertTrue(storedSet.contains("a"))
assertFalse(storedSet.contains("c"))
assertTrue(storedSet.containsAll(setOf("a")))
assertTrue(storedSet.containsAll(setOf("a", "b")))
assertFalse(storedSet.containsAll(setOf("a", "b", "c")))
assertEquals(2, storedSet.size)
assertFalse(storedSet.isEmpty())
// mutable set functionality
storedSet.add("c")
assertEquals("[\"a\",\"b\",\"c\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
storedSet.addAll(setOf("c", "d"))
assertEquals("[\"a\",\"b\",\"c\",\"d\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
storedSet.clear()
assertEquals("[]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS] = "a,b"
storedSet.remove("b")
assertEquals("[\"a\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
storedSet.removeAll(setOf("a", "b"))
assertEquals("[]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS] = "a,b"
storedSet.retainAll(setOf("a", "c"))
assertEquals("[\"a\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
storedSet.add("complex,th\"ings[yay]")
assertEquals("[\"a\",\"complex,th\\\"ings[yay]\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
}
@Test
fun testStoredList() {
val settings = MockAppSettings(AppSettings.KEYS.HIDDEN_MUSIC_APPS to "[\"a\",\"b\"]")
val storedList = StoredList(settings, AppSettings.KEYS.HIDDEN_MUSIC_APPS)
// tests the mass set functionality
val expected = listOf("a", "b")
assertEquals(expected, storedList.getAll())
storedList.setAll(listOf("1", "2"))
assertEquals("[\"1\",\"2\"]", settings[AppSettings.KEYS.HIDDEN_MUSIC_APPS])
storedList.setAll(listOf("a", "b"))
val foundItems = mutableListOf<String>()
storedList.withList {
foundItems.addAll(this)
}
assertEquals(expected, foundItems)
// readonly list functionality
assertTrue(storedList.contains("b"))
assertFalse(storedList.contains("c"))
assertTrue(storedList.containsAll(setOf("a", "b")))
assertFalse(storedList.containsAll(setOf("b", "c")))
assertEquals("b", storedList[1])
assertEquals(1, storedList.indexOf("b"))
assertEquals(1, storedList.lastIndexOf("b"))
assertFalse(storedList.isEmpty())
assertEquals(2, storedList.size)
assertEquals("a,b", storedList.iterator().asSequence().joinToString(","))
assertEquals("a,b", storedList.listIterator().asSequence().joinToString(","))
assertEquals("a,b", storedList.subList(0, 2).joinToString(","))
assertEquals("b", storedList.subList(1, 2).joinToString(","))
// mutable list functionality
storedList.clear()
assertEquals(emptyList<String>(), storedList)
storedList.add("b")
storedList.add(0, "a")
assertEquals(expected, storedList)
storedList.addAll(1, listOf("1"))
storedList.addAll(listOf("2"))
assertEquals(listOf("a", "1", "b", "2"), storedList)
assertTrue(storedList.removeAll(setOf("2", "3")))
assertEquals(listOf("a", "1", "b"), storedList)
assertTrue(storedList.retainAll(setOf("a", "b")))
assertEquals(expected, storedList)
assertEquals("b", storedList.removeAt(1))
assertFalse(storedList.remove("b"))
assertTrue(storedList.remove("a"))
assertTrue(storedList.isEmpty())
storedList.add("b")
storedList[0] = "a"
assertEquals(listOf("a"), storedList)
}
} | 61 | Kotlin | 90 | 546 | ea49ba17a18c353a8ba55f5040e8e4321bf14bd7 | 6,336 | AAIdrive | MIT License |
component-acgcomic/src/main/java/com/rabtman/acgcomic/base/AcgComicConfig.kt | LiycJia | 130,456,054 | true | {"Java": 538054, "Kotlin": 97555} | package com.rabtman.acgcomic.base
import android.app.Application.ActivityLifecycleCallbacks
import android.content.Context
import com.rabtman.acgcomic.api.AcgComicService
import com.rabtman.acgcomic.base.constant.SystemConstant
import com.rabtman.common.base.CommonApplicationLike.Lifecycle
import com.rabtman.common.di.module.GlobeConfigModule.Builder
import com.rabtman.common.integration.ConfigModule
import com.rabtman.common.integration.IRepositoryManager
import io.realm.Realm
import io.realm.RealmConfiguration
/**
* @author Rabtman
*/
class AcgComicConfig : ConfigModule {
override fun applyOptions(context: Context, builder: Builder) {
}
override fun registerComponents(context: Context, repositoryManager: IRepositoryManager) {
repositoryManager.injectRetrofitService(AcgComicService::class.java)
repositoryManager.injectRealmConfigs(
RealmConfiguration.Builder()
.name(SystemConstant.DB_NAME)
.schemaVersion(SystemConstant.DB_VERSION)
.modules(Realm.getDefaultModule(), AcgComicRealmModule())
.build()
)
}
override fun injectAppLifecycle(context: Context, lifecycles: List<Lifecycle>) {
}
override fun injectActivityLifecycle(context: Context,
lifecycles: List<ActivityLifecycleCallbacks>) {
}
}
| 0 | Java | 0 | 2 | 6e48b621b350cd84f195f9acbdeeb2b747d60ced | 1,427 | AcgClub | MIT License |
app/src/main/kotlin/ir/ari/mp3cutter/models/Item.kt | AlirezaIvaz | 516,427,026 | false | {"Java": 64989, "Kotlin": 53376} | package ir.ari.mp3cutter.models
class Item(
var icon: Int,
var title: String,
var onClick: () -> Unit
)
| 1 | null | 1 | 1 | 88a7503b5050754a857ce5fb4abb7e03e5866d43 | 117 | MP3Cutter | Apache License 2.0 |
java/FMU-proxy/fmu-proxy/src/test/kotlin/no/mechatronics/sfi/fmuproxy/avro/TestAvroBouncing.kt | johanrhodin | 137,718,038 | true | {"Kotlin": 268329, "C++": 47244, "Python": 28622, "Thrift": 10225, "HTML": 7642, "CMake": 1764, "Java": 726, "Batchfile": 579} | package no.mechatronics.sfi.fmuproxy.avro
import no.mechatronics.sfi.fmi4j.fmu.Fmu
import no.mechatronics.sfi.fmi4j.modeldescription.CommonModelDescription
import no.mechatronics.sfi.fmuproxy.TestUtils
import no.mechatronics.sfi.fmuproxy.runInstance
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.condition.EnabledOnOs
import org.junit.jupiter.api.condition.OS
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
@EnabledOnOs(OS.WINDOWS)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TestAvroBouncing {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(TestAvroBouncing::class.java)
}
private val fmu: Fmu
private val server: AvroFmuServer
private val client: AvroFmuClient
private val modelDescription: CommonModelDescription
init {
fmu = Fmu.from(File(TestUtils.getTEST_FMUs(),
"FMI_2.0/CoSimulation/win64/FMUSDK/2.0.4/BouncingBall/bouncingBall.fmu"))
modelDescription = fmu.modelDescription
server = AvroFmuServer(fmu)
val port = server.start()
client = AvroFmuClient("localhost", port)
}
@AfterAll
fun tearDown() {
client.close()
server.close()
fmu.close()
}
@Test
fun testGuid() {
val guid = client.modelDescription.guid.also { LOG.info("guid=$it") }
Assertions.assertEquals(modelDescription.guid, guid)
}
@Test
fun testModelName() {
val modelName = client.modelDescription.modelName.also { LOG.info("modelName=$it") }
Assertions.assertEquals(modelDescription.modelName, modelName)
}
@Test
fun testInstance() {
client.newInstance().use { instance ->
val h = client.modelDescription.modelVariables
.getByName("h").asRealVariable()
val dt = 1.0/100
val stop = 100.0
runInstance(instance, dt, stop, {
h.read()
}).also {
LOG.info("Duration=${it}ms")
}
}
}
} | 0 | Kotlin | 0 | 0 | 7f792a04bba6cd810d45f92a2f1f48034fb95009 | 2,202 | FMU-proxy | MIT License |
qr-code/src/main/java/org/odk/collect/qrcode/QRCodeEncoder.kt | kobotoolbox | 42,730,860 | false | null | package org.odk.collect.qrcode
import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import org.odk.collect.androidshared.utils.CompressionUtils
class QRCodeEncoderImpl : QRCodeEncoder {
@Throws(QRCodeEncoder.MaximumCharactersLimitException::class)
override fun encode(data: String): Bitmap {
val compressedData = CompressionUtils.compress(data)
// Maximum capacity for QR Codes is 4,296 characters (Alphanumeric)
if (compressedData.length > 4000) {
throw QRCodeEncoder.MaximumCharactersLimitException()
}
val hints: Map<EncodeHintType, ErrorCorrectionLevel> = mapOf(EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.L)
val bitMatrix = QRCodeWriter().encode(
compressedData,
BarcodeFormat.QR_CODE,
QR_CODE_SIDE_LENGTH,
QR_CODE_SIDE_LENGTH,
hints
)
val bmp = Bitmap.createBitmap(
QR_CODE_SIDE_LENGTH,
QR_CODE_SIDE_LENGTH,
Bitmap.Config.RGB_565
)
for (x in 0 until QR_CODE_SIDE_LENGTH) {
for (y in 0 until QR_CODE_SIDE_LENGTH) {
bmp.setPixel(x, y, if (bitMatrix[x, y]) Color.BLACK else Color.WHITE)
}
}
return bmp
}
private companion object {
private const val QR_CODE_SIDE_LENGTH = 400 // in pixels
}
}
interface QRCodeEncoder {
@Throws(MaximumCharactersLimitException::class)
fun encode(data: String): Bitmap
class MaximumCharactersLimitException : Exception()
}
| 2 | null | 66 | 21 | 5a65ba98811a9ab339b6bfcdacd7be3922ac3f4c | 1,752 | collect | Apache License 2.0 |
app/src/main/java/com/it/rxapp_manager_android/module/base/OrderType.kt | chendeqiang | 142,973,820 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 55, "XML": 80, "Kotlin": 48, "JSON": 1} | package com.it.rxapp_manager_android.module.base
/**
* Created by deqiangchen on 2018/9/14 14:49
*/
enum class OrderType {
TAKE_PLANE(0, "接机"), SEND_PLANE(1, "送机"), TUNIU(3, "途牛旅游"), POINT2POINT(4, "点对点"), TAKE_TRAIN(7, "接站"), SEND_TRAIN(8, "送站"), DAY_RENTER(2, "日租");
private var value: Int
private var key: String
private constructor(value: Int, key: String) {
this.value = value
this.key = key
}
companion object {
@JvmStatic
fun getKey(index: Int): String {
OrderType.values().forEach {
if (it.value == index) {
return it.key
}
}
return ""
}
const val TAKE_PLANE_TYPE = 0
const val SEND_PLANE_TYPE = 1
const val TUNIU_TYPE = 3
const val POINT2POINT_TYPE = 4
const val TAKE_TRAIN_TYPE = 7
const val SEND_TRAIN_TYPE = 8
const val DAY_RENTER_TYPE = 2
}
} | 1 | null | 1 | 1 | c158455b699859a8747a5e4e4562b6b37dfc0693 | 974 | rxapp_manager_android | Apache License 2.0 |
plugin/settings/src/main/kotlin-shared/net/twisterrob/gradle/disableLoggingFor.kt | TWiStErRob | 116,494,236 | false | null | @file:JvmMultifileClass
@file:JvmName("GradleUtils")
package net.twisterrob.gradle
import org.slf4j.ILoggerFactory
import org.slf4j.LoggerFactory
import java.lang.reflect.Method
/**
* Disable logging for a specific class. Useful for disabling noisy plugins.
* Source: https://issuetracker.google.com/issues/247906487#comment10
*
* **WARNING**: Must be called early in the build before the loggers are created.
* If a class caches the logger (likely), they won't re-query it from the factory.
* Author recommends putting the calls in root build.gradle.
*
* Examples:
* * Gradle's configuration cache is really noisy, when nothing really happened (happy path).
* Even when `org.gradle.unsafe.configuration-cache.quiet=true`.
* Source: `org.gradle.configurationcache.problems.ConfigurationCacheProblems`.
* ```text
* 0 problems were found storing the configuration cache.
*
* See the complete report at file:///.../build/reports/configuration-cache/<hashes>/configuration-cache-report.html
* ```
* Note: it is recommended to set `org.gradle.unsafe.configuration-cache-problems=fail`,
* so if there are problems you get an exception, because the warnings will be silenced too.
* * `com.gradle.plugin-publish`: on every configured project where `org.gradle.signing` is also applied.
* Source: `com.gradle.publish.PublishTask`.
* ```text
* > Configure project :module
* Signing plugin detected. Will automatically sign the published artifacts.
* ```
* * AGP 7.4:
* Source: `com.android.build.api.component.impl.MutableListBackedUpWithListProperty`
* Source: `com.android.build.api.component.impl.MutableMapBackedUpWithMapProperty`
* ```text
* > Task :kaptDebugKotlin
* Values of variant API AnnotationProcessorOptions.arguments are queried and may return non final values, this is unsupported
* ```
* * `org.jetbrains.dokka`: on every `dokkaJavadoc` task execution, it outputs about 10 lines of "progress".
* Source: `org.jetbrains.dokka.gradle.AbstractDokkaTask`.
* Sadly it's logging to `org.gradle.api.Task` logger, so it's infeasible to silence
* See [Dokka issue](https://github.com/Kotlin/dokka/issues/1894#issuecomment-1378116917) for more details.
*/
fun disableLoggingFor(name: String) {
val loggerFactory: ILoggerFactory = LoggerFactory.getILoggerFactory()
val addNoOpLogger: Method = loggerFactory::class.java
.getDeclaredMethod("addNoOpLogger", String::class.java)
.apply { isAccessible = true }
addNoOpLogger.invoke(loggerFactory, name)
}
| 90 | null | 5 | 18 | d08cfdf287b7c621d8a5140c1de8fecacbb8cdb0 | 2,558 | net.twisterrob.gradle | The Unlicense |
app/src/main/java/com/ojekbro/framework/mvvm/core/adapter/ErrorStateItemViewHolder.kt | halimbimantara | 304,837,133 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 47, "XML": 74, "Java": 2} | package com.ojekbro.framework.mvvm.core.adapter
import android.view.View
import com.ojekbro.framework.mvvm.databinding.ItemErrorStateBinding
import com.ojekbro.framework.mvvm.core.BaseViewItem
import me.ibrahimyilmaz.kiel.core.RecyclerViewHolder
class ErrorStateItem(
val titleResId: Int,
val subtitleResId: Int
) : BaseViewItem
class ErrorStateItemViewHolder(itemView: View) : RecyclerViewHolder<ErrorStateItem>(itemView) {
val binding: ItemErrorStateBinding = ItemErrorStateBinding.bind(itemView)
override fun bind(position: Int, item: ErrorStateItem) {
super.bind(position, item)
with(binding) {
textTitle.text = itemView.context.getString(item.titleResId)
textSubtitle.text = itemView.context.getString(item.subtitleResId)
}
}
} | 1 | null | 1 | 1 | d5eed331d204a9821626004130819a9e5b875d2e | 806 | kotlin-mvvm-hilt | Apache License 2.0 |
base/src/main/java/cn/neday/base/network/interceptor/AuthenticationInterceptor.kt | nEdAy | 199,621,863 | false | null | package cn.neday.base.network.interceptor
import cn.neday.base.config.MMKVConfig.TOKEN
import com.tencent.mmkv.MMKV
import okhttp3.Interceptor
import okhttp3.Response
class AuthenticationInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain
.request()
.newBuilder()
.header("Authorization", MMKV.defaultMMKV().decodeString(TOKEN) ?: "")
.build()
.let { chain.proceed(it) }
}
| 1 | null | 3 | 11 | 584bc01304ba9faf03b341fb0d6590830118f572 | 463 | Sheep | MIT License |
app/src/main/java/com/andrewm/weatherornot/data/model/forecast/Alert.kt | moorea | 130,636,872 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 63, "Java": 1, "XML": 20} | package com.andrewm.weatherornot.data.model.forecast
import io.realm.RealmObject
open class Alert : RealmObject() {
open var title: String? = null
open var time: Int? = 0
open var expires: Int? = 0
open var description: String? = null
open var uri: String? = null
} | 0 | Kotlin | 1 | 0 | 3350416caf7cf256238d8f8a15f70e75becb65d8 | 287 | weather-or-not | Apache License 2.0 |
lcds/src/main/java/com/v5ent/xiubit/activity/WithDrawCardInfoSetActivity.kt | wuhanligong110 | 148,960,988 | false | {"Java": 5585019, "Kotlin": 539029} | package com.v5ent.xiubit.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.google.gson.Gson
import com.toobei.common.entity.*
import com.toobei.common.event.CardBindSuccessEvent
import com.toobei.common.network.NetworkObserver
import com.toobei.common.network.RetrofitHelper
import com.toobei.common.network.httpapi.CardBindApi
import com.toobei.common.network.httpapi.WithDrawApi
import com.toobei.common.utils.KeyboardUtil
import com.toobei.common.utils.ToastUtil
import com.toobei.common.utils.UpdateViewCallBack
import com.toobei.common.utils.getJson
import com.toobei.common.view.dialog.PromptDialogCommon
import com.toobei.common.view.dialog.PromptDialogMsg
import com.toobei.common.view.timeselector.Utils.TextUtil
import com.v5ent.xiubit.NetBaseActivity
import com.v5ent.xiubit.R
import com.v5ent.xiubit.event.WithDrawSuccessEvent
import com.v5ent.xiubit.service.LoginService
import com.v5ent.xiubit.util.ParamesHelp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_with_drawcard_set.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.xsl781.utils.SimpleTextWatcher
/**
* Created by 11191 on 2018/5/11.
*/
class WithDrawCardInfoSetActivity : NetBaseActivity() {
override fun getContentLayout(): Int = R.layout.activity_with_drawcard_set
private var bankCardInfo: BankCardInfo? = null
private var money: String = "0.00"
//选取的省份城市数据
private var selectPrivice = ""
private var selectCity = ""
private var cityBeans: CityJsonBean? = null
private var bankLists: ArrayList<BankBean>? = null
private var cityPick: OptionsPickerView<String>? = null
private var bankPick: OptionsPickerView<String>? = null
companion object {
val FOR_BINDCARD = 1
val FOR_WITHDROW = 2
}
private var for_what = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bankCardInfo = intent.getSerializableExtra("bankCardInfo") as BankCardInfo
for_what = intent.getIntExtra("for_what", 0)
money = intent.getStringExtra("money") ?: "0.00"
initView()
loadDate()
}
private fun initView() {
headerLayout.showTitle("填写银行卡信息")
phoneInputEt.setText(LoginService.getInstance().curPhone)
if (bankCardInfo?.bankName?.isNullOrBlank() ?: true) {
bankNameTv.text = "请选择银行"
bankNameTv.setTextColor(resources.getColor(R.color.text_blue_common))
} else {
bankNameTv.text = bankCardInfo?.bankName
bankNameTv.setTextColor(resources.getColor(R.color.text_black_common))
}
bankNameTv.setOnClickListener {
queryBanks(UpdateViewCallBack { e, s ->
KeyboardUtil.hideKeyboard(ctx)
bankPick?.show()
})
}
selectCityTv.setOnClickListener {
queryCitys(UpdateViewCallBack { e, s ->
KeyboardUtil.hideKeyboard(ctx)
cityPick?.show()
})
}
completeBtn.setOnClickListener {
when (for_what) {
FOR_WITHDROW -> withdrawMoney()
FOR_BINDCARD -> {
val phoneNum = phoneInputEt.text.toString()
if (bankNameTv.text.length == 0 || "请选择银行".equals(bankNameTv.text)) {
ToastUtil.showCustomToast("请先选择银行")
return@setOnClickListener
}
if (TextUtil.isEmpty(selectCity)) {
ToastUtil.showCustomToast("请选择地区和城市")
return@setOnClickListener
}
if (TextUtil.isEmpty(phoneNum) || phoneNum.length != 11) {
ToastUtil.showCustomToast("手机号码长度为11位,请检查")
return@setOnClickListener
}
bankCardInfo?.city = selectCity
bankCardInfo?.mobile = phoneNum
var intent = Intent(ctx, BindCardPhoneVcodeActivity::class.java)
intent.putExtra("bankCardInfo", bankCardInfo)
intent.putExtra("vcodePhoneNum", phoneNum)
startActivity(intent)
}
}
}
phoneNumInputLl.visibility = if (for_what == FOR_WITHDROW) View.GONE else View.VISIBLE
remindInfoIv.setOnClickListener {
PromptDialogMsg(ctx, "预留手机号说明", resources.getString(R.string.user_phone_explain), "我知道了").show()
}
phoneInputEt.addTextChangedListener(object : SimpleTextWatcher() {
override fun onTextChanged(charSequence: CharSequence?, i: Int, i2: Int, i3: Int) {
super.onTextChanged(charSequence, i, i2, i3)
phoneNumRemindTv.visibility = View.INVISIBLE
completeBtn.isEnabled = (checkPhone() && selectCity != null)
}
})
}
private fun loadDate() {
queryBanks(null)
queryCitys(null)
}
private fun queryBanks(callBack: UpdateViewCallBack<String>?) {
if (bankPick != null) callBack?.updateView(null, null)
else {
RetrofitHelper.getInstance().retrofit.create(CardBindApi::class.java).queryAllbank(ParamesHelp().build())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : NetworkObserver<BaseResponseEntity<PageListBase<BankBean>>>() {
override fun bindViewWithDate(response: BaseResponseEntity<PageListBase<BankBean>>) {
bankLists = response.data.datas as ArrayList<BankBean>?
//银行选择器
bankPick = OptionsPickerBuilder(ctx, OnOptionsSelectListener { options1, options2, options3, v ->
bankNameTv.text = bankLists?.get(options1)?.bankName
bankCardInfo?.bankName = bankLists?.get(options1)?.bankName
if (for_what == FOR_WITHDROW){
completeBtn.isEnabled = !(TextUtil.isEmpty(selectCity))
}else{
completeBtn.isEnabled = !(TextUtil.isEmpty(selectCity)) && checkPhone()
}
}).setContentTextSize(22)//滚轮文字大小
.build<String>()
var bankNames = arrayListOf<String>()
bankLists?.forEach {
bankNames.add(it.bankName)
}
bankPick?.setPicker(bankNames)
callBack?.updateView(null, null)
}
})
}
}
private fun queryCitys(callBack: UpdateViewCallBack<String>?) {
if (cityPick != null) callBack?.updateView(null, null)
else {
try {
selectCityTv.post(Runnable {
val cityJson = getJson(ctx, "city.json")
cityBeans = Gson().fromJson(cityJson, CityJsonBean::class.java)
parssBean()
callBack?.updateView(null, null)
})
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun parssBean() {
if (cityBeans == null) return
var proviceNameist = arrayListOf<String>()
var cityNameList = ArrayList<List<String>>()
cityBeans?.provices?.forEachIndexed({ index, provicesBean ->
proviceNameist.add(provicesBean.text)
var cityTempList = arrayListOf<String>() //本省下的城市列表
provicesBean.children.forEach({
cityTempList.add(it.text)
})
cityNameList.add(cityTempList)
})
cityPick = OptionsPickerBuilder(ctx, OnOptionsSelectListener { options1, options2, options3, v ->
selectPrivice = proviceNameist[options1]
selectCity = cityNameList[options1][options2]
selectCityTv.text = selectPrivice + " " + selectCity
// selectCityTv.setTextColor(resources.getColor(R.color.text_black_common))
if (for_what == FOR_WITHDROW){
completeBtn.isEnabled = !(TextUtil.isEmpty(bankCardInfo?.bankName))
}else{
completeBtn.isEnabled = !(TextUtil.isEmpty(bankCardInfo?.bankName)) && checkPhone()
}
}).setContentTextSize(22)//滚轮文字大小
.build<String>()
cityPick?.setPicker(proviceNameist, cityNameList)
}
private fun withdrawMoney() {
completeBtn.isEnabled = !(selectCity == null)
RetrofitHelper.getInstance().retrofit.create(WithDrawApi::class.java).userWithdrawRequest(
ParamesHelp()
.put("bankCard", bankCardInfo?.bankCard ?: "")
.put("bankName", bankCardInfo?.bankName ?: "")
.put("amount", money)
.put("city", selectPrivice)
.put("kaihuhang", selectCity) //必填,不要问为什么,不填城市不会被录入系统--!
.build())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : NetworkObserver<BaseResponseEntity<BaseEntity>>() {
override fun onNext(response: BaseResponseEntity<BaseEntity>) {
if (response.code == "0") {
EventBus.getDefault().post(WithDrawSuccessEvent())
var intent = Intent(ctx, WithdrawSuccessActivity::class.java)
intent.putExtra("bankCardInfo", bankCardInfo)
intent.putExtra("withdrawMonty", money)
startActivity(intent)
finish()
} else {
var errorMsg = "因${response.errorsMsgStr},提现失败,请稍后重试。"
val errorMsgDialog = PromptDialogCommon(ctx, "提现失败", "因${response.errorsMsgStr},提现失败,请稍后重试。", true)
errorMsgDialog.show()
headerLayout.postDelayed(Runnable { if (errorMsgDialog.isShowing) errorMsgDialog.dismiss() }, 3000)
}
}
override fun bindViewWithDate(response: BaseResponseEntity<BaseEntity>) {}
})
}
private fun checkPhone(): Boolean {
val phone = phoneInputEt.getText().toString();
return phone.length == 11
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun cardBindSuccess(event: CardBindSuccessEvent) {
finish()
}
} | 0 | Java | 1 | 1 | 5723b5a8187a14909f605605b42fb3e7a8c3d768 | 11,263 | xiubit-android | MIT License |
buildSrc/src/main/kotlin/Releases.kt | CapitalCoding | 343,668,725 | false | null | object Releases {
val versionCode = 1
val versionName = "1.0"
}
| 1 | null | 1 | 1 | e1b4fe96b785ae8d636534ebdf5c27170a07f2ad | 72 | quickstart-android | Apache License 2.0 |
ConnectSDK/src/test/kotlin/com/zendesk/connect/ConnectNotificationTests.kt | isabella232 | 478,424,464 | true | {"INI": 2, "YAML": 1, "Gradle": 10, "Shell": 3, "Markdown": 4, "Batchfile": 2, "Proguard": 4, "Text": 1, "Ignore List": 4, "Java": 112, "Java Properties": 2, "XML": 25, "Kotlin": 45} | package com.zendesk.connect
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
class ConnectNotificationTests {
private val payloadKey = "payload"
private val instanceIdKey = "_oid"
private val notificationIdKey = "_onid"
private val titleKey = "title"
private val bodyKey = "body"
private val deepLinkKey = "_odl"
private val testPushKey = "_otm"
private val typeKey = "type"
private val ipmValue = "ipm"
private val nullMap = NullableTypesAsNonNull<Map<String, String>>().nullObject
private lateinit var testData: MutableMap<String, String>
@Before
fun setUp() {
testData = mutableMapOf()
}
@Test
fun `PAYLOAD get key should return the key expected for the payload field`() {
val key = ConnectNotification.Keys.PAYLOAD.key
assertThat(key).isEqualTo(payloadKey)
}
@Test
fun `INSTANCE_ID get key should return the key expected for the instance id field`() {
val key = ConnectNotification.Keys.INSTANCE_ID.key
assertThat(key).isEqualTo(instanceIdKey)
}
@Test
fun `NOTIFICATION_ID get key should return the key expected for the notification id field`() {
val key = ConnectNotification.Keys.NOTIFICATION_ID.key
assertThat(key).isEqualTo(notificationIdKey)
}
@Test
fun `TITLE get key should return the key expected for the title field`() {
val key = ConnectNotification.Keys.TITLE.key
assertThat(key).isEqualTo(titleKey)
}
@Test
fun `BODY get key should return the key expected for the body field`() {
val key = ConnectNotification.Keys.BODY.key
assertThat(key).isEqualTo(bodyKey)
}
@Test
fun `DEEP_LINK get key should return the key expected for the deep link field`() {
val key = ConnectNotification.Keys.DEEP_LINK.key
assertThat(key).isEqualTo(deepLinkKey)
}
@Test
fun `TEST_PUSH get key should return the key expected for the test push field`() {
val key = ConnectNotification.Keys.TEST_PUSH.key
assertThat(key).isEqualTo(testPushKey)
}
@Test
fun `TYPE get key should return the key expected for the type field`() {
val key = ConnectNotification.Keys.TYPE.key
assertThat(key).isEqualTo(typeKey)
}
@Test
fun `IPM get value should return the value expected for an ipm type payload`() {
val value = ConnectNotification.Values.IPM.value
assertThat(value).isEqualTo(ipmValue)
}
// region isConnectPush
@Test
fun `is connect push should return false if given an invalid data payload`() {
val result = ConnectNotification.isConnectPush(nullMap)
assertThat(result).isFalse()
}
@Test
fun `is connect push should return false if payload doesn't contain an instance id`() {
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isFalse()
}
@Test
fun `is connect push should return false if payload contains an empty instance id`() {
testData[ConnectNotification.Keys.INSTANCE_ID.key] = ""
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isFalse()
}
@Test
fun `is connect push should return true if payload contains an instance id`() {
testData[ConnectNotification.Keys.INSTANCE_ID.key] = "some_instance_id"
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isTrue()
}
@Test
fun `is connect push should return false if payload doesn't contain a test push key`() {
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isFalse()
}
@Test
fun `is connect push should return false if payload test push key is empty`() {
testData[ConnectNotification.Keys.TEST_PUSH.key] = ""
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isFalse()
}
@Test
fun `is connect push should return false if payload test push key is false`() {
testData[ConnectNotification.Keys.TEST_PUSH.key] = "false"
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isFalse()
}
@Test
fun `is connect push should return true if payload test push key is true`() {
testData[ConnectNotification.Keys.TEST_PUSH.key] = "true"
val result = ConnectNotification.isConnectPush(testData)
assertThat(result).isTrue()
}
// endregion
@Test
fun `is ipm should return false if given a null data payload`() {
val result = ConnectNotification.isIpm(nullMap)
assertThat(result).isFalse()
}
@Test
fun `is ipm should return false if payload doesn't contain a type`() {
val result = ConnectNotification.isIpm(testData)
assertThat(result).isFalse()
}
@Test
fun `is ipm should return false if payload contains a non-ipm type`() {
testData[ConnectNotification.Keys.TYPE.key] = "mega-seed"
val result = ConnectNotification.isIpm(testData)
assertThat(result).isFalse()
}
@Test
fun `is ipm should return true if payload contains an ipm type`() {
testData[ConnectNotification.Keys.TYPE.key] = ConnectNotification.Values.IPM.value
val result = ConnectNotification.isIpm(testData)
assertThat(result).isTrue()
}
@Test
fun `get notification type should return unknown for a null payload`() {
val result = ConnectNotification.getNotificationType(nullMap)
assertThat(result).isEqualTo(ConnectNotification.Types.UNKNOWN)
}
@Test
fun `get notification type should return unknown for a non connect payload`() {
val result = ConnectNotification.getNotificationType(testData)
assertThat(result).isEqualTo(ConnectNotification.Types.UNKNOWN)
}
@Test
fun `get notification type should return ipm for an in product message payload`() {
testData[ConnectNotification.Keys.INSTANCE_ID.key] = "some_instance_id"
testData[ConnectNotification.Keys.TYPE.key] = ConnectNotification.Values.IPM.value
val result = ConnectNotification.getNotificationType(testData)
assertThat(result).isEqualTo(ConnectNotification.Types.IPM)
}
@Test
fun `get notification type should return system push for a connect system push payload`() {
testData[ConnectNotification.Keys.INSTANCE_ID.key] = "some_instance_id"
val result = ConnectNotification.getNotificationType(testData)
assertThat(result).isEqualTo(ConnectNotification.Types.SYSTEM_PUSH)
}
}
| 0 | null | 0 | 0 | 3a274bae492516d922f4f4046be5d1bb4f341772 | 6,736 | connect-android-sdk | Apache License 2.0 |
app/src/main/java/com/ddiehl/android/htn/listings/report/ReportDialog.kt | damien5314 | 30,708,638 | false | {"Java": 336680, "Kotlin": 129890, "Batchfile": 557, "Shell": 163} | package com.ddiehl.android.htn.listings.report
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.ddiehl.android.htn.R
import com.ddiehl.android.htn.view.BaseDaggerDialogFragment
import com.ddiehl.android.htn.view.getDelegate
class ReportDialog : BaseDaggerDialogFragment() {
companion object {
const val TAG = "ReportDialog"
private const val ARG_RULES = "rules"
private const val ARG_SITE_RULES = "siteRules"
@JvmStatic
fun newInstance(rules: Array<String>, siteRules: Array<String>): ReportDialog {
return ReportDialog().apply {
arguments = Bundle().apply {
putStringArray(ARG_RULES, rules)
putStringArray(ARG_SITE_RULES, siteRules)
}
}
}
}
private val rules by lazy { requireArguments().getStringArray(ARG_RULES) as Array<String> }
private val siteRules by lazy { requireArguments().getStringArray(ARG_SITE_RULES) as Array<String> }
private var selectedIndex = -1
private var selectedButton: RadioButton? = null
internal var listener: Listener? = null
interface Listener {
fun onRuleSubmitted(rule: String)
fun onSiteRuleSubmitted(rule: String)
fun onOtherSubmitted(reason: String)
fun onCancelled()
}
override fun onAttach(context: Context) {
super.onAttach(context)
listener = getDelegate()
}
override fun onDetach() {
listener = null
super.onDetach()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Get report options
val reportOptions = getReportOptions(rules, siteRules)
val numOptions = reportOptions.size
// Create dialog with options
val inflater = LayoutInflater.from(context)
// Inflate parent RadioGroup
@SuppressLint("InflateParams") val view =
inflater.inflate(R.layout.report_dialog_view, null, false) as ViewGroup
val parent = view.findViewById<RadioGroup>(R.id.dialog_view_group)
// Inflate 'other' dialog item
val otherOptionView = inflater.inflate(R.layout.report_dialog_view_edit_item, parent, false)
val otherSelector = otherOptionView.findViewById<RadioButton>(R.id.report_choice_item_selector)
// Add rest of option views
for (i in 0 until numOptions) {
// Inflate item view
val optionView = inflater.inflate(R.layout.report_dialog_view_choice_item, parent, false)
// Get RadioButton and set ID so the RadioGroup can properly manage checked state
val selector = optionView.findViewById<RadioButton>(R.id.report_choice_item_selector)
selector.id = i
// Set checked state change listener that caches selected index
selector.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
selectedIndex = i
selectedButton = selector
}
clearAllChecks(parent)
}
// Set text for option
val selectorText = optionView.findViewById<TextView>(R.id.report_choice_text)
selectorText.text = reportOptions[i]
// Add view to parent
parent.addView(optionView)
}
// Set checked listener for 'other' field
otherSelector.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
selectedIndex = numOptions
selectedButton = otherSelector
}
clearAllChecks(parent)
}
// Add other option view
parent.addView(otherOptionView)
// Build AlertDialog from custom view
return AlertDialog.Builder(requireContext())
.setTitle(R.string.report_menu_title)
.setPositiveButton(R.string.report_submit, this::onSubmit)
.setNegativeButton(R.string.report_cancel, this::onCancelButton)
.setView(view)
.create()
}
private fun clearAllChecks(view: View) {
if (view is RadioButton && view != selectedButton) {
view.isChecked = false
}
if (view is ViewGroup) {
for (i in 0 until view.childCount) {
val child = view.getChildAt(i)
clearAllChecks(child)
}
}
}
private fun getReportOptions(rules: Array<String>, siteRules: Array<String>): Array<String?> {
// Concatenate all options into single array
val reportOptions = arrayOfNulls<String>(rules.size + siteRules.size)
System.arraycopy(rules, 0, reportOptions, 0, rules.size)
System.arraycopy(siteRules, 0, reportOptions, rules.size, siteRules.size)
return reportOptions
}
private fun onSubmit(dialog: DialogInterface, which: Int) {
if (selectedIndex < 0) {
// no rule selected yet
listener!!.onCancelled()
dismiss()
return
}
// If index is in rules array, submit the rule
if (selectedIndex < rules.size) {
submit(rules[selectedIndex], null, null)
} else if (selectedIndex < rules.size + siteRules.size) {
submit(null, siteRules[selectedIndex - rules.size], null)
}
// Otherwise, submit the other reason
// If index is in site rules array, submit the site rule
else {
val otherText = this.dialog!!.findViewById<EditText>(R.id.report_choice_edit_text)
val input = otherText.text.toString().trim { it <= ' ' }
submit(null, null, input)
}
dismiss()
}
private fun onCancelButton(dialog: DialogInterface, which: Int) {
onCancel(dialog)
}
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
listener!!.onCancelled()
}
private fun submit(rule: String?, siteRule: String?, other: String?) {
if (other != null) {
listener!!.onOtherSubmitted(other)
} else if (rule != null) {
listener!!.onRuleSubmitted(rule)
} else if (siteRule != null) {
listener!!.onSiteRuleSubmitted(siteRule)
}
}
}
| 1 | Java | 1 | 3 | 45156b40247dfd9537d23d6858cfc687b6777acb | 6,663 | HoldTheNarwhal | Apache License 2.0 |
app/src/main/java/com/pachain/android/helper/CameraHelper.kt | PAChain | 294,049,706 | false | null | package com.pachain.android.helper
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.*
import android.hardware.camera2.*
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Range
import android.util.Size
import android.view.Surface
import android.view.TextureView
import androidx.core.content.ContextCompat
import java.lang.Exception
import java.lang.NullPointerException
import java.lang.RuntimeException
import java.util.*
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.collections.ArrayList
import kotlin.jvm.Throws
import kotlin.math.abs
class CameraHelper private constructor(builder: Builder) {
companion object {
private const val TAG = "CameraHelper"
private const val MAX_PERVIEW_WIDTH = 2560
private const val MAX_PREVIEW_HEIGHT = 2560
private const val MIN_PREVIEW_WIDTH = 720
private const val MIN_PREVIEW_HEIGHT = 720
const val CAMERA_ID_FRONT = "1"
const val CAMERA_ID_BACK = "0"
class Builder {
internal var previewDisplayView: TextureView? = null
internal var isMirror = false
internal lateinit var specificCameraId: String
internal var cameraListener: CameraListener? = null
internal var previewViewSize: Point? = null
internal var rotation: Int = 0
internal var previewSize: Point? = null
internal var mContext: Context? = null
fun previewOn(value: TextureView): Builder {
previewDisplayView = value
return this
}
fun isMirror(value: Boolean): Builder {
isMirror = value
return this
}
fun previewSize(value: Point): Builder {
previewSize = value
return this
}
fun previewViewSize(value: Point): Builder {
previewViewSize = value
return this
}
fun rotation(value: Int): Builder {
rotation = value
return this
}
fun specificCameraId(value: String): Builder {
specificCameraId = value
return this
}
fun cameraListener(value: CameraListener): Builder {
cameraListener = value
return this
}
fun mContext(value: Context): Builder {
mContext = value
return this
}
fun build(): CameraHelper {
previewViewSize?: Log.e(TAG, "previewViewSize is null, now use default previewSize.")
cameraListener?: Log.e(TAG, "cameraListener is null, callback will not be called.")
previewDisplayView?: throw RuntimeException("you must preview on a textureView or a surfaceView.")
return CameraHelper(this)
}
}
}
private lateinit var mCameraId: String
private var specificCameraId: String
private var cameraListener: CameraListener? = null
private var mTextureView: TextureView? = null
private var rotation: Int = 0
private var previewViewSize: Point? = null
private var specificPreviewSize: Point? = null
private var isMirror = false
private var mContext: Context? = null
/**
* A {@link CameraCaptureSession} for camera preview.
*/
private var mCaptureSession: CameraCaptureSession? = null
/**
* A reference to the opened {@link CameraDevice}
*/
private var mCameraDevice: CameraDevice? = null
private var mPreviewSize: Size? = null
/**
* Orientation of the camera sensor
*/
private var mSensorOrientation: Int = 0
init {
mTextureView = builder.previewDisplayView
specificCameraId = builder.specificCameraId
cameraListener = builder.cameraListener
rotation = builder.rotation
previewViewSize = builder.previewViewSize
specificPreviewSize = builder.previewSize
isMirror = builder.isMirror
mContext = builder.mContext
if (isMirror) mTextureView?.scaleX = -1F
}
private fun getCameraOri(rotation: Int, cameraId: String): Int {
var degrees = rotation * 90
when (rotation) {
Surface.ROTATION_0 -> degrees = 0
Surface.ROTATION_90 -> degrees = 90
Surface.ROTATION_180 -> degrees = 180
Surface.ROTATION_270 -> degrees = 270
}
val result = if (CAMERA_ID_FRONT == cameraId) {
(360 - (mSensorOrientation + degrees) % 360) % 360
} else {
(mSensorOrientation - degrees + 360) % 360
}
Log.i(TAG, "getCameraOri: $rotation $result $mSensorOrientation")
return result
}
private val mSurfaceTextureListener = object: TextureView.SurfaceTextureListener {
override fun onSurfaceTextureSizeChanged(
surface: SurfaceTexture?,
width: Int,
height: Int
) {
Log.i(TAG, "onSurfaceTextureSizeChanged: ")
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean {
Log.i(TAG, "onSurfaceTextureDestroyed: ")
return true
}
override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) {
Log.i(TAG, "onSurfaceTextureAvailable: ")
openCamera()
}
}
private val mDeviceStateCallback = object: CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) {
Log.i(TAG, "onOpened: ")
// This method is called when the camera is opened. We start camera preview here.
mCameraOpenLock.release()
mCameraDevice = camera
createCameraPreviewSession()
mPreviewSize?.let {
cameraListener?.onCameraOpened(camera, mCameraId, it, getCameraOri(rotation, mCameraId), isMirror)
}
}
override fun onDisconnected(camera: CameraDevice) {
Log.i(TAG, "onDisconnected: ")
mCameraOpenLock.release()
camera.close()
mCameraDevice = null
cameraListener?.onCameraClosed()
}
override fun onError(camera: CameraDevice, error: Int) {
Log.i(TAG, "onError: ")
mCameraOpenLock.release()
camera.close()
mCameraDevice = null
cameraListener?.onCameraError(Exception("error occurred, code is $error"))
}
}
private val mCaptureStateCallback = object: CameraCaptureSession.StateCallback() {
override fun onConfigureFailed(session: CameraCaptureSession) {
Log.i(TAG, "onConfigureFailed: ")
cameraListener?.onCameraError(Exception("configuredFailed"))
}
override fun onConfigured(session: CameraCaptureSession) {
Log.i(TAG, "onConfigured: ")
// The camera is already closed
mCameraDevice?: return
// When the session is ready, we start displaying the preview
mCaptureSession = session
try {
mPreviewRequestBuilder?.let {
mCaptureSession?.setRepeatingRequest(it.build(),
object: CameraCaptureSession.CaptureCallback() {}, mBackgroundHandler)
}
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
}
/**
* An additional thread for running tasks that shouldn't block the UI.
*/
private var mBackgroundThread: HandlerThread? = null
/**
* A {@link Handler} for running tasks in the background
*/
private var mBackgroundHandler: Handler? = null
private var mImageReader: ImageReader? = null
private val mOnImageAvailableListener = object: ImageReader.OnImageAvailableListener {
private val lock = ReentrantLock()
override fun onImageAvailable(reader: ImageReader?) {
// Save
Log.e(TAG, "onImageAvailable")
val image = reader?.acquireNextImage()
if (cameraListener != null && image?.format == ImageFormat.JPEG) {
val planes = image.planes
//Locking ensures that y, u, and v come from the same Image
lock.lock()
val byteBuffer = planes[0].buffer
val byteArray = ByteArray(byteBuffer.remaining())
byteBuffer.get(byteArray)
cameraListener?.onPreview(byteArray)
lock.unlock()
}
image?.close()
}
}
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
private var mPreviewRequestBuilder: CaptureRequest.Builder? = null
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private var mCameraOpenLock = Semaphore(1)
private fun getBestSupportedSize(sizes: List<Size>): Size {
val tempSizes = sizes.toTypedArray()
Arrays.sort(tempSizes) { o1, o2 ->
return@sort if (o1 != null && o2 != null) {
if (o1.width > o2.width) {
-1
} else if (o1.width == o2.width) {
if (o1.height > o2.height) -1 else 1
} else {
1
}
} else {
Log.e(TAG, "can't compare")
-1
}
}
val mSizes = tempSizes.asList()
var bestSize = mSizes[0]
var previewViewRatio = if (previewViewSize != null) {
previewViewSize!!.x.toFloat() / previewViewSize!!.y
} else {
bestSize.width.toFloat() / bestSize.height
}
if (previewViewRatio > 1) {
previewViewRatio = 1 / previewViewRatio
}
mSizes.forEach {
if (specificPreviewSize != null && specificPreviewSize?.x == it.width && specificPreviewSize?.y == it.height) {
return it
}
if (it.width > MAX_PERVIEW_WIDTH || it.height > MAX_PREVIEW_HEIGHT ||
it.width < MIN_PREVIEW_WIDTH || it.height < MIN_PREVIEW_HEIGHT) {
return@forEach
}
if (abs(it.height / it.width.toFloat() - previewViewRatio) <
abs(bestSize.height / bestSize.width.toFloat() - previewViewRatio)) {
bestSize = it
}
}
return bestSize
}
@Synchronized
fun start() {
Log.i(TAG, "start")
if (mCameraDevice != null) return
startBackgroundThread()
// When the screen is turned off the turned back on, the SurfaceTexture is already available,
// and "onSurfaceTextureAvailable" will not be called. In that case, we can open a camera
// and start preview from here (otherwise, we wait until the surface is ready in the
// SurfaceTextureListener).
if (mTextureView?.isAvailable == true) {
openCamera()
} else {
mTextureView?.surfaceTextureListener = mSurfaceTextureListener
}
}
@Synchronized
fun stop() {
Log.i(TAG, "stop")
mCameraDevice ?: return
closeCamera()
stopBackgroundThread()
}
fun release() {
stop()
mTextureView = null
cameraListener = null
mContext = null
}
private fun setUpCameraOutputs(cameraManager: CameraManager) {
try {
if (configCameraParams(cameraManager, specificCameraId)) {
return
}
for (cameraId in cameraManager.cameraIdList) {
if (configCameraParams(cameraManager, cameraId)) {
return
}
}
} catch (e: CameraAccessException) {
e.printStackTrace()
} catch (e: NullPointerException) {
cameraListener?.onCameraError(e)
}
}
@Throws(CameraAccessException::class)
private fun configCameraParams(manager: CameraManager, cameraId: String): Boolean {
val characteristics = manager.getCameraCharacteristics(cameraId)
val map = characteristics.
get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
map ?: return false
mPreviewSize = getBestSupportedSize(ArrayList<Size>(map.getOutputSizes(SurfaceTexture::class.java).asList()))
mImageReader = ImageReader.newInstance(mPreviewSize!!.width, mPreviewSize!!.height,
ImageFormat.JPEG, 2)
mImageReader?.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler)
// noinspection ConstantConditions
characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)?.let {
mSensorOrientation = it
}
mCameraId = cameraId
return true
}
/**
* Opens the camera specified by {@link #mCameraId}
*/
private fun openCamera() {
val cameraManager = mContext?.getSystemService(Context.CAMERA_SERVICE) as CameraManager?
cameraManager?: return
Log.e(TAG, "openCamera")
setUpCameraOutputs(cameraManager)
mTextureView?.apply {
configureTransform(width, height)
}
try {
if (!mCameraOpenLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw RuntimeException("Time out waiting to lock camera opening.")
}
mContext?.apply {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraManager.openCamera(mCameraId, mDeviceStateCallback, mBackgroundHandler)
}
}
} catch (e: CameraAccessException) {
cameraListener?.onCameraError(e)
} catch (e: InterruptedException) {
cameraListener?.onCameraError(e)
}
}
/**
* Closes the current {@link CameraDevice}
*/
private fun closeCamera() {
try {
mCameraOpenLock.acquire()
mCaptureSession?.close()
mCaptureSession = null
mCameraDevice?.close()
mCameraDevice = null
cameraListener?.onCameraClosed()
mImageReader?.close()
mImageReader = null
} catch (e: InterruptedException) {
cameraListener?.onCameraError(e)
} finally {
mCameraOpenLock.release()
}
}
/**
* Starts a background thread and its {@link Handler}
*/
private fun startBackgroundThread() {
mBackgroundThread = HandlerThread("CameraBackground")
mBackgroundThread?.start()
mBackgroundHandler = Handler(mBackgroundThread?.looper)
}
private fun stopBackgroundThread() {
mBackgroundThread?.quitSafely()
try {
mBackgroundThread?.join()
mBackgroundThread = null
mBackgroundHandler = null
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/
private fun createCameraPreviewSession() {
try {
val texture = mTextureView?.surfaceTexture
assert(texture != null)
// We configure the size of default buffer to be the size of camera preview we want.
mPreviewSize?.let {
texture?.setDefaultBufferSize(it.width, it.height)
}
// This is the output Surface we need to start preview !!!
val surface = Surface(texture)
// We set up a CaptureRequest.Builder with the output Surface
mPreviewRequestBuilder =
mCameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
// Auto focus
mPreviewRequestBuilder?.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
// Increase exposure
mPreviewRequestBuilder?.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, getRange())
mPreviewRequestBuilder?.addTarget(surface)
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice?.createCaptureSession(listOf(surface, mImageReader?.surface),
mCaptureStateCallback, mBackgroundHandler)
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
/**
* Configures the necessary {@link Matrix} transformation to 'mTextureView'.
* This method should be called after the camera preview size is determined in
* setUpCameraOutputs and also the size of 'mTextureView' is fixed.
*
* @param viewWidth The width of 'mTextureView'
* @param viewHeight The height of 'mTextureView'
*/
private fun configureTransform(viewWidth: Int, viewHeight: Int) {
mTextureView?: return
mPreviewSize?: return
val matrix = Matrix()
val viewRect = RectF(0F, 0F, viewWidth.toFloat(), viewHeight.toFloat())
val bufferRect = RectF(0F, 0F, mPreviewSize!!.height.toFloat(), mPreviewSize!!.width.toFloat())
val centerX = viewRect.centerX()
val centerY = viewRect.centerY()
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY())
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL)
val scale = Math.max(viewHeight.toFloat() / mPreviewSize!!.height,
viewWidth.toFloat() / mPreviewSize!!.width)
matrix.postScale(scale, scale, centerX, centerY)
matrix.postRotate((90 * (rotation.toFloat() - 2)) % 360, centerX, centerY)
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180F, centerX, centerY)
}
Log.i(TAG, "configureTransform: ${getCameraOri(rotation, mCameraId)} ${rotation * 90}")
mTextureView?.setTransform(matrix)
}
fun takePhoto() {
//It must be added here, otherwise the callback will not work.
mImageReader?.let {
mPreviewRequestBuilder?.addTarget(it.surface)
}
mPreviewRequestBuilder?.set(CaptureRequest.JPEG_ORIENTATION, mSensorOrientation)
mPreviewRequestBuilder?.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE)
mCaptureSession?.stopRepeating()
mPreviewRequestBuilder?.let {
mCaptureSession?.capture(it.build(), null, mBackgroundHandler)
}
}
private fun getRange(): Range<Int>? {
val mCameraManager = mContext?.getSystemService(Context.CAMERA_SERVICE) as CameraManager?
var chars: CameraCharacteristics? = null
try {
chars = mCameraManager?.getCameraCharacteristics(mCameraId)
} catch (e: CameraAccessException) {
e.printStackTrace()
}
val ranges = chars?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
var result : Range<Int>? = null
ranges?.let {
it.forEach { range ->
if (range.lower < 10) {
return@forEach
}
if (result == null) {
result = range
} else if (range.lower <= 15 && (range.upper - range.lower) > result!!.upper.minus(result!!.lower)) {
result = range
}
}
}
return result
}
} | 1 | null | 1 | 1 | 61885180edfd4943866e02f35a9467d618df4c34 | 20,093 | Android | Apache License 2.0 |
build-tools/gradle-core-configuration/configuration-cache/src/main/kotlin/org/gradle/configurationcache/flow/FlowServicesProvider.kt | RivanParmar | 526,653,590 | false | null | /*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.flow
import org.gradle.api.flow.FlowProviders
import org.gradle.api.flow.FlowScope
import org.gradle.api.internal.tasks.properties.InspectionSchemeFactory
import org.gradle.api.model.ObjectFactory
import org.gradle.internal.event.ListenerManager
import org.gradle.internal.instantiation.InstantiatorFactory
import org.gradle.internal.service.ServiceRegistry
internal
object FlowServicesProvider {
private
fun createFlowProviders(): FlowProviders =
DefaultFlowProviders()
private
fun createBuildFlowScope(
objectFactory: ObjectFactory,
flowScheduler: FlowScheduler,
flowProviders: FlowProviders,
flowParametersInstantiator: FlowParametersInstantiator,
instantiatorFactory: InstantiatorFactory,
listenerManager: ListenerManager
): FlowScope = objectFactory.newInstance(
BuildFlowScope::class.java,
flowScheduler,
flowProviders,
flowParametersInstantiator,
instantiatorFactory
).also {
listenerManager.addListener(it)
}
private
fun createFlowScheduler(
instantiatorFactory: InstantiatorFactory,
services: ServiceRegistry,
): FlowScheduler = FlowScheduler(
instantiatorFactory,
services,
)
private
fun createFlowParametersInstantiator(
inspectionSchemeFactory: InspectionSchemeFactory,
instantiatorFactory: InstantiatorFactory,
services: ServiceRegistry,
) = FlowParametersInstantiator(
inspectionSchemeFactory,
instantiatorFactory,
services
)
}
| 0 | null | 2 | 17 | 8fb2bb1433e734aa9901184b76bc4089a02d76ca | 2,248 | androlabs | Apache License 2.0 |
compiler/testData/diagnostics/tests/inference/pcla/regresssions/exponentialForksInCS.kt | JetBrains | 3,432,266 | false | null | class Controller<T> {
fun yield(t: T): Boolean = true
}
fun <S> generate(g: suspend Controller<S>.() -> Unit): S = TODO()
fun Controller<*>.foo() {}
fun <V, Y> V.bar(y: Y) {}
interface A<E>
interface B : A<Int>
interface C : A<Long>
fun <F> Controller<F>.baz(a: A<F>, f: F) {}
fun <T> bar(a: A<T>, w: T) {
generate {
if (a is B) {
baz(<!DEBUG_INFO_SMARTCAST!>a<!>, 1)
}
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
foo()
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,051 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/testsWithStdLib/native/trait.kt | JetBrains | 3,432,266 | false | null | // FIR_IDENTICAL
import kotlin.jvm.*
interface Tr {
<!EXTERNAL_DECLARATION_IN_INTERFACE!>external fun foo()<!>
<!EXTERNAL_DECLARATION_CANNOT_HAVE_BODY, EXTERNAL_DECLARATION_IN_INTERFACE!>external fun bar()<!> {}
companion object {
external fun foo()
<!EXTERNAL_DECLARATION_CANNOT_HAVE_BODY!>external fun bar()<!> {}
}
} | 184 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 353 | kotlin | Apache License 2.0 |
app/src/main/java/com/nicow/newplayer/ui/activity/BaseActivity.kt | nicognaW | 271,271,065 | false | null | package com.nicow.newplayer.ui.activity
import androidx.appcompat.app.AppCompatActivity
import com.nicow.newplayer.R
import com.nicow.newplayer.ui.fragment.BottomFragment
open class BaseActivity : AppCompatActivity() {
protected fun createBottomFragment() {
val bottomFragment = BottomFragment.newInstance(" ", " ")
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.bottom_container, bottomFragment)
transaction.commit()
}
} | 1 | null | 2 | 3 | c9c216372709066b2f7c58621a690b9dca47e6ca | 550 | NewPlayer | Do What The F*ck You Want To Public License |
app/src/main/java/pl/mbachorski/koinmachine/CoinApplication.kt | mbachorski | 170,577,233 | false | null | package pl.mbachorski.koinmachine
import android.app.Application
import org.koin.android.ext.android.startKoin
import pl.mbachorski.koinmachine.domain.di.coinMintModule
class CoinApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin(this, listOf(coinMintModule))
}
} | 1 | null | 1 | 1 | 1ff000fcd2e039a2bd7436943b7ab46888d270a7 | 322 | KoinMachine | Apache License 2.0 |
sliding-bar/src/main/java/me/nishant/sliding_bar/SlidingBar.kt | cybercoder-naj | 497,557,821 | false | {"Kotlin": 11716} | package me.nishant.sliding_bar
import android.content.res.Resources
import android.util.Log
import android.util.TypedValue
import android.view.MotionEvent
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.*
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.abs
@ExperimentalComposeUiApi
@Composable
fun SlidingBar(
value: Float,
onValueChanged: (Float) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
stepSize: Float = 0.01f,
colors: SlidingBarColors = SlidingBarDefaults.colors()
) {
var pressed by remember { mutableStateOf(false) }
val radius by animateDpAsState(targetValue = if (pressed) 20.dp else 0.dp)
var canvasSize by remember { mutableStateOf(Size(0f, 0f)) }
var downX by remember { mutableStateOf(0f) }
Canvas(
modifier = modifier
.pointerInteropFilter {
val range = valueRange.endInclusive - valueRange.start
val threshold = canvasSize.width / (range / stepSize)
when (it.action) {
MotionEvent.ACTION_DOWN -> {
if (!enabled)
return@pointerInteropFilter false
val point = Offset(
(value - valueRange.start) / (valueRange.endInclusive - valueRange.start) * canvasSize.width,
canvasSize.height / 2f
)
if (it.x in (point.x - toPx(12.dp))..(point.x + toPx(12.dp)) &&
it.y in (point.y - toPx(12.dp))..(point.y + toPx(12.dp))
) {
pressed = true
downX = it.x
true
} else false
}
MotionEvent.ACTION_MOVE -> {
val dx = it.x - downX
if (abs(dx) >= threshold) {
val newValue = if (dx > 0) value + stepSize else value - stepSize
if (newValue in valueRange) {
onValueChanged(newValue)
downX = it.x
}
}
true
}
MotionEvent.ACTION_UP -> {
downX = 0f
pressed = false
true
}
else -> false
}
}
) {
canvasSize = size
val (width) = size
val point = Offset(
(value - valueRange.start) / (valueRange.endInclusive - valueRange.start) * width,
center.y
)
drawCircle(
color = colors.colorPrimary,
radius = radius.toPx(),
center = point,
alpha = 0.2f
)
drawLine(
color = colors.colorTrack,
start = Offset(0f, center.y),
end = Offset(width, center.y),
strokeWidth = 2.dp.toPx(),
alpha = 0.5f
)
drawLine(
color = colors.colorTrack,
start = Offset(0f, center.y),
end = point,
strokeWidth = 2.dp.toPx()
)
drawCircle(
color = colors.colorPrimary,
radius = 12.dp.toPx(),
center = point
)
}
}
private fun toPx(dp: Dp) =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp.value,
Resources.getSystem().displayMetrics
)
| 2 | Kotlin | 1 | 5 | f698f42cd44967539eb3329381828bb84cbd0fb6 | 4,025 | sliding-bar | MIT License |
mylib-file/mylib-file-gridfs/src/main/kotlin/com/zy/mylib/gridfs/dao/DirectoryInfoDao.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.gridfs.dao
import com.zy.mylib.gridfs.entity.DirectoryInfo
import com.zy.mylib.mongo.repos.BaseMongoRepository
/**
* 目录信息 mongo dao
* @author 代码生成器
*/
interface DirectoryInfoDao : BaseMongoRepository<DirectoryInfo, String> {
fun findByPath(parent: String): DirectoryInfo?
fun findByFullpath(fullpath: String): DirectoryInfo?
} | 0 | Kotlin | 0 | 0 | 5c16d5d9b41628b4c9408df97d225ebea1d605e8 | 958 | mylib | Apache License 2.0 |
inference/inference-core/src/jvmMain/kotlin/io/kinference.core/model/KIModel.kt | JetBrains-Research | 244,400,016 | false | null | package io.kinference.core.model
import io.kinference.core.KIONNXData
import io.kinference.core.graph.KIGraph
import io.kinference.core.markOutput
import io.kinference.graph.Contexts
import io.kinference.model.Model
import io.kinference.ndarray.arrays.memory.ArrayDispatcher
import io.kinference.operator.OperatorSetRegistry
import io.kinference.profiler.*
import io.kinference.protobuf.message.ModelProto
import io.kinference.utils.ModelContext
import kotlinx.coroutines.withContext
import kotlinx.atomicfu.atomic
class KIModel(val id: String, val name: String, val opSet: OperatorSetRegistry, val graph: KIGraph) : Model<KIONNXData<*>>, Profilable {
private val inferenceCycleCounter = atomic(0L)
private val profiles: MutableList<ProfilingContext> = ArrayList()
override fun addProfilingContext(name: String): ProfilingContext = ProfilingContext(name).apply { profiles.add(this) }
override fun analyzeProfilingResults(): ProfileAnalysisEntry = profiles.analyze("Model $name")
override fun resetProfiles() = profiles.clear()
override suspend fun predict(input: List<KIONNXData<*>>, profile: Boolean): Map<String, KIONNXData<*>> = withContext(ModelContext(id, getInferenceCycleId().toString())) {
val contexts = Contexts<KIONNXData<*>>(
null,
if (profile) addProfilingContext("Model $name") else null
)
val modelName = coroutineContext[ModelContext.Key]!!.modelName
val inferenceCycle = coroutineContext[ModelContext.Key]!!.cycleId
ArrayDispatcher.addInferenceContext(modelName, inferenceCycle)
val execResult = graph.execute(input, contexts)
execResult.forEach { it.markOutput() }
ArrayDispatcher.closeInferenceContext(modelName, inferenceCycle)
execResult.associateBy { it.name!! }
}
override suspend fun close() {
graph.close()
ArrayDispatcher.removeModelContext(id)
}
private fun getInferenceCycleId(): Long = inferenceCycleCounter.incrementAndGet()
companion object {
private val modelCounter = atomic(0)
private fun generateModelId(): Int = modelCounter.incrementAndGet()
suspend operator fun invoke(proto: ModelProto): KIModel {
val name = "${proto.domain}:${proto.modelVersion}"
val id = "$name:${generateModelId()}"
val opSet = OperatorSetRegistry(proto.opSetImport)
val graph = KIGraph(proto.graph!!, opSet)
ArrayDispatcher.addModelContext(id)
return KIModel(id, name, opSet, graph)
}
}
}
| 7 | null | 6 | 146 | b6c2e7e0921455472c99d959ff0c09e845ac00eb | 2,572 | kinference | Apache License 2.0 |
app/src/main/java/net/blakelee/coinprofits/tools/DateUtils.kt | blakelee | 96,650,297 | false | null | package net.blakelee.coinprofits.tools
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import java.text.SimpleDateFormat
import java.util.*
class DateFormatter(val period: Period) : IAxisValueFormatter {
override fun getFormattedValue(value: Float, axis: AxisBase?): String {
val current: Locale = Locale.getDefault()
when (period) {
Period.DAY -> return SimpleDateFormat("HH:mm", current).format(value)
Period.WEEK -> return SimpleDateFormat("EEE", current).format(value)
Period.MONTH,
Period.QUARTER,
Period.SEMESTER -> return SimpleDateFormat("M/d", current).format(value)
Period.YEAR -> return SimpleDateFormat("MMM", current).format(value)
Period.ALL -> return SimpleDateFormat("M/YY", current).format(value)
}
}
}
fun TimeFormatter(period: Period): Long {
return when(period) {
Period.DAY -> 1000 * 60 * 60 * 24
Period.WEEK -> 1000 * 60 * 60 * 24 * 7
Period.MONTH -> (1000 * 60 * 60 * 24 * 30.4375).toLong()
Period.QUARTER -> (1000 * 60 * 60 * 24 * 30.4375 * 3).toLong()
Period.SEMESTER -> (1000 * 60 * 60 * 24 * 30.4375 * 6).toLong()
Period.YEAR -> (1000 * 60 * 60 * 24 * 365.25).toLong()
Period.ALL -> 500_000_000_000
}
}
fun SinceFormatter(period: Period, since: Float = 0f): String {
return when(period) {
Period.DAY -> "Since yesterday"
Period.WEEK -> "Since last week"
Period.MONTH -> "Since last month"
Period.QUARTER -> "Since 3 months ago"
Period.SEMESTER -> "Since 6 months ago"
Period.YEAR -> "Since last year"
Period.ALL -> "Since " + SimpleDateFormat("MMMM, YYYY", Locale.getDefault()).format(since)
}
}
enum class Period (val value: Int) {
DAY(0),
WEEK(1),
MONTH(2),
QUARTER(3),
SEMESTER(4),
YEAR(5),
ALL(6)
}
fun LabelCount(period: Period): Pair<Int, Boolean> {
return when (period) {
Period.DAY -> Pair(7, true)
Period.WEEK,
Period.MONTH -> Pair(8, true)
Period.QUARTER,
Period.SEMESTER -> Pair(7, true)
Period.YEAR -> Pair(13, true)
Period.ALL -> Pair(7, false)
}
} | 2 | null | 1 | 4 | 152bf37a11f0da2da7ff91d9493fb2334da5ba59 | 2,305 | CoinProfits | MIT License |
data/src/main/java/com/example/cleanarchitecture/data/ContributorRepositoryImpl.kt | cucerdariancatalin | 573,403,217 | false | null | package com.example.cleanarchitecture.data
import com.example.cleanarchitecture.data.model.ContributorEntityMapper
import com.example.cleanarchitecture.data.remote.api.ContributorApi
import com.example.cleanarchitecture.domain.model.Contributor
import com.example.cleanarchitecture.domain.repository.ContributorRepository
import io.reactivex.Observable
import javax.inject.Inject
class ContributorRepositoryImpl @Inject constructor(
private val contributorApi: ContributorApi,
private val contributorEntityMapper: ContributorEntityMapper
) : ContributorRepository {
override fun getContribution(name: String, owner: String): Observable<List<Contributor>> {
return contributorApi.getContributors(owner, name)
.map { it.map { contributorEntityMapper.mapToDomain(it) } }
}
} | 1 | null | 1 | 3 | 1346d7891b98289e7d5be895f656ed15ed30cb6c | 810 | CleanArchitecture | Apache License 2.0 |
app/src/main/java/com/yuyuko233/notificationSyncHelper/Service.kt | yuyuko233 | 512,717,594 | false | null | package com.yuyuko233.notificationSyncHelper
import android.accessibilityservice.AccessibilityService
import android.app.Notification
import android.os.Looper
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.widget.Toast
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.FormBody
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.util.concurrent.TimeUnit
private val client = OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.writeTimeout(2, TimeUnit.SECONDS)
.readTimeout(2, TimeUnit.SECONDS)
.build()
class Service : AccessibilityService() {
override fun onAccessibilityEvent(event: AccessibilityEvent) {
// 基础过滤
if (!App.config.serviceStatus || event.packageName == "android") return
if (event.eventType != AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED || event.parcelableData == null) return
// 获取通知对象并取标题, 内容
val notification: Notification = event.parcelableData as Notification
val title: String? = notification.extras.getString(Notification.EXTRA_TITLE)
var text: String? = notification.extras.getString(Notification.EXTRA_TEXT)
// 过滤全空通知
if (title == null && text == null) return
if (text == null) {
text = notification.extras.get(Notification.EXTRA_TEXT).toString()
}
// 调试模式下输出
if (App.config.debugMode) {
Toast.makeText(applicationContext, "${event.packageName}\n${title.toString()}\n${text}", Toast.LENGTH_LONG).show()
}
// 推送到主机
val request = Request.Builder()
.url(App.config.bindHostUrl)
.post(
FormBody.Builder()
.add("title", title.toString())
.add("text", text)
.build()
).build()
// 异步回调
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
response.use {
if (response.isSuccessful) {
return
}
Log.e("OkHttpResponseErr", response.toString())
Looper.prepare()
Toast.makeText(
applicationContext,
"${getString(R.string.SyncNotificationErr)}\n$response",
Toast.LENGTH_LONG
).show()
Looper.loop()
}
}
override fun onFailure(call: Call, e: java.io.IOException) {
Log.e("OkHttpOnFailure", e.toString())
Looper.prepare()
Toast.makeText(applicationContext, "${getString(R.string.AppName)} \n $e", Toast.LENGTH_LONG).show()
Looper.loop()
}
})
}
override fun onInterrupt() {
Toast.makeText(applicationContext, "无障碍服务已停止 !", Toast.LENGTH_SHORT).show()
}
} | 0 | Kotlin | 0 | 2 | 57c24ca87417efc79f6ad61658acb157c9ed8cf1 | 3,026 | NotificationSyncHelper | Apache License 2.0 |
app/src/main/java/cucerdariancatalin/snake/presentation/screen/AboutScreen.kt | cucerdariancatalin | 585,189,879 | false | null | package cucerdariancatalin.snake.presentation.screen
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.navigation.NavHostController
import cucerdariancatalin.snake.BuildConfig
import cucerdariancatalin.snake.R
import cucerdariancatalin.snake.domain.base.REPO_URL
import cucerdariancatalin.snake.presentation.component.*
import cucerdariancatalin.snake.presentation.theme.border2dp
import cucerdariancatalin.snake.presentation.theme.padding16dp
import cucerdariancatalin.snake.presentation.theme.padding8dp
import cucerdariancatalin.snake.presentation.theme.width248dp
@Composable
fun AboutScreen(navController: NavHostController) {
val context = LocalContext.current
val builder = remember { CustomTabsIntent.Builder() }
val customTabsIntent = remember { builder.build() }
AppBar(
title = stringResource(R.string.title_about),
onBackClicked = { navController.popBackStack() }) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(
top = it.calculateTopPadding(),
bottom = padding16dp,
start = padding16dp,
end = padding16dp
)
.border(width = border2dp, color = MaterialTheme.colorScheme.onBackground),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
DisplayLarge(text = stringResource(id = R.string.app_name))
TitleLarge(
modifier = Modifier.padding(padding8dp),
text = BuildConfig.VERSION_NAME
)
BodyLarge(
modifier = Modifier.padding(padding16dp),
text = stringResource(R.string.about_game),
textAlign = TextAlign.Justify
)
AppButton(
modifier = Modifier.width(width248dp),
text = stringResource(R.string.source_code)
) { customTabsIntent.launchUrl(context, Uri.parse(REPO_URL)) }
}
}
} | 0 | Kotlin | 0 | 5 | cf30dc3507eef145715cb6ef8a2aebc23c7097c4 | 2,551 | Snake | MIT License |
accelerators/corda/service-bus-integration/service-bus-listener/src/main/kotlin/net/corda/workbench/serviceBus/App.kt | Azure-Samples | 175,045,447 | false | null | package net.corda.workbench.serviceBus
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import io.javalin.translator.json.JavalinJacksonPlugin
fun main (args : Array<String>){
val mapper = ObjectMapper()
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
//mapper.registerModule(Jackson.defaultModule())
//mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
JavalinJacksonPlugin.configure(mapper)
Javalin(1113).init()
} | 18 | Kotlin | 116 | 138 | 5b55efd24d2239a7a2d57fb395b0a230e687dc73 | 528 | blockchain-devkit | MIT License |
gazelle/kotlin/tests/bin/PkgHello.kt | aspect-build | 376,383,688 | false | {"Go": 709217, "Starlark": 239240, "Shell": 31234, "TypeScript": 28237, "HCL": 12200, "Kotlin": 3129, "JavaScript": 592, "CSS": 55} | package foo.pkg
import test.lib.*
fun main() {
println("Hello world from ", Constants.NAME)
} | 88 | Go | 16 | 72 | 02740d4a588dfbfe542ac1fcc49d4fc1b3626ab8 | 99 | aspect-cli | Apache License 2.0 |
DaggerSingleModuleApp/app/src/main/java/com/github/yamamotoj/daggersinglemoduleapp/package16/Foo01612.kt | yamamotoj | 163,851,411 | false | null | package com.github.yamamotoj.daggersinglemoduleapp.package16
import javax.inject.Inject
class Foo01612 @Inject constructor(){
fun method0() { Foo01611().method5() }
fun method1() { method0() }
fun method2() { method1() }
fun method3() { method2() }
fun method4() { method3() }
fun method5() { method4() }
}
| 0 | Kotlin | 0 | 9 | 2a771697dfebca9201f6df5ef8441578b5102641 | 331 | android_multi_module_experiment | Apache License 2.0 |
floaty/src/main/java/com/breens/floaty/CustomLayoutConfiguration.kt | Breens-Mbaka | 690,690,418 | false | {"Kotlin": 13358} | package com.breens.floaty
import android.view.Gravity
object CustomLayoutConfiguration {
var customLayoutResourceId: Int = 0
var floatingWidgetWidth: Float = 0.45f
var floatyWidgetHeight: Float = 0.50f
var floatingWidgetPosition: Int = Gravity.CENTER
}
| 1 | Kotlin | 2 | 30 | 62c470044a35e9252bee8a2d14db3de252ece36c | 271 | Floaty | Apache License 2.0 |
src/main/kotlin/io/realworld/domain/user/UserResource.kt | u-ways | 383,858,549 | false | null | package io.realworld.domain.user
import io.realworld.infrastructure.security.Role.ADMIN
import io.realworld.infrastructure.security.Role.USER
import io.realworld.infrastructure.web.Routes.USERS_PATH
import io.realworld.infrastructure.web.Routes.USER_PATH
import io.realworld.utils.ValidationMessages.Companion.REQUEST_BODY_MUST_NOT_BE_NULL
import javax.annotation.security.PermitAll
import javax.annotation.security.RolesAllowed
import javax.transaction.Transactional
import javax.validation.Valid
import javax.validation.constraints.NotNull
import javax.ws.rs.Consumes
import javax.ws.rs.GET
import javax.ws.rs.POST
import javax.ws.rs.PUT
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType.APPLICATION_JSON
import javax.ws.rs.core.Response
import javax.ws.rs.core.Response.Status.CREATED
import javax.ws.rs.core.Response.Status.OK
import javax.ws.rs.core.Response.ok
import javax.ws.rs.core.SecurityContext
import javax.ws.rs.core.UriBuilder.fromResource
@Path("/")
class UserResource(
private val service: UserService
) {
@POST
@Path(USERS_PATH)
@Transactional
@Consumes(APPLICATION_JSON)
@PermitAll
fun register(
@Valid @NotNull(message = REQUEST_BODY_MUST_NOT_BE_NULL) newUser: UserRegistrationRequest,
): Response = service.register(newUser).run {
ok(this).status(CREATED)
.location(fromResource(UserResource::class.java).path("$USERS_PATH/$username").build())
.build()
}
@POST
@Path("$USERS_PATH/login")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@PermitAll
fun login(
@Valid @NotNull(message = REQUEST_BODY_MUST_NOT_BE_NULL) userLoginRequest: UserLoginRequest
): Response = ok(service.login(userLoginRequest)).status(OK).build()
@GET
@Path(USER_PATH)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed(USER)
fun getLoggedInUser(
@Context securityContext: SecurityContext
): Response = ok(service.get(securityContext.userPrincipal.name)).status(OK).build()
@PUT
@Path(USER_PATH)
@Transactional
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed(USER, ADMIN)
fun updateLoggedInUser(
@Context securityContext: SecurityContext,
@Valid @NotNull(message = REQUEST_BODY_MUST_NOT_BE_NULL) userUpdateRequest: UserUpdateRequest,
): Response = ok(service.update(securityContext.userPrincipal.name, userUpdateRequest)).status(OK).build()
}
| 4 | null | 7 | 6 | 53ef0d7cd7891630cd6fff608a46c0d741709440 | 2,555 | kotlin-quarkus-realworld-example-app | MIT License |
uspek/src/test/java/pl/mareklangiewicz/uspek/data/uspek_test_7.kt | genaku | 111,657,393 | true | {"Kotlin": 32841} | package pl.mareklangiewicz.uspek.data
import pl.mareklangiewicz.uspek.USpek
import pl.mareklangiewicz.uspek.USpek.o
import org.junit.Assert
fun uspek_test_10() {
USpek.uspek("some test") {
"first test" o {
Assert.assertTrue(true)
"second test" o {
Assert.assertTrue(true)
}
}
}
} | 0 | Kotlin | 0 | 0 | 2748a3275cb51ff78f3b2668eafec3798cbb4c35 | 358 | USpek | Apache License 2.0 |
service/src/main/kotlin/app/cash/backfila/client/BackfilaClientServiceClient.kt | cashapp | 209,384,085 | false | {"Kotlin": 835825, "TypeScript": 78838, "Java": 8819, "Shell": 4170, "JavaScript": 1107, "HTML": 990, "Dockerfile": 486} | package app.cash.backfila.client
import app.cash.backfila.protos.clientservice.GetNextBatchRangeRequest
import app.cash.backfila.protos.clientservice.GetNextBatchRangeResponse
import app.cash.backfila.protos.clientservice.PrepareBackfillRequest
import app.cash.backfila.protos.clientservice.PrepareBackfillResponse
import app.cash.backfila.protos.clientservice.RunBatchRequest
import app.cash.backfila.protos.clientservice.RunBatchResponse
interface BackfilaClientServiceClient {
fun prepareBackfill(request: PrepareBackfillRequest): PrepareBackfillResponse
suspend fun getNextBatchRange(request: GetNextBatchRangeRequest): GetNextBatchRangeResponse
suspend fun runBatch(request: RunBatchRequest): RunBatchResponse
/**
* Gives us a way to probe for connection information when something fails to help with debugging.
*/
fun connectionLogData(): String
}
| 50 | Kotlin | 45 | 28 | d696c9b3e9441290fcf65e59cba71f8851f8ecd6 | 875 | backfila | Apache License 2.0 |
common/src/commonMain/kotlin/com/github/mustafaozhan/ccc/common/api/ApiRepositoryImpl.kt | shoanchikato | 389,199,653 | true | {"Kotlin": 263455, "Swift": 50806, "HTML": 797} | /*
* Copyright (c) 2021 <NAME>. All rights reserved.
*/
package com.github.mustafaozhan.ccc.common.api
import com.github.mustafaozhan.ccc.common.api.error.EmptyParameterException
import com.github.mustafaozhan.ccc.common.api.error.ModelMappingException
import com.github.mustafaozhan.ccc.common.api.error.NetworkException
import com.github.mustafaozhan.ccc.common.api.error.TimeoutException
import com.github.mustafaozhan.ccc.common.mapper.toModel
import com.github.mustafaozhan.ccc.common.platformCoroutineContext
import com.github.mustafaozhan.ccc.common.util.Result
import com.github.mustafaozhan.logmob.kermit
import io.ktor.network.sockets.ConnectTimeoutException
import io.ktor.utils.io.errors.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerializationException
internal class ApiRepositoryImpl(
private val apiFactory: ApiFactory
) : ApiRepository {
@Suppress("TooGenericExceptionCaught")
private suspend fun <T> apiRequest(
suspendBlock: suspend () -> T
) = withContext(platformCoroutineContext) {
try {
Result.Success(suspendBlock.invoke())
} catch (e: Throwable) {
Result.Error(
when (e) {
is CancellationException -> e
is IOException -> NetworkException(e)
is ConnectTimeoutException -> TimeoutException(e)
is SerializationException -> ModelMappingException(e)
else -> e
}
)
}
}
override suspend fun getRatesViaBackend(base: String) = apiRequest {
if (base.isEmpty()) throw EmptyParameterException()
else apiFactory.getRatesViaBackend(base).toModel(base)
}.also {
kermit.d { "ApiRepositoryImpl getRatesViaBackend $base" }
}
override suspend fun getRatesViaApi(base: String) = apiRequest {
if (base.isEmpty()) throw EmptyParameterException()
else apiFactory.getRatesViaApi(base).toModel(base)
}.also {
kermit.d { "ApiRepositoryImpl getRatesViaApi $base" }
}
}
| 0 | null | 0 | 0 | a07fa9d230f86201b9ad348c98a23859fc01b082 | 2,151 | CCC | Apache License 2.0 |
app/src/main/kotlin/com/juniperphoton/myersplash/utils/Toaster.kt | JuniperPhoton | 67,424,471 | false | null | package com.juniperphoton.myersplash.utils
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.juniperphoton.myersplash.App
object ToastService {
private var handler = Handler(Looper.getMainLooper())
fun sendShortToast(str: String?) {
if (str == null) {
return
}
if (Looper.getMainLooper() != Looper.myLooper()) {
handler.post { sendToastInternal(str) }
} else {
sendToastInternal(str)
}
}
fun sendShortToast(strId: Int) {
if (strId == 0) {
return
}
if (Looper.getMainLooper() != Looper.myLooper()) {
handler.post { sendToastInternal(App.instance.getString(strId)) }
} else {
handler.post { sendToastInternal(App.instance.getString(strId)) }
}
}
@SuppressLint("InflateParams")
private fun sendToastInternal(str: String?) {
Toast.makeText(App.instance, str, Toast.LENGTH_SHORT).show()
}
} | 27 | null | 23 | 93 | d2e6da91c20b638445c60b089e9aa789c646d22b | 1,061 | MyerSplash.Android | MIT License |
app/src/main/kotlin/com/juniperphoton/myersplash/utils/Toaster.kt | JuniperPhoton | 67,424,471 | false | null | package com.juniperphoton.myersplash.utils
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.juniperphoton.myersplash.App
object ToastService {
private var handler = Handler(Looper.getMainLooper())
fun sendShortToast(str: String?) {
if (str == null) {
return
}
if (Looper.getMainLooper() != Looper.myLooper()) {
handler.post { sendToastInternal(str) }
} else {
sendToastInternal(str)
}
}
fun sendShortToast(strId: Int) {
if (strId == 0) {
return
}
if (Looper.getMainLooper() != Looper.myLooper()) {
handler.post { sendToastInternal(App.instance.getString(strId)) }
} else {
handler.post { sendToastInternal(App.instance.getString(strId)) }
}
}
@SuppressLint("InflateParams")
private fun sendToastInternal(str: String?) {
Toast.makeText(App.instance, str, Toast.LENGTH_SHORT).show()
}
} | 27 | null | 23 | 93 | d2e6da91c20b638445c60b089e9aa789c646d22b | 1,061 | MyerSplash.Android | MIT License |
src/main/kotlin/vvu/study/kotlin/demo/dtos/Dto.kt | vietvuhoang | 440,435,716 | false | {"Kotlin": 31085} | package vvu.study.kotlin.demo.dtos
interface Dto {
}
| 0 | Kotlin | 0 | 0 | c255f42dd048970dc7ed3b4d2e6e09f290f6da50 | 55 | kotlin-demo-app | Apache License 2.0 |
dokka-integration-tests/gradle/src/testTemplateProjectAndroid/kotlin/Android0GradleIntegrationTest.kt | Kotlin | 21,763,603 | false | {"Kotlin": 3740113, "CSS": 63179, "JavaScript": 33594, "TypeScript": 13611, "HTML": 6860, "FreeMarker": 4120, "Java": 3923, "Shell": 3800, "SCSS": 2794} | /*
* Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.dokka.it.gradle
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
import java.io.File
import kotlin.test.BeforeTest
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
internal class AndroidTestedVersionsArgumentsProvider : TestedVersionsArgumentsProvider(TestedVersions.ANDROID)
class Android0GradleIntegrationTest : AbstractGradleIntegrationTest() {
companion object {
/**
* Indicating whether or not the current machine executing the test is a CI
*/
private val isCI: Boolean get() = System.getenv("CI") == "true"
private val isAndroidSdkInstalled: Boolean = System.getenv("ANDROID_SDK_ROOT") != null ||
System.getenv("ANDROID_HOME") != null
fun assumeAndroidSdkInstalled() {
if (isCI) return
if (!isAndroidSdkInstalled) {
throw IllegalStateException("Expected Android SDK is installed")
}
}
}
@BeforeTest
fun prepareProjectFiles() {
assumeAndroidSdkInstalled()
val templateProjectDir = File("projects", "it-android-0")
templateProjectDir.listFiles().orEmpty()
.filter { it.isFile }
.filterNot { it.name == "local.properties" }
.filterNot { it.name.startsWith("gradlew") }
.forEach { topLevelFile -> topLevelFile.copyTo(File(projectDir, topLevelFile.name)) }
File(templateProjectDir, "src").copyRecursively(File(projectDir, "src"))
}
@ParameterizedTest(name = "{0}")
@ArgumentsSource(AndroidTestedVersionsArgumentsProvider::class)
fun execute(buildVersions: BuildVersions) {
val result = createGradleRunner(buildVersions, "dokkaHtml", "-i", "-s").buildRelaxed()
assertEquals(TaskOutcome.SUCCESS, assertNotNull(result.task(":dokkaHtml")).outcome)
val htmlOutputDir = File(projectDir, "build/dokka/html")
assertTrue(htmlOutputDir.isDirectory, "Missing html output directory")
assertTrue(
htmlOutputDir.allHtmlFiles().count() > 0,
"Expected html files in html output directory"
)
htmlOutputDir.allHtmlFiles().forEach { file ->
assertContainsNoErrorClass(file)
assertNoUnresolvedLinks(file, knownUnresolvedDRIs)
assertNoHrefToMissingLocalFileOrDirectory(file)
assertNoEmptyLinks(file)
assertNoEmptySpans(file)
}
assertTrue(
htmlOutputDir.allHtmlFiles().any { file ->
"https://developer.android.com/reference/kotlin/android/content/Context.html" in file.readText()
}, "Expected link to developer.android.com"
)
assertTrue(
htmlOutputDir.allHtmlFiles().any { file ->
"https://developer.android.com/reference/kotlin/androidx/appcompat/app/AppCompatActivity.html" in
file.readText()
}, "Expected link to developer.android.com/.../androidx/"
)
htmlOutputDir.allHtmlFiles().forEach { file ->
assertContainsNoErrorClass(file)
assertNoUnresolvedLinks(file)
assertNoHrefToMissingLocalFileOrDirectory(file)
}
}
// TODO: remove this list when https://github.com/Kotlin/dokka/issues/1306 is closed
private val knownUnresolvedDRIs = setOf(
"it.android/IntegrationTestActivity/findViewById/#kotlin.Int/PointingToGenericParameters(0)/",
"it.android/IntegrationTestActivity/getExtraData/#java.lang.Class[TypeParam(bounds=[androidx.core.app.ComponentActivity.ExtraData])]/PointingToGenericParameters(0)/",
"it.android/IntegrationTestActivity/getSystemService/#java.lang.Class[TypeParam(bounds=[kotlin.Any])]/PointingToGenericParameters(0)/",
"it.android/IntegrationTestActivity/requireViewById/#kotlin.Int/PointingToGenericParameters(0)/"
)
}
| 584 | Kotlin | 413 | 3,192 | 96fce041e6c01a27a343ca6cbc7af8e665e50785 | 4,142 | dokka | Apache License 2.0 |
app/src/main/java/com/immortalweeds/pedometer/model/gps/Admin.kt | Weedlly | 523,343,757 | false | {"Kotlin": 65187} | package com.immortalweeds.pedometer.model.gps
data class Admin(
val iso_3166_1: String,
val iso_3166_1_alpha3: String
) | 0 | Kotlin | 0 | 7 | 411c6fcf45a7a9aa34214148264297b345211ed7 | 128 | Pedometer | Apache License 2.0 |
app/src/main/java/com/example/workoutapp/HistoryActivity.kt | Nikolamv95 | 379,632,898 | false | null | package com.example.workoutapp
import android.opengl.Visibility
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.workoutapp.databinding.ActivityExcerciseBinding
import com.example.workoutapp.databinding.ActivityFinishBinding
import com.example.workoutapp.databinding.ActivityHistoryBinding
class HistoryActivity : AppCompatActivity() {
private lateinit var binding: ActivityHistoryBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHistoryBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbarHistoryActivity)
val actionbar = supportActionBar
actionbar?.setDisplayHomeAsUpEnabled(true)
actionbar?.title = "History"
binding.toolbarHistoryActivity.setOnClickListener {
onBackPressed()
}
getAllCompletedDates()
}
private fun getAllCompletedDates(){
val dbHandler = SqliteOpenHelper(this, null)
val completedDatesList = dbHandler.getAllCompletedDatesList()
if (completedDatesList.size > 0){
binding.tvHistory.visibility = View.VISIBLE
binding.rvHistory.visibility = View.VISIBLE
binding.tvNoDataAvailable.visibility = View.GONE
binding.rvHistory.layoutManager = LinearLayoutManager(this)
val historyAdapter = HistoryAdapter(this, completedDatesList)
binding.rvHistory.adapter = historyAdapter
}else{
binding.tvHistory.visibility = View.GONE
binding.rvHistory.visibility = View.GONE
binding.tvNoDataAvailable.visibility = View.VISIBLE
}
}
} | 0 | Kotlin | 0 | 0 | 38c8304415d29f0b395b1d44c469793280f55412 | 1,857 | WorkoutApp | MIT License |
reposilite-backend/src/main/kotlin/com/reposilite/shared/extensions/PicocliExtensions.kt | dzikoysk | 96,474,388 | false | null | /*
* Copyright (c) 2023 dzikoysk
*
* 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.reposilite.shared.extensions
import com.reposilite.VERSION
import panda.std.Result
import panda.std.Result.error
import panda.std.asSuccess
import picocli.CommandLine
import java.util.TreeSet
abstract class Validator : Runnable {
override fun run() { }
}
internal data class CommandConfiguration<VALUE>(
val name: String,
val configuration: VALUE
)
internal fun <CONFIGURATION : Runnable> loadCommandBasedConfiguration(configuration: CONFIGURATION, description: String): CommandConfiguration<CONFIGURATION> =
description.split(" ", limit = 2)
.let { CommandConfiguration(it[0], it.getOrElse(1) { "" }) }
.also { CommandLine(configuration).execute(*splitArguments(it.configuration)) }
.let { CommandConfiguration(it.name, configuration) }
.also { it.configuration.run() }
private fun splitArguments(args: String): Array<String> =
if (args.isEmpty()) arrayOf() else args.split(" ").toTypedArray()
internal fun createCommandHelp(commands: Map<String, CommandLine>, requestedCommand: String): Result<List<String>, String> {
if (requestedCommand.isNotEmpty()) {
return commands[requestedCommand]
?.let { listOf(it.usageMessage).asSuccess() }
?: error("Unknown command '$requestedCommand'")
}
val uniqueCommands: MutableSet<CommandLine> = TreeSet(Comparator.comparing { it.commandName })
uniqueCommands.addAll(commands.values)
val response = mutableListOf("Reposilite $VERSION Commands:")
uniqueCommands
.forEach { command ->
val specification = command.commandSpec
response.add(" " + command.commandName +
(if (specification.args().isEmpty()) "" else " ") +
specification.args().joinToString(separator = " ", transform = {
if (it.isOption) {
var option = ""
if (!it.required()) option += "["
option += "--"
option += if (it.paramLabel().startsWith("<")) it.paramLabel().substring(1).dropLast(1) else it.paramLabel()
if (it.type() != Boolean::class.javaPrimitiveType) option += "=<value>"
if (!it.required()) option += "]"
option
} else it.paramLabel()
}) +
" - ${specification.usageMessage().description().joinToString(". ")}"
)
}
return response.asSuccess()
}
| 27 | null | 85 | 998 | 1d84b2c54465f0c95d79051e3ae29820b14c2f60 | 3,113 | reposilite | Apache License 2.0 |
module/test/src/main/kotlin/com/github/jameshnsears/chance/ui/utility/compose/UtilityComposeHelper.kt | jameshnsears | 725,514,594 | false | {"Kotlin": 348231, "Shell": 678} | package com.github.jameshnsears.chance.ui.utility.compose
import android.app.Application
import com.github.jameshnsears.chance.data.repository.bag.mock.RepositoryBagTestDouble
import com.github.jameshnsears.chance.data.repository.roll.mock.RepositoryRollTestDouble
import com.github.jameshnsears.chance.data.repository.settings.mock.RepositorySettingsTestDouble
import com.github.jameshnsears.chance.data.sample.bag.SampleBagTestData
import com.github.jameshnsears.chance.data.sample.roll.SampleRollTestData
import com.github.jameshnsears.chance.ui.tab.bag.TabBagAndroidViewModel
import com.github.jameshnsears.chance.ui.zoom.ZoomAndroidViewModel
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
fun getViewModels(): Pair<TabBagAndroidViewModel, ZoomAndroidViewModel> {
val repositorySettings = RepositorySettingsTestDouble.getInstance()
val sampleBagTestData = SampleBagTestData()
val repositoryBag = RepositoryBagTestDouble.getInstance()
runBlocking(Dispatchers.Main) {
repositoryBag.store(sampleBagTestData.allDice)
}
val sampleRollTestData = SampleRollTestData(sampleBagTestData)
val repositoryRoll = RepositoryRollTestDouble.getInstance()
runBlocking(Dispatchers.Main) {
repositoryRoll.store(sampleRollTestData.rollHistory)
}
return Pair(
TabBagAndroidViewModel(
mockk<Application>(),
repositorySettings,
repositoryBag,
repositoryRoll
),
ZoomAndroidViewModel(
mockk<Application>(),
repositoryBag,
repositoryRoll
)
)
}
| 1 | Kotlin | 0 | 0 | a3ceaa3329de9f329ced7b2e02a8177890a8cc73 | 1,653 | Chance | Apache License 2.0 |
ReadJSONFile/app/src/main/java/github/nisrulz/example/readjsonfile/ReadConfig.kt | nisrulz | 52,518,462 | false | {"Java": 272459, "Python": 207106, "Kotlin": 186873, "Shell": 7563, "CMake": 227, "C": 200, "HTML": 174} | package github.nisrulz.example.readjsonfile
import android.content.Context
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import kotlin.text.Charsets.UTF_8
class ReadConfig {
fun loadJSONFromAsset(context: Context, filename: String?): JSONObject? {
var jsonObject: JSONObject? = null
val json = try {
val inputStream = context.assets.open(filename!!)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
String(buffer, UTF_8)
} catch (ex: IOException) {
ex.printStackTrace()
return null
}
try {
jsonObject = JSONObject(json)
} catch (e: JSONException) {
e.printStackTrace()
}
return jsonObject
}
} | 7 | Java | 668 | 1,738 | 3ca3cffbfc1d1f8e64681ff8b16269884aa4bc00 | 886 | android-examples | Apache License 2.0 |
src/commonMain/kotlin/data/socketbonus/SocB3263.kt | marisa-ashkandi | 332,658,265 | false | null | package data.socketbonus
import data.Constants
data class SocB3263 (
override var id: Int = 3263,
override var stat: Constants.StatType = Constants.StatType.CRIT_RATING,
override var amount: Int = 4
) : SocketBonusRaw()
| 21 | Kotlin | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 228 | tbcsim | MIT License |
affogato-core-ktx/src/test/java/com/parsuomash/affogato/core/ktx/datetime/LocalDateKtTest.kt | ghasemdev | 510,960,043 | false | null | package com.parsuomash.affogato.core.ktx.datetime
import com.google.common.truth.Truth.assertThat
import java.text.ParseException
import java.util.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.minus
import kotlinx.datetime.plus
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class LocalDateKtTest {
private val date = Date()
private val now = LocalDate.now()
@Nested
@DisplayName("Converter")
inner class Converter {
@Test
@DisplayName("Long as LocalDate")
fun longAsLocalDate() {
assertThat(1_659_814_200_000.toLocalDate().also(::println)).isEqualTo(LocalDate(2022, 8, 7))
assertThat(date.time.toLocalDate()).isEqualTo(date.toLocalDate())
}
@Test
@DisplayName("localDate as Date")
fun localDateAsDate() {
val date = LocalDate(2020, 1, 2)
val calendar = Calendar.getInstance().apply {
set(2020, 0, 2, 0, 0, 0)
set(Calendar.MILLISECOND, 0)
}
assertThat(date.toDate()).isEqualTo(calendar.time)
}
@Test
@DisplayName("localDate as localDateTime")
fun localDateAsLocalDateTime() {
val date = LocalDate(2020, 1, 2)
val local = LocalDateTime(2020, 1, 2, 0, 0)
assertThat(date.toLocalDateTime()).isEqualTo(local)
}
@Test
@DisplayName("localDate as Calendar")
fun localDateAsCalendar() {
val date = LocalDate(2020, 1, 2)
val calendar = Calendar.getInstance().apply {
set(2020, 0, 2, 0, 0, 0)
set(Calendar.MILLISECOND, 0)
}
assertThat(date.toCalendar()).isEqualTo(calendar)
}
@Test
@DisplayName("String to LocalDate")
fun stringToLocalDate() {
assertThat("8/7/2022".toLocalDate("MM/dd/yyyy"))
.isEqualTo(1_659_814_200_000.toLocalDate().also(::println))
assertThat("Sun Aug 07 16:37:42 IRDT 2022".toLocalDate())
.isEqualTo(1_659_874_062_000.toLocalDate().also(::println))
assertThrows<ParseException> { "7/2022".toLocalDate("MM/dd/yyyy") }
}
@Test
@DisplayName("String to LocalDate or Null")
fun stringToLocalDateOrNull() {
assertThat("8/7/2022".toLocalDateOrNull("MM/dd/yyyy"))
.isEqualTo(1_659_814_200_000.toLocalDate())
assertThat("Sun Aug 07 16:37:42 IRDT 2022".toLocalDateOrNull())
.isEqualTo(1_659_874_062_000.toLocalDate())
assertThat("7/2022".toLocalDateOrNull("MM/dd/yyyy")).isNull()
}
@Test
@DisplayName("LocalDate to String")
fun localDateToString() {
assertThat(1_659_814_200_000.toLocalDate().toString("MM/dd/yyyy")).isEqualTo("08/07/2022")
assertThat(1_659_874_062_000.toLocalDate().toString("EEE MMM dd HH:mm:ss zzz yyyy"))
.isEqualTo("Sun Aug 07 00:00:00 IRDT 2022")
assertThat(1_659_814_200_000.toLocalDate().format("MM/dd/yyyy")).isEqualTo("08/07/2022")
assertThat(1_659_874_062_000.toLocalDate().format("EEE MMM dd HH:mm:ss zzz yyyy"))
.isEqualTo("Sun Aug 07 00:00:00 IRDT 2022")
}
}
@Nested
@DisplayName("Operations")
inner class Operations {
@Test
fun plusLocalDate() {
assertThat(now + 1.days).isEqualTo(now.plus(1.days.inWholeDays, DateTimeUnit.DAY))
}
@Test
fun minusLocalDate() {
assertThat(now - 1.days).isEqualTo(now.minus(1.days.inWholeDays, DateTimeUnit.DAY))
}
@Test
fun isSameDay() {
assertThat(now isSameDay (now + 5.hours)).isTrue()
}
}
}
| 0 | Kotlin | 1 | 9 | f1944a97416221855060a954b539fbd87b74033b | 3,669 | affogato | MIT License |
app/src/main/java/io/horizontalsystems/bitcoinkit/demo/SendReceiveFragment.kt | paycoin-com | 171,249,034 | true | {"Kotlin": 435926, "Java": 48875} | package io.horizontalsystems.bitcoinkit.demo
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import io.horizontalsystems.bitcoinkit.managers.UnspentOutputSelector
class SendReceiveFragment : Fragment() {
private lateinit var viewModel: MainViewModel
private lateinit var receiveAddressButton: Button
private lateinit var receiveAddressText: TextView
private lateinit var sendButton: Button
private lateinit var sendAmount: EditText
private lateinit var sendAddress: EditText
private lateinit var txFeeValue: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity?.let {
viewModel = ViewModelProviders.of(it).get(MainViewModel::class.java)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_send_receive, null)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
receiveAddressText = view.findViewById(R.id.receiveAddressText)
receiveAddressButton = view.findViewById(R.id.receiveAddressButton)
receiveAddressButton.setOnClickListener {
receiveAddressText.text = viewModel.receiveAddress()
}
txFeeValue = view.findViewById(R.id.txFeeValue)
sendAddress = view.findViewById(R.id.sendAddress)
sendAmount = view.findViewById(R.id.sendAmount)
sendButton = view.findViewById(R.id.sendButton)
sendButton.setOnClickListener {
if (sendAddress.text.isEmpty()) {
sendAddress.error = "Send address cannot be blank"
} else if (sendAmount.text.isEmpty()) {
sendAmount.error = "Send amount cannot be blank"
} else {
send()
}
}
sendAmount.addTextChangedListener(textChangeListener)
}
private fun send() {
var message: String
try {
viewModel.send(sendAddress.text.toString(), sendAmount.text.toString().toLong())
sendAmount.text = null
txFeeValue.text = null
sendAddress.text = null
message = "Transaction sent"
} catch (e: Exception) {
message = when (e) {
is UnspentOutputSelector.Error.InsufficientUnspentOutputs,
is UnspentOutputSelector.Error.EmptyUnspentOutputs -> "Insufficient balance"
else -> e.message ?: "Failed to send transaction"
}
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
private val textChangeListener = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
if (sendAddress.text.isEmpty() || sendAmount.text.isEmpty()) {
return
}
try {
txFeeValue.text = viewModel.fee(
value = sendAmount.text.toString().toLong(),
address = sendAddress.text.toString()
).toString()
} catch (e: Exception) {
Toast.makeText(context, e.message, Toast.LENGTH_LONG).show()
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
}
| 0 | Kotlin | 0 | 0 | f79ab6e0b757dccca0decf8ba319721b81ac34b0 | 3,835 | bitcoin-kit-android | MIT License |
shared/src/commonMain/kotlin/com/zizohanto/android/tobuy/ext/Extensions.kt | zizoh | 292,960,353 | false | {"Kotlin": 105596} | package com.zizohanto.android.tobuy.ext
val Throwable.errorMessage: String
get() = message ?: "An error occurred"
fun <T> List<T>.replaceFirst(element: T, predicate: (T) -> Boolean): List<T> {
val items: ArrayList<T> = ArrayList(this)
for ((index, item) in items.withIndex()) {
if (predicate(item)) {
items[index] = element
return items
}
}
return items
}
fun <T> List<T>.removeFirst(predicate: (T) -> Boolean): List<T> {
val items: ArrayList<T> = ArrayList(this)
for ((index, item) in items.withIndex()) {
if (predicate(item)) {
items.removeAt(index)
return items
}
}
return items
} | 0 | Kotlin | 2 | 7 | e597f734c29986aebd5dce972246f0a306e59edb | 702 | Shopping-List-MVI | Apache License 2.0 |
src/main/kotlin/no/nav/k9punsj/tilgangskontroll/audit/EventClassId.kt | navikt | 216,808,662 | false | null | package no.nav.k9punsj.audit
enum class EventClassId(val cefKode: String) {
/** Bruker har sett data. */
AUDIT_ACCESS("audit:access"),
/** Minimalt innsyn, f.eks. ved visning i liste. */
AUDIT_SEARCH("audit:search"),
/** Bruker har lagt inn nye data */
AUDIT_CREATE("audit:create"),
/** Bruker har endret data */
AUDIT_UPDATE("audit:update");
}
| 9 | null | 2 | 1 | f602bd5cc28f99032c48a4c79998d66549915107 | 386 | k9-punsj | MIT License |
src/main/kotlin/io/github/komdosh/alarms/actions/Alarm20Min.kt | Komdosh | 140,246,250 | false | {"Kotlin": 5573} | package io.github.komdosh.alarms.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.ServiceManager
import io.github.komdosh.alarms.services.AlarmService
import java.util.concurrent.TimeUnit
class Alarm20Min : AnAction("Alarm20Min") {
override fun actionPerformed(event: AnActionEvent) {
event.project?.let{
val alarmService = ServiceManager.getService(AlarmService::class.java)
alarmService.setAlertInSeconds(it, TimeUnit.MINUTES, 20)
}
}
}
| 0 | Kotlin | 0 | 1 | a0eeffd72bb3e196d5a42d91ac3bde8120bd8058 | 592 | Alarms | MIT License |
algorithms/src/main/kotlin/com/kotlinground/algorithms/dynamicprogramming/buyandsell/maxProfitWithFee.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 499795, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.dynamicprogramming.buyandsell
import kotlin.math.max
fun maxProfitWithFee(prices: IntArray, fee: Int): Int {
if (prices.isEmpty()) {
return 0
}
var cashWithShares = -prices[0]
var cashWithoutShares = 0
for (i in 1 until prices.size) {
cashWithShares = max(cashWithShares, cashWithoutShares - prices[i])
cashWithoutShares = maxOf(cashWithoutShares, cashWithShares + prices[i] - fee)
}
return cashWithoutShares
}
| 1 | Kotlin | 1 | 0 | 7f06bd333f33a10a52affdb1b2df4305d3552ef4 | 503 | KotlinGround | MIT License |
src/main/kotlin/com/writerai/data/datasources/sharedTo/SharedToDatasourceImpl.kt | Vaibhav2002 | 512,184,098 | false | {"Kotlin": 44267} | package com.writerai.data.datasources.sharedTo
import com.writerai.data.db.tables.ShareTable
import com.writerai.data.models.entities.SharedTo
import com.writerai.data.models.entities.User
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.transaction
class SharedToDatasourceImpl : SharedToDataSource {
init {
transaction { SchemaUtils.create(ShareTable) }
}
override suspend fun getSharedByMe(userId: String): List<SharedTo> = newSuspendedTransaction {
SharedTo.find {
ShareTable.ownerId eq userId
}.toList()
}
override suspend fun getSharedToMe(userId: String): List<SharedTo> = newSuspendedTransaction {
SharedTo.find {
ShareTable.sharedTo eq userId
}.toList()
}
override suspend fun getSharersOfProject(projectId: Int): List<SharedTo> = newSuspendedTransaction {
SharedTo.find {
ShareTable.projectId eq projectId
}.toList()
}
override suspend fun shareTo(ownerId: String, toUser: User, projectId: Int): SharedTo = newSuspendedTransaction {
SharedTo.new {
this.ownerId = ownerId
this.sharedTo = toUser.id.value
this.sharedToEmail = toUser.email
this.projectId = projectId
}
}
override suspend fun removeShare(userId: String, id: Int): SharedTo? = newSuspendedTransaction {
val sharedTo = SharedTo.find {
(ShareTable.ownerId eq userId) and (ShareTable.id eq id)
}.firstOrNull()
sharedTo?.delete()
sharedTo
}
override suspend fun getShare(userId: String, toUser: User, projectId: Int): SharedTo? = newSuspendedTransaction {
SharedTo.find {
(ShareTable.ownerId eq userId) and (ShareTable.sharedTo eq toUser.id.value) and (ShareTable.projectId eq projectId)
}.firstOrNull()
}
} | 0 | Kotlin | 13 | 33 | f77f0747f2846127dc6e413b9f32ccdabce91320 | 2,030 | WriterAI-Backend | MIT License |
next/kmp/core/src/commonTest/kotlin/IpcRequestTest.kt | BioforestChain | 594,577,896 | false | {"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818} | package info.bagen.dwebbrowser
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.dweb_browser.core.http.router.byChannel
import org.dweb_browser.core.ipc.IpcRequestInit
import org.dweb_browser.core.ipc.NativeMessageChannel
import org.dweb_browser.core.ipc.helper.IpcResponse
import org.dweb_browser.core.ipc.kotlinIpcPool
import org.dweb_browser.core.module.BootstrapContext
import org.dweb_browser.core.module.NativeMicroModule
import org.dweb_browser.core.module.channelRequest
import org.dweb_browser.core.std.dns.DnsNMM
import org.dweb_browser.helper.addDebugTags
import org.dweb_browser.helper.collectIn
import org.dweb_browser.pure.http.IPureBody
import org.dweb_browser.pure.http.PureMethod
import org.dweb_browser.test.runCommonTest
import kotlin.test.Test
import kotlin.test.assertEquals
class IpcRequestTest {
init {
addDebugTags(listOf("/.+/"))
}
// 黑盒测试ipcRequest
@Test
fun testIpcRequestInBlackBox() = runCommonTest {
val channel = NativeMessageChannel(kotlinIpcPool.scope, "from.id.dweb", "to.id.dweb")
val fromMM = TestMicroModule()
val toMM = TestMicroModule()
val pid = 0
val senderIpc = kotlinIpcPool.createIpc(channel.port1, pid, fromMM.manifest, toMM.manifest)
val receiverIpc = kotlinIpcPool.createIpc(channel.port2, pid, toMM.manifest, fromMM.manifest)
launch {
// send text body
println("🧨=> send text body")
val response = senderIpc.request(
"https://test.dwebdapp_1.com", IpcRequestInit(
method = PureMethod.POST, body = IPureBody.from("senderIpc")
)
)
val res = response.body.text()
println("🧨=> ${response.statusCode} $res")
assertEquals(res, "senderIpc 除夕快乐")
}
launch {
println("🧨=> 开始监听消息")
receiverIpc.onRequest("test").collectIn(this) { event ->
val request = event.consume()
val data = request.body.toString()
println("receiverIpc结果🧨=> $data ")
assertEquals("senderIpc 除夕快乐", data)
receiverIpc.postMessage(
IpcResponse.fromText(
request.reqId, text = "receiverIpc 除夕快乐", ipc = receiverIpc
)
)
}
senderIpc.onRequest("test").onEach { event ->
val request = event.consume()
val data = request.body.text()
println("senderIpc结果🧨=> $data ${senderIpc.remote.mmid}")
assertEquals("senderIpc", data)
senderIpc.postMessage(
IpcResponse.fromText(
request.reqId, text = "senderIpc 除夕快乐", ipc = senderIpc
)
)
}.launchIn(this)
}
}
@Test
fun testIpcChannel() = runCommonTest {
class TestMicroModule(mmid: String = "test.ipcChannel.dweb") :
NativeMicroModule(mmid, "test IpcChannel") {
inner class TestRuntime(override val bootstrapContext: BootstrapContext) : NativeRuntime() {
override suspend fun _bootstrap() {
routes(
//
"/channel" byChannel { ctx ->
for (msg in ctx.income) {
ctx.sendText((msg.text.toInt() * 2).toString())
}
},
)
}
override suspend fun _shutdown() {
}
}
override fun createRuntime(bootstrapContext: BootstrapContext) = TestRuntime(bootstrapContext)
}
val dns = DnsNMM()
val serverMM = TestMicroModule("server.mm.dweb")
val clientMM = TestMicroModule("client.mm.dweb")
dns.install(clientMM)
dns.install(serverMM)
val dnsRuntime = dns.bootstrap()
val clientRuntime = dnsRuntime.open(clientMM.mmid) as NativeMicroModule.NativeRuntime;
/// 用来测试前面发起的ws不会阻塞后面的请求
val job1 = CompletableDeferred<Unit>()
val job2 = CompletableDeferred<Unit>()
launch(start = CoroutineStart.UNDISPATCHED) {
var actual = 0
var expected = 0
clientRuntime.channelRequest("file://${serverMM.mmid}/channel") {
job1.complete(Unit)
job2.await()
launch {
for (i in 1..10) {
actual += i * 2
sendText("$i")
}
delay(1000)
close()
}
for (frame in income) {
println("client got msg: $frame")
expected += frame.text.toInt()
}
}
assertEquals(expected = expected, actual = actual)
}
launch(start = CoroutineStart.UNDISPATCHED) {
var actual = 0
var expected = 0
job1.await()
clientRuntime.channelRequest("file://${serverMM.mmid}/channel") {
launch {
for (i in 1..10) {
actual += i * 2
sendText("$i")
}
delay(1000)
close()
}
for (frame in income) {
println("client got msg: $frame")
expected += frame.text.toInt()
}
}
assertEquals(expected = expected, actual = actual)
job2.complete(Unit)
}
}
} | 66 | Kotlin | 5 | 20 | 6db1137257e38400c87279f4ccf46511752cd45a | 5,058 | dweb_browser | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.