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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
teamscale-gradle-plugin/src/main/kotlin/com/teamscale/Report.kt
|
escher-cqse
| 533,736,514
| true
|
{"Markdown": 8, "Shell": 4, "Java Properties": 7, "Batchfile": 5, "Java": 254, "Gradle Kotlin DSL": 6, "Kotlin": 24, "INI": 6, "Dockerfile": 1}
|
package com.teamscale
import com.teamscale.client.EReportFormat
import org.gradle.api.file.FileCollection
import java.io.File
import java.io.Serializable
/**
* Report holder used to describe an already configured report
* that should be uploaded to Teamscale.
*/
data class Report(
/** Report format. */
val format: EReportFormat,
/** The report file. */
val reportFile: File,
/** The partition to upload the report to. */
var partition: String,
/** The commit message shown in Teamscale for the upload. */
var message: String
) : Serializable
| 0
| null |
0
| 0
|
4010ee0e72b3972c91ed0fe8c1f3c4a784026525
| 584
|
teamscale-jacoco-agent
|
Apache License 2.0
|
project-system-gradle-sync/src/com/android/tools/idea/gradle/project/sync/SelectedVariant.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.project.sync
import java.io.Serializable
data class SelectedVariant(
/**
* The id of the module in the form returned by [Modules.createUniqueModuleId].
*/
val moduleId: String,
val variantName: String,
val abiName: String?,
/**
* An instance of [VariantDetails] which describes [variantName]. `null` if no models were available when constructing this instance.
*/
val details: VariantDetails?
) : Serializable
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 1,097
|
android
|
Apache License 2.0
|
src/main/kotlin/guru/stefma/androidartifacts/Project.kt
|
StefMa
| 91,171,709
| false
| null |
package guru.stefma.androidartifacts
import com.android.build.gradle.LibraryExtension
import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
/**
* The [LibraryExtension] from the applied **com.android.library** plugin
*/
internal val Project.androidLibraryExtension
get() = extensions.getByType(LibraryExtension::class.java)
/**
* The [PublishingExtension] from the applied **maven-publish** plugin
*/
internal val Project.publishingExtension
get() = extensions.getByType(PublishingExtension::class.java)
/**
* Is true if either the `kotlin-android` or the `org.jetbrains.kotlin.android` plugin
* is applied...
*
* @see PluginIds
*/
internal val Project.hasKotlinAndroidPluginApplied
get() = pluginManager.hasPlugin(PluginIds.kotlinAndroidLegacy) || pluginManager.hasPlugin(PluginIds.kotlinAndroid)
/**
* Is true if either the `kotlin` or the `org.jetbrains.kotlin.jvm` plugin
* is applied...
*
* @see PluginIds
*/
internal val Project.hasKotlinJvmPluginApplied
get() = pluginManager.hasPlugin(PluginIds.kotlinJvmLegacy) || pluginManager.hasPlugin(PluginIds.kotlinJvm)
/**
* Applies the **maven-publish** plugin.
*
* @see PluginIds
*/
internal fun Project.applyMavenPublishPlugin() = pluginManager.apply(PluginIds.mavenPublish)
| 15
|
Kotlin
|
5
| 11
|
ed04801bea56fc59ccb01e0db0f186dbe133e868
| 1,292
|
AndroidArtifacts
|
Apache License 2.0
|
compiler/testData/codegen/box/inlineClasses/inlineClassCollection/inlineCollectionOfInlineClass.kt
|
JetBrains
| 3,432,266
| false
| null |
// WITH_RUNTIME
@Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE")
@kotlin.jvm.JvmInline
value class Z(val x: Int)
@Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE")
@kotlin.jvm.JvmInline
value class ZArray(val storage: IntArray) : Collection<Z> {
override val size: Int
get() = storage.size
override fun contains(element: Z): Boolean {
return storage.contains(element.x)
}
override fun containsAll(elements: Collection<Z>): Boolean {
return elements.all { contains(it) }
}
override fun isEmpty(): Boolean {
return storage.isEmpty()
}
private class ZArrayIterator(val storage: IntArray): Iterator<Z> {
var index = 0
override fun hasNext(): Boolean = index < storage.size
override fun next(): Z = Z(storage[index++])
}
override fun iterator(): Iterator<Z> = ZArrayIterator(storage)
}
fun box(): String {
val zs = ZArray(IntArray(5))
val testSize = zs.size
if (testSize != 5) return "Failed: testSize=$testSize"
val testContains = zs.contains(object {} as Any)
if (testContains) return "Failed: testContains=$testContains"
return "OK"
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,189
|
kotlin
|
Apache License 2.0
|
sections/day19/rx-repo/src/main/kotlin/cc/jianminhuang/day19/data/dao/MemberDao.kt
|
b2etw
| 310,598,084
| false
| null |
package cc.jianminhuang.day19.data.dao
import cc.jianminhuang.day19.data.`do`.Member
import org.springframework.data.repository.reactive.ReactiveCrudRepository
interface MemberDao: ReactiveCrudRepository<Member, Long> {
}
| 1
|
Kotlin
|
1
| 35
|
c88e506c1e038c02840703a6e80b224de139178e
| 223
|
Spring-Kotlin-iThome-2021
|
MIT License
|
common/src/commonMain/kotlin/com/artemchep/keyguard/common/usecase/impl/PutUserExternalBrowserImpl.kt
|
AChep
| 669,697,660
| false
|
{"Kotlin": 5516822, "HTML": 45876}
|
package com.artemchep.keyguard.common.usecase.impl
import com.artemchep.keyguard.common.io.IO
import com.artemchep.keyguard.common.service.settings.SettingsReadWriteRepository
import com.artemchep.keyguard.common.usecase.PutUseExternalBrowser
import org.kodein.di.DirectDI
import org.kodein.di.instance
class PutUserExternalBrowserImpl(
private val settingsReadWriteRepository: SettingsReadWriteRepository,
) : PutUseExternalBrowser {
constructor(directDI: DirectDI) : this(
settingsReadWriteRepository = directDI.instance(),
)
override fun invoke(useExternalBrowser: Boolean): IO<Unit> = settingsReadWriteRepository
.setUseExternalBrowser(useExternalBrowser)
}
| 66
|
Kotlin
|
31
| 995
|
557bf42372ebb19007e3a8871e3f7cb8a7e50739
| 697
|
keyguard-app
|
Linux Kernel Variant of OpenIB.org license
|
app/src/main/java/com/elementary/tasks/core/binding/dialogs/DialogExclusionPickerBinding.kt
|
naz013
| 165,067,747
| false
| null |
package com.elementary.tasks.core.binding.dialogs
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.ToggleButton
import com.elementary.tasks.R
import com.elementary.tasks.core.binding.Binding
class DialogExclusionPickerBinding(view: View) : Binding(view) {
val radioGroup: RadioGroup by bindView(R.id.radioGroup)
val selectInterval: RadioButton by bindView(R.id.selectInterval)
val selectHours: RadioButton by bindView(R.id.selectHours)
val intervalContainer: View by bindView(R.id.intervalContainer)
val hoursContainer: View by bindView(R.id.hoursContainer)
val from: TextView by bindView(R.id.from)
val to: TextView by bindView(R.id.to)
val zero: ToggleButton by bindView(R.id.zero)
val one: ToggleButton by bindView(R.id.one)
val two: ToggleButton by bindView(R.id.two)
val three: ToggleButton by bindView(R.id.three)
val four: ToggleButton by bindView(R.id.four)
val five: ToggleButton by bindView(R.id.five)
val six: ToggleButton by bindView(R.id.six)
val seven: ToggleButton by bindView(R.id.seven)
val eight: ToggleButton by bindView(R.id.eight)
val nine: ToggleButton by bindView(R.id.nine)
val ten: ToggleButton by bindView(R.id.ten)
val eleven: ToggleButton by bindView(R.id.eleven)
val twelve: ToggleButton by bindView(R.id.twelve)
val thirteen: ToggleButton by bindView(R.id.thirteen)
val fourteen: ToggleButton by bindView(R.id.fourteen)
val fifteen: ToggleButton by bindView(R.id.fifteen)
val sixteen: ToggleButton by bindView(R.id.sixteen)
val seventeen: ToggleButton by bindView(R.id.seventeen)
val eighteen: ToggleButton by bindView(R.id.eighteen)
val nineteen: ToggleButton by bindView(R.id.nineteen)
val twenty: ToggleButton by bindView(R.id.twenty)
val twentyOne: ToggleButton by bindView(R.id.twentyOne)
val twentyTwo: ToggleButton by bindView(R.id.twentyTwo)
val twentyThree: ToggleButton by bindView(R.id.twentyThree)
}
| 0
| null |
3
| 6
|
3d26792f05f4183cea6107aeec2d0a065f6b427c
| 2,002
|
reminder-kotlin
|
Apache License 2.0
|
app/src/main/java/seisuke/kodomokeyboard/model/KeyboardState.kt
|
seisuke
| 336,212,833
| false
| null |
package seisuke.kodomokeyboard.model
data class KeyboardState(
val katakana: Boolean,
val dakuon: Boolean
) {
companion object {
fun create(): KeyboardState = KeyboardState(
katakana = false,
dakuon = false
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1e7ffc87dfc4908b6958d9690212c276fc683ff3
| 270
|
kodomo_keyboard
|
MIT License
|
core/src/main/kotlin/com/weedow/searchy/validation/SearchyError.kt
|
Kobee1203
| 260,688,695
| false
| null |
package com.weedow.searchy.validation
/**
* Data Class representing a validation error.
*
* @param errorCode Error code
* @param errorMessage Error message
* @param arguments Error arguments for argument binding via MessageFormat. Can be `null`.
*/
data class SearchyError(
val errorCode: String,
val errorMessage: String,
val arguments: Array<out Any>
) {
/**
* Secondary constructor.
*
* @param errorCode Error code
* @param errorMessage Error message
*/
constructor(errorCode: String, errorMessage: String) : this(errorCode, errorMessage, emptyArray<Any>())
/** @suppress */
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SearchyError
if (errorCode != other.errorCode) return false
if (errorMessage != other.errorMessage) return false
if (!arguments.contentEquals(other.arguments)) return false
return true
}
/** @suppress */
override fun hashCode(): Int {
var result = errorCode.hashCode()
result = 31 * result + errorMessage.hashCode()
result = 31 * result + arguments.contentHashCode()
return result
}
}
| 12
| null |
3
| 22
|
7a0e0bac533fc822ce4a2b58bc1f22eda53e5c72
| 1,267
|
weedow-searchy
|
MIT License
|
komposable-architecture/src/main/java/com/toggl/komposable/internal/OptionalReducer.kt
|
toggl
| 316,494,344
| false
|
{"Kotlin": 163466}
|
package com.toggl.komposable.internal
import com.toggl.komposable.architecture.NoEffect
import com.toggl.komposable.architecture.ReduceResult
import com.toggl.komposable.architecture.Reducer
import com.toggl.komposable.extensions.map
internal class OptionalReducer<LocalState, GlobalState, LocalAction, GlobalAction>(
private val innerReducer: Reducer<LocalState, LocalAction>,
private val mapToLocalState: (GlobalState) -> LocalState?,
private val mapToLocalAction: (GlobalAction) -> LocalAction?,
private val mapToGlobalState: (GlobalState, LocalState?) -> GlobalState,
private val mapToGlobalAction: (LocalAction) -> GlobalAction,
) : Reducer<GlobalState, GlobalAction> {
override fun reduce(
state: GlobalState,
action: GlobalAction,
): ReduceResult<GlobalState, GlobalAction> {
val localAction = mapToLocalAction(action) ?: return ReduceResult(state, NoEffect)
val localState = mapToLocalState(state) ?: return ReduceResult(state, NoEffect)
val (newLocalState, newLocalEffects) = innerReducer.reduce(localState, localAction)
return ReduceResult(
mapToGlobalState(state, newLocalState),
newLocalEffects.map(mapToGlobalAction),
)
}
}
| 8
|
Kotlin
|
20
| 274
|
6c975b17ee94079b66d43d199f106eb6323913a0
| 1,251
|
komposable-architecture
|
Apache License 2.0
|
common-core/src/main/kotlin/com/blacksquircle/ui/core/storage/keyvalue/SettingsManager.kt
|
massivemadness
| 100,590,072
| false
| null |
/*
* Copyright 2023 Squircle CE contributors.
*
* 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.blacksquircle.ui.core.data.storage.keyvalue
import android.content.SharedPreferences
class SettingsManager(private val sharedPreferences: SharedPreferences) {
companion object {
// Look And Feel
const val KEY_COLOR_SCHEME = "COLOR_SCHEME"
const val KEY_FULLSCREEN_MODE = "FULLSCREEN_MODE"
// Other
const val KEY_CONFIRM_EXIT = "CONFIRM_EXIT"
// Font
const val KEY_FONT_SIZE = "FONT_SIZE_2"
const val KEY_FONT_TYPE = "FONT_TYPE_3"
// Editor
const val KEY_WORD_WRAP = "WORD_WRAP"
const val KEY_CODE_COMPLETION = "CODE_COMPLETION"
// const val KEY_ERROR_HIGHLIGHTING = "ERROR_HIGHLIGHTING"
const val KEY_PINCH_ZOOM = "PINCH_ZOOM"
const val KEY_LINE_NUMBERS = "SHOW_LINE_NUMBERS"
const val KEY_HIGHLIGHT_CURRENT_LINE = "HIGHLIGHT_CURRENT_LINE"
const val KEY_HIGHLIGHT_MATCHING_DELIMITERS = "HIGHLIGHT_MATCHING_DELIMITERS"
// Tabs
const val KEY_SELECTED_DOCUMENT_ID = "SELECTED_DOCUMENT_ID"
const val KEY_AUTO_SAVE_FILES = "AUTO_SAVE_FILES"
// Keyboard
const val KEY_USE_EXTENDED_KEYBOARD = "USE_EXTENDED_KEYBOARD"
const val KEY_KEYBOARD_PRESET = "KEYBOARD_PRESET_1"
const val KEY_USE_SOFT_KEYBOARD = "USE_SOFT_KEYBOARD"
// Code Style
const val KEY_AUTO_INDENTATION = "AUTO_INDENTATION"
const val KEY_AUTO_CLOSE_BRACKETS = "AUTO_CLOSE_BRACKETS"
const val KEY_AUTO_CLOSE_QUOTES = "AUTO_CLOSE_QUOTES"
// Tab Options
const val KEY_USE_SPACES_NOT_TABS = "USE_SPACES_NOT_TABS"
const val KEY_TAB_WIDTH = "TAB_WIDTH"
// Encoding
const val KEY_ENCODING_AUTO_DETECT = "ENCODING_AUTO_DETECT"
const val KEY_ENCODING_FOR_OPENING = "ENCODING_FOR_OPENING"
const val KEY_ENCODING_FOR_SAVING = "ENCODING_FOR_SAVING"
// Linebreaks
const val KEY_LINEBREAK_FOR_SAVING = "LINEBREAK_FOR_SAVING"
// File Explorer
const val KEY_SHOW_HIDDEN_FILES = "SHOW_HIDDEN_FILES"
const val KEY_FOLDERS_ON_TOP = "FOLDERS_ON_TOP"
const val KEY_VIEW_MODE = "VIEW_MODE"
const val KEY_SORT_MODE = "SORT_MODE"
}
var colorScheme: String
get() = sharedPreferences.getString(KEY_COLOR_SCHEME, "DARCULA") ?: "DARCULA"
set(value) = sharedPreferences.edit().putString(KEY_COLOR_SCHEME, value).apply()
var fullScreenMode: Boolean
get() = sharedPreferences.getBoolean(KEY_FULLSCREEN_MODE, false)
set(value) = sharedPreferences.edit().putBoolean(KEY_FULLSCREEN_MODE, value).apply()
var confirmExit: Boolean
get() = sharedPreferences.getBoolean(KEY_CONFIRM_EXIT, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_CONFIRM_EXIT, value).apply()
var fontSize: Int
get() = sharedPreferences.getInt(KEY_FONT_SIZE, 14)
set(value) = sharedPreferences.edit().putInt(KEY_FONT_SIZE, value).apply()
var fontType: String
get() = sharedPreferences.getString(KEY_FONT_TYPE, "file:///android_asset/fonts/jetbrains_mono.ttf") ?: "file:///android_asset/fonts/jetbrains_mono.ttf"
set(value) = sharedPreferences.edit().putString(KEY_FONT_TYPE, value).apply()
var selectedUuid: String
get() = sharedPreferences.getString(KEY_SELECTED_DOCUMENT_ID, "whatever") ?: "whatever"
set(value) = sharedPreferences.edit().putString(KEY_SELECTED_DOCUMENT_ID, value).apply()
var wordWrap: Boolean
get() = sharedPreferences.getBoolean(KEY_WORD_WRAP, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_WORD_WRAP, value).apply()
var codeCompletion: Boolean
get() = sharedPreferences.getBoolean(KEY_CODE_COMPLETION, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_CODE_COMPLETION, value).apply()
/*var errorHighlighting: Boolean
get() = sharedPreferences.getBoolean(KEY_ERROR_HIGHLIGHTING, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_ERROR_HIGHLIGHTING, value).apply()*/
var pinchZoom: Boolean
get() = sharedPreferences.getBoolean(KEY_PINCH_ZOOM, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_PINCH_ZOOM, value).apply()
var lineNumbers: Boolean
get() = sharedPreferences.getBoolean(KEY_LINE_NUMBERS, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_LINE_NUMBERS, value).apply()
var highlightCurrentLine: Boolean
get() = sharedPreferences.getBoolean(KEY_HIGHLIGHT_CURRENT_LINE, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_HIGHLIGHT_CURRENT_LINE, value).apply()
var highlightMatchingDelimiters: Boolean
get() = sharedPreferences.getBoolean(KEY_HIGHLIGHT_MATCHING_DELIMITERS, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_HIGHLIGHT_MATCHING_DELIMITERS, value).apply()
var autoSaveFiles: Boolean
get() = sharedPreferences.getBoolean(KEY_AUTO_SAVE_FILES, false)
set(value) = sharedPreferences.edit().putBoolean(KEY_AUTO_SAVE_FILES, value).apply()
var extendedKeyboard: Boolean
get() = sharedPreferences.getBoolean(KEY_USE_EXTENDED_KEYBOARD, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_USE_EXTENDED_KEYBOARD, value).apply()
var keyboardPreset: String
get() = sharedPreferences.getString(KEY_KEYBOARD_PRESET, "{}();,.=|&![]<>+-/*?:_") ?: "{}();,.=|&![]<>+-/*?:_"
set(value) = sharedPreferences.edit().putString(KEY_KEYBOARD_PRESET, value).apply()
var softKeyboard: Boolean
get() = sharedPreferences.getBoolean(KEY_USE_SOFT_KEYBOARD, false)
set(value) = sharedPreferences.edit().putBoolean(KEY_USE_SOFT_KEYBOARD, value).apply()
var autoIndentation: Boolean
get() = sharedPreferences.getBoolean(KEY_AUTO_INDENTATION, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_AUTO_INDENTATION, value).apply()
var autoCloseBrackets: Boolean
get() = sharedPreferences.getBoolean(KEY_AUTO_CLOSE_BRACKETS, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_AUTO_CLOSE_BRACKETS, value).apply()
var autoCloseQuotes: Boolean
get() = sharedPreferences.getBoolean(KEY_AUTO_CLOSE_QUOTES, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_AUTO_CLOSE_QUOTES, value).apply()
var useSpacesInsteadOfTabs: Boolean
get() = sharedPreferences.getBoolean(KEY_USE_SPACES_NOT_TABS, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_USE_SPACES_NOT_TABS, value).apply()
var tabWidth: Int
get() = sharedPreferences.getInt(KEY_TAB_WIDTH, 4)
set(value) = sharedPreferences.edit().putInt(KEY_TAB_WIDTH, value).apply()
var encodingAutoDetect: Boolean
get() = sharedPreferences.getBoolean(KEY_ENCODING_AUTO_DETECT, false)
set(value) = sharedPreferences.edit().putBoolean(KEY_ENCODING_AUTO_DETECT, value).apply()
var encodingForOpening: String
get() = sharedPreferences.getString(KEY_ENCODING_FOR_OPENING, "UTF-8") ?: "UTF-8"
set(value) = sharedPreferences.edit().putString(KEY_ENCODING_FOR_OPENING, value).apply()
var encodingForSaving: String
get() = sharedPreferences.getString(KEY_ENCODING_FOR_SAVING, "UTF-8") ?: "UTF-8"
set(value) = sharedPreferences.edit().putString(KEY_ENCODING_FOR_SAVING, value).apply()
var lineBreakForSaving: String
get() = sharedPreferences.getString(KEY_LINEBREAK_FOR_SAVING, "2") ?: "2"
set(value) = sharedPreferences.edit().putString(KEY_LINEBREAK_FOR_SAVING, value).apply()
var showHidden: Boolean
get() = sharedPreferences.getBoolean(KEY_SHOW_HIDDEN_FILES, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_SHOW_HIDDEN_FILES, value).apply()
var foldersOnTop: Boolean
get() = sharedPreferences.getBoolean(KEY_FOLDERS_ON_TOP, true)
set(value) = sharedPreferences.edit().putBoolean(KEY_FOLDERS_ON_TOP, value).apply()
var viewMode: String
get() = sharedPreferences.getString(KEY_VIEW_MODE, "0") ?: "0"
set(value) = sharedPreferences.edit().putString(KEY_VIEW_MODE, value).apply()
var sortMode: String
get() = sharedPreferences.getString(KEY_SORT_MODE, "0") ?: "0"
set(value) = sharedPreferences.edit().putString(KEY_SORT_MODE, value).apply()
fun remove(key: String) {
sharedPreferences.edit().remove(key).apply()
}
}
| 74
| null |
75
| 708
|
2622fcc49a1d71ea1dec87c460d4586d671646c0
| 9,060
|
Squircle-CE
|
Apache License 2.0
|
gradlePlugin/src/test/java/io/hkhc/utils/test/MockExtensionContainer.kt
|
hkhc
| 242,200,840
| false
|
{"Gradle Kotlin DSL": 14, "Java Properties": 6, "Shell": 2, "Text": 1, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "Markdown": 2, "YAML": 14, "Kotlin": 219, "Java": 20, "XML": 36}
|
/*
* Copyright (c) 2021. Herman Cheung
*
* 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 io.hkhc.utils.test
import org.gradle.api.Action
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.api.plugins.ExtensionsSchema
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.reflect.TypeOf
class MockExtensionContainer : ExtensionContainer {
var mockExtensions: Map<Class<out Any>, Any> = mutableMapOf()
override fun <T : Any?> add(publicType: Class<T>, name: String, extension: T) {
TODO("Not yet implemented")
}
override fun <T : Any?> add(publicType: TypeOf<T>, name: String, extension: T) {
TODO("Not yet implemented")
}
override fun add(name: String, extension: Any) {
TODO("Not yet implemented")
}
override fun <T : Any?> create(
publicType: Class<T>,
name: String,
instanceType: Class<out T>,
vararg constructionArguments: Any?
): T {
TODO("Not yet implemented")
}
override fun <T : Any?> create(
publicType: TypeOf<T>,
name: String,
instanceType: Class<out T>,
vararg constructionArguments: Any?
): T {
TODO("Not yet implemented")
}
override fun <T : Any?> create(name: String, type: Class<T>, vararg constructionArguments: Any?): T {
TODO("Not yet implemented")
}
override fun getExtensionsSchema(): ExtensionsSchema {
TODO("Not yet implemented")
}
override fun <T : Any?> getByType(type: Class<T>): T {
TODO("Not yet implemented")
}
override fun <T : Any?> getByType(type: TypeOf<T>): T {
TODO("Not yet implemented")
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any?> findByType(type: Class<T>): T? {
return mockExtensions[type] as T?
}
override fun <T : Any?> findByType(type: TypeOf<T>): T? {
TODO("Not yet implemented")
}
override fun getByName(name: String): Any {
TODO("Not yet implemented")
}
override fun findByName(name: String): Any? {
TODO("Not yet implemented")
}
override fun <T : Any?> configure(type: Class<T>, action: Action<in T>) {
TODO("Not yet implemented")
}
override fun <T : Any?> configure(type: TypeOf<T>, action: Action<in T>) {
TODO("Not yet implemented")
}
override fun <T : Any?> configure(name: String, action: Action<in T>) {
TODO("Not yet implemented")
}
override fun getExtraProperties(): ExtraPropertiesExtension {
TODO("Not yet implemented")
}
}
| 1
| null |
1
| 1
|
ffa517f9eec0e240e11d057afc53f0d0cb026de8
| 3,124
|
jarbird
|
Apache License 2.0
|
vgscheckout/src/test/java/com/verygoodsecurity/vgscheckout/card/filter/brand/DinnersClubTest.kt
|
verygoodsecurity
| 371,054,567
| false
| null |
package com.verygoodsecurity.vgscheckout.card.filter.brand
import com.verygoodsecurity.vgscheckout.collect.view.card.CardType
import com.verygoodsecurity.vgscheckout.collect.view.card.filter.CardBrandFilter
import com.verygoodsecurity.vgscheckout.collect.view.card.filter.VGSCardFilter
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class DinnersClubTest {
private lateinit var filter: VGSCardFilter
@Before
fun setupFilter() {
filter = CardBrandFilter()
}
@Test
fun test_1() {
val brand = filter.detect("305")
Assert.assertEquals(brand.name, CardType.DINCLUB.name)
}
@Test
fun test_2() {
val brand = filter.detect("3056")
Assert.assertEquals(brand.name, CardType.DINCLUB.name)
}
@Test
fun test_3() {
val brand = filter.detect("38")
Assert.assertEquals(brand.name, CardType.DINCLUB.name)
}
@Test
fun test_4() {
val brand = filter.detect("36")
Assert.assertEquals(brand.name, CardType.DINCLUB.name)
}
@Test
fun test_5() {
val brand = filter.detect("367")
Assert.assertEquals(brand.name, CardType.DINCLUB.name)
}
}
| 5
|
Kotlin
|
2
| 2
|
49fdede7a225435b37837f5396dcfea06217e275
| 1,208
|
vgs-checkout-android
|
MIT License
|
2405.Optimal Partition of String.kt
|
sarvex
| 842,260,390
| false
|
{"Kotlin": 1775678, "PowerShell": 418}
|
internal class Solution {
fun partitionString(s: String): Int {
val ss: Set<Char> = HashSet()
var ans = 1
for (c in s.toCharArray()) {
if (ss.contains(c)) {
++ans
ss.clear()
}
ss.add(c)
}
return ans
}
}
| 0
|
Kotlin
|
0
| 0
|
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
| 261
|
kotlin-leetcode
|
MIT License
|
servomatic/src/main/kotlin/crackers/kobots/app/DeputyJason.kt
|
EAGrahamJr
| 564,081,499
| false
|
{"Kotlin": 59050, "Shell": 3093}
|
/*
* Copyright 2022-2023 by <NAME>, Jr.
*
* 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 crackers.kobots.app
import crackers.kobots.parts.app.KobotSleep
import org.json.JSONObject
fun doArmThing(payload: JSONObject) {
if (payload.optString("sequence") == "ReturnPickup" && !payload.optBoolean("started")) {
logger.info("Drops done")
servoRequest(swirlyHome)
}
}
fun doAlertThing(payload: JSONObject) {
if (payload.optString("sequence") == "proxAlert") {
if (payload.optBoolean("started")) {
logger.info("Alerting")
SuzerainOfServos.stop()
KobotSleep.millis(50)
servoRequest(wavyUp)
} else {
logger.info("Not alerting")
servoRequest(wavyDown)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
57fd5d8d52c1bff9717b31772938efdc5226f589
| 1,305
|
kobots
|
Apache License 2.0
|
LogisticManager/src/main/kotlin/shopassistant/MainWindow.kt
|
ostis-apps
| 209,274,423
| false
|
{"C++": 190974, "Python": 158695, "JavaScript": 121504, "Kotlin": 28151, "CSS": 16444, "CMake": 15212, "Shell": 13239, "HTML": 5019, "Dockerfile": 1567}
|
package shopassistant
import engine.ScRepository
import org.ostis.api.context.UncheckedScContext
import org.ostis.scmemory.model.element.ScElement
import org.ostis.scmemory.model.element.edge.ScEdge
import org.ostis.scmemory.model.element.node.ScNode
import org.ostis.scmemory.model.event.OnAddIngoingEdgeEvent
import org.ostis.scmemory.model.event.OnAddOutgoingEdgeEvent
import org.ostis.scmemory.websocketmemory.memory.SyncOstisScMemory
import java.awt.EventQueue
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.lang.RuntimeException
import java.net.URI
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JOptionPane
fun main(){
EventQueue.invokeLater(::createAndShowGUI)
}
private fun createAndShowGUI() {
val frame = MainWindow()
frame.isVisible = true
}
private class MainWindow : JFrame(){
private val information = JLabel("");
private val scMemory = SyncOstisScMemory(URI("ws://localhost:8090/ws_json"));
init {
scMemory.open();
val scContext = UncheckedScContext(scMemory);
val execNode = scContext.findKeynode("executionStarted").get()?:throw RuntimeException("Init db first")
scMemory.subscribeOnEvent(execNode, OnOutgoingActionEdgeEvent())
title = "Shop assistant";
createUI()
}
private fun createUI() {
information.text = "The propose of this program is to handle events from sales manager about trucks using sc-machine"
add(information)
defaultCloseOperation = EXIT_ON_CLOSE
setSize(600, 100)
setLocationRelativeTo(null)
addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent) {
scMemory.close();
e.window.dispose()
}
})
}
private inner class OnOutgoingActionEdgeEvent: OnAddOutgoingEdgeEvent{
override fun onEvent(mainElement: ScElement?, edge: ScEdge?, edgeTarget: ScElement?) {
val newScMemory = SyncOstisScMemory(URI("ws://localhost:8090/ws_json"))
newScMemory.open();
val stops = ScRepository(newScMemory).getFreightOrderStops(edgeTarget as ScNode)
JOptionPane.showMessageDialog(this@MainWindow, "New truck arrived: $stops");
}
}
}
| 46
|
C++
|
128
| 2
|
dade10e5ffdb02a7cd7dab3ebeb83496ac43d5ae
| 2,314
|
ostis-geography
|
MIT License
|
sample/src/main/java/tech/thdev/androidrecyclerview/network/GitHubInterface.kt
|
taehwandev
| 71,049,057
| false
| null |
package tech.thdev.androidrecyclerview.network
import io.reactivex.rxjava3.core.Flowable
import retrofit2.http.GET
import retrofit2.http.Query
import tech.thdev.androidrecyclerview.data.GitHubUserSearchResponse
/**
* Created by Tae-hwan on 08/11/2016.
*/
interface GitHubInterface {
// https://api.github.com/search/users?q=tom+repos:%3E42&page=3&per_page=50
@GET("/search/users?")
fun searchUser(
@Query(value = "q", encoded = true) userKeyword: String,
@Query("page") page: Int,
@Query("per_page") perPage: Int
): Flowable<GitHubUserSearchResponse>
}
| 1
| null |
4
| 9
|
74b70f90f8d7b3a9bf457416166045d2f5d18a78
| 598
|
AndroidRecyclerView
|
Apache License 2.0
|
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/pragma/interactors/GetTableInfoInteractorTest.kt
|
infinum
| 17,116,181
| false
| null |
package com.infinum.dbinspector.domain.pragma.interactors
import com.infinum.dbinspector.data.Sources
import com.infinum.dbinspector.domain.Interactors
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("GetTableInfoInteractor tests")
internal class GetTableInfoInteractorTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
single { mockk<Sources.Local.Pragma>() }
factory<Interactors.GetTableInfo> { GetTableInfoInteractor(get()) }
}
)
@Test
fun `Invoking interactor invokes source getTableInfo`() {
val interactor: Interactors.GetTableInfo = get()
val source: Sources.Local.Pragma = get()
coEvery { source.getTableInfo(any()) } returns mockk()
launch {
interactor.invoke(any())
}
coVerify(exactly = 1) { source.getTableInfo(any()) }
}
}
| 0
|
Kotlin
|
88
| 902
|
8d2d695ba35e7b0682e2dc235f5a852bf0fa4db3
| 1,162
|
android_dbinspector
|
Apache License 2.0
|
compiler/tests-spec/testData/diagnostics/linked/expressions/when-expression/p-6/neg/7.2.fir.kt
|
JetBrains
| 3,432,266
| false
| null |
// SKIP_TXT
// TESTCASE NUMBER: 1
fun case_1(value_1: Int): String = when {
<!ELSE_MISPLACED_IN_WHEN!>else<!> -> ""
value_1 == 1 -> ""
}
// TESTCASE NUMBER: 2
fun case_2(value_1: Int): String = when {
value_1 == 1 -> ""
<!ELSE_MISPLACED_IN_WHEN!>else<!> -> ""
value_1 == 2 -> ""
}
// TESTCASE NUMBER: 3
fun case_3(): String {
when {
<!ELSE_MISPLACED_IN_WHEN!>else<!> -> return ""
else -> return ""
}
return ""
}
| 154
| null |
5563
| 44,965
|
e6633d3d9214402fcf3585ae8c24213a4761cc8b
| 465
|
kotlin
|
Apache License 2.0
|
kotlin/src/test/kotlin/be/kuleuven/speculaas/SpeculaasTests.kt
|
KULeuven-Diepenbeek
| 226,268,892
| false
|
{"HTML": 6378, "JavaScript": 5252, "CSS": 3780, "Java": 1805, "Kotlin": 1461}
|
package be.kuleuven.speculaas
import org.junit.jupiter.api.Test
import kotlin.test.assertTrue
class SpeculaasTests {
@Test
fun maakNieuweSpeculaasAan_standaardZonderBoter() {
val speculaas = Speculaas()
assertTrue { speculaas.boter == 0 }
}
}
| 0
|
HTML
|
3
| 0
|
db58d44858c3065a786892e3ae5086499e414449
| 273
|
ses-tdd-exercise-1-template
|
MIT License
|
login/src/main/java/com/fuusy/login/repo/LoginRepo.kt
|
125L
| 366,884,930
| true
|
{"Kotlin": 141840, "Java": 4801}
|
package com.fuusy.login.repo
import com.fuusy.common.base.BaseRepository
import com.fuusy.common.network.RetrofitManager
import com.fuusy.common.network.net.StateLiveData
import com.fuusy.service.repo.LoginResp
class LoginRepo : BaseRepository() {
private val service = RetrofitManager.initRetrofit().getService(LoginApi::class.java)
suspend fun login(userName: String, password: String, stateLiveData: StateLiveData<LoginResp>) {
executeResp({ service.login(userName, password) }, stateLiveData)
}
suspend fun register(
userName: String,
password: String,
rePassword: String,
stateLiveData: StateLiveData<LoginResp>
) {
executeResp({ service.register(userName, password, rePassword) }, stateLiveData)
}
}
| 0
| null |
0
| 0
|
5ad4727433c87b2531e0e82d86b9957be639907f
| 784
|
wanandroid_jetpack_kt
|
Apache License 2.0
|
database/database-symbol-processor/src/test/kotlin/ru/tinkoff/kora/database/symbol/processor/jdbc/JdbcParametersTest.kt
|
kora-projects
| 743,624,836
| false
| null |
package ru.tinkoff.kora.database.symbol.processor.jdbc
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.mockito.kotlin.verify
import ru.tinkoff.kora.common.Tag
import ru.tinkoff.kora.database.jdbc.`$JdbcDatabaseConfig_ConfigValueExtractor`.JdbcDatabaseConfig_Impl
import ru.tinkoff.kora.database.jdbc.mapper.parameter.JdbcParameterColumnMapper
import ru.tinkoff.kora.telemetry.common.`$TelemetryConfig_ConfigValueExtractor`
import ru.tinkoff.kora.telemetry.common.`$TelemetryConfig_LogConfig_ConfigValueExtractor`
import ru.tinkoff.kora.telemetry.common.`$TelemetryConfig_MetricsConfig_ConfigValueExtractor`
import ru.tinkoff.kora.telemetry.common.`$TelemetryConfig_TracingConfig_ConfigValueExtractor`
import java.time.Duration
import java.util.*
import kotlin.reflect.full.findAnnotations
import kotlin.reflect.jvm.jvmErasure
class JdbcParametersTest : AbstractJdbcRepositoryTest() {
@Test
fun testConnectionParameter() {
val repository = compile(
listOf<Any>(), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(test) VALUES ('test')")
fun test(connection: Connection)
}
""".trimIndent()
)
repository.invoke<Any>("test", executor.mockConnection)
verify(executor.preparedStatement).execute()
verify(executor.preparedStatement).updateCount
}
@Test
fun testAbstractClassRepository() {
val config = JdbcDatabaseConfig_Impl(
"1",
"2",
"3",
"testPool",
null,
Duration.ofMillis(1000L),
Duration.ofMillis(1000L),
Duration.ofMillis(1000L),
Duration.ofMillis(1000L),
Duration.ofMillis(1000L),
1,
0,
Duration.ofMillis(1000L),
false,
Properties(),
`$TelemetryConfig_ConfigValueExtractor`.TelemetryConfig_Impl(
`$TelemetryConfig_LogConfig_ConfigValueExtractor`.LogConfig_Impl(true),
`$TelemetryConfig_TracingConfig_ConfigValueExtractor`.TracingConfig_Impl(true),
`$TelemetryConfig_MetricsConfig_ConfigValueExtractor`.MetricsConfig_Impl(null, null)
)
)
val repository = compileForArgs(
arrayOf(config, executor),
"""
@Repository
abstract class TestRepository(val config: JdbcDatabaseConfig) : JdbcRepository {
@Query("INSERT INTO test(test) VALUES ('test')")
abstract fun test(connection: Connection)
}
""".trimIndent()
)
repository.invoke<Any>("test", executor.mockConnection)
verify(executor.preparedStatement).execute()
verify(executor.preparedStatement).updateCount
}
@Test
fun testNativeParameter() {
val repository = compile(
listOf<Any>(), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(test) VALUES (:value)")
fun test(value: Int)
}
""".trimIndent()
)
repository.invoke<Any>("test", 42)
verify(executor.preparedStatement).setInt(1, 42)
verify(executor.preparedStatement).updateCount
}
@Test
fun testParametersWithSimilarNames() {
val repository = compile(
listOf<Any>(), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(value1, value2) VALUES (:value, :valueTest)")
fun test(value: String?, valueTest: Int)
}
""".trimIndent()
)
repository.invoke<Any>("test", "test", 42)
verify(executor.mockConnection).prepareStatement("INSERT INTO test(value1, value2) VALUES (?, ?)")
verify(executor.preparedStatement).setString(1, "test")
verify(executor.preparedStatement).setInt(2, 42)
}
@Test
fun testEntityFieldMapping() {
val repository = compile(
listOf<Any>(), """
class StringToJsonbParameterMapper: JdbcParameterColumnMapper<String?> {
override fun set(stmt: PreparedStatement, index: Int, value: String?) {
stmt.setObject(index, mapOf("test" to value))
}
}
""".trimIndent(), """
public data class SomeEntity(val id: Long, @Mapping(StringToJsonbParameterMapper::class) val value: String)
""".trimIndent(), """
@Repository
interface TestRepository: JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:entity.id, :entity.value)")
fun test(entity: SomeEntity)
}
""".trimIndent()
)
repository.invoke<Any>("test", new("SomeEntity", 42L, "test-value"))
verify(executor.preparedStatement).setLong(1, 42L)
verify(executor.preparedStatement).setObject(2, mapOf("test" to "test-value"))
}
@Test
fun testNativeParameterWithMapping() {
val repository = compile(
listOf<Any>(), """
class StringToJsonbParameterMapper: JdbcParameterColumnMapper<String?> {
override fun set(stmt: PreparedStatement, index: Int, value: String?) {
stmt.setObject(index, mapOf("test" to value))
}
}
""".trimIndent(), """
@Repository
interface TestRepository: JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:id, :value)")
fun test(id: Long, @Mapping(StringToJsonbParameterMapper::class) value: String);
}
""".trimIndent()
)
repository.invoke<Any>("test", 42L, "test-value")
verify(executor.preparedStatement).setLong(1, 42L)
verify(executor.preparedStatement).setObject(2, mapOf("test" to "test-value"))
}
@Test
fun testUnknownTypeParameter() {
val mapper = Mockito.mock(JdbcParameterColumnMapper::class.java)
val repository = compile(
listOf(mapper), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:id, :value)")
fun test(id: Long, value: UnknownType)
}
""".trimIndent(), """
class UnknownType {}
""".trimIndent()
)
repository.invoke<Any>("test", 42L, new("UnknownType"))
verify(executor.preparedStatement).setLong(1, 42L)
verify(mapper).set(ArgumentMatchers.same(executor.preparedStatement), ArgumentMatchers.eq(2), ArgumentMatchers.any())
}
@Test
fun testUnknownTypeEntityField() {
val mapper = Mockito.mock(JdbcParameterColumnMapper::class.java)
val repository = compile(
listOf(mapper), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:id, :value0.f)")
fun test(id: Long, value0: TestEntity)
}
""".trimIndent(), """
class UnknownType {}
""".trimIndent(), """
data class TestEntity (val f: UnknownType)
""".trimIndent()
)
repository.invoke<Any>("test", 42L, new("TestEntity", new("UnknownType")))
verify(executor.preparedStatement).setLong(1, 42L)
verify(mapper).set(ArgumentMatchers.same(executor.preparedStatement), ArgumentMatchers.eq(2), ArgumentMatchers.any())
}
@Test
fun testNativeParameterNonFinalMapper() {
val repository = compile(
listOf(newGenerated("TestMapper")), """
open class TestMapper : JdbcParameterColumnMapper<String> {
override fun set(stmt: PreparedStatement, index: Int, value0: String?) {
stmt.setObject(index, mapOf("test" to value0))
}
}
""".trimIndent(), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:id, :value0)")
fun test(id: Long, @Mapping(TestMapper::class) value0: String);
}
""".trimIndent()
)
repository.invoke<Any>("test", 42L, "test-value")
Mockito.verify(executor.preparedStatement).setLong(1, 42L)
Mockito.verify(executor.preparedStatement).setObject(2, mapOf("test" to "test-value"))
}
@Test
fun testMultipleParametersWithSameMapper() {
val repository = compile(
listOf(newGenerated("TestMapper")), """
open class TestMapper : JdbcParameterColumnMapper<String> {
override fun set(stmt: PreparedStatement, index: Int, value0: String?) {
stmt.setObject(index, mapOf("test" to value0))
}
}
""".trimIndent(), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:id, :value0)")
fun test1(id: Long, @Mapping(TestMapper::class) value0: String);
@Query("INSERT INTO test(id, value) VALUES (:id, :value0)")
fun test(id: Long, @Mapping(TestMapper::class) value0: String);
}
""".trimIndent()
)
}
@Test
fun testMultipleParameterFieldsWithSameMapper() {
val repository = compile(
listOf(newGenerated("TestMapper")), """
open class TestMapper : JdbcParameterColumnMapper<TestRecord> {
override fun set(stmt: PreparedStatement, index: Int, value0: TestRecord?) {
stmt.setObject(index, mapOf("test" to value0.toString()))
}
}
""".trimIndent(), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:id, :value0.f1)")
fun test1(id: Long, value0: TestRecord);
@Query("INSERT INTO test(id, value) VALUES (:id, :value0.f1)")
fun test2(id: Long, value0: TestRecord);
@Query("INSERT INTO test(id, value1, value2) VALUES (:id, :value1.f1, :value2.f1)")
fun test2(id: Long, value1: TestRecord, value2: TestRecord);
}
""".trimIndent(), """
data class TestRecord(@Mapping(TestMapper::class) val f1: TestRecord, @Mapping(TestMapper::class) val f2: TestRecord){}
""".trimIndent()
)
}
@Test
fun testTagOnParameter() {
val mapper = Mockito.mock(JdbcParameterColumnMapper::class.java) as JdbcParameterColumnMapper<Int>
val repository = compile(
listOf(mapper), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(test) VALUES (:value)")
fun test(@Tag(TestRepository::class) value: Int)
}
""".trimIndent()
)
repository.invoke<Any>("test", 42)
verify(mapper).set(ArgumentMatchers.same(executor.preparedStatement), ArgumentMatchers.eq(1), ArgumentMatchers.eq(42))
val mapperConstructorParameter = repository.objectClass.constructors.first().parameters[1]
Assertions.assertThat(mapperConstructorParameter.type.jvmErasure).isEqualTo(JdbcParameterColumnMapper::class)
val tag = mapperConstructorParameter.findAnnotations(Tag::class).first()
Assertions.assertThat(tag).isNotNull()
Assertions.assertThat(tag.value.map { it.java }).isEqualTo(listOf(compileResult.loadClass("TestRepository")))
}
@Test
fun testTagOnDataClassParameter() {
val mapper = Mockito.mock(JdbcParameterColumnMapper::class.java) as JdbcParameterColumnMapper<Int>
val repository = compile(
listOf(mapper), """
@Repository
interface TestRepository : JdbcRepository {
@Query("INSERT INTO test(test) VALUES (:value)")
fun test(@Tag(TestRepository::class) value: TestEntity)
}
""".trimIndent(), """
data class TestEntity(val value: String)
""".trimIndent()
)
val mapperConstructorParameter = repository.objectClass.constructors.first().parameters[1]
Assertions.assertThat(mapperConstructorParameter.type.jvmErasure).isEqualTo(JdbcParameterColumnMapper::class)
val tag = mapperConstructorParameter.findAnnotations(Tag::class).first()
Assertions.assertThat(tag).isNotNull()
Assertions.assertThat(tag.value.map { it.java }).isEqualTo(listOf(compileResult.loadClass("TestRepository")))
}
@Test
fun testTagOnEntityField() {
val mapper = Mockito.mock(JdbcParameterColumnMapper::class.java) as JdbcParameterColumnMapper<String>
val repository = compile(
listOf(mapper), """
@Repository
interface TestRepository: JdbcRepository {
@Query("INSERT INTO test(id, value) VALUES (:entity.id, :entity.value)")
fun test(entity: TestEntity)
}
""".trimIndent(), """
data class TestEntity(val id: Long, @field:Tag(TestRepository::class) val value: String?)
""".trimIndent()
)
repository.invoke<Any>("test", new("TestEntity", 42, "test-value"))
verify(executor.preparedStatement).setLong(1, 42)
verify(mapper).set(ArgumentMatchers.same(executor.preparedStatement), ArgumentMatchers.eq(2), ArgumentMatchers.eq("test-value"))
val mapperConstructorParameter = repository.objectClass.constructors.first().parameters[1]
Assertions.assertThat(mapperConstructorParameter.type.jvmErasure).isEqualTo(JdbcParameterColumnMapper::class)
val tag = mapperConstructorParameter.findAnnotations(Tag::class).first()
Assertions.assertThat(tag).isNotNull()
Assertions.assertThat(tag.value.map { it.java }).isEqualTo(listOf(compileResult.loadClass("TestRepository")))
}
}
| 8
| null |
9
| 63
|
bb7d906d3af0ae6f8c68f87327f010b66110f34f
| 14,505
|
kora
|
Apache License 2.0
|
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/signing/SigningConfigVersions.kt
|
RivanParmar
| 526,653,590
| false
|
{"Java": 48334972, "Kotlin": 8897422, "HTML": 109232, "Lex": 13233, "ReScript": 3232, "Makefile": 2194}
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.signing
import java.io.Serializable
/** Class containing information about which signature versions are enabled or disabled. */
data class SigningConfigVersions(
val enableV1Signing: Boolean,
val enableV2Signing: Boolean,
val enableV3Signing: Boolean,
val enableV4Signing: Boolean,
) : Serializable {
companion object {
private const val serialVersionUID = 1L
// The lowest API with v2 signing support
const val MIN_V2_SDK = 24
// The lowest API with v3 signing support
const val MIN_V3_SDK = 28
// The lowest API with v4 signing support
const val MIN_V4_SDK = 30
}
}
| 1
|
Java
|
2
| 17
|
a497291d77bba1aa34271808088fe1e8aab5efe2
| 1,316
|
androlabs
|
Apache License 2.0
|
integration-test-r2dbc/src/test/kotlin/integration/r2dbc/SelectDistinctTest.kt
|
komapper
| 349,909,214
| false
| null |
package integration.r2dbc
import integration.department
import integration.employee
import org.junit.jupiter.api.extension.ExtendWith
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.r2dbc.R2dbcDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
@ExtendWith(Env::class)
class SelectDistinctTest(private val db: R2dbcDatabase) {
@Test
fun distinct() = inTransaction(db) {
val d = Meta.department
val e = Meta.employee
val query = QueryDsl.from(d).innerJoin(e) { d.departmentId eq e.departmentId }
val list = db.runQuery { query }
assertEquals(14, list.size)
val query2 = query.distinct()
val list2 = db.runQuery { query2 }
assertEquals(3, list2.size)
}
}
| 1
|
Kotlin
|
0
| 20
|
2a8827d7c410a5366d875578a635b02dc176e989
| 790
|
komapper
|
Apache License 2.0
|
aire/src/main/java/com/awxkee/aire/BlurPipelines.kt
|
awxkee
| 751,588,641
| false
|
{"C++": 13666290, "C": 178015, "Rust": 162047, "Kotlin": 155237, "Starlark": 7129, "CMake": 4163, "Shell": 1327}
|
/*
*
* * MIT License
* *
* * Copyright (c) 2024 Radzivon Bartoshyk
* * aire [https://github.com/awxkee/aire]
* *
* * Created by Radzivon Bartoshyk on 2/21/24, 6:13 PM
* *
* * Permission is hereby granted, free of charge, to any person obtaining a copy
* * of this software and associated documentation files (the "Software"), to deal
* * in the Software without restriction, including without limitation the rights
* * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* * copies of the Software, and to permit persons to whom the Software is
* * furnished to do so, subject to the following conditions:
* *
* * The above copyright notice and this permission notice shall be included in all
* * copies or substantial portions of the Software.
* *
* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* * SOFTWARE.
* *
*
*/
package com.awxkee.aire
import android.graphics.Bitmap
import androidx.annotation.IntRange
interface BlurPipelines {
fun bokehBlur(
bitmap: Bitmap,
@IntRange(from = 3) kernelSize: Int,
@IntRange(from = 3) sides: Int = 6,
edgeMode: EdgeMode,
scalar: Scalar,
mode: MorphOpMode,
): Bitmap
/**
* Default [gaussian blur](https://en.wikipedia.org/wiki/Gaussian_filter) in perceptual colorspace.
* O(R) complexity, very slow.
*
* @param kernelSize - size of blurring kernel, must be odd, kernel may be almost any reasonable size
* @param sigma - controlling kernel flattening level, default 0 ( will compute preferred automatically ), higher sigma creates more flat kernel
* @param edgeMode - edge controlling mode
*/
fun gaussianBlur(
bitmap: Bitmap,
kernelSize: Int,
sigma: Float = 0f,
edgeMode: EdgeMode,
gaussianPreciseLevel: GaussianPreciseLevel
): Bitmap
/**
* Default gaussian blur, [see more](https://en.wikipedia.org/wiki/Gaussian_filter).
* O(R) complexity, very slow.
*
* @param kernelSize - size of blurring kernel, must be odd, kernel may be almost any reasonable size
* @param sigma - controlling kernel flattening level, default (kernelSize / 6), higher sigma creates more flat kernel
* @param edgeMode - edge controlling mode
*/
fun linearGaussianBlur(
bitmap: Bitmap,
kernelSize: Int,
sigma: Float,
edgeMode: EdgeMode,
transferFunction: TransferFunction,
): Bitmap
fun bilateralBlur(
bitmap: Bitmap,
kernelSize: Int,
rangeSigma: Float,
spatialSigma: Float
): Bitmap
fun fastBilateralBlur(bitmap: Bitmap, kernelSize: Int, spatialSigma: Float, rangeSigma: Float): Bitmap
/***
* Performs motion blur on the image
*
* @param kernelSize - Kernel size, must be odd!
* @param angle - Angle in *degrees*
* @param borderMode - See [EdgeMode]
* @param borderScalar - See [Scalar]
*/
fun motionBlur(bitmap: Bitmap, kernelSize: Int, angle: Float, borderMode: EdgeMode, borderScalar: Scalar): Bitmap
/**
* Box blur averages all pixels to make a blur in perceptual colorspace.
* Produces box filter with very noticeable ringing.
* Convergence of this function is high so strong box effect appears very fast.
* Made in *perceptual* colorspace.
* O(1) complexity, medium speed.
*
* @param radius - radius of blurring kernel, almost any size is supported
*/
fun boxBlur(bitmap: Bitmap, radius: Int): Bitmap
/**
* @param angle - default is PI / 2
*/
fun zoomBlur(
bitmap: Bitmap,
kernelSize: Int,
sigma: Float,
centerX: Float = 0.5f,
centerY: Float = 0.5f,
strength: Float,
angle: Float
): Bitmap
fun poissonBlur(bitmap: Bitmap, kernelSize: Int): Bitmap
/**
* The fastest gaussian blur approximation.
* Made in *perceptual* colorspace.
* O(1) complexity, the fastest
*
* @param radius - blurring radius, radius ~[2, 254]
*/
fun stackBlur(bitmap: Bitmap, radius: Int): Bitmap
/**
* The fastest gaussian blur approximation in linear colorspace, this is much slower
* than perceptual approximation since converting into linear required significant computing,
* using f32 as storage and accumulator, however mathematically it is more correct.
* O(1) complexity, the fastest.
*
* @param radius - blurring radius, blurring radius almost unlimited since transformation is in f32
* @param transferFunction - transfer function in linear and its inverse
*/
fun linearStackBlur(bitmap: Bitmap, radius: Int, transferFunction: TransferFunction): Bitmap
/**
* Extended Binomial Filter of the Gaussian Blur 2 degree, extended box level, very fast compare to gaussian.
* The fastest gaussian blur approximation in linear colorspace, this is much slower
* than perceptual approximation since converting into linear required significant computing,
* using f32 as storage and accumulator, however mathematically it is more correct.
* Result close to stack blur, slightly better and slightly slower
* O(log(R)) complexity, fast.
*
* @param radius - blurring radius, blurring radius almost unlimited since transformation is in f32
* @param transferFunction - transfer function in linear and its inverse
* @param edgeMode - Edge handling mode, *Kernel clip* is not supported here!
*/
fun linearFastGaussian(
bitmap: Bitmap,
radius: Int,
transferFunction: TransferFunction,
edgeMode: EdgeMode
): Bitmap
/**
* Extended Binomial Filter of the Gaussian Blur 3 degree, extended box level, very fast compare to gaussian.
* The fastest gaussian blur approximation in linear colorspace, this is much slower
* than perceptual approximation since converting into linear required significant computing,
* using f32 as storage and accumulator, however mathematically it is more correct.
* Results much better than 2 level and stack blur, slower
* O(log(R)) complexity, fast.
*
* @param radius - blurring radius, blurring radius almost unlimited since transformation is in f32
* @param transferFunction - transfer function in linear and its inverse
* @param edgeMode - Edge handling mode, *Kernel clip* is not supported here!
*/
fun linearFastGaussianNext(
bitmap: Bitmap,
radius: Int,
transferFunction: TransferFunction,
edgeMode: EdgeMode,
): Bitmap
/**
* Extended Binomial Filter of the Gaussian Blur 2 degree, extended box level, very fast compare to gaussian.
* Results close to stack blur.
* Made in *perceptual* colorspace.
* O(log(R)) complexity, fast.
*
* @param radius - blurring radius, radius ~[1, 319]
* @param edgeMode - Edge handling mode, *Kernel clip* is not supported here!
*/
fun fastGaussian2Degree(bitmap: Bitmap, radius: Int, edgeMode: EdgeMode): Bitmap
/**
* Extended Binomial Filter of the Gaussian Blur 3 degree, very fast compare to gaussian.
* Results much better than 2 level and stack blur.
* Made in *perceptual* colorspace.
* O(log(R)) complexity, fast.
*
* @param radius - blurring radius, radius ~[1, 280]
* @param edgeMode - Edge handling mode, *Kernel clip* is not supported here!
*/
fun fastGaussian3Degree(bitmap: Bitmap, radius: Int, edgeMode: EdgeMode): Bitmap
/**
* Extended Binomial Filter of the Gaussian Blur 4 degree, very close level to gaussian,
* very fast compare to gaussian.
* Made in *perceptual* colorspace.
* @param radius - blurring radius
**/
fun fastGaussian4Degree(bitmap: Bitmap, radius: Int): Bitmap
fun medianBlur(
bitmap: Bitmap,
kernelSize: Int
): Bitmap
/**
* Box blur averages all pixels to make a blur.
* Produces box filter with very noticeable ringing.
* Convergence of this function is high so strong box effect appears very fast.
* Made in *linear* colorspace.
* O(1) complexity, slow.
*
* @param radius - radius of blurring kernel, almost any size is supported
* @param transferFunction - transfer function in linear and its inverse
*/
fun linearBoxBlur(bitmap: Bitmap, radius: Int, transferFunction: TransferFunction): Bitmap
/**
* Tent blur just make 2 passes of box blur as per [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem).
* Produces tent filter with noticeable ringing.
* Convergence of this function is high so strong box effect appears very fast.
* Made in *linear* colorspace.
* O(1) complexity, slow.
*
* @param radius - radius of blurring kernel, almost any size is supported
* @param transferFunction - transfer function in linear and its inverse
*/
fun linearTentBlur(bitmap: Bitmap, radius: Int, transferFunction: TransferFunction): Bitmap
/**
* Gaussian blur just make 3 passes of box blur as per [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem).
* Produces ideal gaussian as stated in [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem)
* Convergence of this function is high so strong box effect appears very fast.
* Made in *linear* colorspace.
* O(1) complexity, slow.
*
* @param radius - radius of blurring kernel, almost any size is supported
* @param transferFunction - transfer function in linear and its inverse
*/
fun linearGaussianBoxBlur(
bitmap: Bitmap,
radius: Int,
transferFunction: TransferFunction
): Bitmap
/**
* Tent blur just make 2 passes of box blur as per [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem).
* Produces tent filter with noticeable ringing.
* Convergence of this function is high so strong tent effect appears very fast
* Made in *perceptual* colorspace.
* O(1) complexity, medium speed.
*
* @param radius - radius of blurring kernel, almost any size is supported
*/
fun tentBlur(bitmap: Bitmap, radius: Int): Bitmap
/**
* Gaussian blur just make 3 passes of box blur as per [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem).
* Produces ideal gaussian as stated in [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem)
* Convergence of this function is high so strong gaussian effect appears very fast
* Made in *perceptual* colorspace.
* O(1) complexity, medium speed.
*
* @param radius - radius of blurring kernel, almost any size is supported
*/
fun gaussianBoxBlur(bitmap: Bitmap, radius: Int): Bitmap
fun anisotropicDiffusion(
bitmap: Bitmap,
@IntRange(from = 1) numOfSteps: Int = 20,
conduction: Float = 0.1f,
diffusion: Float = 0.01f
): Bitmap
}
| 0
|
C++
|
3
| 16
|
e5ca5c6a9a1cfb5c73b17c703a0452f0c9c88f75
| 11,572
|
aire
|
MIT License
|
idea/testData/refactoring/move/kotlin/moveTopLevelDeclarations/movePropertyToFile/after/b/specificImports.kt
|
JakeWharton
| 99,388,807
| true
| null |
package b
fun bar() {
test = ""
println(test)
}
| 0
|
Kotlin
|
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 57
|
kotlin
|
Apache License 2.0
|
compose/material/material/benchmark/src/androidTest/java/androidx/compose/material/benchmark/TextInColumnBenchmark.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.layout.benchmark
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.testutils.benchmark.benchmarkDrawPerf
import androidx.compose.testutils.benchmark.benchmarkFirstCompose
import androidx.compose.testutils.benchmark.benchmarkFirstDraw
import androidx.compose.testutils.benchmark.benchmarkFirstLayout
import androidx.compose.testutils.benchmark.benchmarkFirstMeasure
import androidx.compose.testutils.benchmark.benchmarkLayoutPerf
import androidx.compose.testutils.benchmark.toggleStateBenchmarkDraw
import androidx.compose.testutils.benchmark.toggleStateBenchmarkLayout
import androidx.compose.testutils.benchmark.toggleStateBenchmarkMeasure
import androidx.compose.testutils.benchmark.toggleStateBenchmarkRecompose
import androidx.test.filters.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
/** Benchmark that runs [RectsInFlowColumnTestCase]. */
@LargeTest
@RunWith(Parameterized::class)
class RectsInFlowColumnBenchmark(private val numberOfRectangles: Int) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun initParameters(): Array<Any> = arrayOf(10, 100)
}
@get:Rule val benchmarkRule = ComposeBenchmarkRule()
private val rectsInFlowColumnCaseFactory = { RectsInFlowColumnTestCase(numberOfRectangles) }
@Test
fun first_compose() {
benchmarkRule.benchmarkFirstCompose(rectsInFlowColumnCaseFactory)
}
@Test
fun first_measure() {
benchmarkRule.benchmarkFirstMeasure(rectsInFlowColumnCaseFactory)
}
@Test
fun first_layout() {
benchmarkRule.benchmarkFirstLayout(rectsInFlowColumnCaseFactory)
}
@Test
fun first_draw() {
benchmarkRule.benchmarkFirstDraw(rectsInFlowColumnCaseFactory)
}
@Test
fun toggleRectangleColor_recompose() {
benchmarkRule.toggleStateBenchmarkRecompose(rectsInFlowColumnCaseFactory)
}
@Test
fun toggleRectangleColor_measure() {
benchmarkRule.toggleStateBenchmarkMeasure(rectsInFlowColumnCaseFactory)
}
@Test
fun toggleRectangleColor_layout() {
benchmarkRule.toggleStateBenchmarkLayout(rectsInFlowColumnCaseFactory)
}
@Test
fun toggleRectangleColor_draw() {
benchmarkRule.toggleStateBenchmarkDraw(rectsInFlowColumnCaseFactory)
}
@Test
fun layout() {
benchmarkRule.benchmarkLayoutPerf(rectsInFlowColumnCaseFactory)
}
@Test
fun draw() {
benchmarkRule.benchmarkDrawPerf(rectsInFlowColumnCaseFactory)
}
}
| 29
| null |
937
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 3,268
|
androidx
|
Apache License 2.0
|
src/main/java/com/maddin/transportapi/caches/SearchCaches.kt
|
maddinkunze
| 672,936,637
| false
|
{"Kotlin": 178441}
|
package com.maddin.transportapi.caches
import com.maddin.transportapi.components.POI
import com.maddin.transportapi.components.Station
typealias SearchPOICache = SearchCache<POI>
open class SearchPOICacheImpl : SearchCacheImpl<POI>()
typealias SearchStationCache = SearchCache<Station>
open class SearchStationCacheImpl : SearchCacheImpl<Station>(), SearchStationCache
| 0
|
Kotlin
|
0
| 0
|
0a765f97f308e2daca1a8574a12978f55653cb46
| 372
|
transportapi
|
MIT License
|
game-server/src/main/kotlin/org/alter/game/sync/segment/PlayerUpdateBlockSegment.kt
|
AlterRSPS
| 421,831,790
| false
| null |
package gg.rsmod.game.sync.segment
import gg.rsmod.game.fs.def.NpcDef
import gg.rsmod.game.model.ChatMessage
import gg.rsmod.game.model.Tile
import gg.rsmod.game.model.appearance.Gender
import gg.rsmod.game.model.entity.Player
import gg.rsmod.game.model.item.Item
import gg.rsmod.game.sync.SynchronizationSegment
import gg.rsmod.game.sync.block.UpdateBlockType
import gg.rsmod.net.packet.*
/**
* @author Tom <<EMAIL>>
*/
class PlayerUpdateBlockSegment(val other: Player, private val newPlayer: Boolean) : SynchronizationSegment {
override fun encode(buf: GamePacketBuilder) {
var mask = other.blockBuffer.blockValue()
val blocks = other.world.playerUpdateBlocks
var forceFacePawn = false
var forceFaceTile = false
var forceFace: Tile? = null
if (newPlayer) {
mask = mask or blocks.updateBlocks[UpdateBlockType.APPEARANCE]!!.bit
when {
other.blockBuffer.faceDegrees != 0 -> {
mask = mask or blocks.updateBlocks[UpdateBlockType.FACE_TILE]!!.bit
forceFaceTile = true
}
other.blockBuffer.facePawnIndex != -1 -> {
mask = mask or blocks.updateBlocks[UpdateBlockType.FACE_PAWN]!!.bit
forceFacePawn = true
}
else -> {
mask = mask or blocks.updateBlocks[UpdateBlockType.FACE_TILE]!!.bit
forceFace = other.tile.step(other.lastFacingDirection)
}
}
}
val firstExtensionBit = blocks.updateBlockExcessMask8
val secondExtensionBit = blocks.updateBlockExcessMask16
if (mask and 0xFF.inv() != 0) {
mask = mask or firstExtensionBit
}
if (mask and 0xFFFF.inv() != 0) {
mask = mask or secondExtensionBit
}
buf.put(DataType.BYTE, mask)
if (mask and firstExtensionBit != 0) {
buf.put(DataType.BYTE, mask ushr 8)
}
if (mask and secondExtensionBit != 0) {
buf.put(DataType.BYTE, mask ushr 16)
}
blocks.updateBlockOrder.forEach { blockType ->
val force = when (blockType) {
UpdateBlockType.FACE_TILE -> forceFaceTile || forceFace != null
UpdateBlockType.FACE_PAWN -> forceFacePawn
UpdateBlockType.APPEARANCE -> newPlayer
else -> false
}
if (other.hasBlock(blockType) || force) {
write(buf, blockType, forceFace)
}
}
}
private fun write(buf: GamePacketBuilder, blockType: UpdateBlockType, forceFace: Tile?) {
val blocks = other.world.playerUpdateBlocks
when (blockType) {
UpdateBlockType.PUBLIC_CHAT -> {
val structure = blocks.updateBlocks[blockType]!!.values
val chatMessage = other.blockBuffer.publicChat
if (chatMessage.text.length >= 80) return
val compressed = ByteArray(256)
compressed[0] = chatMessage.text.length.toByte()
val compressedLength = other.world.huffman.compress(chatMessage.text, compressed, 1)
buf.put(structure[0].type, structure[0].order, structure[0].transformation,
(chatMessage.color.id shl 8) or chatMessage.effect.id
)
buf.put(structure[1].type, structure[1].order, structure[1].transformation, chatMessage.icon)
buf.put(structure[2].type, structure[2].order, structure[2].transformation, if (chatMessage.type == ChatMessage.ChatType.AUTOCHAT) 1 else 0)
buf.put(structure[3].type, structure[3].order, structure[3].transformation, chatMessage.text.length)
buf.putBytes(structure[4].transformation, compressed, 0, chatMessage.text.length)
//buf.putBytesReverse(structure[4].transformation, compressed, compressedLength)
}
UpdateBlockType.FORCE_CHAT -> {
// NOTE(Tom): do not need the structure since this value is always
// written as a string.
buf.putString(other.blockBuffer.forceChat)
}
UpdateBlockType.MOVEMENT -> {
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(
structure[0].type, structure[0].order, structure[0].transformation,
if (other.blockBuffer.teleport) 127 else if (other.steps?.runDirection != null) 2 else 1
)
}
UpdateBlockType.FACE_TILE -> {
val structure = blocks.updateBlocks[blockType]!!.values
if (forceFace != null) {
val srcX = other.tile.x * 64
val srcZ = other.tile.z * 64
val dstX = forceFace.x * 64
val dstZ = forceFace.z * 64
val degreesX = (srcX - dstX).toDouble()
val degreesZ = (srcZ - dstZ).toDouble()
buf.put(
structure[0].type,
structure[0].order,
structure[0].transformation,
(Math.atan2(degreesX, degreesZ) * 325.949).toInt() and 0x7ff
)
} else {
buf.put(
structure[0].type,
structure[0].order,
structure[0].transformation,
other.blockBuffer.faceDegrees
)
}
}
UpdateBlockType.APPEARANCE -> {
val appBuf = GamePacketBuilder()
appBuf.put(DataType.BYTE, other.appearance.gender.id)
appBuf.put(DataType.BYTE, other.skullIcon)
appBuf.put(DataType.BYTE, other.prayerIcon)
val transmog = other.getTransmogId() >= 0
if (!transmog) {
val translation = arrayOf(-1, -1, -1, -1, 2, -1, 3, 5, 0, 4, 6, 1)
val skippedSlots = BooleanArray(12)
for (i in 0 until 12) {
val item = other.equipment[i] ?: continue
val itemDef = (Item(item.id)).getDef(other.world.definitions)
val wearpos2 = itemDef.wearPos2
if (wearpos2 != -1) skippedSlots[wearpos2] = true
val wearpos3 = itemDef.wearPos3
if (wearpos3 != -1) skippedSlots[wearpos3] = true
}
for (i in 0 until 12) {
if (skippedSlots[i]) {
appBuf.put(DataType.BYTE, 0)
continue
}
val item = other.equipment[i]
if (item == null) {
if (translation[i] == -1) {
appBuf.put(DataType.BYTE, 0)
} else {
appBuf.put(DataType.SHORT, 0x100 + other.appearance.getLook(translation[i]))
}
} else {
appBuf.put(DataType.SHORT, 0x200 + item.id)
}
}
} else {
appBuf.put(DataType.SHORT, 0xFFFF)
appBuf.put(DataType.SHORT, other.getTransmogId())
}
appBuf.put(DataType.BYTE, 20)
for (i in 0 until 12) {
appBuf.put(DataType.BYTE, 0)
}
for (i in 0 until 5) {
val color = Math.max(0, other.appearance.colors[i])
appBuf.put(DataType.BYTE, color)
}
when {
transmog -> {
val def = other.world.definitions.get(NpcDef::class.java, other.getTransmogId())
val animations = arrayOf(
def.standAnim, def.walkAnim, def.walkAnim, def.rotateLeftAnim,
def.rotateRightAnim, def.rotateBackAnim, def.walkAnim
)
animations.forEach { anim ->
appBuf.put(DataType.SHORT, anim)
}
}
other.isAppearimation() -> {
other.anims.forEach { anim ->
appBuf.put(DataType.SHORT, anim)
}
other.setAppearimation(false)
}
else -> {
val animations = arrayOf(808, 823, 819, 820, 821, 822, 824)
val weapon = other.equipment[3] // Assume slot 3 is the weapon.
if (weapon != null) {
val def = weapon.getDef(other.world.definitions)
def.renderAnimations?.forEachIndexed { index, anim ->
var ani = anim
if (anim == 0) {
ani = animations[index]
}
animations[index] = ani
}
}
animations.forEach { anim ->
appBuf.put(DataType.SHORT, anim)
}
}
}
appBuf.putString(other.username)
appBuf.put(DataType.BYTE, other.combatLevel)
appBuf.put(DataType.SHORT, 0) // skillLevel
appBuf.put(DataType.BYTE, 0) // isHidden
appBuf.put(DataType.SHORT, 0)
appBuf.putString("")
appBuf.putString("")
appBuf.putString("")
appBuf.put(DataType.BYTE, other.appearance.gender.id)
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(
structure[0].type,
structure[0].order,
structure[0].transformation,
appBuf.byteBuf.readableBytes()
)
if (structure[1].order == DataOrder.REVERSED) {
val bytes = ByteArray(appBuf.readableBytes)
appBuf.byteBuf.readBytes(bytes)
buf.putBytes(structure[1].transformation, bytes.reversedArray())
} else
buf.putBytes(structure[1].transformation, appBuf.byteBuf)
}
UpdateBlockType.HITMARK -> {
val structure = blocks.updateBlocks[blockType]!!.values
val hitmarkCountStructure = structure[0]
val hitbarCountStructure = structure[1]
val hitbarPercentageStructure = structure[2]
val hitbarToPercentageStructure = structure[3]
val hits = other.blockBuffer.hits
val hitbars = hits.filter { it.hitbar != null }
buf.put(
hitmarkCountStructure.type,
hitmarkCountStructure.order,
hitmarkCountStructure.transformation,
hits.size
)
hits.forEach { hit ->
val hitmarks = Math.min(2, hit.hitmarks.size)
/*
* Inform the client of how many hitmarkers to decode.
*/
if (hitmarks == 0) {
buf.putSmart(32766)
} else if (hitmarks > 1) {
buf.putSmart(32767)
}
for (i in 0 until hitmarks) {
val hitmark = hit.hitmarks[i]
buf.putSmart(hitmark.type)
buf.putSmart(hitmark.damage)
}
buf.putSmart(hit.clientDelay)
}
buf.put(
hitbarCountStructure.type,
hitbarCountStructure.order,
hitbarCountStructure.transformation,
hitbars.size
)
hitbars.forEach { hit ->
val hitbar = hit.hitbar!!
buf.putSmart(hitbar.type)
buf.putSmart(hitbar.depleteSpeed)
if (hitbar.depleteSpeed != 32767) {
var percentage = hitbar.percentage
if (percentage == -1) {
val max = other.getMaxHp()
val curr = Math.min(max, other.getCurrentHp())
percentage =
if (max == 0) 0 else ((curr.toDouble() * hitbar.maxPercentage.toDouble() / max.toDouble())).toInt()
if (percentage == 0 && curr > 0) {
percentage = 1
}
}
buf.putSmart(hitbar.delay)
buf.put(
hitbarPercentageStructure.type,
hitbarPercentageStructure.order,
hitbarPercentageStructure.transformation,
percentage
)
if (hitbar.depleteSpeed > 0) {
buf.put(
hitbarToPercentageStructure.type,
hitbarToPercentageStructure.order,
hitbarToPercentageStructure.transformation,
0
)
}
}
}
}
UpdateBlockType.FACE_PAWN -> {
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(
structure[0].type,
structure[0].order,
structure[0].transformation,
other.blockBuffer.facePawnIndex
)
buf.put(
structure[1].type,
structure[1].order,
structure[1].transformation,
other.blockBuffer.facePawnIndex shr 16
)
}
UpdateBlockType.ANIMATION -> {
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(structure[0].type, structure[0].order, structure[0].transformation, other.blockBuffer.animation)
buf.put(
structure[1].type,
structure[1].order,
structure[1].transformation,
other.blockBuffer.animationDelay
)
}
UpdateBlockType.GFX -> {
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(DataType.BYTE, DataTransformation.SUBTRACT, 1) // gfx_array_how many to read one by one
buf.put(DataType.BYTE, DataTransformation.NEGATE, 0) // gfx_index from the array
buf.put(structure[0].type, structure[0].order, structure[0].transformation, other.blockBuffer.graphicId)
buf.put(structure[1].type, structure[1].order, structure[1].transformation,
(other.blockBuffer.graphicHeight shl 16) or other.blockBuffer.graphicDelay
)
}
UpdateBlockType.FORCE_MOVEMENT -> {
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(
structure[0].type,
structure[0].order,
structure[0].transformation,
other.blockBuffer.forceMovement.diffX1
)
buf.put(
structure[1].type,
structure[1].order,
structure[1].transformation,
other.blockBuffer.forceMovement.diffZ1
)
buf.put(
structure[2].type,
structure[2].order,
structure[2].transformation,
other.blockBuffer.forceMovement.diffX2
)
buf.put(
structure[3].type,
structure[3].order,
structure[3].transformation,
other.blockBuffer.forceMovement.diffZ2
)
buf.put(
structure[4].type,
structure[4].order,
structure[4].transformation,
other.blockBuffer.forceMovement.clientDuration1
)
buf.put(
structure[5].type,
structure[5].order,
structure[5].transformation,
other.blockBuffer.forceMovement.clientDuration2
)
buf.put(
structure[6].type,
structure[6].order,
structure[6].transformation,
other.blockBuffer.forceMovement.directionAngle
)
}
UpdateBlockType.APPLY_TINT -> {
val structure = blocks.updateBlocks[blockType]!!.values
buf.put(
structure[0].type,
structure[0].order,
structure[0].transformation,
other.blockBuffer.recolourStartCycle
) // recolourStartCycle
buf.put(
structure[1].type,
structure[1].order,
structure[1].transformation,
other.blockBuffer.recolourEndCycle
) // recolourEndCycle
buf.put(
structure[2].type,
structure[2].order,
structure[2].transformation,
other.blockBuffer.recolourHue
) // recolourHue
buf.put(
structure[3].type,
structure[3].order,
structure[3].transformation,
other.blockBuffer.recolourSaturation
) // recolourSaturation
buf.put(
structure[4].type,
structure[4].order,
structure[4].transformation,
other.blockBuffer.recolourLuminance
) // recolourLuminance
buf.put(
structure[5].type,
structure[5].order,
structure[5].transformation,
other.blockBuffer.recolourOpacity
) // recolourAmount
}
UpdateBlockType.TEMP_MOVEMENT -> {
val structure = blocks.updateBlocks[blockType]!!.values
//buf.put(structure[0].type, structure[0].order, structure[0].transformation, 1)
}
UpdateBlockType.NAME_CHANGE -> {
//val structure = blocks.updateBlocks[blockType]!!.values
//buf.put(structure[0].type, structure[0].order, structure[0].transformation, 0)
}
else -> throw RuntimeException("Unhandled update block type: $blockType")
}
}
}
| 8
| null |
33
| 23
|
9dbd62d67de547cfedc43b902797306c5db8fb55
| 19,701
|
Alter
|
Apache License 2.0
|
knapsack-solver/src/test/java/com/github/nieldw/knapsack/constraints/ItemWeightConstraintTest.kt
|
nieldw
| 121,665,123
| false
| null |
package com.github.nieldw.knapsack.constraints
import com.github.nieldw.knapsack.Item
import com.github.nieldw.knapsack.KnapsackProblem
import org.junit.jupiter.api.Test
import java.math.BigDecimal
import kotlin.test.assertFailsWith
class ItemWeightConstraintTest {
@Test
fun `should pass with weight below or equal to constraint`() {
val item = Item(1, BigDecimal.ONE, BigDecimal.ZERO)
ItemWeightConstraint(BigDecimal.ONE).check(KnapsackProblem(BigDecimal.ZERO, listOf(item)))
ItemWeightConstraint(BigDecimal.TEN).check(KnapsackProblem(BigDecimal.ZERO, listOf(item)))
}
@Test
fun `should fail with weight above constraint`() {
val item = Item(1, BigDecimal.TEN, BigDecimal.ZERO)
assertFailsWith<KnapsackProblemConstraintViolationException> {
ItemWeightConstraint(BigDecimal.ONE).check(KnapsackProblem(BigDecimal.ZERO, listOf(item)))
}
}
}
| 1
|
Kotlin
|
0
| 0
|
1ff195184f454349a5d198290e2011116a6fb569
| 926
|
knapsack-solver
|
MIT License
|
compose/mpp/demo/src/commonMain/kotlin/androidx/compose/mpp/demo/textfield/TextFields.kt
|
VexorMC
| 838,305,267
| false
|
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
|
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.mpp.demo.textfield
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.mpp.demo.Screen
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.Modifier
import androidx.compose.ui.unit.dp
val TextFields = Screen.Selection(
"TextFields",
Screen.Example("AlmostFullscreen") {
ClearFocusBox {
AlmostFullscreen()
}
},
Screen.Example("Keyboard Actions") {
ClearFocusBox {
KeyboardActionsExample()
}
},
Screen.Example("Password Textfield Example") {
ClearFocusBox {
PasswordTextfieldExample()
}
},
Screen.Example("Emoji") {
ClearFocusBox {
EmojiExample()
}
},
Screen.Example("FastDelete") {
ClearFocusBox {
FastDelete()
}
},
Screen.Example("OutlinedTextField") {
ClearFocusBox {
var text by remember { mutableStateOf("Some text") }
OutlinedTextField(
readOnly = true,
value = text,
onValueChange = { text = it },
label = { Text("OutlinedTextField Label") },
)
}
},
Screen.Example("BasicTextField") {
var text by remember { mutableStateOf("usage of BasicTextField") }
BasicTextField(text, { text = it })
},
Screen.Example("RTL and BiDi") {
ClearFocusBox { RtlAndBidiTextfieldExample() }
}
)
@Composable
private fun AlmostFullscreen() {
val textState = remember {
mutableStateOf(
buildString {
repeat(100) {
appendLine("Text line $it")
}
}
)
}
TextField(
textState.value, { textState.value = it },
Modifier.fillMaxSize().padding(vertical = 40.dp)
)
}
| 0
|
Kotlin
|
0
| 2
|
9730aa39ce1cafe408f28962a59b95b82c68587f
| 2,907
|
compose
|
Apache License 2.0
|
compose/mpp/demo/src/commonMain/kotlin/androidx/compose/mpp/demo/textfield/TextFields.kt
|
VexorMC
| 838,305,267
| false
|
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
|
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.mpp.demo.textfield
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.mpp.demo.Screen
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.Modifier
import androidx.compose.ui.unit.dp
val TextFields = Screen.Selection(
"TextFields",
Screen.Example("AlmostFullscreen") {
ClearFocusBox {
AlmostFullscreen()
}
},
Screen.Example("Keyboard Actions") {
ClearFocusBox {
KeyboardActionsExample()
}
},
Screen.Example("Password Textfield Example") {
ClearFocusBox {
PasswordTextfieldExample()
}
},
Screen.Example("Emoji") {
ClearFocusBox {
EmojiExample()
}
},
Screen.Example("FastDelete") {
ClearFocusBox {
FastDelete()
}
},
Screen.Example("OutlinedTextField") {
ClearFocusBox {
var text by remember { mutableStateOf("Some text") }
OutlinedTextField(
readOnly = true,
value = text,
onValueChange = { text = it },
label = { Text("OutlinedTextField Label") },
)
}
},
Screen.Example("BasicTextField") {
var text by remember { mutableStateOf("usage of BasicTextField") }
BasicTextField(text, { text = it })
},
Screen.Example("RTL and BiDi") {
ClearFocusBox { RtlAndBidiTextfieldExample() }
}
)
@Composable
private fun AlmostFullscreen() {
val textState = remember {
mutableStateOf(
buildString {
repeat(100) {
appendLine("Text line $it")
}
}
)
}
TextField(
textState.value, { textState.value = it },
Modifier.fillMaxSize().padding(vertical = 40.dp)
)
}
| 0
|
Kotlin
|
0
| 2
|
9730aa39ce1cafe408f28962a59b95b82c68587f
| 2,907
|
compose
|
Apache License 2.0
|
feather/src/commonMain/kotlin/compose/icons/feathericons/Umbrella.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.feathericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.FeatherIcons
public val FeatherIcons.Umbrella: ImageVector
get() {
if (_umbrella != null) {
return _umbrella!!
}
_umbrella = Builder(name = "Umbrella", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(23.0f, 12.0f)
arcToRelative(11.05f, 11.05f, 0.0f, false, false, -22.0f, 0.0f)
close()
moveTo(18.0f, 19.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, -6.0f, 0.0f)
verticalLineToRelative(-7.0f)
}
}
.build()
return _umbrella!!
}
private var _umbrella: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 1,529
|
compose-icons
|
MIT License
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/vision/AutoWebcamTest.kt
|
Robotroopers2021
| 418,272,432
| false
|
{"Kotlin": 277670, "Java": 266601}
|
package org.firstinspires.ftc.teamcode.vision
import com.qualcomm.robotcore.hardware.HardwareMap
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName
import org.firstinspires.ftc.teamcode.testing.PipelineTesting
import org.openftc.easyopencv.OpenCvCamera
import org.openftc.easyopencv.OpenCvCameraFactory
import org.openftc.easyopencv.OpenCvCameraRotation
import org.openftc.easyopencv.OpenCvPipeline
class AutoWebcamTest : Subsystem{
private lateinit var webcam : OpenCvCamera
lateinit var pipeline : PipelineTesting
var armpos : Int = 0
fun init(hardwareMap: HardwareMap) {
val cameraMonitorViewId = hardwareMap.appContext.resources.getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.packageName)
val webcamName = hardwareMap[WebcamName::class.java, "Webcam"]
webcam = OpenCvCameraFactory.getInstance().createWebcam(webcamName, cameraMonitorViewId)
pipeline = PipelineTesting()
webcam.setPipeline(pipeline)
webcam.openCameraDeviceAsync(object : OpenCvCamera.AsyncCameraOpenListener {
override fun onOpened() {
webcam.startStreaming(320, 240, OpenCvCameraRotation.UPRIGHT)
}
override fun onError(errorCode: Int) {
}
})
}
override fun sendDashboardPacket(debugging: Boolean) {
}
fun takePicture() {
armpos = (pipeline.storedx/10)
}
fun stopWebcam() {
webcam.pauseViewport()
}
override fun update() {
}
override fun reset() {
webcam.stopStreaming()
}
}
| 0
|
Kotlin
|
0
| 1
|
22e3e7de73a9e451b1edd9eab4c1c8fe04789175
| 1,611
|
FreightFrenzy
|
BSD 3-Clause Clear License
|
Source/app/src/main/java/com/victorx64/officerpersonalarea/LoginActivity.kt
|
Gyallahorn
| 197,547,000
| false
| null |
package com.victorx64.officerpersonalarea
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.analytics.Analytics;
import com.microsoft.appcenter.crashes.Crashes;
import kotlinx.android.synthetic.main.login_web_view.*
// @todo #13 make login activity, get visual part from figma, add phon firebase authentication
class LoginActivity : AppCompatActivity() {
var myWebView : WebView? = null
override fun onCreate(savedInstanceState: Bundle?) {
AppCenter.start(
application, "ff1e2117-dff5-4134-9e9b-460e2f86b717",
Analytics::class.java, Crashes::class.java
)
super.onCreate(savedInstanceState)
setContentView(R.layout.login_web_view)
myWebView = findViewById(R.id.WebView)
WebView.getSettings().setLoadWithOverviewMode(true);
WebView.getSettings().setUseWideViewPort(true);
WebView.settings.javaScriptEnabled = true
WebView.loadUrl("https://officer-persomal-area.web.app/")
// login_button.setOnClickListener{
// val intent = Intent(this, MainActivity::class.java)
// startActivity(intent)
// }
}
}
| 0
|
Kotlin
|
2
| 0
|
4f161373cca3ad60c6bd77e14bdef9a974116070
| 1,270
|
officer-personal-area
|
MIT License
|
kotlinx-coroutines-core/jvm/test/examples/example-delay-duration-03.kt
|
hltj
| 151,721,407
| false
| null |
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from Delay.kt by Knit tool. Do not edit.
package kotlinx.coroutines.examples.exampleDelay03
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
flow {
repeat(10) {
emit(it)
delay(110)
}
}.sample(200)
.toList().joinToString().let { println(it) } }
| 295
| null |
99
| 255
|
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
| 462
|
kotlinx.coroutines-cn
|
Apache License 2.0
|
ui/src/main/kotlin/com/aptopayments/sdk/features/loadfunds/paymentsources/addcard/FieldState.kt
|
AptoPayments
| 197,800,853
| false
| null |
package com.aptopayments.sdk.features.loadfunds.paymentsources.addcard
internal enum class FieldState {
TYPING, ERROR, CORRECT
}
| 0
|
Kotlin
|
0
| 0
|
24680d971d0ae6b2213caf5b1371a29145cadf31
| 134
|
apto-ui-sdk-android
|
MIT License
|
testing/spring/src/testFixtures/kotlin/org/orkg/testing/spring/restdocs/RestDocumentationBaseTest.kt
|
TIBHannover
| 197,416,205
| false
| null |
package org.orkg.testing.spring.restdocs
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.extension.ExtendWith
import org.orkg.testing.annotations.Neo4jContainerIntegrationTest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.restdocs.RestDocumentationContextProvider
import org.springframework.restdocs.RestDocumentationExtension
import org.springframework.restdocs.headers.HeaderDocumentation.headerWithName
import org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders
import org.springframework.restdocs.headers.ResponseHeadersSnippet
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders
import org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest
import org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse
import org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint
import org.springframework.restdocs.payload.FieldDescriptor
import org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath
import org.springframework.restdocs.request.ParameterDescriptor
import org.springframework.restdocs.request.RequestDocumentation.parameterWithName
import org.springframework.restdocs.request.RequestDocumentation.requestParameters
import org.springframework.restdocs.request.RequestParametersSnippet
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder
import org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup
import org.springframework.web.context.WebApplicationContext
/**
* Base class for REST API documentation test.
*
* It initializes MockMVc with a stand-alone set-up for testing a controller
* in isolation. Additionally, spring-restdoc will be pre-configured.
*/
@Neo4jContainerIntegrationTest
@ExtendWith(RestDocumentationExtension::class)
@Deprecated("To be replaced with RestDocsTest")
abstract class RestDocumentationBaseTest {
protected lateinit var mockMvc: MockMvc
@Autowired
protected lateinit var objectMapper: ObjectMapper
protected val snippet = "{class-name}-{method-name}"
@BeforeEach
fun setup(
webApplicationContext: WebApplicationContext,
restDocumentation: RestDocumentationContextProvider
) {
mockMvc = webAppContextSetup(webApplicationContext)
.apply<DefaultMockMvcBuilder>(
documentationConfiguration(restDocumentation)
.operationPreprocessors()
.withRequestDefaults(prettyPrint())
.withResponseDefaults(prettyPrint())
)
.alwaysDo<DefaultMockMvcBuilder>(
document(
"{class-name}-{method-name}",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint())
)
)
.build()
}
protected fun getRequestTo(urlTemplate: String): MockHttpServletRequestBuilder =
get(urlTemplate)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.characterEncoding("utf-8")
protected fun getFileRequestTo(urlTemplate: String): MockHttpServletRequestBuilder =
get(urlTemplate)
.accept(MediaType.parseMediaType("application/n-triples"))
.characterEncoding("utf-8")
protected fun postRequestWithBody(url: String, body: Map<String, Any?>): MockHttpServletRequestBuilder =
RestDocumentationRequestBuilders.post(url)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.characterEncoding("utf-8")
.content(objectMapper.writeValueAsString(body))
protected fun putRequestWithBody(url: String, body: Map<String, Any?>): MockHttpServletRequestBuilder =
RestDocumentationRequestBuilders.put(url)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.characterEncoding("utf-8")
.content(objectMapper.writeValueAsString(body))
protected fun putRequest(url: String): MockHttpServletRequestBuilder =
RestDocumentationRequestBuilders.put(url)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.characterEncoding("utf-8")
protected fun patchRequestWithBody(url: String, body: Map<String, Any?>): MockHttpServletRequestBuilder =
RestDocumentationRequestBuilders.patch(url)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.characterEncoding("utf-8")
.content(objectMapper.writeValueAsString(body))
protected fun deleteRequest(url: String): MockHttpServletRequestBuilder =
RestDocumentationRequestBuilders.delete(url)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.characterEncoding("utf-8")
protected fun createdResponseHeaders(): ResponseHeadersSnippet =
responseHeaders(
headerWithName("Location").description("Location to the created statement")
)
protected fun pageableRequestParameters(vararg descriptors: ParameterDescriptor):
RequestParametersSnippet =
requestParameters(
mutableListOf(
parameterWithName("page").description(
"Page number of items to fetch (default: 1)"
)
.optional(),
parameterWithName("size").description(
"Number of items to fetch per page (default: 10)"
)
.optional(),
parameterWithName("sort").description(
"Key to sort by (default: not provided)"
)
.optional()
).apply {
addAll(descriptors)
}
)
companion object {
fun pageableDetailedFieldParameters(): List<FieldDescriptor> = listOf(
fieldWithPath("content[]").description("The content"),
fieldWithPath("pageable").description("The attribute pageable"),
fieldWithPath("pageable.sort").description("The attribute sort below pageable"),
fieldWithPath("pageable.sort.sorted").description("The attribute sorted below sort"),
fieldWithPath("pageable.sort.unsorted").description("The attribute unsorted below sort"),
fieldWithPath("pageable.sort.empty").description("The attribute empty below sort"),
fieldWithPath("pageable.offset").description("The offset of the results"),
fieldWithPath("pageable.pageNumber").description("The page number of the results"),
fieldWithPath("pageable.pageSize").description("The page size of the results"),
fieldWithPath("pageable.paged").description("The paged attribute in pageable"),
fieldWithPath("pageable.unpaged").description("The unpaged attribute in pageable"),
fieldWithPath("totalPages").description("The total number of pages"),
fieldWithPath("totalElements").description("The total number of elements"),
fieldWithPath("last").description("The last attribute"),
fieldWithPath("size").description("The size attribute"),
fieldWithPath("number").description("The number attribute"),
fieldWithPath("sort").description("The sort attribute"),
fieldWithPath("sort.sorted").description("The sorted attribute inside sort"),
fieldWithPath("sort.unsorted").description("The unsorted attribute inside sort"),
fieldWithPath("sort.empty").description("The empty attribute inside sort"),
fieldWithPath("numberOfElements").description("The number of elements"),
fieldWithPath("first").description("The first attribute"),
fieldWithPath("empty").description("The empty attribute")
)
}
}
| 0
| null |
2
| 5
|
f9de52bdf498fdc200e7f655a52cecff215c1949
| 8,566
|
orkg-backend
|
MIT License
|
sample/src/main/kotlin/gtk3/Window.kt
|
kropp
| 91,442,994
| false
| null |
package gtk3
import kotlin.Boolean
import kotlin.Int
import kotlin.String
import kotlin.Unit
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.asStableRef
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.staticCFunction
import kotlinx.cinterop.toKString
import libgtk3.GList
import libgtk3.GdkEventKey
import libgtk3.GdkGeometry
import libgtk3.GdkGravity
import libgtk3.GdkModifierType
import libgtk3.GdkPixbuf
import libgtk3.GdkScreen
import libgtk3.GdkWindowEdge
import libgtk3.GdkWindowHints
import libgtk3.GdkWindowTypeHint
import libgtk3.GtkAccelGroup
import libgtk3.GtkApplication
import libgtk3.GtkWidget
import libgtk3.GtkWindow
import libgtk3.GtkWindowGroup
import libgtk3.GtkWindowPosition
import libgtk3.GtkWindowType
import libgtk3.gtk_false
import libgtk3.gtk_true
import libgtk3.gtk_window_activate_default
import libgtk3.gtk_window_activate_focus
import libgtk3.gtk_window_activate_key
import libgtk3.gtk_window_add_accel_group
import libgtk3.gtk_window_add_mnemonic
import libgtk3.gtk_window_begin_move_drag
import libgtk3.gtk_window_begin_resize_drag
import libgtk3.gtk_window_close
import libgtk3.gtk_window_deiconify
import libgtk3.gtk_window_fullscreen
import libgtk3.gtk_window_fullscreen_on_monitor
import libgtk3.gtk_window_get_accept_focus
import libgtk3.gtk_window_get_application
import libgtk3.gtk_window_get_attached_to
import libgtk3.gtk_window_get_decorated
import libgtk3.gtk_window_get_default_widget
import libgtk3.gtk_window_get_deletable
import libgtk3.gtk_window_get_destroy_with_parent
import libgtk3.gtk_window_get_focus
import libgtk3.gtk_window_get_focus_on_map
import libgtk3.gtk_window_get_focus_visible
import libgtk3.gtk_window_get_gravity
import libgtk3.gtk_window_get_group
import libgtk3.gtk_window_get_hide_titlebar_when_maximized
import libgtk3.gtk_window_get_icon
import libgtk3.gtk_window_get_icon_list
import libgtk3.gtk_window_get_icon_name
import libgtk3.gtk_window_get_mnemonic_modifier
import libgtk3.gtk_window_get_mnemonics_visible
import libgtk3.gtk_window_get_modal
import libgtk3.gtk_window_get_resizable
import libgtk3.gtk_window_get_role
import libgtk3.gtk_window_get_skip_pager_hint
import libgtk3.gtk_window_get_skip_taskbar_hint
import libgtk3.gtk_window_get_title
import libgtk3.gtk_window_get_titlebar
import libgtk3.gtk_window_get_transient_for
import libgtk3.gtk_window_get_type_hint
import libgtk3.gtk_window_get_urgency_hint
import libgtk3.gtk_window_get_window_type
import libgtk3.gtk_window_has_group
import libgtk3.gtk_window_has_toplevel_focus
import libgtk3.gtk_window_iconify
import libgtk3.gtk_window_is_active
import libgtk3.gtk_window_is_maximized
import libgtk3.gtk_window_maximize
import libgtk3.gtk_window_mnemonic_activate
import libgtk3.gtk_window_move
import libgtk3.gtk_window_new
import libgtk3.gtk_window_present
import libgtk3.gtk_window_present_with_time
import libgtk3.gtk_window_propagate_key_event
import libgtk3.gtk_window_remove_accel_group
import libgtk3.gtk_window_remove_mnemonic
import libgtk3.gtk_window_resize
import libgtk3.gtk_window_set_accept_focus
import libgtk3.gtk_window_set_application
import libgtk3.gtk_window_set_attached_to
import libgtk3.gtk_window_set_decorated
import libgtk3.gtk_window_set_default
import libgtk3.gtk_window_set_default_size
import libgtk3.gtk_window_set_deletable
import libgtk3.gtk_window_set_destroy_with_parent
import libgtk3.gtk_window_set_focus
import libgtk3.gtk_window_set_focus_on_map
import libgtk3.gtk_window_set_focus_visible
import libgtk3.gtk_window_set_geometry_hints
import libgtk3.gtk_window_set_gravity
import libgtk3.gtk_window_set_has_user_ref_count
import libgtk3.gtk_window_set_hide_titlebar_when_maximized
import libgtk3.gtk_window_set_icon
import libgtk3.gtk_window_set_icon_list
import libgtk3.gtk_window_set_icon_name
import libgtk3.gtk_window_set_keep_above
import libgtk3.gtk_window_set_keep_below
import libgtk3.gtk_window_set_mnemonic_modifier
import libgtk3.gtk_window_set_mnemonics_visible
import libgtk3.gtk_window_set_modal
import libgtk3.gtk_window_set_position
import libgtk3.gtk_window_set_resizable
import libgtk3.gtk_window_set_role
import libgtk3.gtk_window_set_skip_pager_hint
import libgtk3.gtk_window_set_skip_taskbar_hint
import libgtk3.gtk_window_set_startup_id
import libgtk3.gtk_window_set_title
import libgtk3.gtk_window_set_titlebar
import libgtk3.gtk_window_set_transient_for
import libgtk3.gtk_window_set_type_hint
import libgtk3.gtk_window_set_urgency_hint
import libgtk3.gtk_window_stick
import libgtk3.gtk_window_unfullscreen
import libgtk3.gtk_window_unmaximize
import libgtk3.gtk_window_unstick
inline fun Container.window(type: GtkWindowType, init: Window.() -> Unit = {}): Window = Window(type).apply { init(); this@window.add(this) }
private fun Window_onActivateDefault_Handler(sender: CPointer<*>?, data: COpaquePointer?) {
data?.asStableRef<Window>()?.get()?.onActivateDefault?.invoke()
}
private fun Window_onActivateFocus_Handler(sender: CPointer<*>?, data: COpaquePointer?) {
data?.asStableRef<Window>()?.get()?.onActivateFocus?.invoke()
}
private fun Window_onKeysChanged_Handler(sender: CPointer<*>?, data: COpaquePointer?) {
data?.asStableRef<Window>()?.get()?.onKeysChanged?.invoke()
}
private fun Window_onSetFocus_Handler(
sender: CPointer<*>?,
`object`: CPointer<GtkWidget>?,
data: COpaquePointer?
) {
data?.asStableRef<Window>()?.get()?.onSetFocus?.invoke(`object`)
}
/**
* A GtkWindow is a toplevel window which can contain other widgets.
* Windows normally have decorations that are under the control
* of the windowing system and allow the user to manipulate the window
* (resize it, move it, close it,...).
*
* # GtkWindow as GtkBuildable
*
* The GtkWindow implementation of the GtkBuildable interface supports a
* custom <accel-groups> element, which supports any number of <group>
* elements representing the #GtkAccelGroup objects you want to add to
* your window (synonymous with gtk_window_add_accel_group().
*
* It also supports the <initial-focus> element, whose name property names
* the widget to receive the focus when the window is mapped.
*
* An example of a UI definition fragment with accel groups:
* |[
* <object class="GtkWindow">
* <accel-groups>
* <group name="accelgroup1"/>
* </accel-groups>
* <initial-focus name="thunderclap"/>
* </object>
*
* ...
*
* <object class="GtkAccelGroup" id="accelgroup1"/>
* ]|
*
* The GtkWindow implementation of the GtkBuildable interface supports
* setting a child as the titlebar by specifying “titlebar” as the “type”
* attribute of a <child> element.
*
* # CSS nodes
*
* |[<!-- language="plain" -->
* window.background
* ├── decoration
* ├── <titlebar child>.titlebar [.default-decoration]
* ╰── <child>
* ]|
*
* GtkWindow has a main CSS node with name window and style class .background,
* and a subnode with name decoration.
*
* Style classes that are typically used with the main CSS node are .csd (when
* client-side decorations are in use), .solid-csd (for client-side decorations
* without invisible borders), .ssd (used by mutter when rendering server-side
* decorations). GtkWindow also represents window states with the following
* style classes on the main node: .tiled, .maximized, .fullscreen. Specialized
* types of window often add their own discriminating style classes, such as
* .popup or .tooltip.
*
* GtkWindow adds the .titlebar and .default-decoration style classes to the
* widget that is added as a titlebar child. */
@GtkDsl
open class Window internal constructor(override val widgetPtr: CPointer<GtkWidget>? = null) : Bin() {
private val self: CPointer<GtkWindow>?
get() = widgetPtr!!.reinterpret()
val window: CPointer<GtkWindow>?
get() = widgetPtr!!.reinterpret()
val onActivateDefault: Signal<Window, CFunction<(CPointer<*>?, COpaquePointer?) -> Unit>> by lazy { Signal<Window, CFunction<(CPointer<*>?, COpaquePointer?) -> Unit>>(widgetPtr!!, this, "activate-default", staticCFunction(::Window_onActivateDefault_Handler)) }
val onActivateFocus: Signal<Window, CFunction<(CPointer<*>?, COpaquePointer?) -> Unit>> by lazy { Signal<Window, CFunction<(CPointer<*>?, COpaquePointer?) -> Unit>>(widgetPtr!!, this, "activate-focus", staticCFunction(::Window_onActivateFocus_Handler)) }
val onKeysChanged: Signal<Window, CFunction<(CPointer<*>?, COpaquePointer?) -> Unit>> by lazy { Signal<Window, CFunction<(CPointer<*>?, COpaquePointer?) -> Unit>>(widgetPtr!!, this, "keys-changed", staticCFunction(::Window_onKeysChanged_Handler)) }
val onSetFocus: Signal1<Window, CPointer<GtkWidget>?, CFunction<(
CPointer<*>?,
CPointer<GtkWidget>?,
COpaquePointer?
) -> Unit>> by lazy { Signal1<Window, CPointer<GtkWidget>?, CFunction<(
CPointer<*>?,
CPointer<GtkWidget>?,
COpaquePointer?
) -> Unit>>(widgetPtr!!, this, "set-focus", staticCFunction(::Window_onSetFocus_Handler)) }
var acceptFocus: Boolean
/**
* Gets the value set by gtk_window_set_accept_focus(). */
get() = gtk_window_get_accept_focus(self) != 0
/**
* Windows may set a hint asking the desktop environment not to receive
* the input focus. This function sets this hint. */
set(value) {
gtk_window_set_accept_focus(self, if (value) gtk_true() else gtk_false())
}
var application: CPointer<GtkApplication>?
/**
* Gets the #GtkApplication associated with the window (if any). */
get() = gtk_window_get_application(self)!!.reinterpret()
/**
* Sets or unsets the #GtkApplication associated with the window.
*
* The application will be kept alive for at least as long as it has any windows
* associated with it (see g_application_hold() for a way to keep it alive
* without windows).
*
* Normally, the connection between the application and the window will remain
* until the window is destroyed, but you can explicitly remove it by setting
* the @application to %NULL.
*
* This is equivalent to calling gtk_application_remove_window() and/or
* gtk_application_add_window() on the old/new applications as relevant. */
set(value) {
gtk_window_set_application(self, value?.reinterpret())
}
var attachedTo: CPointer<GtkWidget>?
/**
* Fetches the attach widget for this window. See
* gtk_window_set_attached_to(). */
get() = gtk_window_get_attached_to(self)!!.reinterpret()
/**
* Marks @window as attached to @attach_widget. This creates a logical binding
* between the window and the widget it belongs to, which is used by GTK+ to
* propagate information such as styling or accessibility to @window as if it
* was a children of @attach_widget.
*
* Examples of places where specifying this relation is useful are for instance
* a #GtkMenu created by a #GtkComboBox, a completion popup window
* created by #GtkEntry or a typeahead search entry created by #GtkTreeView.
*
* Note that this function should not be confused with
* gtk_window_set_transient_for(), which specifies a window manager relation
* between two toplevels instead.
*
* Passing %NULL for @attach_widget detaches the window. */
set(value) {
gtk_window_set_attached_to(self, value?.reinterpret())
}
var decorated: Boolean
/**
* Returns whether the window has been set to have decorations
* such as a title bar via gtk_window_set_decorated(). */
get() = gtk_window_get_decorated(self) != 0
/**
* By default, windows are decorated with a title bar, resize
* controls, etc. Some [window managers][gtk-X11-arch]
* allow GTK+ to disable these decorations, creating a
* borderless window. If you set the decorated property to %FALSE
* using this function, GTK+ will do its best to convince the window
* manager not to decorate the window. Depending on the system, this
* function may not have any effect when called on a window that is
* already visible, so you should call it before calling gtk_widget_show().
*
* On Windows, this function always works, since there’s no window manager
* policy involved. */
set(value) {
gtk_window_set_decorated(self, if (value) gtk_true() else gtk_false())
}
val defaultWidget: CPointer<GtkWidget>?
/**
* Returns the default widget for @window. See
* gtk_window_set_default() for more details. */
get() = gtk_window_get_default_widget(self)!!.reinterpret()
var deletable: Boolean
/**
* Returns whether the window has been set to have a close button
* via gtk_window_set_deletable(). */
get() = gtk_window_get_deletable(self) != 0
/**
* By default, windows have a close button in the window frame. Some
* [window managers][gtk-X11-arch] allow GTK+ to
* disable this button. If you set the deletable property to %FALSE
* using this function, GTK+ will do its best to convince the window
* manager not to show a close button. Depending on the system, this
* function may not have any effect when called on a window that is
* already visible, so you should call it before calling gtk_widget_show().
*
* On Windows, this function always works, since there’s no window manager
* policy involved. */
set(value) {
gtk_window_set_deletable(self, if (value) gtk_true() else gtk_false())
}
var destroyWithParent: Boolean
/**
* Returns whether the window will be destroyed with its transient parent. See
* gtk_window_set_destroy_with_parent (). */
get() = gtk_window_get_destroy_with_parent(self) != 0
/**
* If @setting is %TRUE, then destroying the transient parent of @window
* will also destroy @window itself. This is useful for dialogs that
* shouldn’t persist beyond the lifetime of the main window they're
* associated with, for example. */
set(value) {
gtk_window_set_destroy_with_parent(self, if (value) gtk_true() else gtk_false())
}
var focus: CPointer<GtkWidget>?
/**
* Retrieves the current focused widget within the window.
* Note that this is the widget that would have the focus
* if the toplevel window focused; if the toplevel window
* is not focused then `gtk_widget_has_focus (widget)` will
* not be %TRUE for the widget. */
get() = gtk_window_get_focus(self)!!.reinterpret()
/**
* If @focus is not the current focus widget, and is focusable, sets
* it as the focus widget for the window. If @focus is %NULL, unsets
* the focus widget for this window. To set the focus to a particular
* widget in the toplevel, it is usually more convenient to use
* gtk_widget_grab_focus() instead of this function. */
set(value) {
gtk_window_set_focus(self, value?.reinterpret())
}
var focusOnMap: Boolean
/**
* Gets the value set by gtk_window_set_focus_on_map(). */
get() = gtk_window_get_focus_on_map(self) != 0
/**
* Windows may set a hint asking the desktop environment not to receive
* the input focus when the window is mapped. This function sets this
* hint. */
set(value) {
gtk_window_set_focus_on_map(self, if (value) gtk_true() else gtk_false())
}
var focusVisible: Boolean
/**
* Gets the value of the #GtkWindow:focus-visible property. */
get() = gtk_window_get_focus_visible(self) != 0
/**
* Sets the #GtkWindow:focus-visible property. */
set(value) {
gtk_window_set_focus_visible(self, if (value) gtk_true() else gtk_false())
}
var gravity: GdkGravity
/**
* Gets the value set by gtk_window_set_gravity(). */
get() = gtk_window_get_gravity(self)
/**
* Window gravity defines the meaning of coordinates passed to
* gtk_window_move(). See gtk_window_move() and #GdkGravity for
* more details.
*
* The default window gravity is #GDK_GRAVITY_NORTH_WEST which will
* typically “do what you mean.” */
set(value) {
gtk_window_set_gravity(self, value)
}
val group: CPointer<GtkWindowGroup>?
/**
* Returns the group for @window or the default group, if
* @window is %NULL or if @window does not have an explicit
* window group. */
get() = gtk_window_get_group(self)!!.reinterpret()
var hideTitlebarWhenMaximized: Boolean
/**
* Returns whether the window has requested to have its titlebar hidden
* when maximized. See gtk_window_set_hide_titlebar_when_maximized (). */
get() = gtk_window_get_hide_titlebar_when_maximized(self) != 0
/**
* If @setting is %TRUE, then @window will request that it’s titlebar
* should be hidden when maximized.
* This is useful for windows that don’t convey any information other
* than the application name in the titlebar, to put the available
* screen space to better use. If the underlying window system does not
* support the request, the setting will not have any effect.
*
* Note that custom titlebars set with gtk_window_set_titlebar() are
* not affected by this. The application is in full control of their
* content and visibility anyway. */
set(value) {
gtk_window_set_hide_titlebar_when_maximized(self, if (value) gtk_true() else gtk_false())
}
var icon: CPointer<GdkPixbuf>?
/**
* Gets the value set by gtk_window_set_icon() (or if you've
* called gtk_window_set_icon_list(), gets the first icon in
* the icon list). */
get() = gtk_window_get_icon(self)!!.reinterpret()
/**
* Sets up the icon representing a #GtkWindow. This icon is used when
* the window is minimized (also known as iconified). Some window
* managers or desktop environments may also place it in the window
* frame, or display it in other contexts. On others, the icon is not
* used at all, so your mileage may vary.
*
* The icon should be provided in whatever size it was naturally
* drawn; that is, don’t scale the image before passing it to
* GTK+. Scaling is postponed until the last minute, when the desired
* final size is known, to allow best quality.
*
* If you have your icon hand-drawn in multiple sizes, use
* gtk_window_set_icon_list(). Then the best size will be used.
*
* This function is equivalent to calling gtk_window_set_icon_list()
* with a 1-element list.
*
* See also gtk_window_set_default_icon_list() to set the icon
* for all windows in your application in one go. */
set(value) {
gtk_window_set_icon(self, value?.reinterpret())
}
var iconList: CPointer<GList>?
/**
* Retrieves the list of icons set by gtk_window_set_icon_list().
* The list is copied, but the reference count on each
* member won’t be incremented. */
get() = gtk_window_get_icon_list(self)!!.reinterpret()
/**
* Sets up the icon representing a #GtkWindow. The icon is used when
* the window is minimized (also known as iconified). Some window
* managers or desktop environments may also place it in the window
* frame, or display it in other contexts. On others, the icon is not
* used at all, so your mileage may vary.
*
* gtk_window_set_icon_list() allows you to pass in the same icon in
* several hand-drawn sizes. The list should contain the natural sizes
* your icon is available in; that is, don’t scale the image before
* passing it to GTK+. Scaling is postponed until the last minute,
* when the desired final size is known, to allow best quality.
*
* By passing several sizes, you may improve the final image quality
* of the icon, by reducing or eliminating automatic image scaling.
*
* Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and
* larger images (64x64, 128x128) if you have them.
*
* See also gtk_window_set_default_icon_list() to set the icon
* for all windows in your application in one go.
*
* Note that transient windows (those who have been set transient for another
* window using gtk_window_set_transient_for()) will inherit their
* icon from their transient parent. So there’s no need to explicitly
* set the icon on transient windows. */
set(value) {
gtk_window_set_icon_list(self, value?.reinterpret())
}
var iconName: String
/**
* Returns the name of the themed icon for the window,
* see gtk_window_set_icon_name(). */
get() = gtk_window_get_icon_name(self)?.toKString() ?: ""
/**
* Sets the icon for the window from a named themed icon.
* See the docs for #GtkIconTheme for more details.
* On some platforms, the window icon is not used at all.
*
* Note that this has nothing to do with the WM_ICON_NAME
* property which is mentioned in the ICCCM. */
set(value) {
gtk_window_set_icon_name(self, value)
}
var mnemonicModifier: GdkModifierType
/**
* Returns the mnemonic modifier for this window. See
* gtk_window_set_mnemonic_modifier(). */
get() = gtk_window_get_mnemonic_modifier(self)
/**
* Sets the mnemonic modifier for this window. */
set(value) {
gtk_window_set_mnemonic_modifier(self, value)
}
var mnemonicsVisible: Boolean
/**
* Gets the value of the #GtkWindow:mnemonics-visible property. */
get() = gtk_window_get_mnemonics_visible(self) != 0
/**
* Sets the #GtkWindow:mnemonics-visible property. */
set(value) {
gtk_window_set_mnemonics_visible(self, if (value) gtk_true() else gtk_false())
}
var modal: Boolean
/**
* Returns whether the window is modal. See gtk_window_set_modal(). */
get() = gtk_window_get_modal(self) != 0
/**
* Sets a window modal or non-modal. Modal windows prevent interaction
* with other windows in the same application. To keep modal dialogs
* on top of main application windows, use
* gtk_window_set_transient_for() to make the dialog transient for the
* parent; most [window managers][gtk-X11-arch]
* will then disallow lowering the dialog below the parent. */
set(value) {
gtk_window_set_modal(self, if (value) gtk_true() else gtk_false())
}
var resizable: Boolean
/**
* Gets the value set by gtk_window_set_resizable(). */
get() = gtk_window_get_resizable(self) != 0
/**
* Sets whether the user can resize a window. Windows are user resizable
* by default. */
set(value) {
gtk_window_set_resizable(self, if (value) gtk_true() else gtk_false())
}
var role: String
/**
* Returns the role of the window. See gtk_window_set_role() for
* further explanation. */
get() = gtk_window_get_role(self)?.toKString() ?: ""
/**
* This function is only useful on X11, not with other GTK+ targets.
*
* In combination with the window title, the window role allows a
* [window manager][gtk-X11-arch] to identify "the
* same" window when an application is restarted. So for example you
* might set the “toolbox” role on your app’s toolbox window, so that
* when the user restarts their session, the window manager can put
* the toolbox back in the same place.
*
* If a window already has a unique title, you don’t need to set the
* role, since the WM can use the title to identify the window when
* restoring the session. */
set(value) {
gtk_window_set_role(self, value)
}
var skipPagerHint: Boolean
/**
* Gets the value set by gtk_window_set_skip_pager_hint(). */
get() = gtk_window_get_skip_pager_hint(self) != 0
/**
* Windows may set a hint asking the desktop environment not to display
* the window in the pager. This function sets this hint.
* (A "pager" is any desktop navigation tool such as a workspace
* switcher that displays a thumbnail representation of the windows
* on the screen.) */
set(value) {
gtk_window_set_skip_pager_hint(self, if (value) gtk_true() else gtk_false())
}
var skipTaskbarHint: Boolean
/**
* Gets the value set by gtk_window_set_skip_taskbar_hint() */
get() = gtk_window_get_skip_taskbar_hint(self) != 0
/**
* Windows may set a hint asking the desktop environment not to display
* the window in the task bar. This function sets this hint. */
set(value) {
gtk_window_set_skip_taskbar_hint(self, if (value) gtk_true() else gtk_false())
}
var title: String
/**
* Retrieves the title of the window. See gtk_window_set_title(). */
get() = gtk_window_get_title(self)?.toKString() ?: ""
/**
* Sets the title of the #GtkWindow. The title of a window will be
* displayed in its title bar; on the X Window System, the title bar
* is rendered by the [window manager][gtk-X11-arch],
* so exactly how the title appears to users may vary
* according to a user’s exact configuration. The title should help a
* user distinguish this window from other windows they may have
* open. A good title might include the application name and current
* document filename, for example. */
set(value) {
gtk_window_set_title(self, value)
}
var titlebar: CPointer<GtkWidget>?
/**
* Returns the custom titlebar that has been set with
* gtk_window_set_titlebar(). */
get() = gtk_window_get_titlebar(self)!!.reinterpret()
/**
* Sets a custom titlebar for @window.
*
* A typical widget used here is #GtkHeaderBar, as it provides various features
* expected of a titlebar while allowing the addition of child widgets to it.
*
* If you set a custom titlebar, GTK+ will do its best to convince
* the window manager not to put its own titlebar on the window.
* Depending on the system, this function may not work for a window
* that is already visible, so you set the titlebar before calling
* gtk_widget_show(). */
set(value) {
gtk_window_set_titlebar(self, value?.reinterpret())
}
var transientFor: CPointer<GtkWindow>?
/**
* Fetches the transient parent for this window. See
* gtk_window_set_transient_for(). */
get() = gtk_window_get_transient_for(self)!!.reinterpret()
/**
* Dialog windows should be set transient for the main application
* window they were spawned from. This allows
* [window managers][gtk-X11-arch] to e.g. keep the
* dialog on top of the main window, or center the dialog over the
* main window. gtk_dialog_new_with_buttons() and other convenience
* functions in GTK+ will sometimes call
* gtk_window_set_transient_for() on your behalf.
*
* Passing %NULL for @parent unsets the current transient window.
*
* On Wayland, this function can also be used to attach a new
* #GTK_WINDOW_POPUP to a #GTK_WINDOW_TOPLEVEL parent already mapped
* on screen so that the #GTK_WINDOW_POPUP will be created as a
* subsurface-based window #GDK_WINDOW_SUBSURFACE which can be
* positioned at will relatively to the #GTK_WINDOW_TOPLEVEL surface.
*
* On Windows, this function puts the child window on top of the parent,
* much as the window manager would have done on X. */
set(value) {
gtk_window_set_transient_for(self, value?.reinterpret())
}
var typeHint: GdkWindowTypeHint
/**
* Gets the type hint for this window. See gtk_window_set_type_hint(). */
get() = gtk_window_get_type_hint(self)
/**
* By setting the type hint for the window, you allow the window
* manager to decorate and handle the window in a way which is
* suitable to the function of the window in your application.
*
* This function should be called before the window becomes visible.
*
* gtk_dialog_new_with_buttons() and other convenience functions in GTK+
* will sometimes call gtk_window_set_type_hint() on your behalf. */
set(value) {
gtk_window_set_type_hint(self, value)
}
var urgencyHint: Boolean
/**
* Gets the value set by gtk_window_set_urgency_hint() */
get() = gtk_window_get_urgency_hint(self) != 0
/**
* Windows may set a hint asking the desktop environment to draw
* the users attention to the window. This function sets this hint. */
set(value) {
gtk_window_set_urgency_hint(self, if (value) gtk_true() else gtk_false())
}
val windowType: GtkWindowType
/**
* Gets the type of the window. See #GtkWindowType. */
get() = gtk_window_get_window_type(self)
/**
* Creates a new #GtkWindow, which is a toplevel window that can
* contain other widgets. Nearly always, the type of the window should
* be #GTK_WINDOW_TOPLEVEL. If you’re implementing something like a
* popup menu from scratch (which is a bad idea, just use #GtkMenu),
* you might use #GTK_WINDOW_POPUP. #GTK_WINDOW_POPUP is not for
* dialogs, though in some other toolkits dialogs are called “popups”.
* In GTK+, #GTK_WINDOW_POPUP means a pop-up menu or pop-up tooltip.
* On X11, popup windows are not controlled by the
* [window manager][gtk-X11-arch].
*
* If you simply want an undecorated window (no window borders), use
* gtk_window_set_decorated(), don’t use #GTK_WINDOW_POPUP.
*
* All top-level windows created by gtk_window_new() are stored in
* an internal top-level window list. This list can be obtained from
* gtk_window_list_toplevels(). Due to Gtk+ keeping a reference to
* the window internally, gtk_window_new() does not return a reference
* to the caller.
*
* To delete a #GtkWindow, call gtk_widget_destroy(). */
constructor(type: GtkWindowType) : this(gtk_window_new(type)?.reinterpret())
/**
* Activates the default widget for the window, unless the current
* focused widget has been configured to receive the default action
* (see gtk_widget_set_receives_default()), in which case the
* focused widget is activated. */
fun activateDefault(): Boolean = gtk_window_activate_default(self) != 0
/**
* Activates the current focused widget within the window. */
fun activateFocus(): Boolean = gtk_window_activate_focus(self) != 0
/**
* Activates mnemonics and accelerators for this #GtkWindow. This is normally
* called by the default ::key_press_event handler for toplevel windows,
* however in some cases it may be useful to call this directly when
* overriding the standard key handling for a toplevel window. */
fun activateKey(event: CPointer<GdkEventKey>?): Boolean = gtk_window_activate_key(self, event) != 0
/**
* Associate @accel_group with @window, such that calling
* gtk_accel_groups_activate() on @window will activate accelerators
* in @accel_group. */
fun addAccelGroup(accel_group: CPointer<GtkAccelGroup>?): Unit = gtk_window_add_accel_group(self, accel_group)
/**
* Adds a mnemonic to this window. */
fun addMnemonic(keyval: Int, target: CPointer<GtkWidget>?): Unit = gtk_window_add_mnemonic(self, keyval, target)
/**
* Adds a mnemonic to this window. */
fun addMnemonic(keyval: Int, target: Widget): Unit = gtk_window_add_mnemonic(self, keyval, target.widgetPtr?.reinterpret())
/**
* Starts moving a window. This function is used if an application has
* window movement grips. When GDK can support it, the window movement
* will be done using the standard mechanism for the
* [window manager][gtk-X11-arch] or windowing
* system. Otherwise, GDK will try to emulate window movement,
* potentially not all that well, depending on the windowing system. */
fun beginMoveDrag(
button: Int,
root_x: Int,
root_y: Int,
timestamp: Int
): Unit = gtk_window_begin_move_drag(self, button, root_x, root_y, timestamp)
/**
* Starts resizing a window. This function is used if an application
* has window resizing controls. When GDK can support it, the resize
* will be done using the standard mechanism for the
* [window manager][gtk-X11-arch] or windowing
* system. Otherwise, GDK will try to emulate window resizing,
* potentially not all that well, depending on the windowing system. */
fun beginResizeDrag(
edge: GdkWindowEdge,
button: Int,
root_x: Int,
root_y: Int,
timestamp: Int
): Unit = gtk_window_begin_resize_drag(self, edge, button, root_x, root_y, timestamp)
/**
* Requests that the window is closed, similar to what happens
* when a window manager close button is clicked.
*
* This function can be used with close buttons in custom
* titlebars. */
fun close(): Unit = gtk_window_close(self)
/**
* Asks to deiconify (i.e. unminimize) the specified @window. Note
* that you shouldn’t assume the window is definitely deiconified
* afterward, because other entities (e.g. the user or
* [window manager][gtk-X11-arch])) could iconify it
* again before your code which assumes deiconification gets to run.
*
* You can track iconification via the “window-state-event” signal
* on #GtkWidget. */
fun deiconify(): Unit = gtk_window_deiconify(self)
/**
* Asks to place @window in the fullscreen state. Note that you
* shouldn’t assume the window is definitely full screen afterward,
* because other entities (e.g. the user or
* [window manager][gtk-X11-arch]) could unfullscreen it
* again, and not all window managers honor requests to fullscreen
* windows. But normally the window will end up fullscreen. Just
* don’t write code that crashes if not.
*
* You can track the fullscreen state via the “window-state-event” signal
* on #GtkWidget. */
fun fullscreen(): Unit = gtk_window_fullscreen(self)
/**
* Asks to place @window in the fullscreen state. Note that you shouldn't assume
* the window is definitely full screen afterward.
*
* You can track the fullscreen state via the "window-state-event" signal
* on #GtkWidget. */
fun fullscreenOnMonitor(screen: CPointer<GdkScreen>?, monitor: Int): Unit = gtk_window_fullscreen_on_monitor(self, screen, monitor)
/**
* Returns whether @window has an explicit window group. */
fun hasGroup(): Boolean = gtk_window_has_group(self) != 0
/**
* Returns whether the input focus is within this GtkWindow.
* For real toplevel windows, this is identical to gtk_window_is_active(),
* but for embedded windows, like #GtkPlug, the results will differ. */
fun hasToplevelFocus(): Boolean = gtk_window_has_toplevel_focus(self) != 0
/**
* Asks to iconify (i.e. minimize) the specified @window. Note that
* you shouldn’t assume the window is definitely iconified afterward,
* because other entities (e.g. the user or
* [window manager][gtk-X11-arch]) could deiconify it
* again, or there may not be a window manager in which case
* iconification isn’t possible, etc. But normally the window will end
* up iconified. Just don’t write code that crashes if not.
*
* It’s permitted to call this function before showing a window,
* in which case the window will be iconified before it ever appears
* onscreen.
*
* You can track iconification via the “window-state-event” signal
* on #GtkWidget. */
fun iconify(): Unit = gtk_window_iconify(self)
/**
* Returns whether the window is part of the current active toplevel.
* (That is, the toplevel window receiving keystrokes.)
* The return value is %TRUE if the window is active toplevel
* itself, but also if it is, say, a #GtkPlug embedded in the active toplevel.
* You might use this function if you wanted to draw a widget
* differently in an active window from a widget in an inactive window.
* See gtk_window_has_toplevel_focus() */
fun isActive(): Boolean = gtk_window_is_active(self) != 0
/**
* Retrieves the current maximized state of @window.
*
* Note that since maximization is ultimately handled by the window
* manager and happens asynchronously to an application request, you
* shouldn’t assume the return value of this function changing
* immediately (or at all), as an effect of calling
* gtk_window_maximize() or gtk_window_unmaximize(). */
fun isMaximized(): Boolean = gtk_window_is_maximized(self) != 0
/**
* Asks to maximize @window, so that it becomes full-screen. Note that
* you shouldn’t assume the window is definitely maximized afterward,
* because other entities (e.g. the user or
* [window manager][gtk-X11-arch]) could unmaximize it
* again, and not all window managers support maximization. But
* normally the window will end up maximized. Just don’t write code
* that crashes if not.
*
* It’s permitted to call this function before showing a window,
* in which case the window will be maximized when it appears onscreen
* initially.
*
* You can track maximization via the “window-state-event” signal
* on #GtkWidget, or by listening to notifications on the
* #GtkWindow:is-maximized property. */
fun maximize(): Unit = gtk_window_maximize(self)
/**
* Activates the targets associated with the mnemonic. */
fun mnemonicActivate(keyval: Int, modifier: GdkModifierType): Boolean = gtk_window_mnemonic_activate(self, keyval, modifier) != 0
/**
* Asks the [window manager][gtk-X11-arch] to move
* @window to the given position. Window managers are free to ignore
* this; most window managers ignore requests for initial window
* positions (instead using a user-defined placement algorithm) and
* honor requests after the window has already been shown.
*
* Note: the position is the position of the gravity-determined
* reference point for the window. The gravity determines two things:
* first, the location of the reference point in root window
* coordinates; and second, which point on the window is positioned at
* the reference point.
*
* By default the gravity is #GDK_GRAVITY_NORTH_WEST, so the reference
* point is simply the @x, @y supplied to gtk_window_move(). The
* top-left corner of the window decorations (aka window frame or
* border) will be placed at @x, @y. Therefore, to position a window
* at the top left of the screen, you want to use the default gravity
* (which is #GDK_GRAVITY_NORTH_WEST) and move the window to 0,0.
*
* To position a window at the bottom right corner of the screen, you
* would set #GDK_GRAVITY_SOUTH_EAST, which means that the reference
* point is at @x + the window width and @y + the window height, and
* the bottom-right corner of the window border will be placed at that
* reference point. So, to place a window in the bottom right corner
* you would first set gravity to south east, then write:
* `gtk_window_move (window, gdk_screen_width () - window_width,
* gdk_screen_height () - window_height)` (note that this
* example does not take multi-head scenarios into account).
*
* The [Extended Window Manager Hints Specification](http://www.freedesktop.org/Standards/wm-spec)
* has a nice table of gravities in the “implementation notes” section.
*
* The gtk_window_get_position() documentation may also be relevant. */
fun move(x: Int, y: Int): Unit = gtk_window_move(self, x, y)
/**
* Presents a window to the user. This may mean raising the window
* in the stacking order, deiconifying it, moving it to the current
* desktop, and/or giving it the keyboard focus, possibly dependent
* on the user’s platform, window manager, and preferences.
*
* If @window is hidden, this function calls gtk_widget_show()
* as well.
*
* This function should be used when the user tries to open a window
* that’s already open. Say for example the preferences dialog is
* currently open, and the user chooses Preferences from the menu
* a second time; use gtk_window_present() to move the already-open dialog
* where the user can see it.
*
* If you are calling this function in response to a user interaction,
* it is preferable to use gtk_window_present_with_time(). */
fun present(): Unit = gtk_window_present(self)
/**
* Presents a window to the user in response to a user interaction.
* If you need to present a window without a timestamp, use
* gtk_window_present(). See gtk_window_present() for details. */
fun presentWithTime(timestamp: Int): Unit = gtk_window_present_with_time(self, timestamp)
/**
* Propagate a key press or release event to the focus widget and
* up the focus container chain until a widget handles @event.
* This is normally called by the default ::key_press_event and
* ::key_release_event handlers for toplevel windows,
* however in some cases it may be useful to call this directly when
* overriding the standard key handling for a toplevel window. */
fun propagateKeyEvent(event: CPointer<GdkEventKey>?): Boolean = gtk_window_propagate_key_event(self, event) != 0
/**
* Reverses the effects of gtk_window_add_accel_group(). */
fun removeAccelGroup(accel_group: CPointer<GtkAccelGroup>?): Unit = gtk_window_remove_accel_group(self, accel_group)
/**
* Removes a mnemonic from this window. */
fun removeMnemonic(keyval: Int, target: CPointer<GtkWidget>?): Unit = gtk_window_remove_mnemonic(self, keyval, target)
/**
* Removes a mnemonic from this window. */
fun removeMnemonic(keyval: Int, target: Widget): Unit = gtk_window_remove_mnemonic(self, keyval, target.widgetPtr?.reinterpret())
/**
* Resizes the window as if the user had done so, obeying geometry
* constraints. The default geometry constraint is that windows may
* not be smaller than their size request; to override this
* constraint, call gtk_widget_set_size_request() to set the window's
* request to a smaller value.
*
* If gtk_window_resize() is called before showing a window for the
* first time, it overrides any default size set with
* gtk_window_set_default_size().
*
* Windows may not be resized smaller than 1 by 1 pixels.
*
* When using client side decorations, GTK+ will do its best to adjust
* the given size so that the resulting window size matches the
* requested size without the title bar, borders and shadows added for
* the client side decorations, but there is no guarantee that the
* result will be totally accurate because these widgets added for
* client side decorations depend on the theme and may not be realized
* or visible at the time gtk_window_resize() is issued.
*
* If the GtkWindow has a titlebar widget (see gtk_window_set_titlebar()), then
* typically, gtk_window_resize() will compensate for the height of the titlebar
* widget only if the height is known when the resulting GtkWindow configuration
* is issued.
* For example, if new widgets are added after the GtkWindow configuration
* and cause the titlebar widget to grow in height, this will result in a
* window content smaller that specified by gtk_window_resize() and not
* a larger window. */
fun resize(width: Int, height: Int): Unit = gtk_window_resize(self, width, height)
/**
* Sets the default size of a window. If the window’s “natural” size
* (its size request) is larger than the default, the default will be
* ignored. More generally, if the default size does not obey the
* geometry hints for the window (gtk_window_set_geometry_hints() can
* be used to set these explicitly), the default size will be clamped
* to the nearest permitted size.
*
* Unlike gtk_widget_set_size_request(), which sets a size request for
* a widget and thus would keep users from shrinking the window, this
* function only sets the initial size, just as if the user had
* resized the window themselves. Users can still shrink the window
* again as they normally would. Setting a default size of -1 means to
* use the “natural” default size (the size request of the window).
*
* For more control over a window’s initial size and how resizing works,
* investigate gtk_window_set_geometry_hints().
*
* For some uses, gtk_window_resize() is a more appropriate function.
* gtk_window_resize() changes the current size of the window, rather
* than the size to be used on initial display. gtk_window_resize() always
* affects the window itself, not the geometry widget.
*
* The default size of a window only affects the first time a window is
* shown; if a window is hidden and re-shown, it will remember the size
* it had prior to hiding, rather than using the default size.
*
* Windows can’t actually be 0x0 in size, they must be at least 1x1, but
* passing 0 for @width and @height is OK, resulting in a 1x1 default size.
*
* If you use this function to reestablish a previously saved window size,
* note that the appropriate size to save is the one returned by
* gtk_window_get_size(). Using the window allocation directly will not
* work in all circumstances and can lead to growing or shrinking windows. */
fun setDefaultSize(width: Int, height: Int): Unit = gtk_window_set_default_size(self, width, height)
/**
* This function sets up hints about how a window can be resized by
* the user. You can set a minimum and maximum size; allowed resize
* increments (e.g. for xterm, you can only resize by the size of a
* character); aspect ratios; and more. See the #GdkGeometry struct. */
fun setGeometryHints(
geometry_widget: CPointer<GtkWidget>?,
geometry: CPointer<GdkGeometry>?,
geom_mask: GdkWindowHints
): Unit = gtk_window_set_geometry_hints(self, geometry_widget, geometry, geom_mask)
/**
* Asks to stick @window, which means that it will appear on all user
* desktops. Note that you shouldn’t assume the window is definitely
* stuck afterward, because other entities (e.g. the user or
* [window manager][gtk-X11-arch] could unstick it
* again, and some window managers do not support sticking
* windows. But normally the window will end up stuck. Just don't
* write code that crashes if not.
*
* It’s permitted to call this function before showing a window.
*
* You can track stickiness via the “window-state-event” signal
* on #GtkWidget. */
fun stick(): Unit = gtk_window_stick(self)
/**
* Asks to toggle off the fullscreen state for @window. Note that you
* shouldn’t assume the window is definitely not full screen
* afterward, because other entities (e.g. the user or
* [window manager][gtk-X11-arch]) could fullscreen it
* again, and not all window managers honor requests to unfullscreen
* windows. But normally the window will end up restored to its normal
* state. Just don’t write code that crashes if not.
*
* You can track the fullscreen state via the “window-state-event” signal
* on #GtkWidget. */
fun unfullscreen(): Unit = gtk_window_unfullscreen(self)
/**
* Asks to unmaximize @window. Note that you shouldn’t assume the
* window is definitely unmaximized afterward, because other entities
* (e.g. the user or [window manager][gtk-X11-arch])
* could maximize it again, and not all window
* managers honor requests to unmaximize. But normally the window will
* end up unmaximized. Just don’t write code that crashes if not.
*
* You can track maximization via the “window-state-event” signal
* on #GtkWidget. */
fun unmaximize(): Unit = gtk_window_unmaximize(self)
/**
* Asks to unstick @window, which means that it will appear on only
* one of the user’s desktops. Note that you shouldn’t assume the
* window is definitely unstuck afterward, because other entities
* (e.g. the user or [window manager][gtk-X11-arch]) could
* stick it again. But normally the window will
* end up stuck. Just don’t write code that crashes if not.
*
* You can track stickiness via the “window-state-event” signal
* on #GtkWidget. */
fun unstick(): Unit = gtk_window_unstick(self)
/**
* The default widget is the widget that’s activated when the user
* presses Enter in a dialog (for example). This function sets or
* unsets the default widget for a #GtkWindow. When setting (rather
* than unsetting) the default widget it’s generally easier to call
* gtk_widget_grab_default() on the widget. Before making a widget
* the default widget, you must call gtk_widget_set_can_default() on
* the widget you’d like to make the default. */
fun setDefault(default_widget: CPointer<GtkWidget>?): Unit = gtk_window_set_default(self, default_widget)
/**
* Tells GTK+ whether to drop its extra reference to the window
* when gtk_widget_destroy() is called.
*
* This function is only exported for the benefit of language
* bindings which may need to keep the window alive until their
* wrapper object is garbage collected. There is no justification
* for ever calling this function in an application. */
fun setHasUserRefCount(setting: Boolean): Unit = gtk_window_set_has_user_ref_count(self, if (setting) gtk_true() else gtk_false())
/**
* Asks to keep @window above, so that it stays on top. Note that
* you shouldn’t assume the window is definitely above afterward,
* because other entities (e.g. the user or
* [window manager][gtk-X11-arch]) could not keep it above,
* and not all window managers support keeping windows above. But
* normally the window will end kept above. Just don’t write code
* that crashes if not.
*
* It’s permitted to call this function before showing a window,
* in which case the window will be kept above when it appears onscreen
* initially.
*
* You can track the above state via the “window-state-event” signal
* on #GtkWidget.
*
* Note that, according to the
* [Extended Window Manager Hints Specification](http://www.freedesktop.org/Standards/wm-spec),
* the above state is mainly meant for user preferences and should not
* be used by applications e.g. for drawing attention to their
* dialogs. */
fun setKeepAbove(setting: Boolean): Unit = gtk_window_set_keep_above(self, if (setting) gtk_true() else gtk_false())
/**
* Asks to keep @window below, so that it stays in bottom. Note that
* you shouldn’t assume the window is definitely below afterward,
* because other entities (e.g. the user or
* [window manager][gtk-X11-arch]) could not keep it below,
* and not all window managers support putting windows below. But
* normally the window will be kept below. Just don’t write code
* that crashes if not.
*
* It’s permitted to call this function before showing a window,
* in which case the window will be kept below when it appears onscreen
* initially.
*
* You can track the below state via the “window-state-event” signal
* on #GtkWidget.
*
* Note that, according to the
* [Extended Window Manager Hints Specification](http://www.freedesktop.org/Standards/wm-spec),
* the above state is mainly meant for user preferences and should not
* be used by applications e.g. for drawing attention to their
* dialogs. */
fun setKeepBelow(setting: Boolean): Unit = gtk_window_set_keep_below(self, if (setting) gtk_true() else gtk_false())
/**
* Sets a position constraint for this window. If the old or new
* constraint is %GTK_WIN_POS_CENTER_ALWAYS, this will also cause
* the window to be repositioned to satisfy the new constraint. */
fun setPosition(position: GtkWindowPosition): Unit = gtk_window_set_position(self, position)
/**
* Startup notification identifiers are used by desktop environment to
* track application startup, to provide user feedback and other
* features. This function changes the corresponding property on the
* underlying GdkWindow. Normally, startup identifier is managed
* automatically and you should only use this function in special cases
* like transferring focus from other processes. You should use this
* function before calling gtk_window_present() or any equivalent
* function generating a window map event.
*
* This function is only useful on X11, not with other GTK+ targets. */
fun setStartupId(startup_id: String): Unit = gtk_window_set_startup_id(self, startup_id)
}
| 6
|
Kotlin
|
12
| 90
|
9609e7ab19064d27f05fc76fccd03139306d0001
| 55,292
|
kotlin-native-gtk
|
Apache License 2.0
|
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/cloudlandmarkrecognition/CloudLandmarkRecognitionProcessor.kt
|
SagarBChauhan
| 216,040,454
| true
|
{"Java Properties": 19, "YAML": 4, "Gradle": 59, "Shell": 22, "EditorConfig": 1, "JSON": 8, "Markdown": 23, "Batchfile": 19, "Text": 5, "Ignore List": 36, "INI": 19, "Proguard": 23, "Java": 129, "XML": 217, "Kotlin": 124, "HTML": 1, "JavaScript": 2, "Python": 1}
|
package com.google.firebase.samples.apps.mlkit.kotlin.cloudlandmarkrecognition
import android.graphics.Bitmap
import android.util.Log
import com.google.android.gms.tasks.Task
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions
import com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmark
import com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmarkDetector
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.samples.apps.mlkit.common.FrameMetadata
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay
import com.google.firebase.samples.apps.mlkit.kotlin.VisionProcessorBase
/** Cloud Landmark Detector Demo. */
class CloudLandmarkRecognitionProcessor : VisionProcessorBase<List<FirebaseVisionCloudLandmark>>() {
private val detector: FirebaseVisionCloudLandmarkDetector
init {
val options = FirebaseVisionCloudDetectorOptions.Builder()
.setMaxResults(10)
.setModelType(FirebaseVisionCloudDetectorOptions.STABLE_MODEL)
.build()
detector = FirebaseVision.getInstance().getVisionCloudLandmarkDetector(options)
}
override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionCloudLandmark>> {
return detector.detectInImage(image)
}
override fun onSuccess(
originalCameraImage: Bitmap?,
results: List<FirebaseVisionCloudLandmark>,
frameMetadata: FrameMetadata?,
graphicOverlay: GraphicOverlay
) {
graphicOverlay.clear()
Log.d(TAG, "cloud landmark size: ${results.size}")
results.forEach {
Log.d(TAG, "cloud landmark: $it")
val cloudLandmarkGraphic = CloudLandmarkGraphic(graphicOverlay, it)
graphicOverlay.add(cloudLandmarkGraphic)
}
graphicOverlay.postInvalidate()
}
override fun onFailure(e: Exception) {
Log.e(TAG, "Cloud Landmark detection failed $e")
}
companion object {
private const val TAG = "CloudLmkRecProc"
}
}
| 5
| null |
0
| 5
|
d886d348a681f41f02e78d720cb74fb8c162e339
| 2,150
|
quickstart-android
|
Creative Commons Attribution 4.0 International
|
platform/platform-impl/src/com/intellij/ide/observation/AbstractInProgressService.kt
|
wwwjames
| 78,877,532
| false
|
{"Text": 8034, "INI": 511, "YAML": 424, "Ant Build System": 9, "Batchfile": 31, "Dockerfile": 8, "Shell": 624, "Markdown": 711, "Ignore List": 131, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 253, "XML": 7516, "SVG": 4046, "Kotlin": 53787, "Java": 82598, "HTML": 3748, "Java Properties": 202, "Gradle": 474, "Maven POM": 83, "JavaScript": 227, "CSS": 80, "JSON": 1385, "JFlex": 32, "Makefile": 3, "Groovy": 3249, "Diff": 136, "XSLT": 113, "desktop": 1, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 710, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 7, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 70, "GraphQL": 92, "OpenStep Property List": 48, "Python": 15531, "C": 107, "C++": 40, "fish": 2, "PowerShell": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "TOML": 160, "PlantUML": 7, "Checksums": 48, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 18, "Handlebars": 1, "Rust": 13, "Go": 34, "Go Checksums": 1, "Go Module": 1, "NSIS": 6, "SCSS": 2, "Thrift": 3, "Cython": 12, "Regular Expression": 3, "JSON5": 4}
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.observable
import com.intellij.concurrency.currentThreadContext
import com.intellij.concurrency.installThreadContext
import com.intellij.util.concurrency.BlockingJob
import com.intellij.util.concurrency.annotations.RequiresBlockingContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Allows to track subsystem activities and get a "dumb mode" w.r.t. tracked computations.
*
* To use this class, consider creating a service with an injected [CoroutineScope] and pass this scope here.
* This is needed because the lifetime of tracker is bound by the lifetime of 'plugin ∩ project' that use tracking.
*/
abstract class AbstractInProgressService(private val scope: CoroutineScope) {
@Volatile
private var inProgress: Int = 0
suspend fun <T> trackConfigurationActivity(action: suspend () -> T) : T {
return withBlockingJob { blockingJob ->
withContext(blockingJob) {
action()
}
}
}
@RequiresBlockingContext
fun <T> trackConfigurationActivityBlocking(action: () -> T) : T {
val currentContext = currentThreadContext()
return withBlockingJob { blockingJob ->
installThreadContext(currentContext + blockingJob, true).use {
action()
}
}
}
private inline fun <T> withBlockingJob(consumer: (BlockingJob) -> T) : T {
inProgress += 1
// new job here to track those and only those computations which are invoked under explicit `trackConfigurationActivity`
val tracker = Job()
tracker.invokeOnCompletion {
inProgress -= 1
}
val blockingJob = BlockingJob(tracker)
try {
return consumer(blockingJob)
} finally {
scope.launch {
tracker.children.forEach { it.join() }
tracker.complete()
}.invokeOnCompletion {
tracker.complete()
}
}
}
open fun isInProgress(): Boolean {
return inProgress != 0
}
}
| 1
| null |
1
| 1
|
9d4b7c6230b668e59a1aabb2b54cb89ba840fce4
| 2,120
|
intellij-community
|
Apache License 2.0
|
sphinx/application/network/features/feature-meme-input-stream/src/main/java/chat/sphinx/meme_input_stream/MemeInputStreamRetriever.kt
|
stakwork
| 340,103,148
| false
| null |
package chat.sphinx.meme_input_stream
import chat.sphinx.concept_network_client_crypto.CryptoHeader
import chat.sphinx.concept_network_client_crypto.CryptoScheme
import chat.sphinx.wrapper_meme_server.AuthenticationToken
import chat.sphinx.wrapper_meme_server.headerKey
import chat.sphinx.wrapper_meme_server.headerValue
import chat.sphinx.wrapper_message_media.MediaKeyDecrypted
import io.matthewnelson.concept_coroutines.CoroutineDispatchers
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.closeQuietly
import java.io.InputStream
internal data class MemeInputStreamRetriever(
val url: HttpUrl,
val authenticationToken: AuthenticationToken?,
val mediaKeyDecrypted: MediaKeyDecrypted?
) {
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun getMemeInputStream(
dispatchers: CoroutineDispatchers,
okHttpClient: OkHttpClient
): InputStream? {
val request = Request.Builder().apply {
url(url)
authenticationToken?.let {
addHeader(authenticationToken.headerKey, authenticationToken.headerValue)
}
mediaKeyDecrypted?.value?.let { key ->
val header = CryptoHeader.Decrypt.Builder()
.setScheme(CryptoScheme.Decrypt.JNCryptor)
.setPassword(key)
.build()
addHeader(header.key, header.value)
}
}.build()
var response: Response?
withContext(dispatchers.io) {
response =
try {
okHttpClient.newCall(request).execute()
} catch (e: Exception) {
null
}
if (response?.isSuccessful == null) {
response?.body?.closeQuietly()
}
}
return response?.body?.source()?.inputStream()
}
}
| 47
|
Kotlin
|
3
| 15
|
66dcae0cd11c872df4a40b6a9748dd0eee673cca
| 1,991
|
sphinx-kotlin
|
MIT License
|
features/clipboard/src/main/kotlin/org/michaelbel/template/clipboard/di/ClipboardModule.kt
|
michaelbel
| 354,625,997
| false
| null |
package org.michaelbel.template.clipboard
import android.content.ClipboardManager
import android.content.Context
import androidx.core.content.ContextCompat
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.qualifiers.ApplicationContext
@Module
@InstallIn(ViewModelComponent::class)
object ClipboardModule {
@Provides
fun provideClipboardService(
@ApplicationContext context: Context
): ClipboardManager {
return ContextCompat.getSystemService(
context,
ClipboardManager::class.java
) as ClipboardManager
}
}
| 4
| null |
2
| 9
|
f87a539a759b683a612f75eddb916548af5543c9
| 681
|
android-app-template
|
Apache License 2.0
|
emojify/src/main/kotlin/io/wax911/emojify/util/EmojiTrie.kt
|
AniTrend
| 98,423,653
| false
|
{"Kotlin": 127438}
|
/*
* Copyright 2021 AniTrend
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.wax911.emojify.util
import io.wax911.emojify.contract.model.AbstractEmoji
import io.wax911.emojify.contract.util.trie.Matches
import io.wax911.emojify.util.trie.Node
class EmojiTrie(emojis: Collection<AbstractEmoji>) {
private val root = Node()
var maxDepth = 0
init {
var maximumDepth = 0
emojis.forEach { emoji ->
var tree: Node? = root
val chars = emoji.unicode.toCharArray()
maximumDepth = maximumDepth.coerceAtLeast(chars.size)
chars.forEach { c ->
if (tree?.hasChild(c) == false) {
tree?.addChild(c)
}
tree = tree?.getChild(c)
}
tree?.emoji = emoji
}
maxDepth = maximumDepth
}
/**
* Checks if sequence of chars contain an emoji.
*
* @param sequence Sequence of char that may contain emoji in full or
* partially.
*
* @return
* - [Matches.EXACTLY] if char sequence in its entirety is an emoji
* - [Matches.POSSIBLY] if char sequence matches prefix of an emoji
* - [Matches.IMPOSSIBLE] if char sequence matches no emoji or prefix of an emoji
*/
@Throws(ArrayIndexOutOfBoundsException::class)
@JvmOverloads
fun isEmoji(
sequence: CharArray?,
start: Int = 0,
end: Int = sequence?.size ?: 0,
): Matches {
if (sequence == null) {
return Matches.POSSIBLY
}
if (start < 0 || start > end || end > sequence.size) {
throw ArrayIndexOutOfBoundsException(
"start " + start + ", end " + end + ", length " + sequence.size,
)
}
var tree: Node? = root
for (index in start until end) {
if (tree?.hasChild(sequence[index]) == false) {
return Matches.IMPOSSIBLE
}
tree = tree?.getChild(sequence[index])
}
return if (tree?.isEndOfEmoji == true) {
Matches.EXACTLY
} else {
Matches.POSSIBLY
}
}
/**
* Finds Emoji instance from emoji unicode
*
* @param unicode unicode of emoji to get
*
* @return Emoji instance if unicode matches and emoji, null otherwise.
*/
@Throws(ArrayIndexOutOfBoundsException::class)
@JvmOverloads
fun getEmoji(
unicode: CharArray,
start: Int = 0,
end: Int = unicode.size,
): AbstractEmoji? {
if (start < 0 || start > end || end > unicode.size) {
throw ArrayIndexOutOfBoundsException(
"start " + start + ", end " + end + ", length " + unicode.size,
)
}
var tree: Node? = root
for (index in start until end) {
if (tree?.hasChild(unicode[index]) == false) {
return null
}
tree = tree?.getChild(unicode[index])
}
return tree?.emoji
}
}
| 9
|
Kotlin
|
12
| 26
|
de0b332bf3b453fe4832a502063d90f833d4d60d
| 3,566
|
android-emojify
|
Apache License 2.0
|
backend/data/src/main/kotlin/io/tolgee/security/apiKeyAuth/ApiKeyAuthenticationToken.kt
|
tolgee
| 303,766,501
| false
| null |
package io.tolgee.security.apiKeyAuth
import io.tolgee.dtos.cacheable.UserAccountDto
import io.tolgee.model.ApiKey
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.GrantedAuthority
class ApiKeyAuthenticationToken(val apiKey: ApiKey) : UsernamePasswordAuthenticationToken(
UserAccountDto.fromEntity(
apiKey.userAccount
),
null,
setOf(
GrantedAuthority { "api" }
)
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as ApiKeyAuthenticationToken
if (apiKey != other.apiKey) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + apiKey.hashCode()
return result
}
}
| 100
|
Kotlin
|
40
| 666
|
38c1064783f3ec5d60d0502ec0420698395af539
| 887
|
tolgee-platform
|
Apache License 2.0
|
src/main/kotlin/dev/jonaz/vured/bot/music/AudioPlayerSendHandler.kt
|
vured
| 319,162,419
| false
| null |
package dev.jonaz.vacegaming.musicbot.music
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer
import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame
import net.dv8tion.jda.api.audio.AudioSendHandler
import java.nio.ByteBuffer
class AudioPlayerSendHandler(
private val audioPlayer: AudioPlayer
) : AudioSendHandler {
private val buffer = ByteBuffer.allocate(1024)
private val frame = MutableAudioFrame()
init {
frame.setBuffer(buffer)
}
override fun canProvide(): Boolean {
return audioPlayer.provide(frame)
}
override fun provide20MsAudio(): ByteBuffer {
return buffer.flip()
}
override fun isOpus() = true
}
| 8
| null |
15
| 52
|
121962151284a2f9c8db5094a71aa29b4402712e
| 706
|
vured-bot
|
Apache License 2.0
|
trixnity-core/src/commonMain/kotlin/net/folivo/trixnity/core/serialization/events/StrippedStateEventSerializer.kt
|
benkuly
| 330,904,570
| false
| null |
package net.folivo.trixnity.core.serialization.events
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import mu.KotlinLogging
import net.folivo.trixnity.core.model.events.Event.StrippedStateEvent
import net.folivo.trixnity.core.model.events.StateEventContent
import net.folivo.trixnity.core.serialization.AddFieldsSerializer
import net.folivo.trixnity.core.serialization.canonicalJson
private val log = KotlinLogging.logger {}
class StrippedStateEventSerializer(
private val stateEventContentSerializers: Set<SerializerMapping<out StateEventContent>>,
private val stateEventContentSerializer: StateEventContentSerializer,
) : KSerializer<StrippedStateEvent<*>> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("StrippedStateEventSerializer")
override fun deserialize(decoder: Decoder): StrippedStateEvent<*> {
require(decoder is JsonDecoder)
val jsonObj = decoder.decodeJsonElement().jsonObject
val type = jsonObj["type"]?.jsonPrimitive?.content ?: throw SerializationException("type must not be null")
val isFullyRedacted = jsonObj["content"]?.jsonObject?.isEmpty() == true
val contentSerializer =
StateEventContentSerializer.withRedaction(stateEventContentSerializers, type, isFullyRedacted)
return decoder.json.tryDeserializeOrElse(StrippedStateEvent.serializer(contentSerializer), jsonObj) {
log.warn(it) { "could not deserialize event: $jsonObj" }
StrippedStateEvent.serializer(UnknownStateEventContentSerializer(type))
}
}
override fun serialize(encoder: Encoder, value: StrippedStateEvent<*>) {
require(encoder is JsonEncoder)
val type = stateEventContentSerializers.contentType(value.content)
val jsonElement = encoder.json.encodeToJsonElement(
@Suppress("UNCHECKED_CAST")
AddFieldsSerializer(
StrippedStateEvent.serializer(stateEventContentSerializer) as KSerializer<StrippedStateEvent<*>>,
"type" to type
), value
)
encoder.encodeJsonElement(canonicalJson(jsonElement))
}
}
| 0
| null |
3
| 25
|
607e61dad063037518bcba654a625f218bfb7df9
| 2,589
|
trixnity
|
Apache License 2.0
|
app/src/main/java/com/madonasyombua/sportsdb/ui/theme/Theme.kt
|
Madonahs
| 120,659,933
| false
|
{"Kotlin": 51541}
|
package com.madonasyombua.sportsdb.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
val LightColors = lightColors(
primary = Green700,
primaryVariant = Green900,
onPrimary = Color.White,
secondary = Green700,
secondaryVariant = Green900,
onSecondary = Color.White,
error = Green800,
)
val DarkColors = darkColors(
primary = Green300,
primaryVariant = Green700,
onPrimary = Color.Black,
secondary = Green300,
onSecondary = Color.Black,
error = Green200,
)
@Composable
fun SportsAppTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
MaterialTheme(
content = content,
colors = if (darkTheme) DarkColors else LightColors,
typography = SportsAppTypography
)
}
| 1
|
Kotlin
|
11
| 47
|
52f63ddb4f97b6098fb3be53ceba1de8c4efb947
| 1,015
|
The-Sports-DB
|
Apache License 2.0
|
app/src/main/java/com/puntogris/blint/feature_store/domain/model/CheckableTrader.kt
|
puntogris
| 326,269,924
| false
| null |
package com.puntogris.blint.feature_store.domain.model
data class CheckableTrader(
val trader: Trader,
val isChecked: Boolean
)
| 0
| null |
0
| 1
|
63dcee8de767f8632f3c8a1cf4918f98bc01644d
| 137
|
blint
|
MIT License
|
src/main/kotlin/usecases/user/UpdatePassword.kt
|
ktapi
| 562,243,352
| false
| null |
package usecases.user
import entities.user.Users
import org.ktapi.entities.Validation.lengthAtLeast
import org.ktapi.entities.Validation.validateField
object UpdatePassword {
fun updatePassword(userId: Long, password: String) {
validateField("password", password) { lengthAtLeast(8) }
Users.updatePassword(userId, password)
}
}
| 0
|
Kotlin
|
0
| 0
|
1f2acc29779ed75c24c813f834548cc2ea84c980
| 353
|
ktapi-base
|
The Unlicense
|
viewcomponents/src/main/java/com/afollestad/nocknock/viewcomponents/livedata/ViewLifecycleOwner.kt
|
afollestad
| 64,532,704
| false
| null |
/**
* Designed and developed by <NAME> (@afollestad)
*
* 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.afollestad.nocknock.viewcomponents.livedata
import android.view.View
import android.view.View.OnAttachStateChangeListener
import androidx.lifecycle.Lifecycle.State.CREATED
import androidx.lifecycle.Lifecycle.State.DESTROYED
import androidx.lifecycle.Lifecycle.State.RESUMED
import androidx.lifecycle.Lifecycle.State.STARTED
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.afollestad.nocknock.viewcomponents.R
/** @author <NAME> (@afollestad) */
class ViewLifecycleOwner(view: View) : LifecycleOwner, OnAttachStateChangeListener {
private val lifecycleRegistry = LifecycleRegistry(this)
init {
view.addOnAttachStateChangeListener(this)
}
override fun getLifecycle() = lifecycleRegistry
override fun onViewAttachedToWindow(v: View?) {
lifecycleRegistry.markState(CREATED)
lifecycleRegistry.markState(STARTED)
lifecycleRegistry.markState(RESUMED)
}
override fun onViewDetachedFromWindow(v: View) {
lifecycleRegistry.markState(DESTROYED)
}
}
fun View.lifecycleOwner(): LifecycleOwner {
val tagOwner = getTag(R.id.view_lifecycle_registry) as? ViewLifecycleOwner
return if (tagOwner != null) {
tagOwner
} else {
val newOwner = ViewLifecycleOwner(this)
setTag(R.id.view_lifecycle_registry, newOwner)
newOwner
}
}
| 14
|
Kotlin
|
68
| 375
|
23ba4a69cd2b91cb2cb348a1dccf9107f4c516f9
| 1,950
|
nock-nock
|
Apache License 2.0
|
src/commonTest/kotlin/IntegrationTests.kt
|
mtorials
| 272,526,016
| false
| null |
import de.mtorials.dialphone.DialPhone
import de.mtorials.dialphone.dialevents.MessageReceivedEvent
import de.mtorials.dialphone.dialevents.RoomInviteEvent
import de.mtorials.dialphone.dialevents.answer
import de.mtorials.dialphone.entities.entityfutures.RoomFuture
import de.mtorials.dialphone.listener.Command
import de.mtorials.dialphone.listener.ListenerAdapter
import de.mtorials.dialphone.listener.MessageListener
import de.mtorials.dialphone.listener.listenFor
import de.mtorials.dialphone.model.mevents.MatrixEvent
import de.mtorials.dialphone.model.mevents.roommessage.MRoomMessage
import de.mtorials.dialphone.sendTextMessage
import kotlinx.coroutines.cancelChildren
import kotlin.test.assertEquals
class IntegrationTests {
private val roomId = "!YIqYutrrBUdGDombnI:mtorials.de"
private val testString = "asidh983h54lkwnef"
suspend fun basicTestWithToken(config: Config) {
println("hello")
val phone = DialPhone {
withToken(config.token)
homeserverUrl = config.homeserverUrl
addListeners(
listenFor(MRoomMessage::class) { event, roomId ->
this.getJoinedRoomFutureById(roomId)?.sendTextMessage(event.sender)
},
object : ListenerAdapter(receivePastEvents = true) {
override suspend fun onRoomInvite(event: RoomInviteEvent) { event.invitedRoomActions.join() }
}
)
afterInitialSync { phone ->
println("Inital sync!")
//phone.getJoinedRoomFutures().map { it.receive() }.forEach { phone.getJoinedRoomFutureById(roomId)?.sendTextMessage(it.name) }
}
}
println("created dialphone")
val job = phone.syncAndReturnJob()
phone.addListener(MessageListener(false) {
println(it.message.body)
assertEquals(testString, it.message.body)
it.message.redact("Test")
phone.stop()
}
)
println("Sending msg")
val room: RoomFuture = phone.getJoinedRoomFutureById(roomId) ?: error("Room not found")
// Test room info
assertEquals("[Demo] Manuell", room.receive().name)
assertEquals("@mtorials:mtorials.de", phone.getUserById("@mtorials:mtorials.de")?.id)
room.sendTextMessage(testString)
job.join()
}
suspend fun botTest(config: Config) {
val phone = DialPhone {
withToken(config.token)
homeserverUrl = config.homeserverUrl
bot {
commandPrefix = "&"
generateHelp()
commands(
Command("ping") { params ->
this answer params[0]
}
)
}
}
phone.sync()
}
}
| 7
|
Kotlin
|
0
| 5
|
59b768644894e17f703b9d27578a744d4e9f281c
| 2,859
|
dial-phone
|
Apache License 2.0
|
example/server/src/main/kotlin/cc/scrambledbytes/sse/plugins/Routing.kt
|
scrambledbytes
| 632,011,987
| false
|
{"Kotlin": 47189, "Shell": 295}
|
package cc.scrambledbytes.sse.plugins
import cc.scrambledbytes.sse.debugTrace
import io.ktor.http.*
import io.ktor.http.HttpStatusCode.Companion.Unauthorized
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.delay
fun Application.configureRouting() {
routing {
get("/sse") {
call.response.cacheControl(CacheControl.NoCache(null))
try {
debugTrace("Responding")
call.respondTextWriter(contentType = ContentType.Text.EventStream) {
while (true) {
delay(3_000)
val event = RandomSseEvent()
debugTrace("Writing $event")
write("id: ${event.id}\n")
write("event: ${event.type}\n")
write("data: ${event.data}\n") // TODO multiline data
write("\n")
flush()
}
}
} catch (e: Exception) {
debugTrace("Channel closed: ${e.message}")
} finally {
debugTrace("Shutting down channel")
}
}
get("/sse-401") {
call.respond(Unauthorized)
}
get("/sse-301") {
call.respondRedirect("/sse", permanent = true)
}
get("/sse-500") {
throw IllegalArgumentException("Test")
}
}
}
var count: Int = 0
fun RandomSseEvent(): SseEvent {
return SseEvent(id = count++, type = "test", data = "data - ${System.currentTimeMillis()}")
}
data class SseEvent(
val id: Int,
val type: String,
val data: String,
)
| 0
|
Kotlin
|
0
| 0
|
b730408ff96b3d10f6a79760f4f660ed033a3fc1
| 1,751
|
kmp-sse
|
Apache License 2.0
|
src/main/kotlin/io/github/leandroborgesferreira/dagcommand/domain/Node.kt
|
leandroBorgesFerreira
| 268,720,218
| false
|
{"Kotlin": 45712}
|
package com.github.leandroborgesferreira.dagcommand.domain
data class Node(val name: String, var buildStage: Int, val instability: Double)
| 6
|
Kotlin
|
9
| 39
|
ef7c97e4b2691c9d16953b35dfdd0bdb8691d841
| 140
|
dag-command
|
Apache License 2.0
|
app/src/main/java/com/siju/acexplorer/di/SortModeModule.kt
|
siju-s
| 427,592,750
| false
| null |
package com.siju.acexplorer.di
import android.content.Context
import androidx.preference.PreferenceManager
import com.siju.acexplorer.common.SortModeData
import dagger.Module
import dagger.Provides
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.migration.DisableInstallInCheck
@Module
@DisableInstallInCheck
object SortModeModule {
@Provides
fun getSortModeInfo(@ApplicationContext context: Context) =
SortModeData(PreferenceManager.getDefaultSharedPreferences(context))
}
| 4
|
Kotlin
|
5
| 2
|
68338f005f8365609f115390e7d770197b807763
| 520
|
AceExplorer
|
Apache License 2.0
|
src/main/kotlin/cn/lkgc/jjl/controller/vo/globalnews/GlobalNewsFrontRespVO.kt
|
mirrorb
| 862,651,819
| false
|
{"Kotlin": 144419, "Java": 24940, "Batchfile": 123}
|
package cn.lkgc.jjl.controller.vo.globalnews
import com.fasterxml.jackson.annotation.JsonFormat
import java.io.Serializable
import java.time.LocalDateTime
data class GlobalNewsFrontRespVO(
var newsName: String? = null,
var picture: String? = null,
var description: String? = null,
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
var createTime: LocalDateTime? = null,
) : Serializable
| 0
|
Kotlin
|
0
| 1
|
8b2d574c2cfb97a01e6f9868ab80c77f444d7924
| 424
|
jjl-housekeeping
|
Apache License 2.0
|
validable/src/main/java/tech/devscast/validable/NotBlankValidable.kt
|
devscast
| 433,571,968
| false
|
{"Kotlin": 53661, "Shell": 41}
|
package tech.devscast.validable
/**
* Validates that the value is not blank - neither empty string nor whitespace are valid
*/
class NotBlankValidable(message: String? = null) : BaseValidable(
validator = { value -> value.isNotBlank() },
errorFor = { _ ->
message ?: "This field cannot be blank"
}
)
| 0
|
Kotlin
|
5
| 31
|
d2df31ff136dc5baaa05819d5d21d489c0ddedb1
| 324
|
validable
|
Apache License 2.0
|
backend/services/auth-service/src/main/kotlin/com/puconvocation/database/mongodb/MongoDBConnector.kt
|
mihirpaldhikar
| 796,559,467
| false
|
{"Kotlin": 78495, "TypeScript": 47349, "CSS": 2258, "JavaScript": 1477}
|
/*
* Copyright (c) PU Convocation Management System Authors
*
* This software is owned by PU Convocation Management System Authors.
* No part of the software is allowed to be copied or distributed
* in any form. Any attempt to do so will be considered a violation
* of copyright law.
*
* This software is protected by copyright law and international
* treaties. Unauthorized copying or distribution of this software
* is a violation of these laws and could result in severe penalties.
*/
package com.puconvocation.database.mongodb
import com.mongodb.kotlin.client.coroutine.MongoClient
import com.mongodb.kotlin.client.coroutine.MongoDatabase
class MongoDBConnector(
private val connectionURL: String,
private val database: String,
) {
fun connectToDatabase(): MongoDatabase {
val mongoClient: MongoClient = MongoClient.create(connectionURL)
return mongoClient.getDatabase(database)
}
}
| 0
|
Kotlin
|
0
| 0
|
45c4dd87f8cc0312373deb948f44a691c1bef44a
| 932
|
pu-convocation
|
Freetype Project License
|
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/start/innlesning/barnetrygd/monitorering/MicrometerStatusMalere.kt
|
navikt
| 593,529,397
| false
|
{"Kotlin": 207247, "HTML": 6035, "Dockerfile": 181}
|
package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.monitorering
import io.micrometer.core.instrument.Gauge
import io.micrometer.core.instrument.MeterRegistry
import org.slf4j.LoggerFactory
class MicrometerStatusMalere(registry: MeterRegistry) {
private val log = LoggerFactory.getLogger(this::class.java)
private var status: ApplicationStatus? = null
init {
Gauge
.builder("pensjonopptjening_applikasjonsstatus_ok") { antallOk() }
.tag("status", "ok")
.register(registry)
Gauge
.builder("pensjonopptjening_applikasjonsstatus_feil") { antallFeil() }
.tag("status", "feil")
.tag("feilmelding", feilmelding())
.register(registry)
Gauge
.builder("pensjonopptjening_applikasjonsstatus_ukjent") { antallMangler() }
.tag("status", "ukjent")
.register(registry)
// TODO: skrive om til å bli penere + test
Gauge
.builder("pensjonopptjening_applikasjonsstatus_sum") { antallOk() + antallFeil() + antallMangler() }
.tag("status", "ukjent")
.register(registry)
Gauge
.builder("pensjonopptjening_applikasjonsstatus_kode") { statusKode() }
.tag("status", status?.toString() ?: "null")
.register(registry)
}
fun oppdater(status: ApplicationStatus) {
log.info("Oppdaterer applikasjonsstatus til: $status")
this.status = status
status
}
fun antallOk(): Int {
return if (status == ApplicationStatus.OK) 9 else 0
}
fun antallFeil(): Int {
return if (status is ApplicationStatus.Feil) 10 else 0
}
fun statusKode(): Int {
return when (status) {
null -> 0
is ApplicationStatus.OK -> 1
is ApplicationStatus.IkkeKjort -> 2
is ApplicationStatus.Feil -> 3
}
}
fun antallMangler(): Int {
if (status == null) log.warn("applikasjonsstatus har ikke blitt satt")
val mangler = (status == null || status is ApplicationStatus.IkkeKjort)
return if (mangler) 1 else 0
}
fun feilmelding(): String {
val status = this.status
return if (status is ApplicationStatus.Feil) status.feil else ""
}
}
| 1
|
Kotlin
|
1
| 0
|
db23a94e4e42a9b496318c09bfe27bb79ab057b6
| 2,342
|
omsorgsopptjening-start-innlesning
|
MIT License
|
app/src/main/java/com/project/taewon/googlesearch/repository/SearchRepository.kt
|
TktkOkym
| 165,012,706
| false
| null |
package com.project.taewon.googlesearch.repository
import com.project.taewon.googlesearch.BuildConfig
import com.project.taewon.googlesearch.db.dao.ItemListDao
import com.project.taewon.googlesearch.db.tables.ImageItem
import com.project.taewon.googlesearch.network.response.SearchResponse
import com.project.taewon.googlesearch.network.ApiServices
import retrofit2.Response
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SearchRepository @Inject
constructor(private val services: ApiServices, private val itemListDao: ItemListDao) {
suspend fun getSearchImage(query: String, searchType: String, offset: Int): Response<SearchResponse> {
return services.getSearchImageAsync(BuildConfig.API_KEY, BuildConfig.CX_ID, query, searchType, offset, 0).await()
}
// For Room DB
fun getItemListFromDb() = itemListDao.getAllSneakers()
fun insertItemToDb(item: ImageItem) = itemListDao.insert(item)
fun deleteAllFromDb() = itemListDao.deleteAll()
}
| 0
|
Kotlin
|
1
| 1
|
510f092921748e57ab154f6ed285609b024e15c1
| 998
|
AndroidJetpackGoogleSearch
|
Apache License 2.0
|
kotlin-utils/src/main/kotlin/xyz/lbres/kotlinutils/int/ext/IntExt.kt
|
lbressler13
| 507,666,582
| false
|
{"Kotlin": 326012}
|
package xyz.lbres.kotlinutils.int.ext
import xyz.lbres.kotlinutils.general.simpleIf
/**
* Returns this number if not zero, or the result of calling [getDefaultValue] if it is.
*
* @param getDefaultValue () -> [Int]
* @return [Int] the current value, or the default
*/
fun Int.ifZero(getDefaultValue: () -> Int): Int = simpleIf(isZero(), getDefaultValue(), this)
/**
* Unary check to determine if value is zero
*
* @return [Boolean]: true if value is zero, false otherwise
*/
fun Int.isZero(): Boolean = equals(0)
/**
* Unary check to determine if value is negative
*
* @return [Boolean]: true if value is less than zero, false otherwise
*/
fun Int.isNegative(): Boolean = this < 0
| 1
|
Kotlin
|
0
| 1
|
865c0dcdc548a4d4a9d0f5c53f14a611696dba76
| 698
|
kotlin-utils
|
MIT License
|
appverifier/src/main/java/com/android/mdl/appreader/readercertgen/ReaderCertificateGenerator.kt
|
openwallet-foundation-labs
| 248,844,077
| false
| null |
package com.android.mdl.appreader.readercertgen
import com.android.identity.crypto.Algorithm
import com.android.identity.crypto.Certificate
import com.android.identity.crypto.EcPrivateKey
import com.android.identity.crypto.javaPrivateKey
import com.android.identity.crypto.javaPublicKey
import com.android.identity.crypto.javaX509Certificate
import com.android.mdl.appreader.readercertgen.CertificateGenerator.generateCertificate
import org.bouncycastle.asn1.x509.KeyUsage
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.math.BigInteger
import java.security.InvalidAlgorithmParameterException
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.NoSuchAlgorithmException
import java.security.PrivateKey
import java.security.cert.X509Certificate
import java.security.spec.ECGenParameterSpec
import java.util.Optional
/**
* Generates a key pair for a specific curve, creates a reader certificate around it using
* the given issuing CA certificate and private key to sign it.
*
*
* Usage:
* final KeyPair readerKeyPair = generateECDSAKeyPair(curve);
* X509Certificate dsCertificate = createReaderCertificate(readerKeyPair, iacaCertificate, iacaKeyPair.getPrivate());
*/
object ReaderCertificateGenerator {
fun generateECDSAKeyPair(curve: String): KeyPair {
return try {
// NOTE older devices may not have the right BC installed for this to work
val kpg: KeyPairGenerator
if (listOf("Ed25519", "Ed448").any { it.equals(curve, ignoreCase = true) }) {
kpg = KeyPairGenerator.getInstance(curve, BouncyCastleProvider())
} else {
kpg = KeyPairGenerator.getInstance("EC", BouncyCastleProvider())
kpg.initialize(ECGenParameterSpec(curve))
}
println(kpg.provider.info)
kpg.generateKeyPair()
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
} catch (e: InvalidAlgorithmParameterException) {
throw RuntimeException(e)
}
}
fun createReaderCertificate(
readerKey: EcPrivateKey, //dsKeyPair: KeyPair,
readerRootCert: Certificate, // issuerCert: X509Certificate,
readerRootKey: EcPrivateKey // issuerPrivateKey: PrivateKey
): X509Certificate {
val data = DataMaterial(
subjectDN = "C=UT, CN=OWF Identity Credential mDoc Reader",
// must match DN of issuer character-by-character
// TODO change for other generators
issuerDN = readerRootCert.javaX509Certificate.subjectX500Principal.name,
// reorders string, do not use
// return issuerCert.getSubjectX500Principal().getName();
// NOTE always interpreted as URL for now
issuerAlternativeName = Optional.of("https://www.google.com/")
)
val certData = CertificateMaterial(
// TODO change
serialNumber = BigInteger("476f6f676c655f546573745f44535f31", 16),
startDate = readerRootCert.javaX509Certificate.notBefore,
endDate = readerRootCert.javaX509Certificate.notAfter,
pathLengthConstraint = CertificateMaterial.PATHLENGTH_NOT_A_CA,
keyUsage = KeyUsage.digitalSignature,
// TODO change for reader cert
extendedKeyUsage = Optional.of("1.0.18013.5.1.6")
)
val signingAlgorithm = when (readerRootKey.curve.defaultSigningAlgorithm) {
Algorithm.ES256 -> "SHA256withECDSA"
Algorithm.ES384 -> "SHA384withECDSA"
Algorithm.ES512 -> "SHA512withECDSA"
else -> throw IllegalStateException("Unsupported algorithm for reader root")
}
val keyData = KeyMaterial(
publicKey = readerKey.publicKey.javaPublicKey,
signingAlgorithm = signingAlgorithm,
signingKey = readerRootKey.javaPrivateKey,
issuerCertificate = Optional.of(readerRootCert.javaX509Certificate)
)
// C.1.7.2
return generateCertificate(data, certData, keyData)
}
}
| 99
| null |
83
| 163
|
e6bf25766985521b9a39d4ed7999f22d57064db5
| 4,128
|
identity-credential
|
Apache License 2.0
|
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/ForbiddenImport.kt
|
hcknl
| 158,261,983
| true
|
{"Kotlin": 1062676, "Groovy": 3620, "Shell": 1710, "HTML": 698}
|
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.SplitPattern
import org.jetbrains.kotlin.psi.KtImportDirective
/**
* This rule allows to set a list of forbidden imports. This can be used to discourage the use of unstable, experimental
* or deprecated APIs. Detekt will then report all imports that are forbidden.
*
* <noncompliant>
* package foo
* import kotlin.jvm.JvmField
* import kotlin.SinceKotlin
* </noncompliant>
*
* @configuration imports - imports which should not be used (default: '')
*
* @author <NAME>
* @author <NAME>
*/
class ForbiddenImport(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName, Severity.Style,
"Mark forbidden imports. A forbidden import could be an import for an unstable / experimental api" +
"and hence you might want to mark it as forbidden in order to get warned about the usage.", Debt.TEN_MINS)
private val forbiddenImports = SplitPattern(valueOrDefault(IMPORTS, ""))
override fun visitImportDirective(importDirective: KtImportDirective) {
super.visitImportDirective(importDirective)
val import = importDirective.importedFqName?.asString() ?: ""
if (forbiddenImports.contains(import)) {
report(CodeSmell(issue, Entity.from(importDirective), "The import " +
"$import has been forbidden in the Detekt config."))
}
}
companion object {
const val IMPORTS = "imports"
}
}
| 1
|
Kotlin
|
0
| 1
|
565d86d780c15ade77b5468a9e342ba334181333
| 1,862
|
detekt
|
Apache License 2.0
|
modules/kilua-tempus-dominus/src/commonMain/kotlin/dev/kilua/form/time/AbstractRichDateTime.kt
|
rjaros
| 706,876,956
| false
| null |
/*
* Copyright (c) 2023 Robert Jaros
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.kilua.form.time
import androidx.compose.runtime.Composable
import androidx.compose.runtime.NoLiveLiterals
import dev.kilua.core.DefaultRenderConfig
import dev.kilua.core.RenderConfig
import dev.kilua.externals.Date
import dev.kilua.externals.Intl
import dev.kilua.externals.TempusDominus
import dev.kilua.externals.TempusDominusOptions
import dev.kilua.externals.obj
import dev.kilua.externals.set
import dev.kilua.externals.tempusDominusLocales
import dev.kilua.externals.toDate
import dev.kilua.form.text.text
import dev.kilua.html.Div
import dev.kilua.html.i
import dev.kilua.html.span
import dev.kilua.i18n.DefaultLocale
import dev.kilua.i18n.Locale
import dev.kilua.utils.isDom
import dev.kilua.utils.jsObjectOf
import dev.kilua.utils.toJsArray
import dev.kilua.utils.toKebabCase
import kotlinx.datetime.LocalDate
import web.document
import web.dom.events.Event
import web.toJsNumber
import web.toJsString
import kotlin.time.Duration
/**
* Tempus Dominus component color themes.
*/
public enum class Theme {
Light,
Dark,
Auto;
public val value: String = name.toKebabCase()
override fun toString(): String {
return value
}
}
/**
* Tempus Dominus component view modes.
*/
public enum class ViewMode {
Clock,
Calendar,
Months,
Years,
Decades;
public val value: String = name.toKebabCase()
override fun toString(): String {
return value
}
}
/**
* Tempus Dominus component toolbar placements.
*/
public enum class ToolbarPlacement {
Top,
Bottom;
public val value: String = name.toKebabCase()
override fun toString(): String {
return value
}
}
/**
* Tempus Dominus component month header format.
*/
public enum class MonthHeaderFormat(public val value: String) {
TWODIGIT("2-digit"),
NUMERIC("numeric"),
NARROW("narrow"),
SHORT("short"),
LONG("long");
override fun toString(): String {
return value
}
}
/**
* Tempus Dominus component year header format.
*/
public enum class YearHeaderFormat(public val value: String) {
TWODIGIT("2-digit"),
NUMERIC("numeric");
override fun toString(): String {
return value
}
}
/**
* Tempus Dominus abstract rich date time component.
*/
public abstract class AbstractRichDateTime(
disabled: Boolean? = null,
format: String,
inline: Boolean = false,
locale: Locale = DefaultLocale(),
className: String? = null,
renderConfig: RenderConfig = DefaultRenderConfig(),
) : Div(className, renderConfig = renderConfig) {
/**
* The date/time format.
*/
public open var format: String by updatingProperty(format, skipUpdate = skipUpdate) {
refresh()
}
/**
* Date/time format with auto-detected hour cycle.
*/
internal val inputFormat: String
get() {
val hourCycle = guessHourCycle(locale.language)
return if (hourCycle == HourCycle.H11 || hourCycle == HourCycle.H12) {
format.replace("HH:mm:ss", "hh:mm:ss T").replace("HH:mm", "hh:mm T")
} else format
}
/**
* Inline also modifies the layout, so it is not exposed as a public property.
*/
internal open var inline: Boolean by updatingProperty(inline, skipUpdate = skipUpdate) {
refresh()
}
/**
* The locale for i18n.
*/
public open var locale: Locale by updatingProperty(locale, skipUpdate = skipUpdate) {
refresh()
}
/**
* Determines if the component is disabled.
*/
public open var disabled: Boolean? by updatingProperty(disabled, skipUpdate = skipUpdate) {
if (it == true) {
tempusDominusInstance?.disable()
} else {
tempusDominusInstance?.enable()
}
}
/**
* Determines if the component is required.
*/
public open var required: Boolean? by updatingProperty(skipUpdate = skipUpdate)
/**
* The component name.
*/
public open var name: String? by updatingProperty(skipUpdate = skipUpdate)
/**
* The component custom validity message.
*/
public open var customValidity: String? by updatingProperty(skipUpdate = skipUpdate)
/**
* Days of the week that should be disabled.
*/
public open var daysOfWeekDisabled: List<Int>? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Determines if *Clear* button should be visible.
*/
public open var showClear: Boolean by updatingProperty(true, skipUpdate = skipUpdate) {
refresh()
}
/**
* Determines if *Close* button should be visible.
*/
public open var showClose: Boolean by updatingProperty(true, skipUpdate = skipUpdate) {
refresh()
}
/**
* Determines if *Today* button should be visible.
*/
public open var showToday: Boolean by updatingProperty(true, skipUpdate = skipUpdate) {
refresh()
}
/**
* The increment used to build the hour view.
*/
public open var stepping: Int by updatingProperty(1, skipUpdate = skipUpdate) {
refresh()
}
/**
* Prevents date selection before this date.
*/
public open var minDate: LocalDate? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Prevents date selection after this date.
*/
public open var maxDate: LocalDate? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Shows date and time pickers side by side.
*/
public open var sideBySide: Boolean by updatingProperty(false, skipUpdate = skipUpdate) {
refresh()
}
/**
* A list of enabled dates.
*/
public open var enabledDates: List<LocalDate>? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* A list of disabled dates.
*/
public open var disabledDates: List<LocalDate>? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Keep the popup open after selecting a date.
*/
public open var keepOpen: Boolean by updatingProperty(false, skipUpdate = skipUpdate) {
refresh()
}
/**
* Date/time chooser color theme.
*/
public open var theme: Theme? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Automatically open the chooser popup.
*/
public var allowInputToggle: Boolean by updatingProperty(true, skipUpdate = skipUpdate) {
refresh()
}
/**
* The view date of the date/time chooser.
*/
public open var viewDate: LocalDate? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Automatically open time component after date is selected.
*/
public open var promptTimeOnDateChange: Boolean by updatingProperty(false, skipUpdate = skipUpdate) {
refresh()
}
/**
* The delay for the time component opening after date is selected.
*/
public open var promptTimeOnDateChangeTransitionDelay: Duration? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Default view mode of the date/time chooser.
*/
public open var viewMode: ViewMode? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Date/time chooser toolbar placement.
*/
public open var toolbarPlacement: ToolbarPlacement? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Date/time chooser month header format.
*/
public open var monthHeaderFormat: MonthHeaderFormat? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* Date/time chooser year header format.
*/
public open var yearHeaderFormat: YearHeaderFormat? by updatingProperty(skipUpdate = skipUpdate) {
refresh()
}
/**
* The refresh callback used by the theme change event handler.
*/
protected var refreshCallback: (Event) -> Unit = {
refresh()
}
override fun onInsert() {
initializeTempusDominus()
if (isDom) {
document.addEventListener("kilua.theme.changed", refreshCallback)
}
}
override fun onRemove() {
tempusDominusInstance?.dispose()
tempusDominusInstance = null
if (isDom) {
document.removeEventListener("kilua.theme.changed", refreshCallback)
}
}
/**
* Re-creates the Tempus Dominus instance.
*/
protected fun refresh() {
if (tempusDominusInstance != null) {
tempusDominusInstance?.dispose()
initializeTempusDominus()
}
}
/**
* The Tempus Dominus instance.
*/
protected var tempusDominusInstance: TempusDominus? = null
protected abstract fun initializeTempusDominus()
/**
* Initializes the Tempus Dominus instance.
*/
@NoLiveLiterals
protected fun initializeTempusDominus(defaultValue: Date?, calendarView: Boolean, clockView: Boolean) {
if (renderConfig.isDom) {
val secondsView = format.contains("ss")
val language = locale.language
val locale = tempusDominusLocales[language]?.localization ?: obj()
locale["locale"] = language.toJsString()
locale["format"] = inputFormat.toJsString()
if (monthHeaderFormat != null || yearHeaderFormat != null) {
locale["dayViewHeaderFormat"] = jsObjectOf(
"month" to if (monthHeaderFormat != null) monthHeaderFormat!!.value else "long",
"year" to if (yearHeaderFormat != null) yearHeaderFormat!!.value else "2-digit"
)
}
val initialViewMode = viewMode ?: if (calendarView) ViewMode.Calendar else ViewMode.Clock
val currentTheme = if (theme == null || theme == Theme.Auto) {
document.documentElement?.getAttribute("data-bs-theme")?.let { theme ->
Theme.entries.find { theme == it.value }
}
} else {
theme
}
val component = this
val tempusDominusOptions = obj<TempusDominusOptions> {
this.useCurrent = component.inline
if (defaultValue != null) {
this.defaultDate = defaultValue
}
this.stepping = component.stepping
this.allowInputToggle = component.allowInputToggle
if (component.viewDate != null) {
this.viewDate = component.viewDate!!.toDate()
} else {
if (inline && defaultValue != null) this.viewDate = defaultValue
}
this.promptTimeOnDateChange = component.promptTimeOnDateChange
if (component.promptTimeOnDateChangeTransitionDelay != null)
this.promptTimeOnDateChangeTransitionDelay =
component.promptTimeOnDateChangeTransitionDelay!!.inWholeMilliseconds.toInt()
this.restrictions = obj {
if (component.minDate != null) this.minDate = component.minDate!!.toDate()
if (component.maxDate != null) this.maxDate = component.maxDate!!.toDate()
if (!component.enabledDates.isNullOrEmpty()) this.enabledDates =
component.enabledDates!!.map { it.toDate() }.toJsArray()
if (!component.disabledDates.isNullOrEmpty()) this.disabledDates =
component.disabledDates!!.map { it.toDate() }.toJsArray()
if (!component.daysOfWeekDisabled.isNullOrEmpty()) this.daysOfWeekDisabled =
component.daysOfWeekDisabled!!.map { it.toJsNumber() }.toJsArray()
}
this.display = obj {
this.viewMode = initialViewMode.value
component.toolbarPlacement?.let { this.toolbarPlacement = it.value }
this.sideBySide = component.sideBySide
this.buttons = obj {
this.clear = component.showClear
this.close = component.showClose
this.today = component.showToday
}
this.inline = component.inline
this.keepOpen = component.keepOpen
currentTheme?.let { this.theme = it.value }
this.components = obj {
this.calendar = calendarView
this.clock = clockView
this.seconds = secondsView
}
}
this.localization = locale
}
tempusDominusInstance = TempusDominus(element, tempusDominusOptions)
if (disabled == true) {
tempusDominusInstance?.disable()
}
}
}
public companion object {
/**
* Time format hour cycle.
*/
private enum class HourCycle {
H11, H12, H23, H24
}
/**
* Tries to guess the hour cycle for given language.
*/
private fun guessHourCycle(language: String): HourCycle? {
val template = jsObjectOf("hour" to "numeric")
val hourCycle = Intl.DateTimeFormat(language, template).resolvedOptions().hourCycle
return HourCycle.entries.find { it.name.lowercase() == hourCycle }
}
}
}
/**
* Internal helper function.
*/
@Composable
internal fun Div.commonRichDateTime(
bindId: String,
name: String?,
placeholder: String?,
disabled: Boolean?,
required: Boolean?,
id: String?,
inline: Boolean,
icon: String
) {
this.id = bindId
setAttribute("data-td-target-input", "nearest")
setAttribute("data-td-target-toggle", "nearest")
text(
name = name,
placeholder = placeholder,
disabled = disabled,
required = required,
id = id,
className = "form-control"
) {
visible = !inline
setAttribute("data-td-target", "#$bindId")
onChange {
it.stopPropagation()
}
}
span("input-group-text") {
visible = !inline
setAttribute("data-td-target", "#$bindId")
setAttribute("data-td-toggle", "datetimepicker")
i(icon) {}
}
}
| 0
| null |
2
| 78
|
258bc5dcfa21c3728aa92a3897bb3766855732c0
| 15,634
|
kilua
|
MIT License
|
models/src/main/java/com/vimeo/networking2/Video.kt
|
Geet2312
| 261,973,040
| false
|
{"Java Properties": 2, "Ruby": 3, "YAML": 3, "Gradle": 11, "Shell": 2, "Markdown": 7, "Batchfile": 1, "Text": 1, "Gemfile.lock": 1, "Ignore List": 6, "Git Config": 1, "Kotlin": 258, "XML": 30, "Proguard": 3, "Java": 37}
|
@file:JvmName("VideoUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
import com.vimeo.networking2.common.Entity
import com.vimeo.networking2.enums.LicenseType
import com.vimeo.networking2.enums.VideoStatusType
import com.vimeo.networking2.enums.asEnum
import java.io.Serializable
import java.util.Date
/**
* Video data.
*/
@JsonClass(generateAdapter = true)
data class Video(
/**
* Information for the video's badge.
*/
@Json(name = "badge")
val badge: VideoBadge? = null,
/**
* The categories to which this video belongs.
*/
@Json(name = "categories")
val categories: List<Category>? = null,
/**
* The content ratings of this video.
*/
@Json(name = "content_rating")
val contentRating: List<String>? = null,
/**
* The context of the video's subscription, if this video is part of a subscription.
*/
@Json(name = "context")
val context: VideoContext? = null,
/**
* The time in ISO 8601 format when the video was created.
*/
@Json(name = "created_time")
val createdTime: Date? = null,
/**
* A brief explanation of the video's content.
*/
@Json(name = "description")
val description: String? = null,
/**
* The video's duration in seconds.
*/
@Json(name = "duration")
val duration: Int? = null,
/**
* Information about embedding this video.
*/
@Json(name = "embed")
val embed: VideoEmbed? = null,
/**
* The video's height in pixels.
*/
@Json(name = "height")
val height: Int? = null,
/**
* The video's primary language.
*/
@Json(name = "language")
val language: String? = null,
/**
* The time in ISO 8601 format when the user last modified the video.
*/
@Json(name = "last_user_action_event_date")
val lastUserActionEventDate: Date? = null,
/**
* The Creative Commons license used for the video.
* @see Video.licenseType
*/
@Json(name = "license")
val license: String? = null,
/**
* The link to the video.
*/
@Json(name = "link")
val link: String? = null,
/**
* Live playback information.
*/
@Json(name = "live")
val live: Live? = null,
/**
* The video's metadata.
*/
@Json(name = "metadata")
val metadata: Metadata<VideoConnections, VideoInteractions>? = null,
/**
* The time in ISO 8601 format when the video metadata was last modified.
*/
@Json(name = "modified_time")
val modifiedTime: Date? = null,
/**
* The video's title.
*/
@Json(name = "name")
val name: String? = null,
/**
* The privacy-enabled password to watch this video.
* This data requires a bearer token with the private scope.
*/
@Internal
@Json(name = "password")
val password: String? = null,
/**
* The active picture for this video.
*/
@Json(name = "pictures")
val pictures: PictureCollection? = null,
/**
* The Play representation.
*/
@Internal
@Json(name = "play")
val play: Play? = null,
/**
* The video's privacy setting.
*/
@Json(name = "privacy")
val privacy: Privacy? = null,
/**
* The time in ISO 8601 format when the video was released.
*/
@Json(name = "release_time")
val releaseTime: Date? = null,
/**
* The resource key string of the video.
*/
@Json(name = "resource_key")
val resourceKey: String? = null,
/**
* Information about the review page associated with this video. This data requires a
* bearer token with the private scope.
*/
@Internal
@Json(name = "review_page")
val reviewPage: ReviewPage? = null,
/**
* Information about the file transfer page associated with this video. This data
* requires a bearer token with the private scope.
*/
@Internal
@Json(name = "file_transfer")
val fileTransferPage: FileTransferPage? = null,
/**
* 360 spatial data.
*/
@Json(name = "spatial")
val spatial: Spatial? = null,
/**
* A collection of stats associated with this video.
*/
@Json(name = "stats")
val stats: VideoStats? = null,
/**
* The status code for the availability of the video. This field is deprecated in favor
* of [upload] and [transcode].
* @see Video.statusType
*/
@Json(name = "status")
@Deprecated("This property is deprecated in favor of upload and transcode.")
val status: String? = null,
/**
* An array of all tags assigned to this video.
*/
@Json(name = "tags")
val tags: List<Tag>? = null,
/**
* The transcode information for a video upload.
*/
@Json(name = "transcode")
val transcode: Transcode? = null,
/**
* The upload information for this video.
*/
@Json(name = "upload")
val upload: Upload? = null,
/**
* The video's canonical relative URI.
*/
@Json(name = "uri")
val uri: String? = null,
/**
* The video owner.
*/
@Json(name = "user")
val user: User? = null,
/**
* The video's width in pixels.
*/
@Json(name = "width")
val width: Int? = null
) : Entity, Serializable {
override val identifier: String? = resourceKey
companion object {
private const val serialVersionUID = -23L
}
}
/**
* @see Video.license
* @see LicenseType
*/
val Video.licenseType: LicenseType
get() = license.asEnum(LicenseType.UNKNOWN)
/**
* @see Video.status
* @see VideoStatusType
*/
@Deprecated(message = "This property is deprecated in favor of upload and transcode.")
val Video.statusType: VideoStatusType
get() = status.asEnum(VideoStatusType.UNKNOWN)
| 3
| null |
1
| 1
|
d66b4cddd07ff662175488b8f26823c1fbe1bfcf
| 5,918
|
vimeo-networking-java
|
MIT License
|
ground/src/main/java/com/google/android/ground/model/submission/TaskDataDelta.kt
|
gino-m
| 157,787,424
| true
|
{"Gradle": 10, "YAML": 3, "Java Properties": 2, "Markdown": 7, "Shell": 1, "Text": 3, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 116, "JSON": 1, "Proguard": 1, "Kotlin": 355, "Java": 52, "INI": 2, "Python": 1, "SVG": 3}
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.model.submission
import com.google.android.ground.model.task.Task
import java8.util.Optional
/**
* Represents a change to an individual taskData in a submission.
*
* @property taskId the id of the task task being updated.
* @property taskType the type of task being updated.
* @property newTaskData the new value of the taskData, or empty if removed.
*/
data class TaskDataDelta(
val taskId: String,
val taskType: Task.Type,
val newTaskData: Optional<TaskData>
)
| 0
|
Kotlin
|
0
| 2
|
8197bd086e02e5b9b5324e5e63ccc0844db9fd7f
| 1,106
|
ground-android
|
Apache License 2.0
|
backend/entity/src/main/kotlin/ru/itmo/hict/dto/files.kt
|
AlexandrSinitsyn
| 739,110,646
| false
|
{"Kotlin": 229528, "Vue": 50994, "TypeScript": 19979, "Dockerfile": 9102, "SCSS": 4555, "PLpgSQL": 2489, "JavaScript": 883, "HTML": 376}
|
package ru.itmo.hict.dto
import ru.itmo.hict.entity.AttachedFile
import ru.itmo.hict.entity.File
import ru.itmo.hict.entity.SequenceLevelType
import java.util.*
enum class FileType(val bucket: String, val extension: String = bucket) {
HICT("hict", "hict.hdf5"),
MCOOL("mcool"),
AGP("agp"),
TRACKS("tracks", "bed"),
FASTA("fasta")
}
data class FileInfoDto(
val id: UUID,
val filename: String,
val sequenceLevel: SequenceLevelType,
val filesize: Long,
val creationTime: Date
) {
companion object {
fun File.toInfoDto(): FileInfoDto =
FileInfoDto(id!!, filename, sequenceLevel, fileSize, creationTime!!)
fun AttachedFile.toInfoDto(): FileInfoDto = this.file.toInfoDto()
}
}
| 0
|
Kotlin
|
0
| 0
|
382d9ba7d72eb1bc7fdb37f0e37c695a23e9da6c
| 751
|
hict-platform
|
MIT License
|
tokenization/src/main/java/com/paysafe/android/tokenization/data/entity/paymentHandle/profile/DateOfBirthSerializable.kt
|
paysafegroup
| 768,755,663
| false
|
{"Kotlin": 688855, "Shell": 912}
|
/*
* Copyright (c) 2024 Paysafe Group
*/
package com.paysafe.android.tokenization.data.entity.paymentHandle.profile
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal data class DateOfBirthSerializable(
/** Day. */
@SerialName("day")
val day: Int? = null,
/** Month. */
@SerialName("month")
val month: Int? = null,
/** Year. */
@SerialName("year")
val year: Int? = null
)
| 0
|
Kotlin
|
0
| 0
|
1f4e3e9609cf30bb95a52c9e12e2c4250e54f6e5
| 468
|
paysafe_sdk_android_payments_api
|
MIT License
|
features/discover/src/main/java/com/dhorowitz/openmovie/discover/presentation/ui/DiscoverMoviesGrid.kt
|
horowitz
| 328,383,283
| false
| null |
package com.dhorowitz.openmovie.discover.presentation.ui
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.dhorowitz.openmovie.discover.presentation.model.DiscoverAction
import com.dhorowitz.openmovie.discover.presentation.model.DiscoverAction.*
import com.dhorowitz.openmovie.discover.presentation.model.DiscoverViewEntity
@VisibleForTesting
internal const val DISCOVER_MOVIE_GRID_TAG = "DISCOVER_MOVIE_GRID_TAG"
internal const val DISCOVER_MOVIE_GRID_CELL_TAG = "DISCOVER_MOVIE_GRID_CELL_TAG"
@ExperimentalFoundationApi
@Composable
fun DiscoverMoviesGrid(
items: List<DiscoverViewEntity>,
onAction: (DiscoverAction) -> Unit
) {
LazyVerticalGrid(
cells = GridCells.Fixed(3),
contentPadding = PaddingValues(4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.testTag(DISCOVER_MOVIE_GRID_TAG)
) {
itemsIndexed(items) { index, viewEntity ->
if (index == items.lastIndex) {
LaunchedEffect(Unit) { onAction(Load) }
}
Image(
contentScale = ContentScale.Crop,
painter = rememberImagePainter(viewEntity.imageUrl),
contentDescription = null,
modifier = Modifier
.height(200.dp)
.clickable { onAction(ItemClicked(viewEntity)) }
.testTag(DISCOVER_MOVIE_GRID_CELL_TAG)
)
}
}
}
| 5
| null |
8
| 31
|
d103a284a86e4ffc7a8f949ac722f9cc1fc6c3d7
| 2,321
|
openMovie
|
MIT License
|
ktor-core/src/org/jetbrains/ktor/pipeline/Async.kt
|
cbeust
| 64,515,203
| false
| null |
package org.jetbrains.ktor.pipeline
import org.jetbrains.ktor.application.*
import java.util.concurrent.*
fun <C : Any> PipelineContext<C>.runAsync(exec: Executor, block: PipelineContext<C>.() -> Unit): Nothing {
exec.execute {
runBlockWithResult(block)
}
pause()
}
@Deprecated("Use executeOn(executor, defaultHostPipeline) instead")
fun ApplicationCall.execute(): CompletableFuture<PipelineState> = executeOn(application.executor, application)
fun ApplicationCall.executeOn(exec: Executor, pipeline: Pipeline<ApplicationCall>): CompletableFuture<PipelineState> {
val future = CompletableFuture<PipelineState>()
exec.execute {
try {
future.complete(execution.runBlockWithResult {
execution.execute(this@executeOn, pipeline)
})
} catch (t: Throwable) {
future.completeExceptionally(t)
}
}
return future
}
fun <S: Any> PipelineMachine.executeOn(exec: Executor, subject: S, pipeline: Pipeline<S>): CompletableFuture<PipelineState> {
val future = CompletableFuture<PipelineState>()
exec.execute {
try {
future.complete(runBlockWithResult {
execute(subject, pipeline)
})
} catch (t: Throwable) {
future.completeExceptionally(t)
}
}
return future
}
inline fun <C : Any> PipelineContext<C>.runBlock(block: PipelineContext<C>.() -> Unit): Nothing {
try {
try {
block()
} catch (e: PipelineControlFlow) {
throw e
} catch (t: Throwable) {
fail(t)
}
proceed()
} catch (e: PipelineContinue) {
continuePipeline()
}
}
inline fun PipelineMachine.runBlock(block: () -> Unit): Nothing {
try {
try {
block()
} catch (e: PipelineControlFlow) {
throw e
} catch (t: Throwable) {
fail(t)
}
proceed()
} catch (e: PipelineContinue) {
continuePipeline()
}
}
inline fun <C : Any> PipelineContext<C>.runBlockWithResult(block: PipelineContext<C>.() -> Unit): PipelineState {
try {
runBlock(block)
} catch (e: PipelineCompleted) {
return PipelineState.Succeeded
} catch (e: PipelinePaused) {
return PipelineState.Executing
}
}
inline fun PipelineMachine.runBlockWithResult(block: () -> Unit): PipelineState {
try {
runBlock(block)
} catch (e: PipelineCompleted) {
return PipelineState.Succeeded
} catch (e: PipelinePaused) {
return PipelineState.Executing
}
}
fun PipelineContext<*>.continuePipeline(): Nothing {
while (true) {
try {
proceed()
} catch (e: PipelineContinue) {
continue
}
}
}
fun PipelineMachine.continuePipeline(): Nothing {
while (true) {
try {
proceed()
} catch (e: PipelineContinue) {
continue
}
}
}
| 0
| null |
0
| 1
|
8dc7ac666a336cba0f23a72cc31b8c0b14ad4f09
| 2,995
|
ktor
|
Apache License 2.0
|
rider-fsharp/src/main/java/com/jetbrains/rider/ideaInterop/fileTypes/fsharp/FSharpLanguage.kt
|
JetBrains
| 81,554,746
| false
| null |
package com.jetbrains.rider.ideaInterop.fileTypes.fsharp
import com.jetbrains.rider.ideaInterop.fileTypes.RiderLanguageBase
abstract class FSharpLanguageBase(name: String) : RiderLanguageBase(name, name) {
override fun isCaseSensitive() = true
}
object FSharpLanguage : FSharpLanguageBase("F#")
object FSharpScriptLanguage : FSharpLanguageBase("F# Script")
| 46
| null |
55
| 303
|
fbacf8820f2850a3001a16d9b6426d1b380ae763
| 364
|
resharper-fsharp
|
Apache License 2.0
|
data/src/main/java/com/bayarsahintekin/data/entity/teams/TeamListDbData.kt
|
bayarsahintekin0
| 651,000,613
| false
|
{"Kotlin": 244238, "Ruby": 1087}
|
package com.bayarsahintekin.data.entity.teams
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.bayarsahintekin.data.entity.MetaDbData
import com.bayarsahintekin.data.entity.toData
import com.bayarsahintekin.data.mapper.MetaTypeConverter
import com.bayarsahintekin.data.mapper.TeamsConverters
import com.bayarsahintekin.domain.entity.TeamListEntity
@Entity(tableName = "list_response")
data class ListResponseDbData(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@TypeConverters(TeamsConverters::class)
@ColumnInfo(name = "teams")
val data :List<TeamsDbData>,
@ColumnInfo(name = "meta")
@TypeConverters(MetaTypeConverter::class)
val meta: MetaDbData
)
fun ListResponseDbData.toDomain() = TeamListEntity(
data = data.map { it.toData() },
meta = meta.toData()
)
| 0
|
Kotlin
|
0
| 2
|
ce2a5773e311ae67c72a535b9a8ca7421fee84de
| 891
|
MatchScores
|
Open LDAP Public License v2.2.1
|
data/RF01727/rnartist.kts
|
fjossinet
| 449,239,232
| false
|
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01727"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
5 to 6
32 to 33
}
value = "#a04650"
}
color {
location {
7 to 11
26 to 30
}
value = "#6aaddd"
}
color {
location {
14 to 16
21 to 23
}
value = "#96e854"
}
color {
location {
7 to 6
31 to 31
}
value = "#6f6666"
}
color {
location {
12 to 13
24 to 25
}
value = "#76b5f7"
}
color {
location {
17 to 20
}
value = "#d05b9f"
}
color {
location {
1 to 4
}
value = "#1a1561"
}
color {
location {
34 to 54
}
value = "#e30fd3"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3016050675602d506a0e308f07d071abf1524b67
| 1,357
|
Rfam-for-RNArtist
|
MIT License
|
core/datacap-sql/src/test/kotlin/io/edurt/datacap/sql/builder/ColumnBuilderTest.kt
|
devlive-community
| 537,719,266
| false
|
{"Java": 1998447, "Vue": 742066, "Kotlin": 462615, "TypeScript": 217485, "ANTLR": 188268, "Shell": 13094, "JavaScript": 3357, "CSS": 1627, "HTML": 357, "Dockerfile": 329}
|
package io.edurt.datacap.sql.builder
import org.junit.Assert
import org.junit.Test
import org.slf4j.LoggerFactory.getLogger
class ColumnBuilderTest : BaseBuilderTest() {
private val log = getLogger(this.javaClass)
@Test
fun testCreateColumn() {
ColumnBuilder.BEGIN()
ColumnBuilder.CREATE_COLUMN(tableName)
ColumnBuilder.COLUMNS(columns)
log.info("======== Test basic ========")
val sql = ColumnBuilder.SQL()
log.info(sql)
Assert.assertEquals(sql, "ALTER TABLE TestTable\n" +
"ADD COLUMN(\tid int(32) primary key auto_increment,\n" +
"\tname varchar(32) comment 'name',\n" +
"\tage varchar(200) not null default 'xxx')")
}
@Test
fun testDropColumn() {
ColumnBuilder.BEGIN()
ColumnBuilder.DROP_COLUMN(tableName)
ColumnBuilder.COLUMNS(listOf("id"))
log.info("======== Test basic ========")
val sql = ColumnBuilder.SQL()
log.info(sql)
Assert.assertEquals(sql, "ALTER TABLE TestTable\n" +
"DROP COLUMN \tid")
}
@Test
fun testModifyColumn() {
ColumnBuilder.BEGIN()
ColumnBuilder.MODIFY_COLUMN(tableName)
ColumnBuilder.COLUMNS(listOf(columns.get(0)))
log.info("======== Test basic ========")
val sql = ColumnBuilder.SQL()
log.info(sql)
Assert.assertEquals(sql, "ALTER TABLE TestTable\n" +
"MODIFY \tid int(32) primary key auto_increment")
}
}
| 32
|
Java
|
94
| 865
|
1d6be5c990ed3f952bc28699ea15a68b1e2bc265
| 1,529
|
datacap
|
Apache License 2.0
|
app/src/main/java/com/theelitedevelopers/ecommerce/presentation/home/fragments/adapter/ProductAdapter.kt
|
VhiktorBrown
| 548,116,550
| false
|
{"Kotlin": 36931}
|
package com.theelitedevelopers.ecommerce.presentation.home.fragments.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import com.theelitedevelopers.ecommerce.R
import com.theelitedevelopers.ecommerce.databinding.ProductItemBinding
import com.theelitedevelopers.ecommerce.domain.model.Product
import com.theelitedevelopers.ecommerce.presentation.home.productDetail.ProductDetailActivity
import com.theelitedevelopers.ecommerce.utils.Constants
/**
* @created 08/10/2022 - 6:53 PM
* @project Ecommerce app
* @author The Elite Developers
*/
class ProductAdapter(var context : Context, var productList : List<Product>
) : RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val binding : ProductItemBinding = ProductItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ProductViewHolder(binding)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
//set and display details of each product
holder.binding.productName.text = productList[position].name
holder.binding.productPrice.text = productList[position].addPriceSign()
holder.binding.productType.text = productList[position].productType
/**
* Load the Product Image
*
* The images were not loading because
* they didn't have the 'http' prefix.
* So, I added it.
*/
Picasso.get()
.load("http:" +productList[position].featuredImage)
.placeholder(R.drawable.ecommerce)
.into(holder.binding.productImage)
holder.binding.root.setOnClickListener {
val intent = Intent(context, ProductDetailActivity::class.java)
.putExtra(Constants.PRODUCT_DETAIL, productList[position])
context.startActivity(intent)
}
}
@SuppressLint("NotifyDataSetChanged")
fun setList(list : List<Product>){
productList = list
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return productList.size
}
class ProductViewHolder(var binding : ProductItemBinding) : RecyclerView.ViewHolder(binding.root)
}
| 0
|
Kotlin
|
0
| 1
|
0d0fa0b31b527a8f82e584a888cec6014c66c49b
| 2,515
|
e-commerce-app
|
Apache License 2.0
|
kotlinpoet/build/generated/ksp/generationSource/generationSourceMain/kotlin/dev/kord/codegen/kotlinpoet/WithControlFlowCodeBlock.kt
|
kordlib
| 690,695,909
| false
|
{"Kotlin": 181384}
|
package dev.kord.codegen.kotlinpoet
import com.squareup.kotlinpoet.CodeBlock
public fun CodeBlock.Builder.withControlFlow(
controlFlow: String,
vararg args: Any?,
block: CodeBlockBuilderScope,
): CodeBlock.Builder = beginControlFlow(controlFlow, args = args).apply(block).endControlFlow()
| 0
|
Kotlin
|
0
| 9
|
46fc6334bf0f219b29b075178eb548133dd3decb
| 303
|
codegen-kt
|
MIT License
|
TheMovieDBDagger_v3_Animation/app/src/main/java/com/androidavanzado/popcorn/common/Constants.kt
|
miguelcamposedu
| 261,391,292
| false
| null |
package com.androidavanzado.popcorn.common
class Constants {
companion object {
const val EXTRA_PERSON_NAME = "EXTRA_PERSON_NAME"
const val EXTRA_PERSON_PHOTO = "EXTRA_PERSON_PHOTO"
const val EXTRA_PERSON_ID = "EXTRA_PERSON_ID"
const val SHARED_PREFS_FILE: String = "SHARED_PREFERENCES_FILE"
const val TIMEOUT_INMILIS = 30000L
const val TMDBAPI_BASE_URL = "https://api.themoviedb.org/3/"
const val API_KEY = "<KEY>"
const val IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500"
const val URL_PARAM_API_KEY = "api_key"
const val URL_PARAM_LANGUAGE = "language"
}
}
| 0
|
Kotlin
|
0
| 0
|
919c6738203d900c9c96b16f32ba66e915ec266b
| 651
|
kotlinintroduccion
|
MIT License
|
wallet-sdk/src/main/kotlin/org/stellar/walletsdk/horizon/Stellar.kt
|
stellar
| 523,604,257
| false
| null |
package org.stellar.walletsdk.horizon
import java.time.Duration
import kotlin.math.min
import mu.KotlinLogging
import org.stellar.sdk.*
import org.stellar.sdk.responses.SubmitTransactionTimeoutResponseException
import org.stellar.walletsdk.Config
import org.stellar.walletsdk.StellarConfiguration
import org.stellar.walletsdk.anchor.MemoType
import org.stellar.walletsdk.exception.TransactionSubmitFailedException
import org.stellar.walletsdk.exception.ValidationException
import org.stellar.walletsdk.extension.accountOrNull
import org.stellar.walletsdk.horizon.transaction.TransactionBuilder
import org.stellar.walletsdk.util.toTimeBounds
private val log = KotlinLogging.logger {}
class Stellar
internal constructor(
private val cfg: Config,
) {
val server: Server = cfg.stellar.server
fun account(): AccountService {
return AccountService(cfg)
}
/**
* Creates builder that allows to form Stellar transaction, adding Stellar's
* [operations](https://developers.stellar.org/docs/fundamentals-and-concepts/list-of-operations#payment)
*
* @param sourceAddress Stellar address of account initiating a transaction.
* @param baseFee base fee that will be used for this transaction. If not specified [default
* config fee][StellarConfiguration.baseFee] will be used.
* @param timeBounds [Time Bounds](https://developers.stellar.org/docs/glossary#time-bounds) for
* this transaction. If not specified, [default config timeout]
* [StellarConfiguration.defaultTimeout] will be used.
* @param memo optional transaction memo
* @return transaction builder
*/
suspend fun transaction(
sourceAddress: AccountKeyPair,
baseFee: UInt? = null,
memo: Pair<MemoType, String>? = null,
timeBounds: TimeBounds? = null
): TransactionBuilder {
val sourceAccount =
server.accountOrNull(sourceAddress.address)
?: throw ValidationException("Source account $sourceAddress doesn't exist in the network")
return TransactionBuilder(cfg, sourceAccount, baseFee, memo, timeBounds)
}
/**
* Creates builder that allows to form Stellar transaction, adding Stellar's
* [operations](https://developers.stellar.org/docs/fundamentals-and-concepts/list-of-operations#payment)
*
* @param sourceAddress Stellar address of account initiating a transaction.
* @param baseFee base fee that will be used for this transaction. If not specified [default
* config fee][StellarConfiguration.baseFee] will be used.
* @param timeout Duration after which transaction expires. If not specified, [default config
* timeout][StellarConfiguration.defaultTimeout] will be used.
* @param memo optional transaction memo.
* @return transaction builder
*/
suspend fun transaction(
sourceAddress: AccountKeyPair,
timeout: Duration,
baseFee: UInt? = null,
memo: Pair<MemoType, String>? = null,
): TransactionBuilder {
return transaction(sourceAddress, baseFee, memo, timeout.toTimeBounds())
}
/**
* Creates
* [Fee Bump transaction](https://developers.stellar.org/docs/encyclopedia/fee-bump-transactions)
*
* @param feeAddress address that will pay for the transaction's fee
* @param transaction transaction for which fee should be paid (inner transaction)
* @param baseFee optional base fee for the transaction. If not specified,
* [StellarConfiguration.baseFee] will be used
* @return **unsigned** fee bump transaction
*/
fun makeFeeBump(
feeAddress: AccountKeyPair,
transaction: Transaction,
baseFee: UInt? = null
): FeeBumpTransaction {
return FeeBumpTransaction.Builder(transaction)
.setBaseFee((baseFee ?: cfg.stellar.baseFee).toLong())
.setFeeAccount(feeAddress.address)
.build()
}
/**
* Submit transaction to the Stellar network.
*
* @param signedTransaction Signed transaction that is submitted
* @return `true` if submitted successfully
* @throws [TransactionSubmitFailedException] when submission failed
*/
@Suppress("SwallowedException")
suspend fun submitTransaction(
signedTransaction: AbstractTransaction,
) {
try {
when (signedTransaction) {
is Transaction -> {
log.debug {
"Submit txn to network: sourceAccount = ${signedTransaction.sourceAccount}, memo = " +
"${signedTransaction.memo}, fee = ${signedTransaction.fee}, operationCount = " +
"${signedTransaction.operations.size}, signatureCount = ${signedTransaction
.signatures.size}"
}
val response = server.submitTransaction(signedTransaction)
if (!response.isSuccess) {
throw TransactionSubmitFailedException(response)
}
log.debug { "Transaction submitted with hash ${response.hash}" }
}
is FeeBumpTransaction -> {
log.debug {
"Submit fee bump transaction. Source account :${signedTransaction.feeAccount}. Inner transaction hash: " +
"${signedTransaction.innerTransaction.hashHex()}."
}
val response = server.submitTransaction(signedTransaction)
if (!response.isSuccess) {
throw TransactionSubmitFailedException(response)
}
log.debug { "Transaction submitted with hash ${response.hash}" }
}
else -> error("Unknown transaction type")
}
} catch (e: SubmitTransactionTimeoutResponseException) {
log.info { "Transaction ${signedTransaction.hashHex()} timed out. Resubmitting..." }
return submitTransaction(signedTransaction)
}
}
/**
* Submit transaction with a fee increase. Recommended way of creating transactions. This method
* repeatedly tries to submit transaction, until it's successful. When [timeout] is reached, base
* fee will be increased on the [baseFeeIncrease] value.
*
* @param sourceAccount source account of transaction. Will be used as a signer.
* @param timeout transaction timeout.
* @param baseFeeIncrease amount on which fee will be increased after timeout is reached.
* @param baseFee base transaction fee. If not specified, [default configuration value]
* [StellarConfiguration.baseFee] will be used.
* @param maxFee maximum allowed fee. Increased fee is limited by this value.
* @param memo optional transaction memo.
* @param buildingFunction function that will build the transaction.
* @return transaction that has been submitted to the network.
*/
@Suppress("LongParameterList")
suspend fun submitWithFeeIncrease(
sourceAccount: SigningKeyPair,
timeout: Duration,
baseFeeIncrease: UInt,
baseFee: UInt? = null,
maxFee: UInt = Integer.MAX_VALUE.toUInt(),
memo: Pair<MemoType, String>? = null,
buildingFunction: TransactionBuilder.() -> TransactionBuilder
): Transaction {
return submitWithFeeIncrease(
sourceAccount,
timeout,
baseFeeIncrease,
baseFee,
maxFee,
memo,
{ this.sign(sourceAccount) },
buildingFunction
)
}
/**
* Submit transaction with a fee increase. Recommended way of creating transactions. This method
* repeatedly tries to submit transaction, until it's successful. When [timeout] is reached, base
* fee will be increased on the [baseFeeIncrease] value.
*
* @param sourceAddress source address of transaction
* @param timeout transaction timeout
* @param baseFeeIncrease amount on which fee will be increased after timeout is reached
* @param baseFee base transaction fee. If not specified, [default configuration value]
* [StellarConfiguration.baseFee] will be used
* @param maxFee maximum allowed fee. Increased fee is limited by this value.
* @param memo optional transaction memo
* @param signerFunction function that will be used to sign the transaction
* @param buildingFunction function that will build the transaction
* @return transaction that has been submitted to the network.
*/
@Suppress("LongParameterList")
suspend fun submitWithFeeIncrease(
sourceAddress: AccountKeyPair,
timeout: Duration,
baseFeeIncrease: UInt,
baseFee: UInt? = null,
maxFee: UInt = Integer.MAX_VALUE.toUInt(),
memo: Pair<MemoType, String>? = null,
signerFunction: Transaction.() -> Transaction,
buildingFunction: TransactionBuilder.() -> TransactionBuilder
): Transaction {
val builder = transaction(sourceAddress, timeout, baseFee, memo)
val transaction = builder.buildingFunction().build()
val signedTransaction = transaction.signerFunction()
try {
submitTransaction(signedTransaction)
return transaction
} catch (e: TransactionSubmitFailedException) {
if (e.transactionResultCode == "tx_too_late") {
val newFee = min(maxFee, transaction.fee.toUInt() + baseFeeIncrease)
log.info {
"Transaction ${transaction.hashHex()} has expired. Increasing fee to $newFee Stroops."
}
return submitWithFeeIncrease(
sourceAddress,
timeout,
baseFeeIncrease,
newFee,
maxFee,
memo,
signerFunction,
buildingFunction
)
}
throw e
}
}
/**
* Decode transaction from XDR
*
* @param xdr base64 XDR string
* @return decoded transaction
*/
fun decodeTransaction(xdr: String): AbstractTransaction {
return Transaction.fromEnvelopeXdr(xdr, cfg.stellar.network)
}
}
| 4
|
Kotlin
|
8
| 5
|
c697cc00d28625bf1c2ed81efea796a5917683c0
| 9,477
|
kotlin-wallet-sdk
|
Apache License 2.0
|
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Bandsintown.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.SimpleIcons
public val SimpleIcons.Bandsintown: ImageVector
get() {
if (_bandsintown != null) {
return _bandsintown!!
}
_bandsintown = Builder(name = "Bandsintown", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.783f, 0.0f)
lineTo(24.0f, 0.0f)
verticalLineToRelative(12.0f)
horizontalLineToRelative(-5.217f)
lineTo(18.783f, 0.0f)
close()
moveTo(12.522f, 5.0f)
horizontalLineToRelative(5.217f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(-5.217f)
lineTo(12.522f, 5.0f)
close()
moveTo(6.26f, 5.0f)
horizontalLineToRelative(5.217f)
verticalLineToRelative(7.0f)
lineTo(6.261f, 12.0f)
lineTo(6.261f, 5.0f)
close()
moveTo(24.0f, 24.0f)
lineTo(0.0f, 24.0f)
lineTo(0.0f, 0.0f)
horizontalLineToRelative(5.217f)
verticalLineToRelative(19.0f)
horizontalLineToRelative(13.566f)
verticalLineToRelative(-1.0f)
lineTo(6.26f, 18.0f)
verticalLineToRelative(-5.0f)
lineTo(24.0f, 13.0f)
verticalLineToRelative(11.0f)
close()
}
}
.build()
return _bandsintown!!
}
private var _bandsintown: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,381
|
compose-icons
|
MIT License
|
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Bandsintown.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.SimpleIcons
public val SimpleIcons.Bandsintown: ImageVector
get() {
if (_bandsintown != null) {
return _bandsintown!!
}
_bandsintown = Builder(name = "Bandsintown", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.783f, 0.0f)
lineTo(24.0f, 0.0f)
verticalLineToRelative(12.0f)
horizontalLineToRelative(-5.217f)
lineTo(18.783f, 0.0f)
close()
moveTo(12.522f, 5.0f)
horizontalLineToRelative(5.217f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(-5.217f)
lineTo(12.522f, 5.0f)
close()
moveTo(6.26f, 5.0f)
horizontalLineToRelative(5.217f)
verticalLineToRelative(7.0f)
lineTo(6.261f, 12.0f)
lineTo(6.261f, 5.0f)
close()
moveTo(24.0f, 24.0f)
lineTo(0.0f, 24.0f)
lineTo(0.0f, 0.0f)
horizontalLineToRelative(5.217f)
verticalLineToRelative(19.0f)
horizontalLineToRelative(13.566f)
verticalLineToRelative(-1.0f)
lineTo(6.26f, 18.0f)
verticalLineToRelative(-5.0f)
lineTo(24.0f, 13.0f)
verticalLineToRelative(11.0f)
close()
}
}
.build()
return _bandsintown!!
}
private var _bandsintown: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,381
|
compose-icons
|
MIT License
|
app/gps_alarm/src/main/java/com/gps_alarm/ui/viewmodel/GpsAlarmVM.kt
|
KimBoWoon
| 519,954,177
| false
| null |
package com.gps_alarm.ui.viewmodel
import androidx.compose.runtime.mutableStateOf
import com.data.gpsAlarm.local.LocalDataStore
import com.domain.gpsAlarm.usecase.DataStoreUseCase
import com.gps_alarm.base.BaseVM
import com.gps_alarm.data.Address
import com.gps_alarm.data.SettingInfo
import com.gps_alarm.data.StartServiceData
import com.gps_alarm.ui.util.decode
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.serialization.json.Json
import org.orbitmvi.orbit.Container
import org.orbitmvi.orbit.ContainerHost
import org.orbitmvi.orbit.syntax.simple.intent
import org.orbitmvi.orbit.syntax.simple.postSideEffect
import org.orbitmvi.orbit.syntax.simple.reduce
import org.orbitmvi.orbit.viewmodel.container
import javax.inject.Inject
@HiltViewModel
class GpsAlarmVM @Inject constructor(
private val json: Json,
private val dataStoreUseCase: DataStoreUseCase
) : BaseVM(), ContainerHost<StartServiceData, GpsAlarmVM.GpsAlarmSideEffect> {
var appBarTitle = mutableStateOf("GPS 알람")
override val container: Container<StartServiceData, GpsAlarmSideEffect> = container(StartServiceData())
sealed class GpsAlarmSideEffect {
object CheckPermission : GpsAlarmSideEffect()
}
init {
checkPermission()
getAddressList()
}
private fun checkPermission() {
intent {
postSideEffect(GpsAlarmSideEffect.CheckPermission)
}
}
private fun getAddressList() {
intent {
reduce { state.copy(alarmList = null, loading = true, error = null) }
val addressList = dataStoreUseCase.get(LocalDataStore.Keys.alarmList)?.map { it.decode<Address>(json) } ?: emptyList()
val setting = dataStoreUseCase.get(LocalDataStore.Keys.setting)?.decode(json) ?: SettingInfo()
reduce { state.copy(alarmList = addressList, settingInfo = setting, loading = false, error = null) }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9de4db684a3cf038bbd6cc036549ace1ac611061
| 1,924
|
BoWoon
|
MIT License
|
app/src/main/java/com/example/cs567_3d_ui_project/qgis_driver/resource_objects/http_request_interfaces/IFormat.kt
|
csu-hci-projects
| 694,848,698
| false
|
{"Kotlin": 168968, "Java": 130433, "GLSL": 38243}
|
package com.example.cs567_3d_ui_project.qgis_driver.resource_objects.http_request_interfaces
interface IFormat {
var format: String
}
| 0
|
Kotlin
|
0
| 0
|
ba9b3f53098e2cf35add7c6427de41ef80f920a6
| 138
|
FA23-Visualization-of-Infrastructure-with-a-3D-GIS-Mobile-Application
|
MIT License
|
testing/src/test/java/org/oppia/android/testing/lightweightcheckpointing/ExplorationCheckpointTestHelperTest.kt
|
oppia
| 148,093,817
| false
|
{"Kotlin": 13302271, "Starlark": 693163, "Java": 34760, "Shell": 18872}
|
package org.oppia.android.testing.lightweightcheckpointing
import android.app.Application
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import dagger.BindsInstance
import dagger.Component
import dagger.Module
import dagger.Provides
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.oppia.android.app.model.ExplorationCheckpoint
import org.oppia.android.app.model.ProfileId
import org.oppia.android.domain.exploration.lightweightcheckpointing.ExplorationCheckpointController
import org.oppia.android.domain.exploration.lightweightcheckpointing.ExplorationStorageModule
import org.oppia.android.domain.oppialogger.LogStorageModule
import org.oppia.android.domain.topic.FRACTIONS_EXPLORATION_ID_0
import org.oppia.android.domain.topic.FRACTIONS_EXPLORATION_ID_1
import org.oppia.android.domain.topic.RATIOS_EXPLORATION_ID_0
import org.oppia.android.testing.TestLogReportingModule
import org.oppia.android.testing.data.DataProviderTestMonitor
import org.oppia.android.testing.environment.TestEnvironmentConfig
import org.oppia.android.testing.robolectric.RobolectricModule
import org.oppia.android.testing.threading.TestCoroutineDispatchers
import org.oppia.android.testing.threading.TestDispatcherModule
import org.oppia.android.testing.time.FakeOppiaClock
import org.oppia.android.testing.time.FakeOppiaClockModule
import org.oppia.android.util.caching.AssetModule
import org.oppia.android.util.caching.CacheAssetsLocally
import org.oppia.android.util.caching.LoadLessonProtosFromAssets
import org.oppia.android.util.caching.TopicListToCache
import org.oppia.android.util.data.DataProvidersInjector
import org.oppia.android.util.data.DataProvidersInjectorProvider
import org.oppia.android.util.locale.LocaleProdModule
import org.oppia.android.util.logging.EnableConsoleLog
import org.oppia.android.util.logging.EnableFileLog
import org.oppia.android.util.logging.GlobalLogLevel
import org.oppia.android.util.logging.LogLevel
import org.oppia.android.util.networking.NetworkConnectionUtilDebugModule
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import javax.inject.Inject
import javax.inject.Singleton
/** Tests for [ExplorationCheckpointTestHelper]. */
// FunctionName: test names are conventionally named with underscores.
@Suppress("FunctionName")
@RunWith(AndroidJUnit4::class)
@LooperMode(LooperMode.Mode.PAUSED)
@Config(application = ExplorationCheckpointTestHelperTest.TestApplication::class)
class ExplorationCheckpointTestHelperTest {
@Inject lateinit var context: Context
@Inject lateinit var fakeOppiaClock: FakeOppiaClock
@Inject lateinit var explorationCheckpointTestHelper: ExplorationCheckpointTestHelper
@Inject lateinit var explorationCheckpointController: ExplorationCheckpointController
@Inject lateinit var testCoroutineDispatchers: TestCoroutineDispatchers
@Inject lateinit var monitorFactory: DataProviderTestMonitor.Factory
private val profileId = ProfileId.newBuilder().setInternalId(0).build()
@Before
fun setUp() {
setUpTestApplicationComponent()
fakeOppiaClock.setFakeTimeMode(FakeOppiaClock.FakeTimeMode.MODE_UPTIME_MILLIS)
}
private fun setUpTestApplicationComponent() {
ApplicationProvider.getApplicationContext<TestApplication>().inject(this)
}
@Test
fun testSaveCheckpointForFractionsStory0Exploration0_checkCheckpointIsSaved() {
explorationCheckpointTestHelper.saveCheckpointForFractionsStory0Exploration0(
profileId = profileId,
version = FRACTIONS_STORY_0_EXPLORATION_0_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint = retrieveCheckpoint(profileId, FRACTIONS_EXPLORATION_ID_0)
assertThat(checkpoint.explorationTitle).isEqualTo(FRACTIONS_EXPLORATION_0_TITLE)
assertThat(checkpoint.pendingStateName)
.isEqualTo(FRACTIONS_STORY_0_EXPLORATION_0_FIRST_STATE_NAME)
}
@Test
fun testUpdateCheckpointForFractionsStory0Exploration0_checkCheckpointIsSaved() {
explorationCheckpointTestHelper.saveCheckpointForFractionsStory0Exploration0(
profileId = profileId,
version = FRACTIONS_STORY_0_EXPLORATION_0_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint = retrieveCheckpoint(profileId, FRACTIONS_EXPLORATION_ID_0)
assertThat(checkpoint.explorationTitle).isEqualTo(FRACTIONS_EXPLORATION_0_TITLE)
assertThat(checkpoint.pendingStateName)
.isEqualTo(FRACTIONS_STORY_0_EXPLORATION_0_FIRST_STATE_NAME)
explorationCheckpointTestHelper.updateCheckpointForFractionsStory0Exploration0(
profileId = profileId,
version = FRACTIONS_STORY_0_EXPLORATION_0_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint1 = retrieveCheckpoint(profileId, FRACTIONS_EXPLORATION_ID_0)
assertThat(checkpoint1.explorationTitle).isEqualTo(FRACTIONS_EXPLORATION_0_TITLE)
assertThat(checkpoint1.pendingStateName)
.isEqualTo(FRACTIONS_STORY_0_EXPLORATION_0_SECOND_STATE_NAME)
}
@Test
fun testSaveCheckpointForFractionsStory0Exploration1_checkCheckpointIsSaved() {
explorationCheckpointTestHelper.saveCheckpointForFractionsStory0Exploration1(
profileId,
version = FRACTIONS_STORY_0_EXPLORATION_1_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint = retrieveCheckpoint(profileId, FRACTIONS_EXPLORATION_ID_1)
assertThat(checkpoint.explorationTitle).isEqualTo(FRACTIONS_EXPLORATION_1_TITLE)
assertThat(checkpoint.pendingStateName)
.isEqualTo(FRACTIONS_STORY_0_EXPLORATION_1_FIRST_STATE_NAME)
}
@Test
fun testUpdateCheckpointForFractionsStory0Exploration1_checkCheckpointIsSaved() {
explorationCheckpointTestHelper.saveCheckpointForFractionsStory0Exploration1(
profileId = profileId,
version = FRACTIONS_STORY_0_EXPLORATION_1_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint = retrieveCheckpoint(profileId, FRACTIONS_EXPLORATION_ID_1)
assertThat(checkpoint.explorationTitle).isEqualTo(FRACTIONS_EXPLORATION_1_TITLE)
assertThat(checkpoint.pendingStateName)
.isEqualTo(
FRACTIONS_STORY_0_EXPLORATION_1_FIRST_STATE_NAME
)
explorationCheckpointTestHelper.updateCheckpointForFractionsStory0Exploration1(
profileId = profileId,
version = FRACTIONS_STORY_0_EXPLORATION_1_CURRENT_VERSION,
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint1 = retrieveCheckpoint(profileId, FRACTIONS_EXPLORATION_ID_1)
assertThat(checkpoint1.explorationTitle).isEqualTo(FRACTIONS_EXPLORATION_1_TITLE)
assertThat(checkpoint1.pendingStateName)
.isEqualTo(FRACTIONS_STORY_0_EXPLORATION_1_SECOND_STATE_NAME)
}
@Test
fun testSaveCheckpointForRatiosStory0Exploration0_checkCheckpointIsSaved() {
explorationCheckpointTestHelper.saveCheckpointForRatiosStory0Exploration0(
profileId = profileId,
version = RATIOS_STORY_0_EXPLORATION_0_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint = retrieveCheckpoint(profileId, RATIOS_EXPLORATION_ID_0)
assertThat(checkpoint.explorationTitle).isEqualTo(RATIOS_EXPLORATION_0_TITLE)
assertThat(checkpoint.pendingStateName).isEqualTo(RATIOS_STORY_0_EXPLORATION_0_FIRST_STATE_NAME)
}
@Test
fun testUpdateCheckpointForRatiosStory0Exploration0_checkCheckpointIsSaved() {
explorationCheckpointTestHelper.saveCheckpointForRatiosStory0Exploration0(
profileId = profileId,
version = RATIOS_STORY_0_EXPLORATION_0_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint = retrieveCheckpoint(profileId, RATIOS_EXPLORATION_ID_0)
assertThat(checkpoint.explorationTitle).isEqualTo(RATIOS_EXPLORATION_0_TITLE)
assertThat(checkpoint.pendingStateName).isEqualTo(RATIOS_STORY_0_EXPLORATION_0_FIRST_STATE_NAME)
explorationCheckpointTestHelper.updateCheckpointForRatiosStory0Exploration0(
profileId = profileId,
version = RATIOS_STORY_0_EXPLORATION_0_CURRENT_VERSION
)
// Verify saved checkpoint has correct exploration title and pending state name.
val checkpoint1 = retrieveCheckpoint(profileId, RATIOS_EXPLORATION_ID_0)
assertThat(checkpoint1.explorationTitle).isEqualTo(RATIOS_EXPLORATION_0_TITLE)
assertThat(checkpoint1.pendingStateName)
.isEqualTo(RATIOS_STORY_0_EXPLORATION_0_SECOND_STATE_NAME)
}
private fun retrieveCheckpoint(
profileId: ProfileId,
explorationId: String
): ExplorationCheckpoint {
val retrieveCheckpointProvider =
explorationCheckpointController.retrieveExplorationCheckpoint(profileId, explorationId)
return monitorFactory.waitForNextSuccessfulResult(retrieveCheckpointProvider)
}
// TODO(#89): Move this to a common test application component.
@Module
class TestModule {
@Provides
@Singleton
fun provideContext(application: Application): Context {
return application
}
// TODO(#59): Either isolate these to their own shared test module, or use the real logging
// module in tests to avoid needing to specify these settings for tests.
@EnableConsoleLog
@Provides
fun provideEnableConsoleLog(): Boolean = true
@EnableFileLog
@Provides
fun provideEnableFileLog(): Boolean = false
@GlobalLogLevel
@Provides
fun provideGlobalLogLevel(): LogLevel = LogLevel.VERBOSE
@CacheAssetsLocally
@Provides
fun provideCacheAssetsLocally(): Boolean = false
@Provides
@TopicListToCache
fun provideTopicListToCache(): List<String> = listOf()
@Provides
@LoadLessonProtosFromAssets
fun provideLoadLessonProtosFromAssets(testEnvironmentConfig: TestEnvironmentConfig): Boolean =
testEnvironmentConfig.isUsingBazel()
}
// TODO(#89): Move this to a common test application component.
@Singleton
@Component(
modules = [
TestModule::class, TestLogReportingModule::class, LogStorageModule::class,
TestDispatcherModule::class, RobolectricModule::class, FakeOppiaClockModule::class,
ExplorationStorageModule::class, NetworkConnectionUtilDebugModule::class, AssetModule::class,
LocaleProdModule::class
]
)
interface TestApplicationComponent : DataProvidersInjector {
@Component.Builder
interface Builder {
@BindsInstance
fun setApplication(application: Application): Builder
fun build(): TestApplicationComponent
}
fun inject(explorationCheckpointTestHelperTest: ExplorationCheckpointTestHelperTest)
}
class TestApplication : Application(), DataProvidersInjectorProvider {
private val component: TestApplicationComponent by lazy {
DaggerExplorationCheckpointTestHelperTest_TestApplicationComponent.builder()
.setApplication(this)
.build()
}
fun inject(explorationCheckpointTestHelperTest: ExplorationCheckpointTestHelperTest) {
component.inject(explorationCheckpointTestHelperTest)
}
override fun getDataProvidersInjector(): DataProvidersInjector = component
}
}
| 590
|
Kotlin
|
517
| 315
|
95699f922321f49a3503783187a14ad1cef0d5d3
| 11,488
|
oppia-android
|
Apache License 2.0
|
common/ui/compose/src/main/java/app/tivi/common/compose/ui/PosterCard.kt
|
chrisbanes
| 100,624,553
| false
| null |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.common.compose.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.tivi.common.ui.resources.R as UiR
import app.tivi.data.entities.TiviShow
import app.tivi.data.entities.TmdbImageEntity
@Composable
fun PosterCard(
show: TiviShow,
modifier: Modifier = Modifier,
poster: TmdbImageEntity? = null,
) {
Card(modifier = modifier) {
PosterCardContent(show = show, poster = poster)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PosterCard(
show: TiviShow,
onClick: () -> Unit,
modifier: Modifier = Modifier,
poster: TmdbImageEntity? = null,
) {
Card(onClick = onClick, modifier = modifier) {
PosterCardContent(show = show, poster = poster)
}
}
@Composable
private fun PosterCardContent(
show: TiviShow,
poster: TmdbImageEntity?,
) {
Box(modifier = Modifier.fillMaxSize()) {
Text(
text = show.title ?: "No title",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.padding(4.dp)
.align(Alignment.CenterStart),
)
if (poster != null) {
AsyncImage(
model = poster,
requestBuilder = { crossfade(true) },
contentDescription = stringResource(
UiR.string.cd_show_poster_image,
show.title ?: "show",
),
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
}
}
}
@Composable
fun PlaceholderPosterCard(
modifier: Modifier = Modifier,
) {
Card(modifier = modifier) {
Box {
// TODO: display something better
}
}
}
| 38
|
Kotlin
|
792
| 5,749
|
5dc4d831fd801afab556165d547042c517f98875
| 2,873
|
tivi
|
Apache License 2.0
|
ui/ui-animation-core/src/commonMain/kotlin/androidx/compose/animation/core/Animation.kt
|
Sathawale27
| 284,157,908
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.core
import androidx.compose.ui.util.annotation.VisibleForTesting
import kotlin.math.sign
/**
* This interface provides a convenient way to query from an [VectorizedAnimationSpec] or
* [FloatDecayAnimationSpec]: It spares the need to pass the starting conditions and in some cases
* ending condition for each value or velocity query, and instead only requires the play time to be
* passed for such queries.
*
* The implementation of this interface should cache the starting conditions and ending
* conditions of animations as needed.
*
* __Note__: [Animation] does not track the lifecycle of an animation. It merely reacts to play time
* change and returns the new value/velocity as a result. It can be used as a building block for
* more lifecycle aware animations. In contrast, [AnimatedValue] and [TransitionAnimation] are
* stateful and manage their own lifecycles, and subscribe/unsubscribe from an
* [AnimationClockObservable] as needed.
*
* @see [AnimatedValue]
* @see [androidx.compose.animation.transition]
* @suppress
*/
interface Animation<T, V : AnimationVector> {
/**
* This amount of time in milliseconds that the animation will run before it finishes
*/
val durationMillis: Long
/**
* The [TwoWayConverter] that will be used to convert value/velocity from any arbitrary data
* type to [AnimationVector]. This makes it possible to animate different dimensions of the
* data object independently (e.g. x/y dimensions of the position data).
*/
val converter: TwoWayConverter<T, V>
/**
* Returns the value of the animation at the given play time.
*
* @param playTime the play time that is used to determine the value of the animation.
*/
fun getValue(playTime: Long): T
/**
* Returns the velocity (in [AnimationVector] form) of the animation at the given play time.
*
* @param playTime the play time that is used to calculate the velocity of the animation.
*/
fun getVelocityVector(playTime: Long): V
/**
* Returns whether the animation is finished at the given play time.
*
* @param playTime the play time used to determine whether the animation is finished.
*/
fun isFinished(playTime: Long): Boolean {
return playTime >= durationMillis
}
}
/**
* Returns the velocity of the animation at the given play time.
*
* @param playTime the play time that is used to calculate the velocity of the animation.
*/
internal fun <T, V : AnimationVector> Animation<T, V>.getVelocity(playTime: Long): T =
converter.convertFromVector(getVelocityVector(playTime))
/**
* Creates a [TargetBasedAnimation] from a given [VectorizedAnimationSpec] of [AnimationVector] type. This
* convenient method is intended for when the value being animated (i.e. start value, end value,
* etc) is of [AnimationVector] type.
*
* @param startValue the value that the animation will start from
* @param endValue the value that the animation will end at
* @param startVelocity the initial velocity to start the animation at
* @suppress
*/
@VisibleForTesting(otherwise = 3 /*PACKAGE_PRIVATE*/)
fun <V : AnimationVector> VectorizedAnimationSpec<V>.createAnimation(
startValue: V,
endValue: V,
startVelocity: V
): TargetBasedAnimation<V, V> =
TargetBasedAnimation(
animationSpec = this,
startValue = startValue,
endValue = endValue,
startVelocityVector = startVelocity,
converter = TwoWayConverter({ it }, { it })
)
/**
* Creates a [TargetBasedAnimation] from a given [VectorizedAnimationSpec] of [AnimationVector] type.
*
* @param startValue the value that the animation will start from
* @param endValue the value that the animation will end at
* @param startVelocityVector the initial velocity (in the form of [AnimationVector]) to start the
* animation at.
* @param converter a [TwoWayConverter] that converts the from [AnimationVector] to the animation
* data type [T], and vice versa.
*
* @see TargetBasedAnimation
*/
internal fun <T, V : AnimationVector> VectorizedAnimationSpec<V>.createAnimation(
startValue: T,
endValue: T,
startVelocityVector: V,
converter: TwoWayConverter<T, V>
) = TargetBasedAnimation<T, V>(
animationSpec = this,
startValue = startValue,
endValue = endValue,
startVelocityVector = startVelocityVector,
converter = converter
)
/**
* Creates a [TargetBasedAnimation] with the given start/end conditions of the animation, and
* the provided [animationSpec].
*
* The resulting [Animation] assumes that the start value and velocity, as well as end value do
* not change throughout the animation, and cache these values. This caching enables much more
* convenient query for animation value and velocity (where only playtime needs to be passed
* into the methods).
*
* __Note__: When interruptions happen to the [TargetBasedAnimation], a new instance should
* be created that use the current value and velocity as the starting conditions. This type of
* interruption handling is the default behavior for both [AnimatedValue] and
* [TransitionAnimation]. Consider using those APIs for the interruption handling, as well as
* built-in animation lifecycle management.
*
* @param animationSpec the [AnimationSpec] that will be used to calculate value/velocity
* @param startValue the start value of the animation
* @param endValue the end value of the animation
* @param startVelocity the start velocity (of type [T] of the animation
* @param converter the [TwoWayConverter] that is used to convert animation type [T] from/to [V]
*/
fun <T, V : AnimationVector> TargetBasedAnimation(
animationSpec: AnimationSpec<T>,
startValue: T,
endValue: T,
startVelocity: T,
converter: TwoWayConverter<T, V>
) = TargetBasedAnimation(
animationSpec,
startValue,
endValue,
converter,
converter.convertToVector(startVelocity)
)
/**
* This is a convenient animation wrapper class that works for all target based animations, i.e.
* animations that has a pre-defined end value, unlike decay.
*
* It assumes that the starting value and velocity, as well as ending value do not change throughout
* the animation, and cache these values. This caching enables much more convenient query for
* animation value and velocity (where only playtime needs to be passed into the methods).
*
* __Note__: When interruptions happen to the [TargetBasedAnimation], a new instance should
* be created that use the current value and velocity as the starting conditions. This type of
* interruption handling is the default behavior for both [AnimatedValue] and
* [TransitionAnimation]. Consider using those APIs for the interruption handling, as well as
* built-in animation lifecycle management.
*
* @param animationSpec the [VectorizedAnimationSpec] that will be used to calculate value/velocity
* @param startValue the start value of the animation
* @param endValue the end value of the animation
* @param converter the [TwoWayConverter] that is used to convert animation type [T] from/to [V]
* @param startVelocityVector the start velocity of the animation in the form of [AnimationVector]
*
* @see [TransitionAnimation]
* @see [androidx.compose.animation.transition]
* @see [AnimatedValue]
*/
class TargetBasedAnimation<T, V : AnimationVector> internal constructor(
internal val animationSpec: VectorizedAnimationSpec<V>,
startValue: T,
val endValue: T,
override val converter: TwoWayConverter<T, V>,
startVelocityVector: V? = null
) : Animation<T, V> {
/**
* Creates a [TargetBasedAnimation] with the given start/end conditions of the animation, and
* the provided [animationSpec].
*
* The resulting [Animation] assumes that the start value and velocity, as well as end value do
* not change throughout the animation, and cache these values. This caching enables much more
* convenient query for animation value and velocity (where only playtime needs to be passed
* into the methods).
*
* __Note__: When interruptions happen to the [TargetBasedAnimation], a new instance should
* be created that use the current value and velocity as the starting conditions. This type of
* interruption handling is the default behavior for both [AnimatedValue] and
* [TransitionAnimation]. Consider using those APIs for the interruption handling, as well as
* built-in animation lifecycle management.
*
* @param animationSpec the [AnimationSpec] that will be used to calculate value/velocity
* @param startValue the start value of the animation
* @param endValue the end value of the animation
* @param converter the [TwoWayConverter] that is used to convert animation type [T] from/to [V]
* @param startVelocityVector the start velocity vector, null by default (meaning 0 velocity).
*/
constructor(
animationSpec: AnimationSpec<T>,
startValue: T,
endValue: T,
converter: TwoWayConverter<T, V>,
startVelocityVector: V? = null
) : this(
animationSpec.vectorize(converter),
startValue,
endValue,
converter,
startVelocityVector
)
private val startValueVector = converter.convertToVector.invoke(startValue)
private val endValueVector = converter.convertToVector.invoke(endValue)
private val startVelocityVector =
startVelocityVector ?: converter.convertToVector.invoke(startValue).newInstance()
override fun getValue(playTime: Long): T {
return if (playTime < durationMillis) {
converter.convertFromVector.invoke(
animationSpec.getValue(
playTime, startValueVector,
endValueVector, startVelocityVector
)
)
} else {
endValue
}
}
override val durationMillis: Long = animationSpec.getDurationMillis(
start = startValueVector,
end = endValueVector,
startVelocity = this.startVelocityVector
)
private val endVelocity = animationSpec.getEndVelocity(
startValueVector,
endValueVector,
this.startVelocityVector
)
override fun getVelocityVector(playTime: Long): V {
return if (playTime < durationMillis) {
animationSpec.getVelocity(
playTime,
startValueVector,
endValueVector,
startVelocityVector
)
} else {
endVelocity
}
}
}
/**
* Fixed Decay animation wraps around a [FloatDecayAnimationSpec] and assumes its starting value and
* velocity never change throughout the animation.
*
* @param anim decay animation that will be used
* @param startValue starting value that will be passed to the decay animation
* @param startVelocity starting velocity for the decay animation
*/
class DecayAnimation(
private val anim: FloatDecayAnimationSpec,
private val startValue: Float,
private val startVelocity: Float = 0f
) : Animation<Float, AnimationVector1D> {
private val target: Float = anim.getTarget(startValue, startVelocity)
private val velocityVector: AnimationVector1D = AnimationVector1D(0f)
override val converter: TwoWayConverter<Float, AnimationVector1D>
get() = Float.VectorConverter
// TODO: Remove the MissingNullability suppression when b/134803955 is fixed.
@Suppress("AutoBoxing", "MissingNullability")
override fun getValue(playTime: Long): Float {
if (!isFinished(playTime)) {
return anim.getValue(playTime, startValue, startVelocity)
} else {
return target
}
}
override fun getVelocityVector(playTime: Long): AnimationVector1D {
if (!isFinished(playTime)) {
velocityVector.value = anim.getVelocity(playTime, startValue, startVelocity)
} else {
velocityVector.value = anim.absVelocityThreshold * sign(startVelocity)
}
return velocityVector
}
override val durationMillis: Long = anim.getDurationMillis(startValue, startVelocity)
}
| 0
| null |
1
| 1
|
549e3e3003cd308939ff31799cf1250e86d3e63e
| 12,901
|
androidx
|
Apache License 2.0
|
knobview/src/main/java/app/trian/knobview/command/ToggleEnabledCommand.kt
|
triandamai
| 697,094,517
| false
|
{"Kotlin": 22629}
|
package app.trian.knobview.command
import app.trian.knobview.KnobView
class ToggleEnabledCommand(
private val knobView: KnobView
) :KnobCommand {
override fun execute(isEnabled: Boolean) {
knobView.isKnobEnabled = !knobView.isKnobEnabled
}
}
| 0
|
Kotlin
|
0
| 0
|
71815c3aa8a9edcf22d7b7b50a44426d02b8ac41
| 265
|
knob-view
|
MIT License
|
mobile_app1/module1014/src/main/java/module1014packageKt0/Foo16.kt
|
uber-common
| 294,831,672
| false
| null |
package module1014packageKt0;
annotation class Foo16Fancy
@Foo16Fancy
class Foo16 {
fun foo0(){
module1014packageKt0.Foo15().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
}
| 6
|
Java
|
6
| 72
|
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
| 235
|
android-build-eval
|
Apache License 2.0
|
networking/src/main/java/nick/networking/GitHubJobsService.kt
|
nihk
| 165,444,955
| false
|
{"Gradle": 10, "Java Properties": 2, "Shell": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Text": 1, "Proguard": 8, "XML": 62, "Kotlin": 84, "Java": 1}
|
package nick.networking
import io.reactivex.Single
import nick.data.model.Position
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface GitHubJobsService {
companion object {
const val BASE_URL = "https://jobs.github.com/"
}
@GET("positions.json")
fun fetchPositions(
@Query("description") description: String? = null,
@Query("location") location: String? = null,
@Query("lat") latitude: Double? = null,
@Query("long") longitude: Double? = null,
@Query("full_time") isFullTime: Boolean? = null,
@Query("page") page: Int? = null
): Single<List<Position>>
@GET("positions/{id}.json")
fun fetchPosition(
@Path("id") id: Int,
@Query("markdown") markdown: Boolean? = true
): Single<Position>
}
| 0
|
Kotlin
|
0
| 2
|
600fd5c8148ddc6225983296b0a0e7254cd1c8c7
| 835
|
IAmJob
|
The Unlicense
|
packages/runtime/src/commonMain/kotlin/dev/elide/ElideRuntime.kt
|
elide-dev
| 506,113,888
| false
| null |
/*
* Copyright (c) 2023 Elide Ventures, LLC.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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 dev.elide
/** Elide runtime tools -- coming soon. */
public object ElideRuntime {
public const val SERVICE_VERSION: String = "v3"
}
| 75
| null |
15
| 88
|
8ffe4f06741a080d86ec2b09c71b7b0a79ddcaf0
| 718
|
elide
|
MIT License
|
core/designsystem/src/main/java/com/eshc/goonersapp/core/designsystem/__IconPack.kt
|
eshc123
| 640,451,475
| false
| null |
package com.eshc.goonersapp.core.designsystem
import androidx.compose.ui.graphics.vector.ImageVector
import com.eshc.goonersapp.core.designsystem.iconpack.IcGrid
import com.eshc.goonersapp.core.designsystem.iconpack.IcList
import kotlin.collections.List as ____KtList
public object IconPack
private var __Icons: ____KtList<ImageVector>? = null
public val IconPack.Icons: ____KtList<ImageVector>
get() {
if (__Icons != null) {
return __Icons!!
}
__Icons= listOf(IcGrid, IcList)
return __Icons!!
}
| 3
| null |
1
| 1
|
ef6c51f062825f6e71f20e7ada10d90370d6976f
| 526
|
GoonersApp
|
Apache License 2.0
|
desktop/gui/src/main/kotlin/com/soyle/stories/storyevent/storyEventDetails/presenters/LinkLocationToStoryEventPresenter.kt
|
Soyle-Productions
| 239,407,827
| false
| null |
package com.soyle.stories.storyevent.storyEventDetails.presenters
import com.soyle.stories.gui.View
import com.soyle.stories.storyevent.storyEventDetails.StoryEventDetailsViewModel
import com.soyle.stories.usecase.storyevent.linkLocationToStoryEvent.LinkLocationToStoryEvent
import java.util.*
internal class LinkLocationToStoryEventPresenter(
private val storyEventId: UUID,
private val view: View.Nullable<StoryEventDetailsViewModel>
) : LinkLocationToStoryEvent.OutputPort {
override fun receiveLinkLocationToStoryEventResponse(response: LinkLocationToStoryEvent.ResponseModel) {
if (response.storyEventId != storyEventId) return
view.updateOrInvalidated {
val selectedLocationId = response.locationId
copy(
selectedLocationId = selectedLocationId?.toString(),
selectedLocation = selectedLocationId?.let {
locations.find { it.id.uuid == selectedLocationId }
}
)
}
}
override fun receiveLinkLocationToStoryEventFailure(failure: Exception) {
}
}
| 45
|
Kotlin
|
0
| 9
|
1a110536865250dcd8d29270d003315062f2b032
| 997
|
soyle-stories
|
Apache License 2.0
|
src/main/kotlin/com/github/krix38/quicklist/service/EmitterService.kt
|
krix38
| 199,082,164
| false
| null |
package com.github.krix38.quicklist.service
import org.slf4j.LoggerFactory.getLogger
import org.springframework.stereotype.Service
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
@Service
class EmitterService(
private val emittersMap: ConcurrentHashMap<String, ConcurrentHashMap<String, SseEmitter>> = ConcurrentHashMap()
) {
companion object {
private val logger = getLogger(EmitterService::class.java)
}
fun addEmitter(id: String): SseEmitter {
val uuid = java.util.UUID.randomUUID().toString()
val newEmitter = SseEmitter().apply {
setEmitterCallbacks(id, uuid)
send(uuid)
}
emittersMap.getOrPut(id) { ConcurrentHashMap() }[uuid] = newEmitter
return newEmitter
}
fun sendMessageToAllEmitters(id: String?, event: MutableSet<ResponseBodyEmitter.DataWithMediaType>){
if(!id.isNullOrEmpty()){
emittersMap[id]?.forEachValue(1) {
sendEvent(it, event)
}
}
}
private fun sendEvent(emitter: SseEmitter?, event: MutableSet<ResponseBodyEmitter.DataWithMediaType>) {
try {
emitter?.send(event)
} catch (exception: IOException) {
logger.error(exception.message)
}
}
private fun SseEmitter.setEmitterCallbacks(id: String, uuid: String) {
onCompletion {
removeEmitter(id, uuid)
}
onError {
removeEmitter(id, uuid)
}
onTimeout {
removeEmitter(id, uuid)
}
}
private fun removeEmitter(id: String, uuid: String) {
emittersMap[id]?.let {
it.remove(uuid)
if (it.isEmpty()) {
emittersMap.remove(id)
}
}
}
}
| 14
| null |
1
| 1
|
e47e2c31743886ab007f836da3c4c9fadaf4d955
| 1,957
|
quicklist
|
MIT License
|
octicons/src/commonMain/kotlin/compose/icons/octicons/ArrowUpLeft24.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package com.woowla.compose.icon.collections.octicons.octicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.octicons.Octicons
public val Octicons.ArrowUpLeft24: ImageVector
get() {
if (_arrowUpLeft24 != null) {
return _arrowUpLeft24!!
}
_arrowUpLeft24 = Builder(name = "ArrowUpLeft24", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.75f, 15.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
verticalLineToRelative(-9.0f)
arcTo(0.75f, 0.75f, 0.0f, false, true, 5.75f, 5.0f)
horizontalLineToRelative(9.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineTo(7.56f)
lineToRelative(10.22f, 10.22f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, -0.326f, 1.275f)
arcToRelative(0.749f, 0.749f, 0.0f, false, true, -0.734f, -0.215f)
lineTo(6.5f, 7.56f)
verticalLineToRelative(7.19f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, 0.75f)
close()
}
}
.build()
return _arrowUpLeft24!!
}
private var _arrowUpLeft24: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,072
|
compose-icons
|
MIT License
|
app/src/main/java/h/lillie/weartube/Main.kt
|
LillieH1000
| 736,381,334
| false
|
{"Kotlin": 24719}
|
package h.lillie.weartube
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.Space
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import coil.load
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
@SuppressLint("WakelockTimeout")
@Suppress("Deprecation")
class Main : AppCompatActivity() {
private lateinit var wifiLock: WifiManager.WifiLock
private lateinit var wakeLock: PowerManager.WakeLock
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "WearTube:WifiLock")
wifiLock.setReferenceCounted(false)
wifiLock.acquire()
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WearTube:WakeLock")
wakeLock.setReferenceCounted(false)
wakeLock.acquire()
val scrollView: ScrollView = findViewById(R.id.scrollView)
val scrollLayout: LinearLayout = findViewById(R.id.scrollLayout)
val deviceWidth: Int = windowManager.currentWindowMetrics.bounds.width()
val searchBar: EditText = findViewById(R.id.searchBar)
searchBar.setOnKeyListener(View.OnKeyListener { _, keyCode, _ ->
if (keyCode == KeyEvent.KEYCODE_ENTER) {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(searchBar.windowToken, 0)
scrollLayout.removeAllViews()
scrollView.requestFocus()
CoroutineScope(Dispatchers.Main).launch {
val searchRequest: String = Extractor().searchRequest(this@Main, searchBar.text.toString())
val searchContents: JSONArray = JSONObject(searchRequest).getJSONObject("contents").getJSONObject("twoColumnSearchResultsRenderer").getJSONObject("primaryContents").getJSONObject("sectionListRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("itemSectionRenderer").getJSONArray("contents")
for (i in 0 until searchContents.length()) {
try {
val videoID: String = searchContents.getJSONObject(i).getJSONObject("videoRenderer").optString("videoId")
val videoTitle: String = searchContents.getJSONObject(i).getJSONObject("videoRenderer").getJSONObject("title").getJSONArray("runs").getJSONObject(0).optString("text")
val videoArtworkArray: JSONArray = searchContents.getJSONObject(i).getJSONObject("videoRenderer").getJSONObject("thumbnail").getJSONArray("thumbnails")
val videoArtworkUrl: String = videoArtworkArray.getJSONObject((videoArtworkArray.length() - 1)).optString("url")
val videoRelativeView = RelativeLayout(this@Main)
videoRelativeView.layoutParams = RelativeLayout.LayoutParams(deviceWidth, 100)
val videoImageView = ImageView(this@Main)
videoImageView.layoutParams = LinearLayout.LayoutParams(110, 100)
videoImageView.scaleType = ImageView.ScaleType.FIT_XY
videoImageView.load(videoArtworkUrl)
val videoTitleTextView = TextView(this@Main)
videoTitleTextView.layoutParams = LinearLayout.LayoutParams(deviceWidth - 120, 100)
videoTitleTextView.x = 120f
videoTitleTextView.text = videoTitle
videoTitleTextView.gravity = Gravity.CENTER_VERTICAL
val videoButton = View(this@Main)
videoButton.layoutParams = LinearLayout.LayoutParams(deviceWidth, 200)
videoButton.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
val playerRequest: String = Extractor().playerRequest(this@Main, videoID)
val playerObject = JSONObject(playerRequest)
val nextRequest: String = Extractor().nextRequest(this@Main, videoID)
val nextObject = JSONObject(nextRequest)
val artworkArray: JSONArray = playerObject.getJSONObject("videoDetails").getJSONObject("thumbnail").getJSONArray("thumbnails")
val artworkUrl: String = artworkArray.getJSONObject((artworkArray.length() - 1)).optString("url")
val title: String = nextObject.getJSONObject("contents").getJSONObject("singleColumnWatchNextResults").getJSONObject("results").getJSONObject("results").getJSONArray("contents").getJSONObject(1).getJSONObject("slimVideoMetadataSectionRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("elementRenderer").getJSONObject("newElement").getJSONObject("type").getJSONObject("componentType").getJSONObject("model").getJSONObject("videoMetadataModel").getJSONObject("videoMetadata").getJSONObject("title").optString("content")
val author: String = playerObject.getJSONObject("videoDetails").optString("author")
val videoUrl: String = playerObject.getJSONObject("streamingData").optString("hlsManifestUrl")
Application.setVideoData(
Gson().toJson(Data(
videoUrl,
artworkUrl,
title,
author
)))
startActivity(Intent(this@Main, Player::class.java))
}
}
videoRelativeView.addView(videoImageView)
videoRelativeView.addView(videoTitleTextView)
videoRelativeView.addView(videoButton)
scrollLayout.addView(videoRelativeView)
val spaceView = Space(this@Main)
spaceView.minimumHeight = 4
scrollLayout.addView(spaceView)
} catch (e: JSONException) {
Log.e("JSONException", e.toString())
}
}
}
return@OnKeyListener true
}
return@OnKeyListener false
})
}
override fun onDestroy() {
super.onDestroy()
if (wifiLock.isHeld) {
wifiLock.release()
}
if (wakeLock.isHeld) {
wakeLock.release()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7de01d8f41426d39654dd6b9c34baa3e1cd3d775
| 7,837
|
WearTube
|
MIT License
|
analysis/analysis-api-impl-base/tests/org/jetbrains/kotlin/analysis/api/impl/base/test/annotations/TestAnnotationRenderer.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.impl.base.test.annotations
import org.jetbrains.kotlin.analysis.api.annotations.KtAnnotationsList
import org.jetbrains.kotlin.analysis.api.impl.base.test.indented
import org.jetbrains.kotlin.analysis.api.symbols.DebugSymbolRenderer
object TestAnnotationRenderer {
fun renderAnnotations(annotations: KtAnnotationsList) = buildString {
appendLine("annotations: [")
for (annotation in annotations.annotations) {
appendLine(DebugSymbolRenderer.renderAnnotationApplication(annotation).indented(indent = 2))
}
appendLine("]")
}
}
| 135
|
Kotlin
|
4980
| 40,442
|
817f9f13b71d4957d8eaa734de2ac8369ad64770
| 829
|
kotlin
|
Apache License 2.0
|
transformer-rendition/alfresco-promena-lib-transformer-rendition/src/test/kotlin/pl/beone/promena/alfresco/lib/transformerrendition/external/rendition/PromenaRenditionGetterTest.kt
|
BeOne-PL
| 235,078,324
| false
|
{"Markdown": 15, "Text": 1, "Maven POM": 10, "Shell": 10, "Ignore List": 7, "Java": 13, "Kotlin": 204, "XML": 53, "Java Properties": 34, "INI": 12, "Dockerfile": 10, "YAML": 7}
|
package pl.beone.promena.alfresco.lib.transformerrendition.external.rendition
import io.kotlintest.shouldBe
import org.alfresco.model.ContentModel
import org.alfresco.model.RenditionModel
import org.alfresco.rad.test.AbstractAlfrescoIT
import org.alfresco.rad.test.AlfrescoTestRunner
import org.alfresco.service.cmr.repository.ChildAssociationRef
import org.alfresco.service.cmr.repository.NodeRef
import org.alfresco.service.namespace.NamespaceService.CONTENT_MODEL_1_0_URI
import org.alfresco.service.namespace.QName
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import pl.beone.promena.alfresco.lib.transformerrendition.contract.rendition.RenditionGetter
import pl.beone.promena.alfresco.lib.transformerrendition.external.util.createNameBasedOnDate
import pl.beone.promena.alfresco.lib.transformerrendition.external.util.createOrGetIntegrationTestsFolder
import pl.beone.promena.alfresco.module.core.applicationmodel.model.PromenaModel.PROPERTY_RENDITION_NAME
@RunWith(AlfrescoTestRunner::class)
class PromenaRenditionGetterTest : AbstractAlfrescoIT() {
private lateinit var nodeRef: NodeRef
private lateinit var nodeRefDoclib: ChildAssociationRef
private lateinit var nodeRefDoclib2: ChildAssociationRef
private lateinit var nodeRefPdf: ChildAssociationRef
private lateinit var nodeRef2: NodeRef
private lateinit var nodeRef2Pdf: ChildAssociationRef
private lateinit var renditionGetter: RenditionGetter
@Before
fun setUp() {
val integrationTestsFolder = serviceRegistry.createOrGetIntegrationTestsFolder()
nodeRef = integrationTestsFolder.createNode()
nodeRefDoclib = nodeRef.createRenditionNode().setRenditionName("doclib")
nodeRefDoclib2 = nodeRef.createRenditionNode().setRenditionName("doclib")
nodeRef.createRenditionNode()
nodeRefPdf = nodeRef.createRenditionNode().setRenditionName("pdf")
nodeRef2 = integrationTestsFolder.createNode()
nodeRef2Pdf = nodeRef2.createRenditionNode().setRenditionName("pdf")
renditionGetter = PromenaRenditionGetter(serviceRegistry.nodeService)
}
@Test
fun getRenditions() {
renditionGetter.getRenditions(nodeRef) shouldBe listOf(nodeRefDoclib, nodeRefDoclib2, nodeRefPdf)
renditionGetter.getRenditions(nodeRef2) shouldBe listOf(nodeRef2Pdf)
}
@Test
fun getRendition() {
renditionGetter.getRendition(nodeRef, "doclib") shouldBe nodeRefDoclib2
renditionGetter.getRendition(nodeRef, "pdf") shouldBe nodeRefPdf
renditionGetter.getRendition(nodeRef2, "pdf") shouldBe nodeRef2Pdf
}
@Test
fun getRendition_absentRenditions() {
renditionGetter.getRendition(nodeRef, "absent") shouldBe null
}
private fun NodeRef.createNode(targetType: QName = ContentModel.TYPE_CONTENT, name: String? = null): NodeRef {
val determinedNamePattern = name ?: createNameBasedOnDate()
return serviceRegistry.fileFolderService.create(this, determinedNamePattern, targetType).nodeRef
}
private fun NodeRef.createRenditionNode(): ChildAssociationRef =
serviceRegistry.nodeService.createNode(
this,
RenditionModel.ASSOC_RENDITION,
QName.createQName(CONTENT_MODEL_1_0_URI, createNameBasedOnDate()),
ContentModel.TYPE_THUMBNAIL,
emptyMap()
)
private fun ChildAssociationRef.setRenditionName(renditionName: String): ChildAssociationRef =
this.also { serviceRegistry.nodeService.setProperty(this.childRef, PROPERTY_RENDITION_NAME, renditionName) }
}
| 3
|
Kotlin
|
0
| 0
|
e981f383fbec1dd65538f101b26dc1dc3b8a6b38
| 3,616
|
promena-alfresco
|
Apache License 2.0
|
node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/SetsSerializationTest.kt
|
vegetish
| 106,048,965
| true
|
{"Kotlin": 3900840, "Java": 213817, "Groovy": 30106, "Shell": 839, "Batchfile": 106}
|
package net.corda.nodeapi.internal.serialization
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.util.DefaultClassResolver
import net.corda.core.serialization.serialize
import net.corda.node.services.statemachine.SessionData
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.kryoSpecific
import org.junit.Assert.*
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.util.*
class SetsSerializationTest : TestDependencyInjectionBase() {
private companion object {
val javaEmptySetClass = Collections.emptySet<Any>().javaClass
}
@Test
fun `check set can be serialized as root of serialization graph`() {
assertEqualAfterRoundTripSerialization(emptySet<Int>())
assertEqualAfterRoundTripSerialization(setOf(1))
assertEqualAfterRoundTripSerialization(setOf(1, 2))
}
@Test
fun `check set can be serialized as part of SessionData`() {
run {
val sessionData = SessionData(123, setOf(1))
assertEqualAfterRoundTripSerialization(sessionData)
}
run {
val sessionData = SessionData(123, setOf(1, 2))
assertEqualAfterRoundTripSerialization(sessionData)
}
run {
val sessionData = SessionData(123, emptySet<Int>())
assertEqualAfterRoundTripSerialization(sessionData)
}
}
@Test
fun `check empty set serialises as Java emptySet`() = kryoSpecific("Checks Kryo header properties") {
val nameID = 0
val serializedForm = emptySet<Int>().serialize()
val output = ByteArrayOutputStream().apply {
write(KryoHeaderV0_1.bytes)
write(DefaultClassResolver.NAME + 2)
write(nameID)
write(javaEmptySetClass.name.toAscii())
write(Kryo.NOT_NULL.toInt())
}
assertArrayEquals(output.toByteArray(), serializedForm.bytes)
}
}
| 11
|
Kotlin
|
0
| 0
|
f9614123968035cb325c6de0b84cf2718643f399
| 1,958
|
corda
|
Apache License 2.0
|
protocol/notify/src/main/kotlin/com/walletconnect/notify/data/jwt/getNotifications/EncodeGetNotificationsRequestJwtUseCase.kt
|
WalletConnect
| 435,951,419
| false
|
{"Kotlin": 2502705, "Java": 4366, "Shell": 1892}
|
@file:JvmSynthetic
package com.walletconnect.notify.data.jwt.getNotifications
import com.walletconnect.android.internal.common.jwt.did.EncodeDidJwtPayloadUseCase
import com.walletconnect.android.internal.common.model.AccountId
import com.walletconnect.foundation.common.model.PublicKey
import com.walletconnect.foundation.util.jwt.encodeDidPkh
import com.walletconnect.foundation.util.jwt.encodeDidWeb
import com.walletconnect.foundation.util.jwt.encodeEd25519DidKey
internal class EncodeGetNotificationsRequestJwtUseCase(
private val app: String,
private val accountId: AccountId,
private val authenticationKey: PublicKey,
private val limit: Int,
private val after: String?,
) : EncodeDidJwtPayloadUseCase<GetNotificationsRequestJwtClaim> {
override fun invoke(params: EncodeDidJwtPayloadUseCase.Params): GetNotificationsRequestJwtClaim = with(params) {
GetNotificationsRequestJwtClaim(
issuedAt = issuedAt,
expiration = expiration,
issuer = issuer,
keyserverUrl = keyserverUrl,
audience = encodeEd25519DidKey(authenticationKey.keyAsBytes),
subject = encodeDidPkh(accountId.value),
app = encodeDidWeb(app),
limit = limit,
after = after,
)
}
}
| 78
|
Kotlin
|
71
| 199
|
e373c535d7cefb2f932368c79622ac05763b411a
| 1,299
|
WalletConnectKotlinV2
|
Apache License 2.0
|
src/main/kotlin/ru/qiwi/devops/mission/control/service/search/SearchRequest.kt
|
qiwi
| 329,911,226
| false
| null |
package ru.qiwi.devops.mission.control.service.search
data class SearchRequest(
val filter: String,
val limit: Int
)
| 1
|
Kotlin
|
1
| 1
|
a5b4a1dc716841bbf0439fa309e3a2b85bbeb1d3
| 125
|
k8s-mission-control
|
MIT License
|
app/src/main/java/cz/blackchameleon/trendingprojects/framework/remote/LanguageMo.kt
|
klepackovakarolina
| 327,316,960
| false
| null |
package cz.blackchameleon.trendingprojects.framework.remote
import android.os.Parcelable
import cz.blackchameleon.domain.Language
import kotlinx.android.parcel.Parcelize
/**
* API object representation of language object
*
* @author <NAME> on 29.11.2020.
*/
@Parcelize
data class LanguageMo(
val urlParam: String?,
val name: String?
) : Parcelable {
fun toLanguage() = Language(
urlParam ?: "",
name ?: ""
)
}
| 0
|
Kotlin
|
0
| 0
|
43b8ca613f068f06dbc7c8a20569c0788f0bdf39
| 447
|
trending-projects
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.