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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bluetooth/bluetooth/src/androidTest/java/androidx/bluetooth/BluetoothAddressTest.kt | androidx | 256,589,781 | false | null | /*
* 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.bluetooth
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/** Test cases for [BluetoothAddress] */
@RunWith(JUnit4::class)
class BluetoothAddressTest {
companion object {
// TODO(kihongs) Change to actual public address if possible
private const val TEST_ADDRESS_PUBLIC = "00:43:A8:23:10:F0"
private const val TEST_ADDRESS_RANDOM_STATIC = "F0:43:A8:23:10:11"
private const val TEST_ADDRESS_UNKNOWN = "F0:43:A8:23:10:12"
}
@Test
fun constructorWithAddressTypePublic() {
val addressType = BluetoothAddress.ADDRESS_TYPE_PUBLIC
val bluetoothAddress = BluetoothAddress(TEST_ADDRESS_PUBLIC, addressType)
assertThat(bluetoothAddress.address).isEqualTo(TEST_ADDRESS_PUBLIC)
assertThat(bluetoothAddress.addressType).isEqualTo(addressType)
}
@Test
fun constructorWithAddressTypeRandomStatic() {
val addressType = BluetoothAddress.ADDRESS_TYPE_RANDOM_STATIC
val bluetoothAddress = BluetoothAddress(TEST_ADDRESS_RANDOM_STATIC, addressType)
assertThat(bluetoothAddress.address).isEqualTo(TEST_ADDRESS_RANDOM_STATIC)
assertThat(bluetoothAddress.addressType).isEqualTo(addressType)
}
@Test
fun constructorWithAddressTypeUnknown() {
val addressType = BluetoothAddress.ADDRESS_TYPE_UNKNOWN
val bluetoothAddress = BluetoothAddress(TEST_ADDRESS_UNKNOWN, addressType)
assertThat(bluetoothAddress.address).isEqualTo(TEST_ADDRESS_UNKNOWN)
assertThat(bluetoothAddress.addressType).isEqualTo(addressType)
}
@Test
fun constructorWithInvalidAddressType() {
val invalidAddressType = -1
assertFailsWith<IllegalArgumentException> {
BluetoothAddress(TEST_ADDRESS_UNKNOWN, invalidAddressType)
}
}
@Test
fun constructorWithInvalidAddress() {
val invalidAddress = "invalidAddress"
assertFailsWith<IllegalArgumentException> {
BluetoothAddress(invalidAddress, BluetoothAddress.ADDRESS_TYPE_UNKNOWN)
}
}
@Test
fun equality() {
val publicAddress =
BluetoothAddress(TEST_ADDRESS_PUBLIC, BluetoothAddress.ADDRESS_TYPE_PUBLIC)
val sameAddress =
BluetoothAddress(TEST_ADDRESS_PUBLIC, BluetoothAddress.ADDRESS_TYPE_PUBLIC)
val addressWithDifferentAddress =
BluetoothAddress(TEST_ADDRESS_RANDOM_STATIC, BluetoothAddress.ADDRESS_TYPE_PUBLIC)
val addressWithDifferentType =
BluetoothAddress(TEST_ADDRESS_PUBLIC, BluetoothAddress.ADDRESS_TYPE_RANDOM_STATIC)
assertThat(sameAddress).isEqualTo(publicAddress)
assertThat(sameAddress.hashCode()).isEqualTo(publicAddress.hashCode())
assertThat(publicAddress).isNotEqualTo(addressWithDifferentAddress)
assertThat(publicAddress).isNotEqualTo(addressWithDifferentType)
}
}
| 28 | null | 937 | 5,108 | 89ec14e39cf771106a8719337062572717cbad31 | 3,634 | androidx | Apache License 2.0 |
04.Recyclerviews/app/src/main/java/com/example/recyclerviews/MainAdapter.kt | NguyenNgocLe | 508,998,453 | false | {"Kotlin": 39811} | package com.example.recyclerviews
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.recyclerviews.databinding.RecyclerviewItemBinding
class MainAdapter(private val taskList: List<Task>) : RecyclerView.Adapter<MainAdapter.MainViewHolder>() {
inner class MainViewHolder(private val itemBinding: RecyclerviewItemBinding) :
RecyclerView.ViewHolder(itemBinding.root) {
fun bindItem(task: Task) {
itemBinding.titleTv.text = task.title
itemBinding.timeTv.text = task.timestamp
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
return MainViewHolder(
RecyclerviewItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
// binding data into item cells
val task = taskList[position]
holder.bindItem(task)
}
override fun getItemCount(): Int {
return taskList.size
}
} | 0 | Kotlin | 0 | 1 | 4f4da6deb73e1c11234b071a8e4ad61d501e4a13 | 1,176 | AndroidBasic | MIT License |
components/ledger/ledger-consensual-flow/src/test/kotlin/net/corda/ledger/consensual/flow/impl/transaction/ConsensualTransactionBuilderImplTest.kt | corda | 346,070,752 | false | null | package net.corda.ledger.consensual.flow.impl.transaction
import net.corda.ledger.common.data.transaction.CordaPackageSummaryImpl
import net.corda.ledger.common.test.dummyCpkSignerSummaryHash
import net.corda.ledger.consensual.test.ConsensualLedgerTest
import net.corda.ledger.consensual.testkit.ConsensualStateClassExample
import net.corda.ledger.consensual.testkit.consensualStateExample
import net.corda.v5.crypto.SecureHash
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import kotlin.test.assertIs
internal class ConsensualTransactionBuilderImplTest: ConsensualLedgerTest() {
@Test
fun `can build a simple Transaction`() {
val tx = consensualTransactionBuilder
.withStates(consensualStateExample)
.toSignedTransaction()
assertIs<SecureHash>(tx.id)
}
@Test
fun `can't sign twice`() {
assertThrows(IllegalStateException::class.java) {
val builder = consensualTransactionBuilder
.withStates(consensualStateExample)
builder.toSignedTransaction()
builder.toSignedTransaction()
}
}
@Test
fun `cannot build Transaction without Consensual States`() {
val exception = assertThrows(IllegalArgumentException::class.java) {
consensualTransactionBuilder.toSignedTransaction()
}
assertEquals("At least one consensual state is required", exception.message)
}
@Test
fun `cannot build Transaction with Consensual States without participants`() {
val exception = assertThrows(IllegalArgumentException::class.java) {
consensualTransactionBuilder
.withStates(consensualStateExample)
.withStates(ConsensualStateClassExample("test", emptyList()))
.toSignedTransaction()
}
assertEquals("All consensual states must have participants", exception.message)
}
@Test
fun `includes CPI and CPK information in metadata`() {
val tx = consensualTransactionBuilder
.withStates(consensualStateExample)
.toSignedTransaction() as ConsensualSignedTransactionImpl
val metadata = tx.wireTransaction.metadata
assertEquals(1, metadata.getLedgerVersion())
val expectedCpiMetadata = CordaPackageSummaryImpl(
"CPI name",
"CPI version",
"46616B652D76616C7565",
"416E6F746865722D46616B652D76616C7565",
)
assertEquals(expectedCpiMetadata, metadata.getCpiMetadata())
val expectedCpkMetadata = listOf(
CordaPackageSummaryImpl(
"MockCpk",
"1",
dummyCpkSignerSummaryHash.toString(),
"SHA-256:0101010101010101010101010101010101010101010101010101010101010101"
),
CordaPackageSummaryImpl(
"MockCpk",
"3",
dummyCpkSignerSummaryHash.toString(),
"SHA-256:0303030303030303030303030303030303030303030303030303030303030303"
)
)
assertEquals(expectedCpkMetadata, metadata.getCpkMetadata())
}
}
| 82 | Kotlin | 7 | 24 | 17f5d2e5585a8ac56e559d1c099eaee414e6ec5a | 3,248 | corda-runtime-os | Apache License 2.0 |
ui/src/commonMain/kotlin/com/popalay/barnee/ui/screen/bartender/BartenderScreen.kt | Popalay | 349,051,151 | false | null | /*
* Copyright (c) 2023 <NAME>
*
* 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.popalay.barnee.ui.screen.bartender
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import com.moriatsushi.insetsx.ExperimentalSoftwareKeyboardApi
import com.moriatsushi.insetsx.ime
import com.popalay.barnee.domain.Action
import com.popalay.barnee.domain.bartender.BartenderAction
import com.popalay.barnee.domain.bartender.BartenderState
import com.popalay.barnee.domain.bartender.BartenderStateMachine
import com.popalay.barnee.domain.navigation.AppScreens
import com.popalay.barnee.domain.navigation.NavigateBackAction
import com.popalay.barnee.domain.navigation.ParcelableScreen
import com.popalay.barnee.domain.navigation.ReplaceCurrentScreenAction
import com.popalay.barnee.ui.common.BarneeTextField
import com.popalay.barnee.ui.common.BottomSheetContent
import com.popalay.barnee.ui.extensions.injectStateMachine
import com.popalay.barnee.ui.icons.Cross
import com.popalay.barnee.ui.platform.collectAsStateWithLifecycle
import com.popalay.barnee.ui.screen.drinklist.DrinkListItem
import com.popalay.barnee.util.asStateFlow
import com.popalay.barnee.util.displayName
import com.popalay.barnee.util.toMinimumData
import io.matthewnelson.component.parcelize.Parcelize
@Parcelize
class BartenderScreen : ParcelableScreen {
@Composable
override fun Content() {
val stateMachine = injectStateMachine<BartenderStateMachine>()
val state by stateMachine.stateFlow.asStateFlow().collectAsStateWithLifecycle()
BartenderScreen(state, stateMachine::dispatch)
}
}
@OptIn(ExperimentalSoftwareKeyboardApi::class)
@Composable
private fun BartenderScreen(
state: BartenderState,
onAction: (Action) -> Unit
) {
Crossfade(targetState = state.generatedDrink, label = "bartender-content") { drink ->
if (drink != null) {
BottomSheetContent(
title = { Text(text = "Welcome ${drink.displayName}!") },
body = {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth()
) {
DrinkListItem(
data = drink,
onClick = { onAction(ReplaceCurrentScreenAction(AppScreens.Drink(drink.toMinimumData()))) },
modifier = Modifier.fillMaxWidth(0.5F)
)
}
},
navigation = {
IconButton(onClick = { onAction(NavigateBackAction) }) {
Icon(
imageVector = Icons.Cross,
tint = MaterialTheme.colors.onSurface,
contentDescription = "Close"
)
}
},
bottomPadding = WindowInsets.ime.asPaddingValues()
)
} else {
val promptFocus = remember { FocusRequester() }
LaunchedEffect(Unit) {
promptFocus.requestFocus()
}
BottomSheetContent(
title = { Text(text = "Let's shake!") },
action = {
IconButton(
onClick = { onAction(BartenderAction.OnGenerateDrinkClicked) },
enabled = state.isPromptValid && !state.isLoading
) {
if (state.isLoading) {
CircularProgressIndicator(
strokeWidth = 2.dp,
modifier = Modifier.size(16.dp)
)
} else {
Icon(
imageVector = if (state.isError) Icons.Default.Refresh else Icons.Default.Done,
contentDescription = "Shake"
)
}
}
},
body = {
Column {
BarneeTextField(
value = state.prompt,
onValueChange = { onAction(BartenderAction.OnPromptChanged(it)) },
label = { Text(text = "Explain what you want") },
placeholder = { Text(text = "e.g. sour cocktail with gin and cherry") },
isError = state.isError,
enabled = !state.isLoading,
singleLine = true,
textStyle = MaterialTheme.typography.body1,
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Unspecified,
focusedIndicatorColor = Color.Unspecified,
unfocusedIndicatorColor = Color.Unspecified,
disabledIndicatorColor = Color.Unspecified,
errorIndicatorColor = Color.Unspecified,
),
keyboardOptions = KeyboardOptions(
imeAction = if (state.isPromptValid) ImeAction.Done else ImeAction.None
),
keyboardActions = KeyboardActions(
onDone = {
if (state.isPromptValid) {
onAction(BartenderAction.OnGenerateDrinkClicked)
}
}
),
modifier = Modifier
.fillMaxWidth()
.focusRequester(promptFocus)
)
if (state.isError) {
Text(
text = state.error,
color = MaterialTheme.colors.error,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(start = 16.dp)
)
}
}
},
navigation = {
IconButton(onClick = { onAction(NavigateBackAction) }) {
Icon(
imageVector = Icons.Cross,
tint = MaterialTheme.colors.onSurface,
contentDescription = "Close"
)
}
},
bottomPadding = WindowInsets.ime.asPaddingValues()
)
}
}
}
| 21 | Kotlin | 3 | 15 | 22cd50b851d7be321339e8674099aa01fe7e1c3f | 9,230 | Barnee | MIT License |
src/main/java/com/vdzon/maven/plugin/deptree/ArtifactModuleService.kt | robbertvdzon | 93,847,699 | false | {"JavaScript": 27122, "Kotlin": 23789, "HTML": 12535} | package com.vdzon.maven.plugin.deptree
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.vdzon.maven.plugin.deptree.jsonmodel.ArtifactModules
import java.io.File
class ArtifactModuleService {
fun serializeArtifactModules(artifactModules: ArtifactModules): String {
val mapper = ObjectMapper(YAMLFactory())
return mapper.writeValueAsString(artifactModules)
}
fun deserializeArtifactModules(yaml: String): ArtifactModules {
val mapper = ObjectMapper(YAMLFactory())
return mapper.readValue(yaml, ArtifactModules::class.java)
}
fun getExistsingOrNewArtifactModules(yamlFilename: String, artifactModuleService: ArtifactModuleService) = if (artifactModulesFileExists(yamlFilename)) readArtifactModules(artifactModuleService, yamlFilename) else ArtifactModules()
private fun readArtifactModules(artifactModuleService: ArtifactModuleService, yamlFilename: String) = artifactModuleService.deserializeArtifactModules(File(yamlFilename).readText(charset = Charsets.UTF_8))
private fun artifactModulesFileExists(yamlFilename: String) = File(yamlFilename).exists()
} | 0 | JavaScript | 0 | 0 | 04f2292e27a83df5a8a658bb5553dd1127c87cfc | 1,191 | deptree | The Unlicense |
android/src/main/java/one/tesseract/devwallet/ui/settings/key/KeySettingsFragment.kt | tesseract-one | 588,297,120 | false | {"Rust": 54740, "Swift": 33820, "Kotlin": 23532, "Shell": 2642} | package one.tesseract.devwallet.ui.settings.key
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import one.tesseract.devwallet.Application
import one.tesseract.devwallet.databinding.FragmentKeySettingsBinding
class KeySettingsFragment : Fragment() {
private var _binding: FragmentKeySettingsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val viewModel = ViewModelProvider(this).get(KeySettingsViewModel::class.java)
//late bind
val application = this.activity?.application as Application
viewModel.provider = application.core.keySettingsProvider()
viewModel.load()
_binding = FragmentKeySettingsBinding.inflate(inflater, container, false)
binding.model = viewModel
binding.lifecycleOwner = this
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Rust | 4 | 3 | e031304ed1d1906b34548c77a808e6093b0049c1 | 1,291 | dev-wallet | Apache License 2.0 |
meteor-core/src/commonTest/kotlin/fake/FakeViewModel.kt | getspherelabs | 646,328,849 | false | null | package fake
import io.spherelabs.meteor.configs.MeteorConfigs
import io.spherelabs.meteor.store.Store
import io.spherelabs.meteor.viewmodel.CommonViewModel
import io.spherelabs.meteor.viewmodel.createMeteor
import io.spherelabs.meteorviewmodel.commonflow.NonNullCommonFlow
import io.spherelabs.meteorviewmodel.commonflow.NonNullCommonStateFlow
import io.spherelabs.meteorviewmodel.commonflow.asCommonFlow
import io.spherelabs.meteorviewmodel.commonflow.asCommonStateFlow
class FakeViewModel : CommonViewModel<FakeCountState, FakeCountWish, FakeCountEffect>() {
override val store: Store<FakeCountState, FakeCountWish, FakeCountEffect> = createMeteor(
configs = MeteorConfigs.build {
initialState = FakeCountState()
storeName = "fake.FakeViewModel"
reducer = FakeCountReducer
middleware = FakeCountMiddleware
}
)
val effect: NonNullCommonFlow<FakeCountEffect> = store.effect.asCommonFlow()
val state: NonNullCommonStateFlow<FakeCountState> = store.state.asCommonStateFlow()
}
| 6 | Kotlin | 1 | 9 | 0e6b5aecfcea88d5c6ff7070df2e0ce07edc5457 | 1,060 | meteor | Apache License 2.0 |
app/src/main/java/dev/tcode/thinmp/view/swipe/SwipeToDismissView.kt | tcode-dev | 392,735,283 | false | {"Kotlin": 247868} | package dev.tcode.thinmp.view.swipe
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.DismissDirection
import androidx.compose.material.DismissValue
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.SwipeToDismiss
import androidx.compose.material.rememberDismissState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import java.util.UUID
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeToDismissView(callback: () -> Unit, content: @Composable RowScope.() -> Unit) {
key(UUID.randomUUID()) {
val dismissState = rememberDismissState(confirmStateChange = {
if (it == DismissValue.DismissedToStart) {
callback()
true
} else {
false
}
})
SwipeToDismiss(state = dismissState, directions = setOf(DismissDirection.EndToStart), background = {}, dismissContent = content)
}
} | 0 | Kotlin | 0 | 7 | 22ec049746cce5e019ebf38cb35a4b306c628892 | 1,000 | ThinMP_Android_Kotlin | MIT License |
bitapp/src/main/java/com/atech/bit/ui/fragments/events/EventViewModel.kt | BIT-Lalpur-App | 489,575,997 | false | {"Kotlin": 581061} | package com.atech.bit.ui.fragments.events
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import com.atech.core.firebase.firestore.Db
import com.atech.core.firebase.firestore.EventModel
import com.atech.core.firebase.firestore.FirebaseCases
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class EventViewModel @Inject constructor(
private val cases: FirebaseCases
) : ViewModel() {
val allEvents = cases.getData
.invoke(
EventModel::class.java,
Db.Event
).asLiveData()
fun getAttach(path: String) = cases.getAttach.invoke(
Db.Event,
path
).asLiveData()
} | 2 | Kotlin | 5 | 13 | a1a0834158159750b71fb6a51d3e007524e2796c | 699 | BIT-App | MIT License |
compose-multiplatform-lifecycle-viewmodel/src/androidxCommonMain/kotlin/ViewModel.androidxCommon.kt | huanshankeji | 570,509,992 | false | {"Kotlin": 330635} | package com.huanshankeji.androidx.lifecycle.viewmodel.compose
import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
actual inline fun <reified VM : ViewModel> viewModel(key: String?, noinline initializer: CreationExtras.() -> VM): VM =
viewModel(key = key, initializer = initializer)
| 20 | Kotlin | 0 | 16 | 44e6bb560653463549d3a09e011b15f8f4b88743 | 432 | compose-multiplatform-material | Apache License 2.0 |
libraries/rib-base/src/main/java/com/badoo/ribs/routing/transition/Transition.kt | badoo | 170,855,556 | false | null | package com.badoo.ribs.routing.transition
import android.animation.ValueAnimator
import com.badoo.ribs.routing.transition.effect.helper.ReverseHolder
/**
* Interfaces between internal routing changes and client code animations.
*/
interface Transition {
fun start()
fun end()
fun reverse()
companion object {
fun multiple(vararg transitions: Collection<Transition?>) = object : Transition {
override fun start() {
transitions.forEach {
it.forEach { it?.start() }
}
}
override fun end() {
transitions.forEach {
it.forEach { it?.end() }
}
}
override fun reverse() {
transitions.forEach {
it.forEach { it?.reverse() }
}
}
}
fun from(valueAnimator: ValueAnimator, reverseHolder: ReverseHolder = ReverseHolder()) =
object : Transition {
override fun start() {
valueAnimator.start()
}
override fun end() {
valueAnimator.end()
}
override fun reverse() {
valueAnimator.reverse()
reverseHolder.isReversing = !reverseHolder.isReversing
}
}
}
}
| 34 | null | 50 | 162 | cec2ca936ed17ddd7720b4b7f8fca4ce12033a89 | 1,423 | RIBs | Apache License 2.0 |
app/src/main/java/com/example/fuzzychainsaw/view/cloud/Star.kt | skywish | 307,710,933 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 18, "XML": 14, "Java": 1, "Protocol Buffer": 1} | package com.example.fuzzychainsaw.view.cloud
class Star(
var x: Float,
var y: Float,
var angleInRadians: Float,
var speed: Float,
var offset: Float,
var maxOffset: Int,
var alpha: Int
) | 1 | null | 1 | 1 | 0eb11212ed557493f78cfb641ea7bf2b45c03397 | 214 | FuzzyChainsaw | Apache License 2.0 |
schoolapi/src/main/java/me/sungbin/schoolapi/library/school/SchoolException.kt | jisungbin | 318,529,634 | false | null | package me.sungbin.schoolapi.library.school
class SchoolException(message: String) : Exception(message) | 0 | Kotlin | 0 | 2 | 0526e60cf2c21a774db2b390c62d2f3055550579 | 104 | SchoolAPI | MIT License |
core-api/src/main/java/pl/netigen/coreapi/rateus/IRateUs.kt | netigenkluzowicz | 165,630,654 | false | null | package pl.netigen.coreapi.rateus
import pl.netigen.coreapi.main.Store
/**
* Rate us module is used for show user dialog to encourage him to rate application in store and/or write application review
*
*/
interface IRateUs {
/**
* After this number of calls [increaseOpeningCounter], rate us dialog will be showed
*/
val numberOfChecksBeforeShowingDialog: Int
/**
* Counts calls of [increaseOpeningCounter]
*/
val openingCounter: Int
/**
* It should be called to count number of times user launches app
*
*/
fun increaseOpeningCounter()
/**
* Checks how many user uses app [openingCounter], and shows Rate Us dialog when this reach [numberOfChecksBeforeShowingDialog]
*
* @return if Rate Us dialog should be showed
*/
fun shouldOpenRateUs(): Boolean
/**
* Saves info that user don't wants to see Rate Us dialog again
*
*/
fun doNotShowRateUsAgain()
/**
* Checks if [shouldOpenRateUs] and if it is true shows Rate Us dialog
*
* @return if Rate Us dialog is opened
*/
fun openRateDialogIfNeeded(): Boolean
/**
* Shows Rate Us dialog
*
*/
fun openRateDialog()
/**
* Called on click in dialog
*
* Directs user to current [Store], with intention to rate application
*
*
*/
fun clickYes()
/**
* Called on click in dialog, after that rate us dialog will not be showed again
*
*/
fun clickNo()
/**
* Called on click in dialog, after that [openingCounter] is reset, and dialog will be showed later again
*
*/
fun clickLater()
}
| 8 | Kotlin | 0 | 1 | bab19b5f5f649424ea38fb9fe1f77d0be58ad3f8 | 1,677 | api_android | Apache License 2.0 |
app/src/main/java/com/kazufukurou/nanji/model/TimeSystem.kt | artyommironov | 200,369,203 | false | null | package com.kazufukurou.nanji.model
import android.annotation.SuppressLint
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class TimeSystem(
private val locale: Locale,
private val useTwentyFourHours: Boolean
) : Time {
override fun getPercentText(value: Int): String = "$value%"
override fun getDateText(cal: Calendar): String {
return DateFormat.getDateInstance(DateFormat.FULL, locale)
.apply { timeZone = cal.timeZone }
.format(cal.time)
}
@SuppressLint("SimpleDateFormat")
override fun getTimeText(cal: Calendar): String {
return SimpleDateFormat(if (useTwentyFourHours) "H:mm" else "h:mm a")
.apply { timeZone = cal.timeZone }
.format(cal.time)
}
}
| 4 | Kotlin | 1 | 7 | 246b0029f7697e410ed4262405885d677a405ae1 | 771 | nanji | Apache License 2.0 |
app/src/main/java/com/fwhyn/myapplication/util/other/doctor_reservation/GetWaitingTime.kt | fwhyn | 549,536,246 | false | {"Kotlin": 345398, "Java": 135939} | package com.fwhyn.myapplication.util.other.doctor_reservation
class GetWaitingTime {
fun getWaitingTimeOrNull(doctors: List<Doctor>, patient: Int): Int? {
// make sure that do not edit original source of doctor
val copyOfDoctors = getCopyOfDoctors(doctors)
var availableDoctor: Doctor? = null
if (copyOfDoctors.isNotEmpty()) {
for (i in 1..patient) {
availableDoctor = getAvailableDoctor(copyOfDoctors)
incrementDoctorTimeStep(availableDoctor)
}
}
return availableDoctor?.timeStep
}
private fun getCopyOfDoctors(doctorsToCopy: List<Doctor>): List<Doctor> {
val copiedArray = ArrayList<Doctor>()
doctorsToCopy.map {
copiedArray.add(it.copy())
}
return copiedArray
}
private fun getAvailableDoctor(doctors: List<Doctor>): Doctor {
val timeStep = getMinTimeStep(doctors)
val doctorsWithMinTimeStep = getDoctorsWithMinTimeStep(timeStep, doctors)
return getDoctorWithMinConsultationTime(doctorsWithMinTimeStep)
}
private fun getMinTimeStep(doctors: List<Doctor>): Int {
val doctor = getDoctorWithMinTimeStepIncrement(doctors)
return doctor.timeStep
}
private fun getDoctorWithMinTimeStepIncrement(doctors: List<Doctor>): Doctor {
return doctors.minBy { it.timeStep + it.consultationTimeMinute }
}
private fun getDoctorsWithMinTimeStep(timeStep: Int, doctors: List<Doctor>): List<Doctor> {
val doctorList = ArrayList<Doctor>()
doctors.map {
if (timeStep == it.timeStep) {
doctorList.add(it)
}
}
return doctorList
}
private fun getDoctorWithMinConsultationTime(doctors: List<Doctor>): Doctor {
return doctors.minBy { it.consultationTimeMinute }
}
private fun incrementDoctorTimeStep(doctor: Doctor) {
doctor.timeStep += doctor.consultationTimeMinute
}
} | 0 | Kotlin | 0 | 0 | 6634e98a42906b74083a18432e53bfe66b83c0c7 | 2,010 | MyApplication_Android | Apache License 2.0 |
src/main/java/net/eduard/api/server/ChatSystem.kt | EduardMaster | 103,982,025 | false | null | package net.eduard.api.server
interface ChatSystem : PluginSystem {
fun isMuted(playerName : String) : Boolean
fun mute(playerName: String)
fun getPlayersMuted() : List<String>
} | 0 | null | 5 | 7 | bb778365ce76fabbdbc516b918b4feedee7edf12 | 194 | MineToolkit | MIT License |
app/src/main/java/com/sefford/artdrian/usecases/DownloadWallpaper.kt | Sefford | 562,415,198 | false | {"Kotlin": 86829} | package com.sefford.artdrian.usecases
import android.os.Environment
import arrow.core.Either
import com.sefford.artdrian.common.FileManager
import java.io.File
import javax.inject.Inject
class DownloadWallpaper @Inject constructor(
private val fileManager: FileManager
) {
suspend fun download(url: String): Either<PersistingError, String> {
return Either.catch {
fileManager.saveFileIntoDirectory(
url,
Environment.DIRECTORY_PICTURES + File.separator + "Wallpapers" + File.separator + "Artdrian" + File.separator +
url.substringAfterLast("/"))
}.mapLeft { exception ->
PersistingError(exception)
}
}
class PersistingError(val exception: Throwable)
}
| 1 | Kotlin | 1 | 2 | 341cd0a2d30936aa40f6f00cf184a8aac6b8a39d | 775 | Artdrian | Apache License 2.0 |
domain-model/src/main/kotlin/net/octosystems/foodversity/model/units/body/TotalDailyEnergyExpenditure.kt | schmitzCatz | 640,629,294 | false | null | package net.octosystems.foodversity.model.units.body
import net.octosystems.foodversity.model.units.energy.KiloCalorie
data class TotalDailyEnergyExpenditure(
val bmr: BasalMetabolicRate,
val amr: ActiveMetabolicRate,
) {
val value: KiloCalorie
get() = KiloCalorie.of((bmr.value + amr.value).getValue())
}
| 0 | Kotlin | 0 | 0 | 08dc2ea082be38244c504d0c9988bbf8cfcac446 | 328 | foodversity | Apache License 2.0 |
src/main/kotlin/dev/crashteam/repricer/service/encryption/PasswordEncryptor.kt | crashteamdev | 513,840,113 | false | {"Kotlin": 391804, "Java": 188503, "Dockerfile": 613, "PLpgSQL": 483} | package dev.crashteam.repricer.service.encryption
interface PasswordEncryptor {
fun encryptPassword(password: String): ByteArray
fun decryptPassword(password: ByteArray): String
}
| 11 | Kotlin | 0 | 0 | 6462eedc6672434a33641f1e41ae96f711e477eb | 190 | ke-space | Apache License 2.0 |
fxgl/src/main/kotlin/com/almasb/fxgl/scene/FXGLScene.kt | Ravanla | 205,673,093 | true | {"YAML": 2, "Maven POM": 20, "Markdown": 7, "Text": 15, "Ignore List": 1, "XML": 25, "Shell": 1, "Kotlin": 258, "Java": 262, "CSS": 6, "kvlang": 2, "JavaScript": 11, "JSON": 6, "Java Properties": 7} | package com.almasb.fxgl.scene
import com.almasb.fxgl.dsl.FXGL
import javafx.beans.property.BooleanProperty
import javafx.beans.property.DoubleProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.geometry.Point2D
import javafx.scene.ImageCursor
import javafx.scene.effect.Effect
import javafx.scene.image.Image
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.BackgroundImage
import javafx.scene.layout.BackgroundRepeat
import javafx.scene.paint.Paint
import javafx.scene.shape.Rectangle
import javafx.scene.transform.Scale
/**
* Base class for all FXGL scenes.
*/
abstract class FXGLScene
@JvmOverloads constructor(width: Int = FXGL.getAppWidth(), height: Int = FXGL.getAppHeight()) : Scene() {
val viewport = Viewport(width.toDouble(), height.toDouble())
val paddingTop = Rectangle()
val paddingBot = Rectangle()
val paddingLeft = Rectangle()
val paddingRight = Rectangle()
init {
paddingTop.widthProperty().bind(root.prefWidthProperty())
paddingTop.heightProperty().bind(contentRoot.translateYProperty())
paddingBot.translateYProperty().bind(root.prefHeightProperty().subtract(paddingTop.heightProperty()))
paddingBot.widthProperty().bind(root.prefWidthProperty())
paddingBot.heightProperty().bind(paddingTop.heightProperty())
paddingLeft.widthProperty().bind(contentRoot.translateXProperty())
paddingLeft.heightProperty().bind(root.prefHeightProperty())
paddingRight.translateXProperty().bind(root.prefWidthProperty().subtract(paddingLeft.widthProperty()))
paddingRight.widthProperty().bind(contentRoot.translateXProperty())
paddingRight.heightProperty().bind(root.prefHeightProperty())
root.children.addAll(paddingTop, paddingBot, paddingLeft, paddingRight)
}
val width: Double
get() = root.prefWidth
val height: Double
get() = root.prefHeight
/**
* Applies given effect to the scene.
*
* @param effect the effect to apply
* @return currently applied effect or null if no effect is applied
*/
var effect: Effect?
get() = contentRoot.effect
set(effect) {
contentRoot.effect = effect
}
private val active = SimpleBooleanProperty(false)
/**
* Removes any effects applied to the scene.
*/
fun clearEffect() {
effect = null
}
/**
* @param image cursor image
* @param hotspot hotspot location
*/
fun setCursor(image: Image, hotspot: Point2D) {
root.cursor = ImageCursor(image, hotspot.x, hotspot.y)
}
/**
* If a scene is active it is being shown by the display.
*
* @return active property
*/
fun activeProperty(): BooleanProperty {
return active
}
fun appendCSS(css: CSS) {
root.stylesheets.add(css.externalForm)
}
fun clearCSS() {
root.stylesheets.clear()
}
fun bindSize(scaledWidth: DoubleProperty, scaledHeight: DoubleProperty, scaleRatioX: DoubleProperty, scaleRatioY: DoubleProperty) {
root.prefWidthProperty().bind(scaledWidth)
root.prefHeightProperty().bind(scaledHeight)
val scale = Scale()
scale.xProperty().bind(scaleRatioX)
scale.yProperty().bind(scaleRatioY)
contentRoot.transforms.setAll(scale)
contentRoot.translateXProperty().bind(scaledWidth.divide(2).subtract(scaleRatioX.multiply(viewport.width).divide(2)))
contentRoot.translateYProperty().bind(scaledHeight.divide(2).subtract(scaleRatioY.multiply(viewport.height).divide(2)))
}
fun setBackgroundColor(color: Paint) {
root.background = Background(BackgroundFill(color, null, null))
}
/**
* Convenience method to load the texture and repeat as often as needed to cover the background.
*/
fun setBackgroundRepeat(textureName: String) {
setBackgroundRepeat(FXGL.texture(textureName).image)
}
/**
* The image is repeated as often as needed to cover the background.
*/
fun setBackgroundRepeat(image: Image) {
root.background = Background(BackgroundImage(image,
BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, null, null))
}
} | 0 | Java | 0 | 1 | 25433dbdebb4c358eabe622063fac0ccc8a910f6 | 4,309 | FXGL | MIT License |
app/src/main/java/com/example/root/kotlin_eyepetizer/custome/SplashTextView_Chinese.kt | jiwenjie | 156,038,520 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 123, "XML": 91, "Java": 17} | package com.example.root.kotlin_eyepetizer.custome
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.TextView
/**
* author:Jiwenjie
* email:<EMAIL>
* time:2018/11/07
* desc: 中文的字体显示
* tips: 如果只写只有一个参数的构造器 会失效
* version:1.0
*/
class SplashTextView_Chinese : TextView {
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet): super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int): super(context, attrs, defStyle)
override fun setTypeface(tf: Typeface?) {
super.setTypeface(Typeface.createFromAsset(context.assets, "fonts/FZLanTingHeiS-L-GB-Regular.TTF"))
}
} | 1 | null | 1 | 1 | 104af621e315bc5588f97206ca04438a082875b9 | 741 | Kotlin_Eyepetizer | Apache License 2.0 |
app/src/main/java/com/uttarakhand/kisanseva2/model/Data.kt | shivamkumard107 | 281,345,064 | false | null | package com.uttarakhand.kisanseva2.model
data class Data(
val address: String,
val district: String,
val items: List<Item>,
val local_access_token: String,
val name: String,
val phone: String,
val products: List<Any>
) | 0 | null | 2 | 3 | 3fd81824f4cf12ad9ed2ee95dddde65e3732da79 | 247 | KisanSeva2 | MIT License |
tmp/arrays/kotlinAndJava/411.kt | mandelshtamd | 249,374,670 | true | {"Kotlin": 7965847} | //File M.java
import kotlin.Metadata;
import org.jetbrains.annotations.NotNull;
public final class M {
public final long component1(long $this$component1) {
return $this$component1 + 1L;
}
public final long component2(long $this$component2) {
return $this$component2 + (long)2;
}
@NotNull
public final String doTest() {
String s = "";
long var2 = 0L;
for(long var4 = 2L; var2 <= var4; ++var2) {
long a = this.component1(var2);
long b = this.component2(var2);
s = s + a + ':' + b + ';';
}
return s;
}
}
//File Main.kt
fun box(): String {
val s = M().doTest()
return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s"
}
| 1 | Kotlin | 1 | 1 | da010bdc91c159492ae74456ad14d93bdb5fdd0a | 717 | bbfgradle | Apache License 2.0 |
simplified-accounts-api/src/main/java/org/nypl/simplified/accounts/api/AccountPassword.kt | ThePalaceProject | 367,082,997 | false | null | package org.nypl.simplified.accounts.api
/**
* An account password.
*/
data class AccountPassword(val value: String) {
override fun toString(): String {
return "[REDACTED]"
}
}
| 1 | null | 4 | 8 | 95ea5f21c6408207eddccb7210721743d57a500f | 189 | android-core | Apache License 2.0 |
web/src/main/kotlin/app/himawari/dto/json/ApiEnums.kt | cxpqwvtj | 69,770,215 | false | null | // Code generated by Node.js script
package app.himawari.dto.json
enum class VacationType(val description: String) {
PAID_DAY_OFF("有給休暇"),
SP_DAY_OFF("特別休暇"),
AM_OFF("AM休"),
PM_OFF("PM休"),
TRANSFER_DAY_OFF("振替休暇")
}
enum class ResultType(val description: String) {
success(""),
failure("")
} | 1 | null | 1 | 1 | 36e3586eae320a5b39d086cb102d33cfcd8bf606 | 321 | himawari | MIT License |
frontend/chrome-extension/options/src/main/kotlin/com/jakewharton/sdksearch/options/Options.kt | avjinder | 136,703,041 | true | {"Gradle": 39, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "EditorConfig": 1, "Text": 1, "Markdown": 4, "XML": 51, "Kotlin": 84, "Proguard": 2, "JSON": 1, "HTML": 1, "INI": 1, "Java": 1, "YAML": 1} | package com.jakewharton.sdksearch.options
import com.chrome.platform.Chrome
import com.jakewharton.sdksearch.options.presenter.OptionsPresenter
import com.jakewharton.sdksearch.options.ui.OptionsUiBinder
import com.jakewharton.sdksearch.reference.PRODUCTION_DAC
import com.jakewharton.sdksearch.reference.PRODUCTION_GIT_WEB
import com.jakewharton.sdksearch.store.config.StorageAreaConfigStore
import kotlinx.coroutines.experimental.DefaultDispatcher
import kotlinx.coroutines.experimental.Unconfined
import kotlinx.coroutines.experimental.launch
import kotlin.browser.document
fun main(vararg args: String) {
val configStore = StorageAreaConfigStore(Chrome.storage.sync, PRODUCTION_GIT_WEB, PRODUCTION_DAC)
val presenter = OptionsPresenter(DefaultDispatcher, configStore)
presenter.start()
val binder = OptionsUiBinder(document, presenter.events)
document.addEventListener("DOMContentLoaded", {
launch(Unconfined) {
var oldModel: OptionsPresenter.Model? = null
for (model in presenter.models) {
binder.bind(model, oldModel)
oldModel = model
}
}
})
}
| 0 | Kotlin | 0 | 2 | 954f98c8c0f5661e8a1d58362ac316e0ba1b92bd | 1,108 | SdkSearch | Apache License 2.0 |
sample/src/main/java/com/zackratos/ultimatebarx/sample/MainActivity.kt | msdgwzhy6 | 278,021,402 | false | {"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 19, "XML": 34, "INI": 1, "Java": 1} | package com.zackratos.ultimatebarx.sample
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.zackratos.ultimatebarx.library.UltimateBarX
import com.zackratos.ultimatebarx.sample.viewpager.ViewPagerActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
UltimateBarX.create(UltimateBarX.STATUS_BAR)
.fitWindow(true)
.bgColorRes(R.color.deepSkyBlue)
.apply(this)
UltimateBarX.create(UltimateBarX.NAVIGATION_BAR)
.fitWindow(true)
.bgColorRes(R.color.deepSkyBlue)
.apply(this)
btnTransparent.setOnClickListener { start(TransparentActivity::class.java) }
btnSwitch.setOnClickListener { start(SwitchActivity::class.java) }
btnViewPager.setOnClickListener { start(ViewPagerActivity::class.java) }
btnScroll.setOnClickListener { start(ScrollActivity::class.java) }
}
private fun start(clazz: Class<out Activity>) {
startActivity(Intent(this, clazz))
}
}
| 1 | null | 1 | 1 | eaadcc4e08b5c91db4b8fd0016b753e9b29bcde8 | 1,315 | UltimateBarX | Apache License 2.0 |
src/main/kotlin/com/micabytes/ink/Conditional.kt | micabytes | 54,374,606 | false | null | package com.micabytes.ink
import com.micabytes.ink.util.InkParseException
import java.util.*
internal class Conditional @Throws(InkParseException::class)
constructor(header: String,
parent: Container,
lineNumber: Int) : Container(getId(parent), "", parent, lineNumber) {
internal enum class SequenceType {
SEQUENCE_NONE,
SEQUENCE_CYCLE,
SEQUENCE_ONCE,
SEQUENCE_SHUFFLE,
SEQUENCE_STOP
}
private var seqType: SequenceType = SequenceType.SEQUENCE_NONE
init {
val str = header.substring(1).trim({ it <= ' ' })
if (!str.isEmpty()) {
if (!str.endsWith(":"))
throw InkParseException("Error in conditional block; initial condition not ended by \':\'. Line number: $lineNumber")
val condition = str.substring(0, str.length - 1).trim({ it <= ' ' })
verifySequenceCondition(condition)
if (seqType == SequenceType.SEQUENCE_NONE) {
children.add(ConditionalOption(header, this, lineNumber))
}
}
}
fun resolveConditional(story: Story): Container {
index = size
when (seqType) {
SequenceType.SEQUENCE_NONE -> {
for (opt in children) {
if ((opt as ConditionalOption).evaluate(story)) {
return opt
}
}
}
SequenceType.SEQUENCE_CYCLE -> return children[count % children.size] as Container
SequenceType.SEQUENCE_ONCE -> if (count < size) return children[count] as Container
SequenceType.SEQUENCE_SHUFFLE -> return children[Random().nextInt(children.size)] as Container
SequenceType.SEQUENCE_STOP -> return children[if (count >= children.size) children.size - 1 else count] as Container
}
val empty = ConditionalOption("", this, 0)
children.remove(empty)
return empty
}
private fun verifySequenceCondition(str: String) {
if (STOPPING.equals(str, ignoreCase = true))
seqType = SequenceType.SEQUENCE_STOP
if (SHUFFLE.equals(str, ignoreCase = true))
seqType = SequenceType.SEQUENCE_SHUFFLE
if (CYCLE.equals(str, ignoreCase = true))
seqType = SequenceType.SEQUENCE_CYCLE
if (ONCE.equals(str, ignoreCase = true))
seqType = SequenceType.SEQUENCE_ONCE
}
companion object {
private const val STOPPING = "stopping"
private const val SHUFFLE = "shuffle"
private const val CYCLE = "cycle"
private const val ONCE = "once"
fun isConditionalHeader(str: String): Boolean {
return str.startsWith(Symbol.CBRACE_LEFT) && !str.contains(Symbol.CBRACE_RIGHT)
}
}
}
| 0 | Kotlin | 1 | 17 | b413aa6bf6c26706a37b0659bc4361217dca050d | 2,536 | mica-ink | MIT License |
config/src/main/kotlin/org/springframework/security/config/web/servlet/CorsDsl.kt | lenxin | 310,797,201 | true | {"INI": 18, "Shell": 7, "Batchfile": 1, "Java": 2837, "SQL": 14, "HTML": 34, "CSS": 17, "Gradle Kotlin DSL": 2, "Kotlin": 138, "Java Server Pages": 49, "Java Properties": 14, "JavaScript": 15, "Python": 1, "PLSQL": 1, "Markdown": 4, "Ruby": 2} | package org.springframework.security.config.web.servlet
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.CorsConfigurer
/**
* A Kotlin DSL to configure [HttpSecurity] CORS using idiomatic Kotlin code.
*
* @author <NAME>
* @since 5.3
*/
@SecurityMarker
class CorsDsl {
private var disabled = false
/**
* Disable CORS.
*/
fun disable() {
disabled = true
}
internal fun get(): (CorsConfigurer<HttpSecurity>) -> Unit {
return { cors ->
if (disabled) {
cors.disable()
}
}
}
}
| 0 | Java | 0 | 0 | 9cc4bd14b66afcb0142c9a0df35738342a5eeaa4 | 679 | spring-security | Apache License 2.0 |
android/src/main/java/si/inova/kotlinova/utils/ViewModel.kt | ksenchy | 248,297,669 | false | {"Gradle": 12, "XML": 18, "Markdown": 2, "Text": 1, "Java Properties": 2, "Shell": 2, "Ignore List": 8, "Batchfile": 1, "JavaScript": 1, "INI": 1, "Kotlin": 235, "Proguard": 5, "Java": 1, "Groovy": 2} | /*
* Copyright 2020 INOVA IT d.o.o.
*
* 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.
*
*/
@file:JvmName("ViewModelUtils")
package si.inova.kotlinova.utils
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
/**
* @author Matej Drobnic
*/
/**
* Convenience method to quickly load [ViewModel] without manually specifying its class.
*/
inline fun <reified T : ViewModel> ViewModelProvider.load(): T {
return get(T::class.java)
}
/**
* Create ViewModel for specified activity
*/
inline fun <reified T : ViewModel> ViewModelProvider.Factory.create(activity: FragmentActivity): T {
return ViewModelProviders.of(activity, this).load()
}
/**
* Create ViewModel for specified fragment
*/
inline fun <reified T : ViewModel> ViewModelProvider.Factory.create(fragment: Fragment): T {
return ViewModelProviders.of(fragment, this).load()
}
/**
* Create ViewModel for activity that hosts specified fragment.
* Used to share same ViewModel instances across different fragments inside activity.
*/
inline fun <reified T : ViewModel> ViewModelProvider.Factory.createFromActivity(
fragment: Fragment
): T {
return ViewModelProviders.of(fragment.requireActivity(), this).load()
} | 1 | null | 1 | 1 | d385e2198a647432283265ce25a50b1268b0a19a | 2,348 | kotlinova | MIT License |
application/src/main/java/de/pbauerochse/worklogviewer/fx/Theme.kt | Bhanditz | 168,944,765 | false | null | package de.pbauerochse.worklogviewer.fx
import de.pbauerochse.worklogviewer.util.FormattingUtil.getFormatted
/**
* Available themes for the WorklogViewer UI
*/
enum class Theme(val stylesheet: String) {
/**
* The light theme as it has always been
* present in the worklog viewer
*/
LIGHT("/fx/css/light.css"),
/**
* A new darker theme
*/
DARK("/fx/css/dark.css");
override fun toString(): String {
return getFormatted("theme.${name.toLowerCase()}.label")
}
}
| 1 | null | 1 | 1 | bf2cd66f3fc030d501f5a0c72827ba3e30aae555 | 523 | youtrack-worklog-viewer | MIT License |
exercises/practice/scale-generator/src/main/kotlin/Scale.kt | exercism | 47,675,865 | false | null | class Scale(private val tonic: String) {
fun chromatic(): List<String> {
TODO("Implement this function to complete the task")
}
fun interval(intervals: String): List<String> {
TODO("Implement this function to complete the task")
}
}
| 40 | null | 194 | 224 | ff80badd116c6ce558335ae1547cd23c8940e05a | 268 | kotlin | MIT License |
src/main/kotlin/com/jetbrains/snakecharm/lang/psi/impl/SmkRuleLikeImpl.kt | JetBrains-Research | 165,259,818 | false | {"Gradle Kotlin DSL": 2, "YAML": 47, "Markdown": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Python": 60, "Text": 111, "INI": 2, "Gherkin": 118, "Kotlin": 253, "Java": 5, "XML": 3, "SVG": 7, "HTML": 44, "Snakemake": 116, "JFlex": 1, "Roff": 2} | package com.jetbrains.snakecharm.lang.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.NamedStub
import com.jetbrains.python.PyElementTypes
import com.jetbrains.python.PyNames.UNNAMED_ELEMENT
import com.jetbrains.python.psi.PyStatementList
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.impl.PyBaseElementImpl
import com.jetbrains.python.psi.impl.PyElementPresentation
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.snakecharm.SnakemakeIcons
import com.jetbrains.snakecharm.lang.SnakemakeNames
import com.jetbrains.snakecharm.lang.parser.SnakemakeLexer
import com.jetbrains.snakecharm.lang.psi.SmkRuleLike
import com.jetbrains.snakecharm.lang.psi.SmkSection
import com.jetbrains.snakecharm.lang.psi.impl.SmkPsiUtil.getIdentifierNode
import javax.swing.Icon
abstract class SmkRuleLikeImpl<StubT : NamedStub<PsiT>, PsiT : SmkRuleLike<S>, out S : SmkSection>
: PyBaseElementImpl<StubT>, SmkRuleLike<S>
//TODO: PyNamedElementContainer; PyStubElementType<SMKRuleStub, SmkRule>
// SnakemakeNamedElement, SnakemakeScopeOwner
{
constructor(node: ASTNode) : super(node)
constructor(stub: StubT, nodeType: IStubElementType<StubT, PsiT>) : super(stub, nodeType)
override fun getName(): String? {
val stub = stub
if (stub != null) {
return stub.name
}
return getNameNode()?.text
}
override fun setName(name: String): PsiElement {
val newNameNode = PyUtil.createNewName(this, name)
getNameNode()?.let {
node.replaceChild(it, newNameNode)
}
return this
}
override fun getSectionKeywordNode() = node.findChildByType(sectionTokenType)
override fun getNameIdentifier() = getNameNode()?.psi
/**
* Use name start offset here, required for navigation & find usages, e.g. when ask for usages on name identifier
*/
override fun getTextOffset() = getNameNode()?.startOffset ?: super.getTextOffset()
protected open fun getNameNode() = getIdentifierNode(node)
override fun getSectionByName(sectionName: String): S? {
require(sectionName != SnakemakeNames.SECTION_RUN) {
"Run section not supported here"
}
return getSections().find {
it.sectionKeyword == sectionName
} as? S
}
override fun getStatementList() = childToPsiNotNull<PyStatementList>(PyElementTypes.STATEMENT_LIST)
// iterate over children, not statements, since SMKRuleRunParameter isn't a statement
override fun getSections(): List<SmkSection> = statementList.children.filterIsInstance<SmkSection>()
override fun getIcon(flags: Int): Icon {
PyPsiUtils.assertValid(this)
return SnakemakeIcons.FILE
}
override fun getPresentation() = object : PyElementPresentation(this) {
override fun getPresentableText() =
"${SnakemakeLexer.KEYWORD_LIKE_SECTION_TOKEN_TYPE_2_KEYWORD[sectionTokenType]}: ${name ?: UNNAMED_ELEMENT}"
override fun getLocationString() = "(${containingFile.name})"
}
} | 88 | Python | 7 | 61 | ac0d9c4a246b287f99b857865a24378eeaad5419 | 3,169 | snakecharm | MIT License |
emulator/src/com/android/tools/idea/emulator/EmulatorToolWindowFactory.kt | JetBrains | 60,701,247 | false | null | /*
* 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.tools.idea.emulator
import com.android.tools.idea.avdmanager.HardwareAccelerationCheck.isChromeOSAndIsNotHWAccelerated
import com.android.tools.idea.isAndroidEnvironment
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.ToolWindowWindowAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowContentUiType
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowType
/**
* [ToolWindowFactory] implementation for the Emulator tool window.
*/
class EmulatorToolWindowFactory : ToolWindowFactory, DumbAware {
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
toolWindow.setDefaultContentUiType(ToolWindowContentUiType.TABBED)
EmulatorToolWindowManager.initializeForProject(project)
}
override fun init(toolWindow: ToolWindow) {
toolWindow.stripeTitle = EMULATOR_TOOL_WINDOW_TITLE
toolWindow.setTitleActions(listOf(object : ToolWindowWindowAction() {
override fun update(e: AnActionEvent) {
if (getToolWindow(e)?.type.let { it == ToolWindowType.FLOATING || it == ToolWindowType.WINDOWED }) {
e.presentation.isEnabledAndVisible = false
return
}
super.update(e)
e.presentation.icon = AllIcons.Actions.MoveToWindow
}
}))
}
override fun isApplicable(project: Project): Boolean {
val available = isAndroidEnvironment(project) && (canLaunchEmulator() || DeviceMirroringSettings.getInstance().deviceMirroringEnabled)
if (available) {
EmulatorToolWindowManager.initializeForProject(project)
}
return available
}
private fun canLaunchEmulator(): Boolean =
!isChromeOSAndIsNotHWAccelerated()
} | 1 | Kotlin | 220 | 857 | 8d22f48a9233679e85e42e8a7ed78bbff2c82ddb | 2,513 | android | Apache License 2.0 |
core-ktx/src/main/java/com/netposa/commonsdk/core/io/Closeable.kt | treech | 259,178,223 | false | {"Java": 243345, "Kotlin": 73586} | package com.netposa.commonsdk.core.io
import java.io.Closeable
/**
* Created by yeguoqiang on 2020/1/11.
*/
fun Closeable?.closeQuietly() {
if (this == null) {
return
}
try {
close()
} catch (rethrown: RuntimeException) {
throw rethrown
} catch (_: Exception) {
}
} | 1 | null | 1 | 1 | bb3aabb93a95fcedb6f3df31194e6bbb0fbd125e | 318 | CommonSDK | Apache License 2.0 |
buildSrc/src/main/kotlin/CommonJavaConfig.kt | NotAlexNoyle | 781,125,249 | false | null | import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.StandardJavadocDocletOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.withType
fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, javaRelease: Int = 17, banSlf4j: Boolean = true) {
applyCommonConfiguration()
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "checkstyle")
tasks
.withType<JavaCompile>()
.matching { it.name == "compileJava" || it.name == "compileTestJava" }
.configureEach {
val disabledLint = listOf(
"processing", "path", "fallthrough", "serial"
)
options.release.set(javaRelease)
options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" })
options.isDeprecation = true
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "9.1"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:${Versions.JUNIT}")
"testImplementation"("org.mockito:mockito-core:${Versions.MOCKITO}")
"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.MOCKITO}")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
options.encoding = "UTF-8"
(options as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
configure<JavaPluginExtension> {
withJavadocJar()
if (sourcesJar) {
withSourcesJar()
}
}
if (banSlf4j) {
configurations["compileClasspath"].apply {
resolutionStrategy.componentSelection {
withModule("org.slf4j:slf4j-api") {
reject("No SLF4J allowed on compile classpath")
}
}
}
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
}
| 1 | null | 1 | 1 | 9c21f9e0d733b5a3bcbbfd79dd4bb0fff9440b3d | 3,004 | WorldEdit | MIT License |
app/src/main/java/com/kickstarter/viewmodels/PledgeFragmentViewModel.kt | sertacokan | 199,089,081 | true | {"Java Properties": 2, "Gradle": 4, "Shell": 4, "Markdown": 3, "Batchfile": 1, "Ruby": 20, "Gemfile.lock": 1, "Ignore List": 3, "Makefile": 1, "Git Config": 1, "SVG": 4, "YAML": 2, "XML": 360, "Text": 4, "Java": 490, "Kotlin": 152, "INI": 1, "JSON": 6, "GraphQL": 5} | package com.kickstarter.viewmodels
import android.text.SpannableString
import android.util.Pair
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
import com.kickstarter.libs.ActivityRequestCodes
import com.kickstarter.libs.Environment
import com.kickstarter.libs.FragmentViewModel
import com.kickstarter.libs.rx.transformers.Transformers.*
import com.kickstarter.libs.utils.*
import com.kickstarter.models.*
import com.kickstarter.services.apiresponses.ShippingRulesEnvelope
import com.kickstarter.ui.ArgumentsKey
import com.kickstarter.ui.data.ActivityResult
import com.kickstarter.ui.data.CardState
import com.kickstarter.ui.data.PledgeData
import com.kickstarter.ui.data.ScreenLocation
import com.kickstarter.ui.fragments.PledgeFragment
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.math.RoundingMode
interface PledgeFragmentViewModel {
interface Inputs {
/** Call when user deselects a card they want to pledge with. */
fun closeCardButtonClicked(position: Int)
/** Call when logged out user clicks the continue button. */
fun continueButtonClicked()
/** Call when user clicks the decrease pledge button. */
fun decreasePledgeButtonClicked()
/** Call when user clicks the increase pledge button. */
fun increasePledgeButtonClicked()
/** Call when the new card button is clicked. */
fun newCardButtonClicked()
/** Call when the view has been laid out. */
fun onGlobalLayout()
/** Call when user clicks the pledge button. */
fun pledgeButtonClicked(cardId: String)
/** Call when user selects a card they want to pledge with. */
fun selectCardButtonClicked(position: Int)
/** Call when user selects a shipping location. */
fun shippingRuleSelected(shippingRule: ShippingRule)
}
interface Outputs {
/** Emits the additional pledge amount string. */
fun additionalPledgeAmount(): Observable<String>
/** Emits when the additional pledge amount should be hidden. */
fun additionalPledgeAmountIsGone(): Observable<Boolean>
/** Emits when the reward card should be animated. */
fun animateRewardCard(): Observable<PledgeData>
/** Emits a list of stored cards for a user. */
fun cards(): Observable<List<StoredCard>>
/** Emits a boolean determining if the continue button should be hidden. */
fun continueButtonIsGone(): Observable<Boolean>
/** Emits a string representing the total pledge amount in the user's preferred currency. */
fun conversionText(): Observable<String>
/** Returns `true` if the conversion should be hidden, `false` otherwise. */
fun conversionTextViewIsGone(): Observable<Boolean>
/** Emits a boolean determining if the decrease pledge button should be enabled. */
fun decreasePledgeButtonIsEnabled(): Observable<Boolean>
/** Emits the estimated delivery date string of the reward. */
fun estimatedDelivery(): Observable<String>
/** Emits a boolean determining if the estimated delivery info should be hidden. */
fun estimatedDeliveryInfoIsGone(): Observable<Boolean>
/** Emits a boolean determining if the increase pledge button should be enabled.*/
fun increasePledgeButtonIsEnabled(): Observable<Boolean>
/** Emits a boolean determining if the payment container should be hidden. */
fun paymentContainerIsGone(): Observable<Boolean>
/** Emits the pledge amount string of the reward. */
fun pledgeAmount(): Observable<SpannableString>
/** Emits the currently selected shipping rule. */
fun selectedShippingRule(): Observable<ShippingRule>
/** Emits the shipping amount of the selected shipping rule. */
fun shippingAmount(): Observable<SpannableString>
/** Emits a pair of list of shipping rules to be selected and the project. */
fun shippingRulesAndProject(): Observable<Pair<List<ShippingRule>, Project>>
/** Emits when the shipping rules section should be hidden. */
fun shippingRulesSectionIsGone(): Observable<Boolean>
/** Emits when the cards adapter should update the selected position. */
fun showPledgeCard(): Observable<Pair<Int, CardState>>
/** Emits when the pledge call was unsuccessful. */
fun showPledgeError(): Observable<Void>
/** Emits when we should start the [com.kickstarter.ui.activities.LoginToutActivity]. */
fun startLoginToutActivity(): Observable<Void>
/** Emits when we should start the [com.kickstarter.ui.activities.NewCardActivity]. */
fun startNewCardActivity(): Observable<Void>
/** Emits when we the pledge was successful and should start the [com.kickstarter.ui.activities.ThanksActivity]. */
fun startThanksActivity(): Observable<Project>
/** Emits the total amount string of the pledge.*/
fun totalAmount(): Observable<SpannableString>
}
class ViewModel(@NonNull val environment: Environment) : FragmentViewModel<PledgeFragment>(environment), Inputs, Outputs {
private val closeCardButtonClicked = PublishSubject.create<Int>()
private val continueButtonClicked = PublishSubject.create<Void>()
private val decreasePledgeButtonClicked = PublishSubject.create<Void>()
private val increasePledgeButtonClicked = PublishSubject.create<Void>()
private val newCardButtonClicked = PublishSubject.create<Void>()
private val onGlobalLayout = PublishSubject.create<Void>()
private val pledgeButtonClicked = PublishSubject.create<String>()
private val selectCardButtonClicked = PublishSubject.create<Int>()
private val shippingRule = PublishSubject.create<ShippingRule>()
private val animateRewardCard = BehaviorSubject.create<PledgeData>()
private val additionalPledgeAmount = BehaviorSubject.create<String>()
private val additionalPledgeAmountIsGone = BehaviorSubject.create<Boolean>()
private val cards = BehaviorSubject.create<List<StoredCard>>()
private val continueButtonIsGone = BehaviorSubject.create<Boolean>()
private val conversionText = BehaviorSubject.create<String>()
private val conversionTextViewIsGone = BehaviorSubject.create<Boolean>()
private val decreasePledgeButtonIsEnabled = BehaviorSubject.create<Boolean>()
private val estimatedDelivery = BehaviorSubject.create<String>()
private val estimatedDeliveryInfoIsGone = BehaviorSubject.create<Boolean>()
private val increasePledgeButtonIsEnabled = BehaviorSubject.create<Boolean>()
private val paymentContainerIsGone = BehaviorSubject.create<Boolean>()
private val pledgeAmount = BehaviorSubject.create<SpannableString>()
private val shippingAmount = BehaviorSubject.create<SpannableString>()
private val shippingRulesAndProject = BehaviorSubject.create<Pair<List<ShippingRule>, Project>>()
private val selectedShippingRule = BehaviorSubject.create<ShippingRule>()
private val shippingRulesSectionIsGone = BehaviorSubject.create<Boolean>()
private val showPledgeCard = BehaviorSubject.create<Pair<Int, CardState>>()
private val showPledgeError = BehaviorSubject.create<Void>()
private val startLoginToutActivity = PublishSubject.create<Void>()
private val startNewCardActivity = PublishSubject.create<Void>()
private val startThanksActivity = PublishSubject.create<Project>()
private val totalAmount = BehaviorSubject.create<SpannableString>()
private val apiClient = environment.apiClient()
private val apolloClient = environment.apolloClient()
private val currentConfig = environment.currentConfig()
private val currentUser = environment.currentUser()
private val ksCurrency = environment.ksCurrency()
val inputs: Inputs = this
val outputs: Outputs = this
init {
val userIsLoggedIn = this.currentUser.isLoggedIn
.distinctUntilChanged()
val reward = arguments()
.map { it.getParcelable(ArgumentsKey.PLEDGE_REWARD) as Reward }
val screenLocation = arguments()
.map { it.getSerializable(ArgumentsKey.PLEDGE_SCREEN_LOCATION) as ScreenLocation }
val project = arguments()
.map { it.getParcelable(ArgumentsKey.PLEDGE_PROJECT) as Project }
reward
.map { it.estimatedDeliveryOn() }
.filter { ObjectUtils.isNotNull(it) }
.map { dateTime -> dateTime?.let { DateTimeUtils.estimatedDeliveryOn(it) } }
.compose(bindToLifecycle())
.subscribe(this.estimatedDelivery)
val projectAndReward = project
.compose<Pair<Project, Reward>>(combineLatestPair(reward))
projectAndReward
.compose(bindToLifecycle())
projectAndReward
.map { it.first.currency() != it.first.currentCurrency() }
.map { BooleanUtils.negate(it) }
.subscribe(this.conversionTextViewIsGone)
val rewardMinimum = reward
.map { it.minimum() }
rewardMinimum
.compose<Pair<Double, Project>>(combineLatestPair(project))
.map<SpannableString> { ViewUtils.styleCurrency(it.first, it.second, this.ksCurrency) }
.compose(bindToLifecycle())
.subscribe(this.pledgeAmount)
val shippingRules = project
.compose<Pair<Project, Reward>>(combineLatestPair(reward))
.filter { RewardUtils.isShippable(it.second) }
.switchMap<ShippingRulesEnvelope> { this.apiClient.fetchShippingRules(it.first, it.second).compose(neverError()) }
.map { it.shippingRules() }
.share()
val rulesAndProject = shippingRules
.compose<Pair<List<ShippingRule>, Project>>(combineLatestPair(project))
rulesAndProject
.compose(bindToLifecycle())
.subscribe(this.shippingRulesAndProject)
reward
.map { RewardUtils.isShippable(it) }
.map { BooleanUtils.negate(it) }
.compose(bindToLifecycle())
.subscribe(this.shippingRulesSectionIsGone)
reward
.map { ObjectUtils.isNull(it.estimatedDeliveryOn()) || RewardUtils.isNoReward(it) }
.compose(bindToLifecycle())
.subscribe(this.estimatedDeliveryInfoIsGone)
val defaultShippingRule = shippingRules
.filter { it.isNotEmpty() }
.switchMap { getDefaultShippingRule(it) }
val additionalPledgeAmount = BehaviorSubject.create<Double>(0.0)
this.increasePledgeButtonClicked
.compose(bindToLifecycle())
.subscribe { additionalPledgeAmount.onNext(additionalPledgeAmount.value + 1) }
this.decreasePledgeButtonClicked
.compose(bindToLifecycle())
.subscribe { additionalPledgeAmount.onNext(additionalPledgeAmount.value - 1) }
additionalPledgeAmount
.compose<Pair<Double, Project>>(combineLatestPair(project))
.map<String> { this.ksCurrency.format(it.first, it.second, RoundingMode.HALF_UP) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.additionalPledgeAmount)
additionalPledgeAmount
.map { IntegerUtils.isZero(it.toInt()) }
.distinctUntilChanged()
.subscribe(this.additionalPledgeAmountIsGone)
additionalPledgeAmount
.map { IntegerUtils.isZero(it.toInt()) }
.map { BooleanUtils.negate(it) }
.distinctUntilChanged()
.subscribe(this.decreasePledgeButtonIsEnabled)
Observable
.merge(rewardMinimum, rewardMinimum.compose<Pair<Double, Double>>(combineLatestPair(additionalPledgeAmount)).map { it.first + it.second })
.map { RewardUtils.isMaxRewardAmount(it) }
.map { BooleanUtils.negate(it) }
.distinctUntilChanged()
.subscribe(this.increasePledgeButtonIsEnabled)
Observable.combineLatest(screenLocation, reward, project, ::PledgeData)
.compose<PledgeData>(takeWhen(this.onGlobalLayout))
.compose(bindToLifecycle())
.subscribe { this.animateRewardCard.onNext(it) }
userIsLoggedIn
.map { BooleanUtils.negate(it) }
.compose(bindToLifecycle())
.subscribe(this.paymentContainerIsGone)
userIsLoggedIn
.compose(bindToLifecycle())
.subscribe(this.continueButtonIsGone)
val shippingRule = Observable.merge(this.shippingRule, defaultShippingRule)
shippingRule
.compose(bindToLifecycle())
.subscribe(this.selectedShippingRule)
val shippingAmount = shippingRule
.map { it.cost() }
shippingAmount
.compose<Pair<Double, Project>>(combineLatestPair(project))
.map<SpannableString> { ViewUtils.styleCurrency(it.first, it.second, this.ksCurrency) }
.compose(bindToLifecycle())
.subscribe(this.shippingAmount)
val basePledgeAmount = rewardMinimum
.compose<Pair<Double, Double>>(combineLatestPair(additionalPledgeAmount))
.map { it.first + it.second }
val unshippableTotal = basePledgeAmount
.compose<Pair<Double, Reward>>(combineLatestPair(reward))
.filter { RewardUtils.isNoReward(it.second) || !RewardUtils.isShippable(it.second) }
.map<Double> { it.first }
.distinctUntilChanged()
val shippableTotal = basePledgeAmount
.compose<Pair<Double, Double>>(combineLatestPair(shippingAmount))
.map { it.first + it.second }
.compose<Pair<Double, Reward>>(combineLatestPair(reward))
.filter { RewardUtils.isReward(it.second) && RewardUtils.isShippable(it.second) }
.map<Double> { it.first }
.distinctUntilChanged()
val total = Observable.merge(unshippableTotal, shippableTotal)
.compose<Pair<Double, Project>>(combineLatestPair(project))
total
.map<SpannableString> { ViewUtils.styleCurrency(it.first, it.second, this.ksCurrency) }
.compose(bindToLifecycle())
.subscribe(this.totalAmount)
total
.map { this.ksCurrency.formatWithUserPreference(it.first, it.second, RoundingMode.UP, 2) }
.compose(bindToLifecycle())
.subscribe(this.conversionText)
userIsLoggedIn
.filter { BooleanUtils.isTrue(it) }
.switchMap { getListOfStoredCards() }
.delaySubscription(total)
.compose(bindToLifecycle())
.subscribe(this.cards)
val selectedPosition = BehaviorSubject.create(RecyclerView.NO_POSITION)
this.showPledgeCard
.map { it.first }
.compose(bindToLifecycle())
.subscribe(selectedPosition)
this.selectCardButtonClicked
.compose(bindToLifecycle())
.subscribe { this.showPledgeCard.onNext(Pair(it, CardState.PLEDGE)) }
this.closeCardButtonClicked
.compose(bindToLifecycle())
.subscribe { this.showPledgeCard.onNext(Pair(it, CardState.SELECT)) }
this.newCardButtonClicked
.compose(bindToLifecycle())
.subscribe(this.startNewCardActivity)
this.continueButtonClicked
.compose(bindToLifecycle())
.subscribe(this.startLoginToutActivity)
activityResult()
.filter { it.isRequestCode(ActivityRequestCodes.SAVE_NEW_PAYMENT_METHOD) }
.filter(ActivityResult::isOk)
.switchMap { getListOfStoredCards() }
.compose(bindToLifecycle())
.subscribe(this.cards)
val location: Observable<Location?> = Observable.merge(Observable.just(null as Location?), shippingRule.map { it.location() })
val checkoutNotification = Observable.combineLatest(project,
total.map { it.first.toString() },
this.pledgeButtonClicked,
location.map { it?.id()?.toString() },
reward)
{ p, a, id, l, r -> Checkout(p, a, id, l, r) }
.switchMap {
this.apolloClient.checkout(it.project, it.amount, it.paymentSourceId, it.locationId, it.reward)
.doOnSubscribe { this.showPledgeCard.onNext(Pair(selectedPosition.value, CardState.LOADING)) }
.materialize()
}
.share()
val checkoutValues = checkoutNotification
.compose(values())
Observable.merge(checkoutNotification.compose(errors()), checkoutValues.filter { BooleanUtils.isFalse(it) })
.compose(ignoreValues())
.compose(bindToLifecycle())
.subscribe{
this.showPledgeError.onNext(null)
this.showPledgeCard.onNext(Pair(selectedPosition.value, CardState.PLEDGE))
}
project
.compose<Project>(takeWhen(checkoutValues.filter { BooleanUtils.isTrue(it) }))
.compose(bindToLifecycle())
.subscribe(this.startThanksActivity)
}
private fun getDefaultShippingRule(shippingRules: List<ShippingRule>): Observable<ShippingRule> {
return currentConfig.observable()
.map { it.countryCode() }
.map { countryCode ->
shippingRules.firstOrNull { it.location().country() == countryCode }
?: shippingRules.first()
}
}
override fun closeCardButtonClicked(position: Int) = this.closeCardButtonClicked.onNext(position)
override fun continueButtonClicked() = this.continueButtonClicked.onNext(null)
override fun decreasePledgeButtonClicked() = this.decreasePledgeButtonClicked.onNext(null)
override fun increasePledgeButtonClicked() = this.increasePledgeButtonClicked.onNext(null)
override fun newCardButtonClicked() = this.newCardButtonClicked.onNext(null)
override fun onGlobalLayout() = this.onGlobalLayout.onNext(null)
override fun pledgeButtonClicked(cardId: String) = this.pledgeButtonClicked.onNext(cardId)
override fun shippingRuleSelected(shippingRule: ShippingRule) = this.shippingRule.onNext(shippingRule)
override fun selectCardButtonClicked(position: Int) = this.selectCardButtonClicked.onNext(position)
override fun additionalPledgeAmount(): Observable<String> = this.additionalPledgeAmount
override fun additionalPledgeAmountIsGone(): Observable<Boolean> = this.additionalPledgeAmountIsGone
override fun animateRewardCard(): Observable<PledgeData> = this.animateRewardCard
@NonNull
override fun cards(): Observable<List<StoredCard>> = this.cards
@NonNull
override fun continueButtonIsGone(): Observable<Boolean> = this.continueButtonIsGone
@NonNull
override fun conversionTextViewIsGone(): Observable<Boolean> = this.conversionTextViewIsGone
@NonNull
override fun conversionText(): Observable<String> = this.conversionText
@NonNull
override fun decreasePledgeButtonIsEnabled(): Observable<Boolean> = this.decreasePledgeButtonIsEnabled
@NonNull
override fun estimatedDelivery(): Observable<String> = this.estimatedDelivery
@NonNull
override fun estimatedDeliveryInfoIsGone(): Observable<Boolean> = this.estimatedDeliveryInfoIsGone
@NonNull
override fun increasePledgeButtonIsEnabled(): Observable<Boolean> = this.increasePledgeButtonIsEnabled
@NonNull
override fun paymentContainerIsGone(): Observable<Boolean> = this.paymentContainerIsGone
@NonNull
override fun pledgeAmount(): Observable<SpannableString> = this.pledgeAmount
@NonNull
override fun selectedShippingRule(): Observable<ShippingRule> = this.selectedShippingRule
@NonNull
override fun shippingAmount(): Observable<SpannableString> = this.shippingAmount
@NonNull
override fun shippingRulesAndProject(): Observable<Pair<List<ShippingRule>, Project>> = this.shippingRulesAndProject
@NonNull
override fun shippingRulesSectionIsGone(): Observable<Boolean> = this.shippingRulesSectionIsGone
@NonNull
override fun showPledgeCard(): Observable<Pair<Int, CardState>> = this.showPledgeCard
@NonNull
override fun showPledgeError(): Observable<Void> = this.showPledgeError
@NonNull
override fun startLoginToutActivity(): Observable<Void> = this.startLoginToutActivity
@NonNull
override fun startNewCardActivity(): Observable<Void> = this.startNewCardActivity
@NonNull
override fun startThanksActivity(): Observable<Project> = this.startThanksActivity
@NonNull
override fun totalAmount(): Observable<SpannableString> = this.totalAmount
private fun getListOfStoredCards(): Observable<List<StoredCard>> {
return this.apolloClient.getStoredCards()
.compose(bindToLifecycle())
.compose(neverError())
}
data class Checkout(val project: Project, val amount: String, val paymentSourceId: String, val locationId: String?, val reward: Reward?)
}
}
| 0 | Java | 0 | 0 | a68b63ad942ff111d0a4e970fb12e3933cd6ac95 | 22,991 | android-oss | Apache License 2.0 |
kzen-auto-js/src/main/kotlin/tech/kzen/auto/client/objects/document/report/input/model/ReportInputState.kt | alexoooo | 131,353,826 | false | null | package tech.kzen.auto.client.objects.document.report.input.model
import tech.kzen.auto.client.objects.document.report.input.browse.model.InputBrowserState
import tech.kzen.auto.client.objects.document.report.input.select.model.InputSelectedState
data class ReportInputState(
val browser: InputBrowserState = InputBrowserState(),
val selected: InputSelectedState = InputSelectedState(),
val column: InputColumnState = InputColumnState()
) {
fun anyLoading(): Boolean {
return browser.anyLoading() ||
selected.anyLoading() ||
column.columnListingLoading
}
}
| 1 | Kotlin | 1 | 1 | 352ad83b12d51b4957e6fda0b943e84543d72849 | 620 | kzen-auto | MIT License |
src/infra/cache/src/main/kotlin/kiit/cache/SimpleSyncCache.kt | slatekit | 55,942,000 | false | null | package kiit.cache
import kiit.common.Identity
import kiit.common.log.Logger
import kiit.results.Outcome
class SimpleSyncCache(private val cache: Cache) : Cache {
override val id: Identity get() = cache.id
override val settings: CacheSettings = cache.settings
override val listener: ((CacheEvent) -> Unit)? get() = cache.listener
override val logger: Logger? get() = cache.logger
@Synchronized
override fun size(): Int = cache.size()
@Synchronized
override fun keys(): List<String> = cache.keys()
@Synchronized
override fun contains(key: String): Boolean = cache.contains(key)
@Synchronized
override fun stats(): List<CacheStats> = cache.stats()
@Synchronized
override fun stats(key:String): CacheStats? = cache.stats(key)
@Synchronized
override fun <T> get(key: String): T? = cache.get(key)
@Synchronized
override fun <T> getOrLoad(key: String): T? = cache.getOrLoad(key)
@Synchronized
override fun <T> getFresh(key: String): T? = cache.getFresh(key)
@Synchronized
override fun <T> put(key: String, desc: String, seconds: Int, fetcher: suspend () -> T?) = cache.put(key, desc, seconds, fetcher)
@Synchronized
override fun <T> set(key: String, value: T?) = cache.set(key, value)
@Synchronized
override fun delete(key: String): Outcome<Boolean> = cache.delete(key)
@Synchronized
override fun deleteAll(): Outcome<Boolean> = cache.deleteAll()
@Synchronized
override fun refresh(key: String):Outcome<Boolean> = cache.refresh(key)
@Synchronized
override fun expire(key: String):Outcome<Boolean> = cache.expire(key)
@Synchronized
override fun expireAll():Outcome<Boolean> = cache.expireAll()
companion object {
/**
* Convenience method to build async cache using Default channel coordinator
*/
fun of(id:Identity, settings: CacheSettings? = null, listener:((CacheEvent) -> Unit)? = null):SimpleSyncCache {
val raw = SimpleCache(id,settings ?: CacheSettings(10), listener )
val syncCache = SimpleSyncCache(raw)
return syncCache
}
}
}
| 6 | null | 13 | 112 | d17b592aeb28c5eb837d894e98492c69c4697862 | 2,174 | slatekit | Apache License 2.0 |
spring-cloud-gateway/gateway-starter/src/main/kotlin/com/livk/factory/RequestHashingGatewayFilterFactory.kt | livk-cloud | 441,105,335 | false | {"Kotlin": 92224} | package com.livk.factory
import com.livk.auto.service.annotation.SpringAutoService
import org.bouncycastle.util.encoders.Hex
import org.springframework.cloud.gateway.filter.GatewayFilter
import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils
import org.springframework.http.codec.HttpMessageReader
import org.springframework.http.server.reactive.ServerHttpRequest
import org.springframework.stereotype.Component
import org.springframework.util.Assert
import org.springframework.web.reactive.function.server.HandlerStrategies
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
/**
*
*
* This filter hashes the request body, placing the value in the X-Hash header.
* Note: This causes the gateway to be memory constrained.
* Sample usage: RequestHashing=SHA-256
*
*
* @author livk
*/
@Component
@SpringAutoService
class RequestHashingGatewayFilterFactory : AbstractGatewayFilterFactory<RequestHashingGatewayFilterFactory.Config>(
Config::class.java
) {
private val messageReaders: List<HttpMessageReader<*>> = HandlerStrategies.withDefaults().messageReaders()
override fun apply(config: Config): GatewayFilter {
return GatewayFilter { exchange: ServerWebExchange, chain: GatewayFilterChain ->
ServerWebExchangeUtils
.cacheRequestBodyAndRequest(exchange) { httpRequest ->
ServerRequest
.create(
exchange.mutate()
.request(httpRequest)
.build(), messageReaders
)
.bodyToMono(String::class.java)
.doOnNext { requestPayload: String ->
exchange
.attributes[HASH_ATTR] = computeHash(config.messageDigest, requestPayload)
}
.then(Mono.defer {
var cachedRequest = exchange.getAttribute<ServerHttpRequest>(
ServerWebExchangeUtils.CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR
)
Assert.notNull(
cachedRequest,
"cache request shouldn't be null"
)
exchange.attributes
.remove(ServerWebExchangeUtils.CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR)
val hash = exchange.getAttribute<String>(HASH_ATTR)
cachedRequest = cachedRequest!!.mutate()
.header(HASH_HEADER, hash)
.build()
chain.filter(
exchange.mutate()
.request(cachedRequest)
.build()
)
})
}
}
}
override fun shortcutFieldOrder(): List<String> {
return listOf("algorithm")
}
private fun computeHash(messageDigest: MessageDigest, requestPayload: String): String {
return Hex.toHexString(messageDigest.digest(requestPayload.toByteArray(StandardCharsets.UTF_8)))
}
class Config {
lateinit var messageDigest: MessageDigest
private set
fun algorithm(algorithm: String) {
messageDigest = MessageDigest.getInstance(algorithm)
}
}
companion object {
private const val HASH_ATTR = "hash"
private const val HASH_HEADER = "X-Hash"
}
}
| 2 | Kotlin | 7 | 26 | c7e3ac94714adc686232aac9d2c2b6a9936e08b6 | 4,006 | spring-cloud-kotlin | Apache License 2.0 |
buildSrc/src/main/kotlin/versions.kt | aSoft-Ltd | 319,525,074 | false | null | object vers {
val kotlin = "1.4.21"
val agp = "4.1.0"
val nexus_staging = "0.22.0"
object asoft {
val test = "1.1.0"
val expect = "0.0.10"
val builders = "1.2.0"
val either = "0.0.20"
}
object kotlinx {
val serialization = "1.0.1"
}
} | 0 | Kotlin | 1 | 1 | 5d75719518b347e0d65a252607d6a608f3bb2fbc | 304 | either | MIT License |
integration-test/src/main/kotlin/komapper/liquibaseEntities.kt | momosetkn | 844,062,460 | false | {"Kotlin": 499731, "Java": 178} | @file:Suppress("ktlint:standard:filename")
package komapper
import org.komapper.annotation.KomapperColumn
import org.komapper.annotation.KomapperEntity
import org.komapper.annotation.KomapperId
import org.komapper.annotation.KomapperTable
import java.time.LocalDateTime
@KomapperEntity
@KomapperTable(name = "databasechangelog")
data class Databasechangelog(
@KomapperId @KomapperColumn(name = "id") val id: String,
@KomapperColumn(name = "author") val author: String,
@KomapperColumn(name = "filename") val filename: String,
@KomapperColumn(name = "dateexecuted") val dateexecuted: LocalDateTime,
@KomapperColumn(name = "orderexecuted") val orderexecuted: Int,
@KomapperColumn(name = "exectype") val exectype: String,
@KomapperColumn(name = "md5sum") val md5sum: String?,
@KomapperColumn(name = "description") val description: String?,
@KomapperColumn(name = "comments") val comments: String?,
@KomapperColumn(name = "tag") val tag: String?,
@KomapperColumn(name = "liquibase") val liquibase: String?,
@KomapperColumn(name = "contexts") val contexts: String?,
@KomapperColumn(name = "labels") val labels: String?,
@KomapperColumn(name = "deployment_id") val deploymentId: String?
)
@KomapperEntity
@KomapperTable(name = "databasechangeloglock")
data class Databasechangeloglock(
@KomapperId @KomapperColumn(name = "id") val id: Int,
@KomapperColumn(name = "locked") val locked: Boolean,
@KomapperColumn(name = "lockgranted") val lockgranted: LocalDateTime?,
@KomapperColumn(name = "lockedby") val lockedby: String?
)
| 5 | Kotlin | 1 | 5 | d47b2dd7f585f3aa563e86ab52242e0b5d2ffaad | 1,594 | liquibase-kotlin | Apache License 2.0 |
java-time/src/test/kotlin/com/github/debop/javatimes/TemporalIntervalWindowedTest.kt | debop | 62,798,850 | false | {"Kotlin": 256811} | package com.github.debop.javatimes
import mu.KLogging
import org.amshove.kluent.shouldEqualTo
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class TemporalIntervalWindowedTest : AbstractJavaTimesTest() {
companion object : KLogging()
@Test
fun `windowed year`() {
val start = nowZonedDateTime().startOfYear()
val endExclusive = start + 5.yearPeriod()
val interval = start..endExclusive
val windowed = interval.windowedYear(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedYear(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedYear(1, -2)
}
}
@Test
fun `windowed month`() {
val start = nowZonedDateTime().startOfMonth()
val endExclusive = start + 5.monthPeriod()
val interval = start..endExclusive
val windowed = interval.windowedMonth(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedMonth(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedMonth(1, -2)
}
}
@Test
fun `windowed week`() {
val start = nowZonedDateTime().startOfWeek()
val endExclusive = start + 5.weekPeriod()
val interval = start..endExclusive
val windowed = interval.windowedWeek(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedWeek(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedWeek(1, -2)
}
}
@Test
fun `windowed days`() {
val start = nowZonedDateTime().startOfDay()
val endExclusive = start + 5.days()
val interval = start..endExclusive
val windowed = interval.windowedDay(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedDay(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedDay(1, -2)
}
}
@Test
fun `windowed hours`() {
val start = nowZonedDateTime().startOfHour()
val endExclusive = start + 5.hours()
val interval = start..endExclusive
val windowed = interval.windowedHour(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedHour(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedHour(1, -2)
}
}
@Test
fun `windowed minutes`() {
val start = nowZonedDateTime().startOfMinute()
val endExclusive = start + 5.minutes()
val interval = start..endExclusive
val windowed = interval.windowedMinute(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedMinute(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedMinute(1, -2)
}
}
@Test
fun `windowed seconds`() {
val start = nowZonedDateTime().startOfSecond()
val endExclusive = start + 5.seconds()
val interval = start..endExclusive
val windowed = interval.windowedSecond(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedSecond(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedSecond(1, -2)
}
}
@Test
fun `windowed millis`() {
val start = nowZonedDateTime().startOfMillis()
val endExclusive = start + 5.millis()
val interval = start..endExclusive
val windowed = interval.windowedMilli(3, 2)
windowed.forEach { items ->
assertTrue { items.first() in interval }
assertTrue { items.last() in interval }
}
windowed.count() shouldEqualTo 3
assertThrows<IllegalArgumentException> {
interval.windowedMilli(-1, 2)
}
assertThrows<IllegalArgumentException> {
interval.windowedMilli(1, -2)
}
}
} | 3 | Kotlin | 7 | 83 | cbb0efedaa53bdf9d77b230d8477cb0ae0d7abd7 | 5,430 | koda-time | Apache License 2.0 |
src/main/kotlin/github/cheng/application/env/extensions.kt | YiGuan-z | 702,319,315 | false | {"Kotlin": 88335} | package github.cheng.application.env
import github.cheng.envOfNullable
/**
*
* @author caseycheng
* @date 2023/10/24-11:44
* @doc
**/
internal fun resolveValue(value: String, root: ApplicationConfig): String? {
//检查时候是环境变量
val isEnvVariable = value.startsWith("\$")
if (!isEnvVariable) return value
val keyWithDefault = value.drop(1)
//检查是否存在默认值
val separatorIndex = keyWithDefault.indexOf(':')
//如果存在默认值,则,返回环境变量或者默认值
if (separatorIndex != -1) {
val key = keyWithDefault.substring(0, separatorIndex)
return envOfNullable(key) ?: keyWithDefault.drop(separatorIndex + 1)
}
//如果不存在默认值,则尝试从配置中获取并返回
val selfReference = root.propertyOrNull(keyWithDefault)
if (selfReference != null) {
return selfReference.getString()
}
//如果不存在,那么就看看是否是可选的
val isOptional = keyWithDefault.first() == '?'
//获取可选的key
val key = if (isOptional) keyWithDefault.drop(1) else keyWithDefault
//从环境变量中返回它,不是可选的项将会抛出异常。
return envOfNullable(key) ?: if (isOptional) {
null
} else {
throw ApplicationConfigurationException("Environment variable $key is not defined")
}
}
| 0 | Kotlin | 0 | 0 | c6e213acebde1e41b335fee9a4d48f6244165ca9 | 1,170 | telegram-stickers-collect-bot | MIT License |
modules/tak/compose/icons/src/main/kotlin/dev/jonpoulton/alakazam/tak/compose/icons/Radial.kt | jonapoul | 375,762,483 | false | {"Kotlin": 2898393, "Shell": 670} | @file:Suppress("MatchingDeclarationName")
package dev.jonpoulton.alakazam.tak.compose.icons
import android.content.res.Configuration
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import dev.jonpoulton.alakazam.tak.compose.icons.radial.AddHostile
import dev.jonpoulton.alakazam.tak.compose.icons.radial.AngleUnits
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Back
import dev.jonpoulton.alakazam.tak.compose.icons.radial.BlastRings
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Bloodhound
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Bluetooth
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Breadcrumbs
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Bullseye
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Camera
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Cas
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Cff
import dev.jonpoulton.alakazam.tak.compose.icons.radial.CffAlt
import dev.jonpoulton.alakazam.tak.compose.icons.radial.CffPlus
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Chat
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Clamp
import dev.jonpoulton.alakazam.tak.compose.icons.radial.ClearTracks
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Close
import dev.jonpoulton.alakazam.tak.compose.icons.radial.CompassRose
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Connections
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Copy
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DataPackage
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Deg
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DegGrid
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DegMag
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DegMil
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DegTrue
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Delete
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DetailsProgress
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Display
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DistUnit
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DistanceLock
import dev.jonpoulton.alakazam.tak.compose.icons.radial.DropPin
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Edit
import dev.jonpoulton.alakazam.tak.compose.icons.radial.EnterCoordinates
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Expand
import dev.jonpoulton.alakazam.tak.compose.icons.radial.FahRedx
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Fine
import dev.jonpoulton.alakazam.tak.compose.icons.radial.FovDirection
import dev.jonpoulton.alakazam.tak.compose.icons.radial.FovSize
import dev.jonpoulton.alakazam.tak.compose.icons.radial.FovVisibility
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Geofence
import dev.jonpoulton.alakazam.tak.compose.icons.radial.GoTo
import dev.jonpoulton.alakazam.tak.compose.icons.radial.GpsError
import dev.jonpoulton.alakazam.tak.compose.icons.radial.GreenFlag
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Hostile
import dev.jonpoulton.alakazam.tak.compose.icons.radial.HostileList
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Id
import dev.jonpoulton.alakazam.tak.compose.icons.radial.ImageOverlay
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Kmm
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Label
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Lock
import dev.jonpoulton.alakazam.tak.compose.icons.radial.LrfSlide
import dev.jonpoulton.alakazam.tak.compose.icons.radial.ManualPointEntry
import dev.jonpoulton.alakazam.tak.compose.icons.radial.MgrsLocation
import dev.jonpoulton.alakazam.tak.compose.icons.radial.MiddlePoint
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Mils
import dev.jonpoulton.alakazam.tak.compose.icons.radial.MilsGrid
import dev.jonpoulton.alakazam.tak.compose.icons.radial.MilsMag
import dev.jonpoulton.alakazam.tak.compose.icons.radial.MultiPolyline
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Nineline
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Nm
import dev.jonpoulton.alakazam.tak.compose.icons.radial.NoPoint
import dev.jonpoulton.alakazam.tak.compose.icons.radial.PairingLine
import dev.jonpoulton.alakazam.tak.compose.icons.radial.PairingLineToSelf
import dev.jonpoulton.alakazam.tak.compose.icons.radial.PolarEntry
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Range
import dev.jonpoulton.alakazam.tak.compose.icons.radial.RedsMsds
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Rotate
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Send
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Support
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Tasking
import dev.jonpoulton.alakazam.tak.compose.icons.radial.TrackDetails
import dev.jonpoulton.alakazam.tak.compose.icons.radial.UnitFt
import dev.jonpoulton.alakazam.tak.compose.icons.radial.Video
import dev.jonpoulton.alakazam.tak.compose.icons.radial.ViewshedLine
/**
* A standardized set of icons to be utilized for the radial menu and child menu components.
*/
public object RadialTakIcons
private val allIcons = listOf(
TakIcons.Radial.AddHostile,
TakIcons.Radial.AngleUnits,
TakIcons.Radial.Back,
TakIcons.Radial.BlastRings,
TakIcons.Radial.Bloodhound,
TakIcons.Radial.Bluetooth,
TakIcons.Radial.Breadcrumbs,
TakIcons.Radial.Bullseye,
TakIcons.Radial.Camera,
TakIcons.Radial.Cas,
TakIcons.Radial.Cff,
TakIcons.Radial.CffAlt,
TakIcons.Radial.CffPlus,
TakIcons.Radial.Chat,
TakIcons.Radial.Clamp,
TakIcons.Radial.ClearTracks,
TakIcons.Radial.Close,
TakIcons.Radial.CompassRose,
TakIcons.Radial.Connections,
TakIcons.Radial.Copy,
TakIcons.Radial.DataPackage,
TakIcons.Radial.Deg,
TakIcons.Radial.DegGrid,
TakIcons.Radial.DegMag,
TakIcons.Radial.DegMil,
TakIcons.Radial.DegTrue,
TakIcons.Radial.Delete,
TakIcons.Radial.DetailsProgress,
TakIcons.Radial.Display,
TakIcons.Radial.DistanceLock,
TakIcons.Radial.DistUnit,
TakIcons.Radial.DropPin,
TakIcons.Radial.Edit,
TakIcons.Radial.EnterCoordinates,
TakIcons.Radial.Expand,
TakIcons.Radial.FahRedx,
TakIcons.Radial.Fine,
TakIcons.Radial.FovDirection,
TakIcons.Radial.FovSize,
TakIcons.Radial.FovVisibility,
TakIcons.Radial.Geofence,
TakIcons.Radial.GoTo,
TakIcons.Radial.GpsError,
TakIcons.Radial.GreenFlag,
TakIcons.Radial.Hostile,
TakIcons.Radial.HostileList,
TakIcons.Radial.Id,
TakIcons.Radial.ImageOverlay,
TakIcons.Radial.Kmm,
TakIcons.Radial.Label,
TakIcons.Radial.Lock,
TakIcons.Radial.LrfSlide,
TakIcons.Radial.ManualPointEntry,
TakIcons.Radial.MgrsLocation,
TakIcons.Radial.MiddlePoint,
TakIcons.Radial.Mils,
TakIcons.Radial.MilsGrid,
TakIcons.Radial.MilsMag,
TakIcons.Radial.MultiPolyline,
TakIcons.Radial.Nineline,
TakIcons.Radial.Nm,
TakIcons.Radial.NoPoint,
TakIcons.Radial.PairingLine,
TakIcons.Radial.PairingLineToSelf,
TakIcons.Radial.PolarEntry,
TakIcons.Radial.Range,
TakIcons.Radial.RedsMsds,
TakIcons.Radial.Rotate,
TakIcons.Radial.Send,
TakIcons.Radial.Support,
TakIcons.Radial.Tasking,
TakIcons.Radial.TrackDetails,
TakIcons.Radial.UnitFt,
TakIcons.Radial.Video,
TakIcons.Radial.ViewshedLine,
)
@Preview(name = "Dark", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun PreviewIcons() = PreviewIconGrid(allIcons)
| 0 | Kotlin | 0 | 0 | 7769263ac0c6f0976facff732cf533dfd7ec44a3 | 7,508 | alakazam | Apache License 2.0 |
app/src/main/java/com/dluvian/nozzle/ui/components/hint/NoPostsHint.kt | dluvian | 645,936,540 | false | {"Kotlin": 576513} | package com.dluvian.nozzle.ui.components.hint
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.dluvian.nozzle.R
@Composable
fun NoPostsHint() {
BaseHint(text = stringResource(id = R.string.no_posts_found))
}
| 3 | Kotlin | 3 | 26 | c296b8a888868db3b0c7ed250e1af0c4608cf959 | 265 | Nozzle | MIT License |
src/main/kotlin/com/antwerkz/expression/types/Capture.kt | evanchooly | 640,129,156 | false | null | package com.antwerkz.expression.types
internal class Capture : Type("capture") {
init {
containsChildren = true
}
override fun copy() = Capture().copy(this)
override fun evaluate(): String {
val list = value as List<Type>
val evaluated = list.joinToString("") { it.evaluate() }
return "(${evaluated})"
}
}
| 0 | null | 0 | 9 | fdaf5ae2a918bae77fd76d4ca0205b8cea7b3407 | 360 | super-expressive | MIT License |
app/src/main/java/com/botigocontigo/alfred/utils/executors/Executor.kt | UTN-FRBA-Mobile | 146,629,720 | false | null | package com.botigocontigo.alfred.utils.executors
interface Executor<asyncOperationType> {
fun sync(function: (asyncOperationType) -> Unit): Executor<asyncOperationType>
fun async(function: () -> asyncOperationType): Executor<asyncOperationType>
fun run()
} | 0 | Kotlin | 4 | 1 | 558eb3967b3026bf66ae12d25b98c8055b3a9949 | 271 | Alfred | MIT License |
typescript-kotlin/src/main/kotlin/typescript/isSourceFile.fun.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:JsModule("typescript")
@file:JsNonModule
package typescript
external fun isSourceFile(node: Node): Boolean /* node is SourceFile */
| 0 | Kotlin | 1 | 10 | bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0 | 185 | react-types-kotlin | Apache License 2.0 |
app/src/main/java/com/melody/switch/demo/IosSwitchButtonStyle1.kt | TheMelody | 527,584,656 | false | {"Kotlin": 9574} | package com.melody.switch.demo
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* 仅支持点击
* @author TheMelody
* email [email protected]
* created 2022/7/16 10:09
*/
@Composable
fun IosSwitchButtonStyle1(
modifier: Modifier,
checked: Boolean,
onCheckedChange: ((Boolean) -> Unit),
width: Dp = 49.dp,
height: Dp = 30.dp,
checkedTrackColor: Color = Color(0xFF4D7DEE),
uncheckedTrackColor: Color = Color(0xFFC7C7C7),
gapBetweenThumbAndTrackEdge: Dp = 2.dp
){
val switchONState = remember { mutableStateOf(checked) }
val thumbRadius = (height / 2) - gapBetweenThumbAndTrackEdge
val animatePosition by animateFloatAsState(
targetValue = if (checked)
with(LocalDensity.current) { (width - thumbRadius - gapBetweenThumbAndTrackEdge).toPx() }
else
with(LocalDensity.current) { (thumbRadius + gapBetweenThumbAndTrackEdge).toPx() }
)
val animateTrackColor by animateColorAsState(
targetValue = if (checked) checkedTrackColor else uncheckedTrackColor
)
Canvas(
modifier = modifier
.size(width = width, height = height)
.pointerInput(Unit) {
detectTapGestures(
onTap = {
switchONState.value = !switchONState.value
onCheckedChange.invoke(switchONState.value)
}
)
}
) {
// Track
drawRoundRect(
color = animateTrackColor,
cornerRadius = CornerRadius(x = height.toPx(), y = height.toPx()),
)
// Thumb
drawCircle(
color = Color.White,
radius = thumbRadius.toPx(),
center = Offset(
x = animatePosition,
y = size.height / 2
)
)
}
} | 0 | Kotlin | 1 | 7 | 3d94bb58bcc28d89b60279a9776b594b2c64d2d6 | 2,589 | ComposeIOSSwitchButton | Apache License 2.0 |
app/src/main/java/com/startingground/cognebus/practice/QuestionPracticeFragment.kt | StartingGround | 434,992,176 | false | null | package com.startingground.cognebus.practice
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import com.startingground.cognebus.R
import com.startingground.cognebus.databinding.FragmentQuestionPracticeBinding
import com.startingground.cognebus.utilities.OnTouchListenerForScrollingInsideViewPager2
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class QuestionPracticeFragment : Fragment() {
private var binding: FragmentQuestionPracticeBinding? = null
private val sharedPracticeViewModel: PracticeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_question_practice, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.sharedPracticeViewModel = sharedPracticeViewModel
binding?.lifecycleOwner = viewLifecycleOwner
sharedPracticeViewModel.currentFlashcard.observe(viewLifecycleOwner){
if(it == null) {
findNavController().popBackStack()
}
}
binding?.topAppBar?.setNavigationOnClickListener {
activity?.onBackPressed()
}
val viewPager: ViewPager2? = activity?.findViewById(R.id.practice_pager)
binding?.topAppBar?.setOnMenuItemClickListener {
when(it.itemId){
R.id.move_to_answer ->{
viewPager?.currentItem = 1
true
}
else -> false
}
}
binding?.topAppBar?.title = getString(R.string.practice_question_fragment_top_app_bar_title, 0, 0)
sharedPracticeViewModel.flashcardNumber.observe(viewLifecycleOwner){
val (currentFlashcardNumber, totalNumberOfFlashcards) = it
binding?.topAppBar?.title = getString(R.string.practice_question_fragment_top_app_bar_title, currentFlashcardNumber, totalNumberOfFlashcards)
}
binding?.questionMathView?.setOnTouchListener(
OnTouchListenerForScrollingInsideViewPager2(binding?.questionMathView, requireContext())
)
}
} | 0 | Kotlin | 0 | 0 | ca4a7ec801bccf08b34bec55eb6ffad6a43f72f3 | 2,629 | Cognebus | MIT License |
3014.Minimum Number of Pushes to Type Word I.kt | sarvex | 842,260,390 | false | {"Kotlin": 1775678, "PowerShell": 418} | internal class Solution {
fun minimumPushes(word: String): Int {
val n = word.length
var ans = 0
var k = 1
for (i in 0 until n / 8) {
ans += k * 8
++k
}
ans += k * (n % 8)
return ans
}
}
| 0 | Kotlin | 0 | 0 | 71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48 | 231 | kotlin-leetcode | MIT License |
app/src/main/java/com/vinicius/githubapi/di/networkModule.kt | KhomDrake | 384,569,418 | false | null | package com.vinicius.githubapi.di
import com.vinicius.githubapi.remote.network.ClientBuilder
import com.vinicius.githubapi.remote.network.GithubApi
import com.vinicius.githubapi.remote.network.RetrofitBuilder
import org.koin.dsl.module
import retrofit2.Retrofit
val networkModule = module {
single { ClientBuilder.build() }
single { RetrofitBuilder.build(get()) }
single { get<Retrofit>().create(GithubApi::class.java) }
} | 0 | Kotlin | 0 | 0 | 54ff30b6598f469be66ef2cbbfe7eff815114d5f | 436 | The-Github-API | X.Net License |
src/main/kotlin/me/akhsaul/common/plugin/VideoPlugin.kt | akhsaul | 455,415,695 | false | null | package me.akhsaul.common.plugin
import okhttp3.HttpUrl
import me.akhsaul.common.enum.VideoQuality
interface VideoPlugin : HostPlugin {
var quality: VideoQuality
fun getVideoSrc(): List<HttpUrl>
fun getVideoDetails(): List<Map<String, String>>
} | 0 | Kotlin | 0 | 0 | fc0335a4bad6d032aa558f4c041024663102f231 | 259 | Utils-Common | Apache License 2.0 |
app/shared/bitcoin-primitives/public/src/commonMain/kotlin/build/wallet/bitcoin/keys/ExtendedPrivateKey.kt | proto-at-block | 761,306,853 | false | {"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.bitcoin.keys
import dev.zacsweers.redacted.annotations.Redacted
/**
* Represents a private extended bitcoin key derived for segwit wallet (BIP-84).
*/
@Redacted
data class ExtendedPrivateKey(
val xprv: String,
val mnemonic: String,
) {
init {
require(xprv.isNotBlank())
require(mnemonic.isNotBlank())
}
}
| 0 | C | 10 | 98 | 1f9f2298919dac77e6791aa3f1dbfd67efe7f83c | 346 | bitkey | MIT License |
app/src/main/java/com/github/okwrtdsh/idobatter/room/Message.kt | jphacks | 212,725,366 | false | null | package com.github.okwrtdsh.idobatter.room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "message_table")
class Message(
@PrimaryKey val uuid: String,
val created: Long,
val content: String,
val lat: Double,
val lng: Double,
val hops: Int,
@ColumnInfo(name = "is_fab") var isFab: Boolean,
@ColumnInfo(name = "is_auther") val isAuther: Boolean,
@ColumnInfo(name = "is_uploaded") var isUploaded: Boolean,
@ColumnInfo(name = "limit_dist") val limitDist: Int,
@ColumnInfo(name = "limit_time") val limitTime: Int,
@ColumnInfo(name = "limit_hops") val limitHops: Int
)
| 0 | Kotlin | 2 | 3 | 999675551543932cf8ffa5f70a4eeeb6f2957c5d | 680 | KB_1914 | MIT License |
down-work-biz/src/commonTest/kotlin/stub/DownWorkDeleteStubTest.kt | ponomain | 589,205,451 | false | null | package stub
import DownWorkContext
import DownWorkOrderStubs
import DownWorkProcessor
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import models.DownWorkCommand
import models.DownWorkMode
import models.DownWorkOrder
import models.DownWorkOrderId
import models.DownWorkState
import stubs.DownWorkStub
import kotlin.test.Test
import kotlin.test.assertEquals
@OptIn(ExperimentalCoroutinesApi::class)
class DownWorkDeleteStubTest {
private val processor = DownWorkProcessor()
val id = DownWorkOrderId("666")
val title = "test title"
val description = "description 666"
@Test
fun delete() = runTest {
val ctx = DownWorkContext(
command = DownWorkCommand.DELETE,
state = DownWorkState.NONE,
workMode = DownWorkMode.STUB,
stubCase = DownWorkStub.SUCCESS,
orderRequest = DownWorkOrder(
id = id,
title = title,
description = description
),
)
processor.exec(ctx)
with(DownWorkOrderStubs.get()) {
assertEquals(id, ctx.orderResponse.id)
assertEquals(title, ctx.orderResponse.title)
assertEquals(description, ctx.orderResponse.description)
}
}
@Test
fun badId() = runTest {
val ctx = DownWorkContext(
command = DownWorkCommand.DELETE,
state = DownWorkState.NONE,
workMode = DownWorkMode.STUB,
stubCase = DownWorkStub.BAD_ID,
orderRequest = DownWorkOrder(
id = id,
title = title,
description = description
),
)
processor.exec(ctx)
assertEquals(DownWorkOrder(), ctx.orderResponse)
assertEquals("id", ctx.errors.firstOrNull()?.field)
assertEquals("validation", ctx.errors.firstOrNull()?.group)
}
@Test
fun databaseError() = runTest {
val ctx = DownWorkContext(
command = DownWorkCommand.DELETE,
state = DownWorkState.NONE,
workMode = DownWorkMode.STUB,
stubCase = DownWorkStub.DB_ERROR,
orderRequest = DownWorkOrder(
id = id,
title = title,
description = description,
),
)
processor.exec(ctx)
assertEquals(DownWorkOrder(), ctx.orderResponse)
assertEquals("internal", ctx.errors.firstOrNull()?.group)
}
@Test
fun badNoCase() = runTest {
val ctx = DownWorkContext(
command = DownWorkCommand.DELETE,
state = DownWorkState.NONE,
workMode = DownWorkMode.STUB,
stubCase = DownWorkStub.BAD_TITLE,
orderRequest = DownWorkOrder(
id = id,
title = title,
description = description,
),
)
processor.exec(ctx)
assertEquals(DownWorkOrder(), ctx.orderResponse)
assertEquals("stub", ctx.errors.firstOrNull()?.field)
}
} | 0 | Kotlin | 0 | 0 | 7f6e0b91e4ead6f8f3a825ad74fa21235bc85536 | 3,091 | DownWork | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/glue/CfnClassifierXMLClassifierPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.glue
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.glue.CfnClassifier
/**
* A classifier for `XML` content.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.glue.*;
* XMLClassifierProperty xMLClassifierProperty = XMLClassifierProperty.builder()
* .classification("classification")
* .rowTag("rowTag")
* // the properties below are optional
* .name("name")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-xmlclassifier.html)
*/
@CdkDslMarker
public class CfnClassifierXMLClassifierPropertyDsl {
private val cdkBuilder: CfnClassifier.XMLClassifierProperty.Builder =
CfnClassifier.XMLClassifierProperty.builder()
/** @param classification An identifier of the data format that the classifier matches. */
public fun classification(classification: String) {
cdkBuilder.classification(classification)
}
/** @param name The name of the classifier. */
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param rowTag The XML tag designating the element that contains each record in an XML
* document being parsed. This can't identify a self-closing element (closed by `/>` ). An
* empty row element that contains only attributes can be parsed as long as it ends with a
* closing tag (for example, `<row item_a="A" item_b="B"></row>` is okay, but
* `<row item_a="A" item_b="B" />` is not).
*/
public fun rowTag(rowTag: String) {
cdkBuilder.rowTag(rowTag)
}
public fun build(): CfnClassifier.XMLClassifierProperty = cdkBuilder.build()
}
| 3 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,128 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/fixeam/icoser/ui/main/fragment/SmartVideoFragment.kt | qq1790141618 | 748,453,146 | false | {"Kotlin": 378582, "HTML": 2476} | package com.fixeam.icoser.ui.main.fragment
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.fragment.app.Fragment
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.Timeline
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.fixeam.icoser.R
import com.fixeam.icoser.databinding.FragmentSmartVideoBinding
import com.fixeam.icoser.databinding.SmartVideoItemBinding
import com.fixeam.icoser.model.formatTime
import com.fixeam.icoser.model.getBestMedia
import com.fixeam.icoser.model.getScreenWidth
import com.fixeam.icoser.model.isDarken
import com.fixeam.icoser.model.shareTextContent
import com.fixeam.icoser.model.startAlbumActivity
import com.fixeam.icoser.model.startModelActivity
import com.fixeam.icoser.network.Media
import com.fixeam.icoser.network.accessLog
import com.fixeam.icoser.network.appreciate
import com.fixeam.icoser.network.appreciateCancel
import com.fixeam.icoser.network.requestMediaData
import com.fixeam.icoser.network.setMediaCollection
import com.fixeam.icoser.network.updateAccessLog
import com.fixeam.icoser.network.userMediaLike
import com.fixeam.icoser.painter.GlideBlurTransformation
class SmartVideoFragment : Fragment() {
private var mediaList: MutableList<Media> = mutableListOf()
private var playIndex: Int = 5
private lateinit var binding: FragmentSmartVideoBinding
private var sharedPreferences: SharedPreferences? = null
private var isMyFavor = false
private var startFrom = 0
private var id = -1
private var albumId = -1
private var modelId = -1
private var getMoreAllow = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(arguments != null){
isMyFavor = requireArguments().getBoolean("is-my-favor", false)
id = requireArguments().getInt("id", -1)
albumId = requireArguments().getInt("album-id", -1)
modelId = requireArguments().getInt("model-id", -1)
startFrom = requireArguments().getInt("start-from", 0)
if(isMyFavor || id > 1 || albumId > 1 || modelId > 1){
getMoreAllow = false
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSmartVideoBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sharedPreferences = requireContext().getSharedPreferences("video_progress", Context.MODE_PRIVATE)
requestMedia(createViewPager = true)
}
private fun requestMedia(insert: Boolean = false, createViewPager: Boolean = false){
var number = 20
if(isMyFavor || id > 1 || albumId > 1 || modelId > 1){
number = 9999
}
if(!isMyFavor){
requestMediaData(requireContext(), modelId, albumId, id, number){
if(insert){
playIndex += it.size
mediaList.addAll(0, it)
} else {
mediaList.addAll(it)
}
if(createViewPager){
createViewPager()
} else {
refreshViewPager(it.size, insert)
}
}
} else {
mediaList.clear()
for (mediaFavor in userMediaLike){
mediaList.add(mediaFavor.content)
}
createViewPager()
}
}
private var adapter = MyPagerAdapter()
private fun createViewPager(){
val viewPager: ViewPager2 = binding.viewPager
viewPager.getChildAt(0)?.overScrollMode = View.OVER_SCROLL_NEVER
viewPager.adapter = adapter
viewPager.offscreenPageLimit = 1
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
val adapter = viewPager.adapter
if (adapter != null && playIndex != position) {
// 暂停之前页面的视频播放
val lastViewHolder = (viewPager.getChildAt(0) as RecyclerView).findViewHolderForAdapterPosition(playIndex)
if (lastViewHolder is MyViewHolder) {
lastViewHolder.binding.videoView.player?.pause()
}
// 播放当前页面的视频
val displayViewHolder = (viewPager.getChildAt(0) as RecyclerView).findViewHolderForAdapterPosition(position)
if (displayViewHolder is MyViewHolder) {
displayViewHolder.binding.videoView.player?.play()
}
// 更新播放位置
playIndex = position
}
if(getMoreAllow) {
if (position <= 3) {
requestMedia(insert = true, createViewPager = false)
} else if (mediaList.size - position <= 3) {
requestMedia(insert = false, createViewPager = false)
}
}
}
})
if(getMoreAllow){
viewPager.setCurrentItem(playIndex, false)
}
if(startFrom > 0){
viewPager.setCurrentItem(startFrom, false)
}
}
@SuppressLint("NotifyDataSetChanged")
private fun refreshViewPager(number: Int, insert: Boolean = false) {
val viewPager: ViewPager2 = binding.viewPager
val currentItemCount = adapter.itemCount
val currentPosition = viewPager.currentItem // 记录当前位置
if (insert) {
adapter.notifyDataSetChanged()
viewPager.post {
viewPager.setCurrentItem(currentPosition + number, false)
}
} else {
adapter.notifyItemRangeInserted(currentItemCount, number)
}
}
inner class MyPagerAdapter : RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding = SmartVideoItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return mediaList.size
}
@OptIn(UnstableApi::class) @SuppressLint("SetTextI18n", "ClickableViewAccessibility")
override fun onBindViewHolder(holder: MyViewHolder, @SuppressLint("RecyclerView") position: Int) {
val media = mediaList[position]
val item = holder.binding
var accessLogId = 0
accessLog(requireContext(), media.id.toString(), "VISIT_MEDIA"){
accessLogId = it
}
// 创建背景图
Glide.with(requireContext())
.load("${media.cover}/short1200px")
.apply(RequestOptions.bitmapTransform(GlideBlurTransformation(requireContext())))
.into(item.blurBackground)
// 获取最佳视频分辨率并设置到资源
var bestResolutionRatio = 720
if(sharedPreferences != null){
bestResolutionRatio = sharedPreferences!!.getInt("best_resolution_ratio", 720)
}
val bestMediaIndex = getBestMedia(media.format, bestResolutionRatio)
val bestMediaUrl = media.format[bestMediaIndex].url
val mediaItem = MediaItem.fromUri(bestMediaUrl)
// 获取播放器实例并注册
val player = ExoPlayer.Builder(requireContext()).build()
item.videoView.player = player
item.videoView.useController = false
player.setMediaItem(mediaItem)
player.prepare()
// 设置赞过
fun setIsAppreciate(){
if(media.like != null){
item.appreciate.setImageResource(R.drawable.appreciate_fill)
item.appreciate.imageTintList = ColorStateList.valueOf(Color.parseColor("#F53F3F"))
} else {
item.appreciate.setImageResource(R.drawable.appreciate)
val color = when(isDarken(requireActivity())){
true -> Color.WHITE
false -> Color.BLACK
}
item.appreciate.imageTintList = ColorStateList.valueOf(color)
}
}
item.appreciate.setOnClickListener {
item.appreciate.isEnabled = false
if(media.like == null){
media.like = 1
setIsAppreciate()
appreciate(media.id){result, id ->
if(result){
media.like = id
} else {
media.like = null
setIsAppreciate()
Toast.makeText(requireContext(), "操作失败", Toast.LENGTH_SHORT).show()
}
item.appreciate.isEnabled = true
}
} else {
appreciateCancel(media.like!!){
media.like = null
setIsAppreciate()
item.appreciate.isEnabled = true
}
}
}
setIsAppreciate()
// 设置收藏
fun setIsLike(){
if(media.is_collection != null){
item.favor.setImageResource(R.drawable.like_fill)
item.favor.imageTintList = ColorStateList.valueOf(Color.parseColor("#FDCDC5"))
} else {
item.favor.setImageResource(R.drawable.like)
val color = when(isDarken(requireActivity())){
true -> Color.WHITE
false -> Color.BLACK
}
item.favor.imageTintList = ColorStateList.valueOf(color)
}
}
item.favor.setOnClickListener {
setMediaCollection(media){
if(media.is_collection == null){
if(it){
media.is_collection = "true"
} else {
media.is_collection = null
}
} else {
if(it){
media.is_collection = null
} else {
media.is_collection = "true"
}
}
setIsLike()
}
}
setIsLike()
// 点击暂停/播放
var clickTime = 0
val appreciateDoubleClick = Handler(Looper.getMainLooper())
val appreciateClearClick = Runnable {
clickTime = 0
if(player.isPlaying){
player.pause()
} else {
player.play()
}
}
item.videoView.setOnClickListener {
clickTime++
if(clickTime >= 2){
clickTime = 0
item.appreciate.callOnClick()
appreciateDoubleClick.removeCallbacks(appreciateClearClick)
} else {
appreciateDoubleClick.postDelayed(appreciateClearClick, 500)
}
}
// 更新文本
item.mediaName.text = media.name
item.mediaDescription.text = media.album_name
if(media.description != null){
item.mediaDescription.text = "${media.album_name} ${media.description}"
}
// 更新按钮
Glide.with(requireContext())
.load("${media.model_avatar_image}/yswidth300px")
.into(item.modelAvatar)
item.modelAvatar.setOnClickListener { startModelActivity(requireContext(), media.bind_model_id) }
item.share.setOnClickListener {
player.pause()
shareTextContent(
context = requireContext(),
text = "来自iCoser的分享内容:模特 - ${media.bind_model_id}, 写真集 - ${media.bind_album_id}, 视频 - ${media.name}, 访问链接:https://app.fixeam.com/media?video-id=${media.id}"
)
}
item.album.setOnClickListener { startAlbumActivity(requireContext(), media.bind_album_id) }
// 更新视频相关组件
item.playButton.visibility = View.GONE
// 更新播放进度函数
fun updateProgressDisplay(currentPosition: Long, updatePlayerPosition: Boolean = false){
// 获取视频总时长计算百分比
val duration = player.duration
val percent = currentPosition.toFloat() / duration.toFloat()
// 更新进度时间显示
item.progressText.text = "${formatTime(currentPosition)} / ${formatTime(duration)}"
// 更新进度条显示
val currentWidth = item.progressBar.layoutParams.width
val animator = ValueAnimator.ofInt(currentWidth, (getScreenWidth(requireContext()) * percent).toInt())
animator.addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Int
item.progressBar.layoutParams.width = animatedValue
item.progressBar.requestLayout()
}
animator.duration = 100
animator.start()
// 如果需要则更新视频播放进度
if(updatePlayerPosition){
player.seekTo(currentPosition)
}
}
// 进度条触摸
item.progressBarContainter.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
// 用户开始触摸屏幕增加进度条高度
val animator = ValueAnimator.ofInt(item.progressBar.layoutParams.height, (resources.displayMetrics.density * 8).toInt())
animator.addUpdateListener { animation ->
item.progressBar.layoutParams.height = animation.animatedValue as Int
item.progressBar.requestLayout()
}
animator.duration = 100
animator.start()
return true
}
MotionEvent.ACTION_MOVE -> {
// 更新进度条的进度
val percent = event.x / getScreenWidth(requireContext())
val currentPosition = (player.duration * percent).toLong()
updateProgressDisplay(currentPosition, true)
return true
}
MotionEvent.ACTION_UP -> {
// 用户结束触摸屏幕还原进度条高度
val animator = ValueAnimator.ofInt(item.progressBar.layoutParams.height, (resources.displayMetrics.density * 3).toInt())
animator.addUpdateListener { animation ->
item.progressBar.layoutParams.height = animation.animatedValue as Int
item.progressBar.requestLayout()
}
animator.duration = 100
animator.start()
return true
}
}
return false
}
})
// 定时器
var handler: Handler? = null
var runnable: Runnable? = null
player.addListener(object : Player.Listener {
override fun onTimelineChanged(timeline: Timeline, reason: Int) {
// 获取存储共享器 从本地存储中读取上次播放的位置
if(sharedPreferences != null) {
val lastPlayedPosition =
sharedPreferences!!.getInt("last_played_position_${media.id}", 0)
updateProgressDisplay(lastPlayedPosition.toLong(), true)
}
super.onTimelineChanged(timeline, reason)
}
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
if (playWhenReady) {
item.playButton.visibility = View.GONE
} else {
item.playButton.visibility = View.VISIBLE
}
}
override fun onPlaybackStateChanged(state: Int) {
if (state == Player.STATE_ENDED) {
item.playButton.visibility = View.VISIBLE
item.progressBar.layoutParams = item.progressBar.layoutParams.apply {
width = 0
}
item.progressText.text = "00:00 / 00:00"
player.seekTo(0.toLong())
}
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
if (isPlaying) {
item.playButton.visibility = View.GONE
item.loading.clearAnimation()
item.loading.visibility = View.GONE
handler = Handler(Looper.getMainLooper())
runnable = object : Runnable {
override fun run() {
// 更新进度条
val currentPosition = player.currentPosition
updateProgressDisplay(currentPosition)
// 记录播放位置
if(sharedPreferences != null){
sharedPreferences!!.edit().putInt("last_played_position_${media.id}",
currentPosition.toInt()
).apply()
}
updateAccessLog(accessLogId, (currentPosition / 1000).toInt())
handler?.postDelayed(this, 500) // 延迟1秒钟
}
}
handler?.postDelayed(runnable!!, 500)
} else {
item.playButton.visibility = View.VISIBLE
handler?.removeCallbacks(runnable!!)
handler = null
runnable = null
}
}
override fun onIsLoadingChanged(isLoading: Boolean) {
if(isLoading && !player.isPlaying){
val animation = AnimationUtils.loadAnimation(requireContext(),
R.anim.loading
)
item.loading.startAnimation(animation)
item.loading.visibility = View.VISIBLE
} else {
item.loading.clearAnimation()
item.loading.visibility = View.GONE
if(position == 5){
player.play()
}
}
super.onIsLoadingChanged(isLoading)
}
})
}
override fun onViewRecycled(holder: MyViewHolder) {
// 释放 AndroidX Media3 ExoPlayer 资源
holder.binding.videoView.player?.pause()
holder.binding.videoView.player?.stop()
holder.binding.videoView.player?.release()
holder.binding.videoView.player = null
super.onViewRecycled(holder)
}
}
inner class MyViewHolder(var binding: SmartVideoItemBinding) : RecyclerView.ViewHolder(binding.root)
// 界面切换时的相关事件
private var lastIsPlaying = false
private fun leaveFragment(){
val viewPager: ViewPager2 = binding.viewPager
val lastViewHolder = (viewPager.getChildAt(0) as RecyclerView).findViewHolderForAdapterPosition(playIndex)
if (lastViewHolder is MyViewHolder) {
val player = lastViewHolder.binding.videoView.player
if (player != null && player.isPlaying) {
lastIsPlaying = true
player.pause()
}
}
}
private fun enterFragment(){
if(lastIsPlaying){
val viewPager: ViewPager2 = binding.viewPager
val lastViewHolder = (viewPager.getChildAt(0) as RecyclerView).findViewHolderForAdapterPosition(playIndex)
if (lastViewHolder is MyViewHolder) {
val player = lastViewHolder.binding.videoView.player
if (player != null && !isHide) {
lastIsPlaying = false
player.play()
}
}
}
}
private var isHide: Boolean = false
override fun onStop() {
leaveFragment()
super.onStop()
}
override fun onPause() {
leaveFragment()
super.onPause()
}
override fun onHiddenChanged(hidden: Boolean) {
if (hidden) {
isHide = true
leaveFragment()
} else {
isHide = false
enterFragment()
}
super.onHiddenChanged(hidden)
}
override fun onResume() {
enterFragment()
super.onResume()
}
} | 0 | Kotlin | 0 | 0 | 14212926ab851d64cc6f5a157bdea7129837016f | 22,546 | iCoserKT | MIT License |
src/main/kotlin/org/dropProject/dao/Assignment.kt | ULHT-CM-2020-21 | 402,800,255 | true | {"HTML": 940423, "Kotlin": 513102, "JavaScript": 122743, "Java": 47015, "CSS": 13667} | /*-
* ========================LICENSE_START=================================
* DropProject
* %%
* Copyright (C) 2019 <NAME>
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package org.dropProject.dao
import org.dropProject.Constants
import org.dropProject.forms.SubmissionMethod
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import javax.persistence.*
val formatter = DateTimeFormatter.ofPattern("dd MMM HH:mm")
enum class Language {
JAVA, KOTLIN
}
enum class TestVisibility {
HIDE_EVERYTHING,
SHOW_OK_NOK, // show only if it passes all the hidden tests or not
SHOW_PROGRESS // show the number of tests that pass
}
enum class LeaderboardType {
TESTS_OK, // ordered by number of passed tests (desc)
ELLAPSED, // ordered by number of passed tests (desc) and then ellapsed (asc)
COVERAGE // ordered by number of passed tests (desc) and then coverage (desc)
}
@Entity
data class Assignment(
@Id
val id: String,
@Column(nullable = false)
var name: String,
var packageName: String? = null,
var dueDate: LocalDateTime? = null,
@Column(nullable = false)
var submissionMethod: SubmissionMethod,
@Column(nullable = false)
var language: Language = Language.JAVA,
var acceptsStudentTests: Boolean = false,
var minStudentTests: Int? = null,
var calculateStudentTestsCoverage: Boolean = false,
var hiddenTestsVisibility: TestVisibility? = null,
var cooloffPeriod: Int? = null, // minutes
var maxMemoryMb: Int? = null,
var showLeaderBoard: Boolean = false,
var leaderboardType: LeaderboardType? = null,
val gitRepositoryUrl: String,
@Column(columnDefinition = "TEXT")
var gitRepositoryPubKey: String? = null,
@Column(columnDefinition = "TEXT")
var gitRepositoryPrivKey: String? = null,
var gitRepositoryFolder: String, // relative to assignment.root.location
@Column(nullable = false)
val ownerUserId: String,
var active: Boolean = false,
var archived: Boolean = false,
var buildReportId: Long? = null, // build_report.id
@Transient
var numSubmissions: Int = 0,
@Transient
var numUniqueSubmitters: Int = 0,
@Transient
var public: Boolean = true,
@Transient
var lastSubmissionDate: Date? = null
) {
fun dueDateFormatted(): String? {
return dueDate?.format(formatter)
}
}
| 0 | null | 0 | 0 | 4d25b1363d76838de1a7f624cc1539062ddbb383 | 3,176 | drop-project | Apache License 2.0 |
app/src/main/java/com/jacquessmuts/hellothere/HelloThereAdapter.kt | JacquesSmuts | 114,380,032 | false | null | package com.jacquessmuts.hellothere
/**
* Created by <NAME> on 12/15/2017.
*/
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jacquessmuts.hellothere.data.HelloThereItem
import pl.droidsonroids.gif.GifImageView
class HelloThereAdapter(val helloThereList: ArrayList<HelloThereItem>,
val itemClick: (HelloThereItem) -> Unit) :
RecyclerView.Adapter<HelloThereAdapter.ViewHolder>() {
companion object {
}
//this method is returning the view for each item in the list
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HelloThereAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_hello_there, parent, false)
return ViewHolder(v, itemClick)
}
//this method is binding the data on the list
override fun onBindViewHolder(holder: HelloThereAdapter.ViewHolder, position: Int) {
holder.bindItems(helloThereList[position])
var imageResource = R.drawable.maingif
if (helloThereList[position].isGrievious){
imageResource = R.drawable.secondgif
}
holder.imageView.setImageResource(imageResource)
}
//this method is giving the size of the list
override fun getItemCount(): Int {
return helloThereList.size
}
//the class is hodling the list view
class ViewHolder(itemView: View, private val itemClick: (HelloThereItem) -> Unit) : RecyclerView.ViewHolder(itemView) {
var imageView : GifImageView = itemView.findViewById(R.id.image_hello_there)
fun bindItems(item: HelloThereItem) {
// val imageViewHelloThere = itemView.findViewById<GifImageView>(R.id.image_hello_there)
// Picasso.with(itemView.context).load(HelloThereAdapter.HELLO_THERE_URL).into(imageViewHelloThere);
itemView.setOnClickListener{ itemClick(item)}
}
}
} | 1 | Kotlin | 1 | 0 | a72b108cab255ae59f77b101a810d685c5370685 | 2,011 | HelloThere | MIT License |
app/src/main/java/com/example/rifsa_mobile/model/entity/remotefirebase/HarvestEntity.kt | RIFSA | 491,493,199 | false | {"Kotlin": 301341} | package com.example.rifsa_mobile.model.entity.remotefirebase
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Parcelize
@Entity(tableName="HarvestTable")
class HarvestEntity(
@PrimaryKey(autoGenerate = true)
var localId : Int = 0,
var id : String="",
var firebaseUserId : String = "",
var date : String="",
val day : Int = 0,
val month : Int = 0,
val year : Int = 0,
var typeOfGrain : String="",
var weight : Int = 0,
var income : Int = 0,
var note : String="",
var isUploaded : Boolean = true,
var uploadReminderId : Int = 0
): Parcelable | 0 | Kotlin | 3 | 6 | 1ebadecd73d6ff26122d941b1ca724f4184b8a7b | 678 | Rifsa-Mobile | The Unlicense |
app/src/test/java/br/com/lucolimac/pokedex/UnitTest.kt | lucasomac | 627,122,617 | false | {"Kotlin": 71812} | package br.com.lucolimac.pokedex
import org.junit.Assert.assertEquals
import org.junit.Test
class UnitTest {
@Test
// @DisplayName("Test of addiction")
fun additionIsCorrect() {
assertEquals(4, 2 + 2)
}
} | 1 | Kotlin | 0 | 0 | 31ed8c59e5b6be1069888c4c0dc6518cec660f97 | 229 | Pokedex | RSA Message-Digest License |
src/main/kotlin/br/com/zup/integration/bcb/CriaChaveBcbResponse.kt | DinizEduardo | 355,275,492 | true | {"Kotlin": 88775} | package br.com.zup.integration.bcb
import br.com.zup.pix.TipoChave
import java.time.LocalDateTime
data class CriaChaveBcbResponse(
val keyType: PixKeyType,
val key: String,
val bankAccount: BankAccount,
val owner: Owner,
val createdAt: LocalDateTime
) {
}
enum class PixKeyType(val domainType: TipoChave?) {
CPF(TipoChave.CPF),
CNPJ(null),
PHONE(TipoChave.CELULAR),
EMAIL(TipoChave.EMAIL),
RANDOM(TipoChave.ALEATORIA);
companion object {
private val mapping = PixKeyType.values().associateBy(PixKeyType::domainType)
fun by(domainType: TipoChave): PixKeyType {
return mapping[domainType] ?: throw IllegalArgumentException("PixKeyType invalid or not found for $domainType")
}
}
}
| 0 | Kotlin | 0 | 0 | 80ed382b7e12b7d0d074644ad5ce501175bfb9dc | 771 | orange-talents-02-template-pix-keymanager-grpc | Apache License 2.0 |
catalog/src/main/kotlin/com/adevinta/spark/catalog/examples/samples/toggles/RadioButtonExamples.kt | adevinta | 598,741,849 | false | {"Kotlin": 2285397} | /*
* Copyright (c) 2023 Adevinta
*
* 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.adevinta.spark.catalog.examples.samples.toggles
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.adevinta.spark.SparkTheme
import com.adevinta.spark.catalog.R
import com.adevinta.spark.catalog.model.Example
import com.adevinta.spark.catalog.util.SampleSourceUrl
import com.adevinta.spark.components.spacer.VerticalSpacer
import com.adevinta.spark.components.toggles.ContentSide
import com.adevinta.spark.components.toggles.RadioButton
import com.adevinta.spark.components.toggles.RadioButtonLabelled
private const val RadioButtonExampleDescription = "RadioButton examples"
private const val RadioButtonExampleSourceUrl = "$SampleSourceUrl/RadioButtonSamples.kt"
public val RadioButtonExamples: List<Example> = listOf(
Example(
name = "Standalone radio button",
description = RadioButtonExampleDescription,
sourceUrl = RadioButtonExampleSourceUrl,
) {
Column {
var selected by remember { mutableStateOf(true) }
val onClick = { selected = !selected }
RadioButton(
selected = selected,
onClick = onClick,
enabled = true,
)
RadioButton(
selected = selected,
onClick = onClick,
enabled = false,
)
}
},
Example(
name = "Labeled radio button content side",
description = RadioButtonExampleDescription,
sourceUrl = RadioButtonExampleSourceUrl,
) {
RadioButtonContentSideExample()
},
Example(
name = "Labeled radio button group",
description = RadioButtonExampleDescription,
sourceUrl = RadioButtonExampleSourceUrl,
) {
LabeledRadioButtonGroupExample()
},
)
@Composable
private fun RadioButtonContentSideExample() {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
val label = stringResource(id = R.string.component_checkbox_content_side_example_label)
ContentSide.values().forEach { contentSide ->
var selected by remember { mutableStateOf(false) }
RadioButtonLabelled(
modifier = Modifier.fillMaxWidth(),
enabled = true,
selected = selected,
contentSide = contentSide,
onClick = { selected = !selected },
) {
Text(
text = label,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
}
@Composable
private fun LabeledRadioButtonGroupExample() {
val labels = listOf(
stringResource(id = R.string.component_checkbox_group_example_option1_label),
stringResource(id = R.string.component_checkbox_group_example_option2_label),
)
Column(verticalArrangement = Arrangement.spacedBy(24.dp)) {
LabeledRadioButtonGroupHorizontalExample(labels)
LabeledRadioButtonVerticalGroupExample(labels)
}
}
@Composable
private fun LabeledRadioButtonVerticalGroupExample(
labels: List<String>,
) {
var childrenStates by remember {
mutableStateOf(List(labels.size) { false })
}
Column {
Text(
text = stringResource(id = R.string.component_toggle_vertical_group_title),
style = SparkTheme.typography.headline2,
)
VerticalSpacer(space = 8.dp)
labels.forEachIndexed { index, label ->
val selected = childrenStates.getOrElse(index) { false }
val onClick = {
childrenStates = childrenStates.mapIndexed { i, selected ->
if (i == index && selected.not()) {
true
} else if (i != index && selected) {
false
} else {
selected
}
}
}
RadioButtonLabelled(
enabled = true,
selected = selected,
contentSide = ContentSide.End,
onClick = onClick,
) {
Text(text = label)
}
}
}
}
@Composable
private fun LabeledRadioButtonGroupHorizontalExample(labels: List<String>) {
Column {
Text(
text = stringResource(id = R.string.component_toggle_horizontal_group_title),
style = SparkTheme.typography.headline2,
)
VerticalSpacer(space = 8.dp)
var childrenStates by remember {
mutableStateOf(List(labels.size) { false })
}
Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
labels.forEachIndexed { index, label ->
val selected = childrenStates.getOrElse(index) { false }
val onClick = {
childrenStates = childrenStates.mapIndexed { i, selected ->
if (i == index && selected.not()) {
true
} else if (i != index && selected) {
false
} else {
selected
}
}
}
RadioButtonLabelled(
enabled = true,
selected = selected,
onClick = onClick,
) { Text(label) }
}
}
}
}
| 29 | Kotlin | 24 | 67 | bb0e00f2b574a3c57c5c3bd91969362c7c91c7fa | 7,071 | spark-android | MIT License |
demo/src/main/java/com/aliernfrog/toptoastdemo/MainActivity.kt | aliernfrog | 522,699,218 | false | {"Kotlin": 22272} | package com.aliernfrog.toptoastdemo
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.Crossfade
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import com.aliernfrog.toptoast.component.TopToast
import com.aliernfrog.toptoast.component.TopToastHost
import com.aliernfrog.toptoast.enum.TopToastColor
import com.aliernfrog.toptoast.state.TopToastState
import com.aliernfrog.toptoastdemo.enum.ToastMethod
import com.aliernfrog.toptoastdemo.ui.component.SegmentedButtons
import com.aliernfrog.toptoastdemo.ui.component.form.FormSection
import com.aliernfrog.toptoastdemo.ui.theme.TopToastComposeTheme
class MainActivity : ComponentActivity() {
private lateinit var topToastState: TopToastState
private var swipeToDismiss: Boolean
get() = topToastState.allowSwipeToDismiss
set(value) { topToastState.allowSwipeToDismiss = value }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
topToastState = TopToastState(
composeView = null,
appTheme = {
TopToastComposeTheme(content = it)
}
)
topToastState.setComposeView(window.decorView)
setContent {
TopToastComposeTheme {
AppContent()
TopToastHost(topToastState)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AppContent() {
val uriHandler = LocalUriHandler.current
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
var dialogShown by remember { mutableStateOf(false) }
var selectedToastMethod by rememberSaveable {
mutableStateOf(ToastMethod.COMPOSE)
}
var toastText by rememberSaveable {
mutableStateOf("Hello world!")
}
var toastDuration by rememberSaveable {
mutableStateOf<Int?>(null)
}
var toastIcon by rememberSaveable {
mutableStateOf<ImageVector?>(null)
}
var showDialogAfterToast by rememberSaveable {
mutableStateOf(false)
}
var toastIconTintColor by rememberSaveable {
mutableStateOf(TopToastColor.PRIMARY)
}
var onToastClick by rememberSaveable {
mutableStateOf<Pair<String, (() -> Unit)?>>("Unclickable" to null)
}
var dismissToastOnClick by rememberSaveable {
mutableStateOf(true)
}
LaunchedEffect(selectedToastMethod) {
toastDuration = selectedToastMethod.defaultDuration
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.app_name)) },
scrollBehavior = scrollBehavior,
actions = {
var actionsShown by remember { mutableStateOf(false) }
Box {
IconButton(
onClick = { actionsShown = true }
) {
Icon(Icons.Default.MoreVert, contentDescription = "More actions")
}
DropdownMenu(
expanded = actionsShown,
onDismissRequest = { actionsShown = false }
) {
DropdownMenuItem(
text = { Text("Show dialog") },
onClick = {
dialogShown = true
actionsShown = false
}
)
DropdownMenuItem(
text = { Text("Show Android toast") },
onClick = {
Toast.makeText(applicationContext, toastText, Toast.LENGTH_SHORT).show()
actionsShown = false
}
)
}
}
}
)
},
floatingActionButton = {
FloatingActionButton(
onClick = {
selectedToastMethod.execute(
topToastState,
toastText,
toastIcon,
toastIconTintColor,
toastDuration ?: selectedToastMethod.defaultDuration,
swipeToDismiss,
dismissToastOnClick,
onToastClick.second
)
if (showDialogAfterToast) dialogShown = true
},
shape = RoundedCornerShape(16.dp)
) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection)
) { paddingValues ->
Column(
Modifier
.padding(paddingValues)
.fillMaxSize()
.verticalScroll(rememberScrollState())
.navigationBarsPadding(),
horizontalAlignment = Alignment.CenterHorizontally
) {
FormSection(title = "Method") {
SegmentedButtons(
options = ToastMethod.entries.map { it.label },
selectedIndex = selectedToastMethod.ordinal,
onSelect = { selectedToastMethod = ToastMethod.entries[it] },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
)
Text(
text = selectedToastMethod.description,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(horizontal = 16.dp)
)
}
FormSection(title = "General") {
OutlinedTextField(
value = toastText,
onValueChange = { toastText = it },
label = {
Text("Text")
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
)
AnimatedContent(
targetState = selectedToastMethod == ToastMethod.COMPOSE,
modifier = Modifier
.animateContentSize()
.padding(horizontal = 16.dp, vertical = 8.dp)
) { isSeconds ->
if (isSeconds) OutlinedTextField(
value = (toastDuration ?: "").toString(),
onValueChange = { toastDuration = it.toIntOrNull() },
label = {
Text("Duration (seconds)")
},
placeholder = {
Text(selectedToastMethod.defaultDuration.toString())
},
singleLine = true,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number
),
modifier = Modifier.fillMaxWidth()
) else SegmentedButtons(
options = listOf("Toast.LENGTH_SHORT", "Toast.LENGTH_LONG"),
selectedIndex = toastDuration ?: selectedToastMethod.defaultDuration,
onSelect = { toastDuration = it },
modifier = Modifier.fillMaxWidth()
)
}
Crossfade(selectedToastMethod == ToastMethod.COMPOSE) { enabled ->
CheckBoxRow(
label = "Swipe to dismiss"+if (!enabled) "\nNot supported by Android Toast API" else "",
checked = enabled && swipeToDismiss,
onCheckedChange = { swipeToDismiss = it },
enabled = enabled
)
}
CheckBoxRow(
label = "Show dialog after showing toast",
checked = showDialogAfterToast,
onCheckedChange = { showDialogAfterToast = it }
)
}
FormSection(title = "Icon") {
Row(
modifier = Modifier
.height(IntrinsicSize.Max)
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.aligned(Alignment.CenterHorizontally),
verticalAlignment = Alignment.Bottom
) {
listOf(
null,
Icons.Rounded.Check,
Icons.Rounded.Close,
Icons.Rounded.Info
).forEach { icon ->
val onSelect = { toastIcon = icon }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.aligned(Alignment.Bottom),
modifier = Modifier
.fillMaxHeight()
.width(50.dp)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = false),
onClick = onSelect
)
) {
icon?.let {
Icon(
imageVector = it,
contentDescription = null,
tint = toastIconTintColor.getColor()
)
} ?: Text("None")
RadioButton(
selected = toastIcon == icon,
onClick = onSelect
)
}
}
}
Row(
modifier = Modifier
.height(IntrinsicSize.Max)
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.aligned(Alignment.CenterHorizontally),
verticalAlignment = Alignment.Bottom
) {
TopToastColor.entries.forEach { topToastColor ->
val color = topToastColor.getColor()
val onSelect = { toastIconTintColor = topToastColor }
Box(
modifier = Modifier
.fillMaxHeight()
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = false),
onClick = onSelect
)
.size(45.dp)
.padding(4.dp)
.clip(CircleShape)
.background(color),
contentAlignment = Alignment.Center
) {
if (toastIconTintColor == topToastColor) Icon(
imageVector = Icons.Default.Check,
contentDescription = "Selected",
tint = MaterialTheme.colorScheme.contentColorFor(color)
)
}
}
}
}
FormSection(title = "On click") {
AnimatedContent(targetState = selectedToastMethod == ToastMethod.COMPOSE) { available ->
if (!available) Text(
text = "Not supported by Android Toast API",
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
) else Column {
listOf(
"Unclickable" to null,
"Do nothing" to {},
"Show dialog" to { dialogShown = true },
"Close app" to { finish() }
).forEach { option ->
val onSelect = { onToastClick = option }
val selected = option.first == onToastClick.first
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onSelect)
.padding(horizontal = 16.dp, vertical = 4.dp)
) {
RadioButton(
selected = selected,
onClick = onSelect,
modifier = Modifier.padding(end = 8.dp)
)
Text(text = option.first)
}
}
Crossfade(onToastClick.second != null) { enabled ->
CheckBoxRow(
label = "Dismiss toast on click"+
if (!enabled) "\nToast is unclickable" else "",
checked = enabled && dismissToastOnClick,
onCheckedChange = { dismissToastOnClick = it },
enabled = enabled
)
}
}
}
}
FormSection(
title = "Info",
bottomDivider = false
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth()
) {
TopToast(
text = "top-toast-compose - v${BuildConfig.VERSION_NAME}",
icon = rememberVectorPainter(Icons.Rounded.Info),
iconTintColor = MaterialTheme.colorScheme.secondary,
onClick = {
uriHandler.openUri("https://github.com/aliernfrog/top-toast-compose")
}
)
}
Spacer(modifier = Modifier.height(60.dp))
}
}
}
if (dialogShown) AlertDialog(
onDismissRequest = { dialogShown = false },
title = { Text("TopToast") },
text = {
Text("Toasts shown using Android Toast API can show on top of bottom sheets and alert dialogs such as this")
},
confirmButton = {
TextButton(onClick = { dialogShown = false }) {
Text("Dismiss")
}
}
)
}
@Composable
private fun CheckBoxRow(
label: String,
checked: Boolean,
enabled: Boolean = true,
onCheckedChange: (Boolean) -> Unit
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.run {
if (enabled) clickable { onCheckedChange(!checked) } else this
}
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Text(
text = label,
modifier = Modifier.weight(1f).fillMaxWidth(),
color = MaterialTheme.colorScheme.onSurface.copy(
alpha = if (enabled) 1f else 0.5f
)
)
Checkbox(
checked = checked,
onCheckedChange = onCheckedChange,
enabled = enabled
)
}
}
} | 0 | Kotlin | 0 | 1 | fffa2f9398dfc76253ad56cbddb448c790ad131b | 21,391 | top-toast-compose | MIT License |
composeApp/src/desktopMain/kotlin/org/openswim/database/dao/Clubs.kt | Grufoony | 856,821,082 | false | {"Kotlin": 22774} | package org.openswim.database.dao
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable
object Clubs : IntIdTable("clubs") {
val name = varchar("name", 255)
}
class Club(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Club>(Clubs)
var name by Clubs.name
} | 5 | Kotlin | 0 | 0 | 48eefb6253bd150599f2dfa9d88a90ea8d795df6 | 423 | OpenSwim | MIT License |
common/core/src/commonMain/kotlin/settings/SettingsModule.kt | Modnica12 | 660,310,210 | false | null | package settings
import org.koin.dsl.module
fun settingsModule() = module {
single<EncryptedSettingsHolder> { EncryptedSettingsHolder(platformConfiguration = get()) }
}
| 0 | Kotlin | 0 | 0 | 317333700166237768afa315dc633b835b95c258 | 175 | Compose-DTracker | Apache License 2.0 |
rest-with-spring-boot-and-kotlin-gabriel-darlan/src/main/kotlin/br/com/gdarlan/config/FileStorageConfig.kt | gabrieldarlan | 550,487,916 | false | null | package br.com.gdarlan.config
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
@Configuration
@ConfigurationProperties(prefix = "file")
class FileStorageConfig(
var uploadDir: String = "",
) | 0 | Kotlin | 0 | 0 | 6d1253d8d886a0eb71b17f11d42a34f55a52e6bd | 282 | rest-with-spring-boot-and-kotlin-gabriel-darlan | Apache License 2.0 |
app/src/main/java/gladun/vlad/weather/data/WeatherRepository.kt | VVGladun | 395,139,066 | false | null | package gladun.vlad.weather.data
import android.content.res.Resources
import gladun.vlad.weather.R
import gladun.vlad.weather.data.model.CountryFilterItem
import gladun.vlad.weather.data.model.WeatherDetails
import gladun.vlad.weather.data.model.WeatherListItem
import gladun.vlad.weather.data.model.toEntity
import gladun.vlad.weather.data.network.WeatherApiClient
import gladun.vlad.weather.data.persistence.PreferenceStore
import gladun.vlad.weather.data.persistence.dao.CountryDao
import gladun.vlad.weather.data.persistence.dao.ForecastDao
import gladun.vlad.weather.inject.BackgroundDispatcher
import gladun.vlad.weather.util.Constants
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WeatherRepository @Inject constructor(
private val weatherApiClient: WeatherApiClient,
private val countryDao: CountryDao,
private val forecastDao: ForecastDao,
private val preferenceStore: PreferenceStore,
private val resources: Resources,
@BackgroundDispatcher private val coroutineDispatcher: CoroutineDispatcher
) {
/**
* Triggers full data update - updates both countries and forecasts
*/
suspend fun updateWeatherData() = withContext(coroutineDispatcher) {
// load the data from the backend
val newWeatherData = weatherApiClient.getWeatherData()
// cleanse the weather data, to avoid storing incomplete / useless items
// - we can add analytics to log non-fatal exceptions for them later
val forecastDtos = newWeatherData.data.filter {
it.weatherTemp?.toIntOrNull() != null && it.lastUpdated != null && it.country?.countryId != null
&& !it.venueName.isNullOrBlank() && !it.venueId.isNullOrEmpty()
}
// save into the database
forecastDao.upsert(forecastDtos.map { it.toEntity() })
countryDao.upsert(forecastDtos
.distinctBy { it.country!!.countryId }
.map { it.country!!.toEntity() })
}
/**
* Flow of filtered weather data for the list of forecasts
*/
fun getFilteredWeatherList(): Flow<List<WeatherListItem>> {
return combine(
forecastDao.getAllForecasts(),
preferenceStore.selectedCountry
) { forecasts, countryFilter ->
if (countryFilter == Constants.ID_ALL_COUNTRIES) {
forecasts
} else {
forecasts.filter { it.countryId == countryFilter }
}.map { WeatherListItem.fromEntity(it) }
}
}
fun getWeatherDataItemCount(): Flow<Int> = forecastDao.getForecastItemCount()
fun getWeatherDetails(venueId: String): Flow<WeatherDetails> {
return forecastDao.getForecastForVenue(venueId).mapNotNull {
WeatherDetails.fromEntity(it, resources)
}
}
private val showAllCountriesItem = CountryFilterItem(
countryId = Constants.ID_ALL_COUNTRIES,
countryName = resources.getString(R.string.filter_all_countries),
isSelected = true
)
fun getCountryFilterItems(): Flow<List<CountryFilterItem>> {
return combine(
countryDao.getAll(),
preferenceStore.selectedCountry
) { countries, countryFilter ->
if (countryFilter == Constants.ID_ALL_COUNTRIES) {
countries.map { CountryFilterItem.fromEntity(it, false) }.toMutableList().apply {
add(0, showAllCountriesItem)
}
} else {
countries.map { CountryFilterItem.fromEntity(it, it.id == countryFilter) }.toMutableList().apply {
add(0, showAllCountriesItem.copy(isSelected = false))
}
}
}
}
suspend fun setFilterByCountry(countryId: String) {
preferenceStore.saveSelectedCountry(countryId)
}
} | 0 | Kotlin | 0 | 0 | 76f947839a77e6c3c183d460b056bf9191fb8fd1 | 4,044 | weatherapp | MIT License |
gradle-plugin/src/main/kotlin/dev/schlaubi/mikbot/gradle/Util.kt | DRSchlaubi | 409,332,765 | false | null | package dev.schlaubi.mikbot.gradle
import dev.schlaubi.mikbot.gradle.extension.PluginExtension
import dev.schlaubi.mikbot.gradle.extension.pluginExtensionName
import dev.schlaubi.mikbot.gradle.extension.pluginId
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.tasks.TaskContainer
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
import kotlin.io.path.readBytes
internal fun readPluginsJson(path: Path): List<PluginInfo> = Files.readString(path).run { Json.decodeFromString(this) }
internal fun List<PluginInfo>.writeTo(path: Path) {
Files.writeString(path, Json.encodeToString(this))
}
internal fun List<PluginInfo>.addPlugins(vararg plugins: PluginInfo): List<PluginInfo> {
val existingPlugins = map(::PluginWrapper)
val addedPlugins = plugins.map(::PluginWrapper)
val (new, toUpdate) = addedPlugins.partition { it !in existingPlugins }
val backlog = existingPlugins.filter { it !in addedPlugins }
val map = existingPlugins.associateBy { (plugin) -> plugin.id }
val updated = toUpdate.map { (plugin) ->
val (parent) = map.getValue(plugin.id) // retrieve existing releases
val newReleases = (parent.releases + plugin.releases).distinctBy(PluginRelease::version)
if (newReleases.size == parent.releases.size) {
parent // do not change existing sha512 checksums
} else {
plugin.copy(releases = newReleases)
}
}
return (new + backlog).map(PluginWrapper::pluginInfo) + updated
}
internal val Project.pluginFilePath: String
get() = "${pluginId}/${version}/plugin-${pluginId}-${version}.zip"
private data class PluginWrapper(val pluginInfo: PluginInfo) {
override fun equals(other: Any?): Boolean = (other as? PluginWrapper)?.pluginInfo?.id == pluginInfo.id
override fun hashCode(): Int = pluginInfo.id.hashCode()
}
internal fun Project.buildDependenciesString(): String {
val plugin = configurations.getByName("plugin")
val optionalPlugin = configurations.getByName("optionalPlugin")
val required = plugin.allDependencies.map(Dependency::toDependencyString)
val optional = optionalPlugin.allDependencies.map { it.toDependencyString(true) }
return (required + optional).joinToString(", ")
}
internal fun Dependency.toDependencyString(optional: Boolean = false): String {
val name = if (this is ProjectDependency) {
dependencyProject.pluginId
} else {
name.substringAfter("mikbot-")
}
return "$name${if (optional) "?" else ""}@>=$version"
}
/**
* Tries to configure this project for raw PF4J.
*/
@Suppress("unused")
fun Project.usePF4J() {
extensions.configure<PluginExtension>(pluginExtensionName) {
with(it) {
ignoreDependencies.set(true)
pluginMainFileLocation.set(
buildDir.resolve("resources").resolve("main").resolve("plugin.properties").toPath()
)
}
}
}
fun Path.sha512Checksum(): String = readBytes().sha512Checksum()
fun ByteArray.sha512Checksum(): String {
val digest = MessageDigest.getInstance("SHA-512")
val hashBytes = digest.digest(this)
return hashBytes.fold("") { str, it -> str + "%02x".format(it) }
}
internal inline fun <reified T : Task> TaskContainer.task(name: String, crossinline block: T.() -> Unit) =
create(name, T::class.java) {
it.block()
}
internal inline fun <reified T : Task> TaskContainer.register(name: String, crossinline block: T.() -> Unit) =
register(name, T::class.java) {
it.block()
}
internal fun pluginNotAppliedError(name: String): Nothing =
error("Please make sure the $name plugin is applied before the mikbot plugin")
| 17 | Kotlin | 11 | 34 | 7adfe219c243360c4f144d0eef16f1202e0f993d | 3,962 | mikbot | MIT License |
app/src/main/java/pl/dawidfiruzek/kursandroid/data/api/UsersResponse.kt | dawidfiruzek | 125,333,359 | false | null | package pl.dawidfiruzek.kursandroid.data.api
data class UsersResponse(
val login: String
)
| 0 | Kotlin | 0 | 0 | aea5e18e07522ca32753a04a6464e6e801bf175c | 100 | Kurs-Android | Apache License 2.0 |
mylib-security/mylib-security-base/src/main/kotlin/com/zy/mylib/security/dto/mapper/RoleConvert.kt | ismezy | 140,005,112 | false | null | /*
* Copyright © 2020 ismezy (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zy.mylib.security.dto.mapper
import com.zy.mylib.security.entity.Role
import com.zy.mylib.security.dto.AddRoleRequest
import com.zy.mylib.security.dto.UpdateRoleRequest
import com.zy.mylib.security.dto.AddRoleResponse
import com.zy.mylib.security.dto.UpdateRoleResponse
import com.zy.mylib.security.dto.QueryRoleResponse
import com.zy.mylib.security.dto.GetRoleResponse
import org.mapstruct.Mapper
/**
* 角色 DTO Response mapper
* @author 代码生成器
*/
@Mapper(componentModel = "spring")
interface RoleConvert {
fun fromAddRoleRequest(req: AddRoleRequest): Role
fun fromUpdateRoleRequest(req: UpdateRoleRequest): Role
fun toAddRoleResponse(entity: Role): AddRoleResponse
fun toUpdateRoleResponse(entity: Role): UpdateRoleResponse
fun toQueryRoleResponse(entity: Role): QueryRoleResponse
fun toGetRoleResponse(entity: Role): GetRoleResponse
}
| 0 | Kotlin | 0 | 0 | c67d53ff65a72c37bf9c2cb7d37ba4c470c1e8cc | 1,467 | mylib | Apache License 2.0 |
app/src/main/java/com/rmoralf/xkcd/presentation/ui/theme/Theme.kt | rmoralf | 487,837,879 | false | null | package com.rmoralf.xkcd.presentation.ui.theme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val _lightColorPalette = lightColors(
// primary = Purple500,
// primaryVariant = Purple700,
// secondary = Teal200,
primary = xkcdPrimary,
primaryVariant = xkcdPrimaryVariant,
secondary = xkcdSecondary,
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black
)
@Composable
fun XkcdTheme(content: @Composable () -> Unit) {
MaterialTheme(
colors = _lightColorPalette,
typography = Typography,
shapes = Shapes,
content = content
)
} | 0 | Kotlin | 0 | 0 | fb31453325c27751564e69be13d00ad24b1179e9 | 849 | xkcd | MIT License |
codekk/src/main/java/com/codekk/model/net/CodekkUrl.kt | android-develop-team | 104,902,767 | false | null | package com.codekk.model.net
/**
* by y on 2017/5/16
*/
object CodekkUrl {
private const val BASE_API = "http://api.codekk.com/"
const val OP_LIST_URL = BASE_API + "op/page/" //获取开源项目
const val OP_DETAIL_URL = BASE_API + "op/detail/" //获取单个开源项目 ReadMe
const val OP_SEARCH_URL = BASE_API + "op/search" //搜索开源项目
const val OPA_LIST_URL = BASE_API + "opa/page/" //获取源码解析文章列表
const val OPA_DETAIL_URL = BASE_API + "opa/detail/" //获取单个源码解析文章详情
const val OPA_SEARCH_URL = BASE_API + "opa/user/"
const val JOB_LIST_URL = BASE_API + "job/page/" //获取职位内推文章列表
const val JOB_DETAIL_URL = BASE_API + "job/detail/" //获取单个职位内推文章详情
const val BLOG_LIST_URL = BASE_API + "blog/page/" //获取博客文章列表
const val BLOG_DETAIL_URL = BASE_API + "blog/detail/" //获取单个博客文章详情
const val RECOMMEND_LIST_URL = BASE_API + "recommend/page/" //获取今日推荐列表
const val RECOMMEND_SEARCH_URL = BASE_API + "recommend/user/" //根据推荐者查询推荐列表
}
| 0 | Kotlin | 0 | 0 | 5bcaa3a94ade134f750b2ebd9e10d472d7ef9772 | 950 | AppK | Apache License 2.0 |
app/src/main/java/com/example/expensetracker/ui/common/Functions.kt | seyone22 | 719,374,552 | false | {"Kotlin": 288946} | package com.example.expensetracker.ui.common
import android.icu.text.DecimalFormat
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.example.expensetracker.model.CurrencyFormat
@Composable
fun FormattedCurrency(
modifier: Modifier = Modifier,
value : Double,
currency : CurrencyFormat
) {
if (currency.pfx_symbol != "") {
Text(text = "${currency.pfx_symbol}${DecimalFormat("#.##").format(value)}")
} else {
Text(text = "${DecimalFormat("#.##").format(value)}${currency.sfx_symbol}")
}
} | 17 | Kotlin | 0 | 0 | a5969f7a30d0384125ec3fdce71eb6890b327d19 | 607 | Expense_Tracker | MIT License |
build-logic/project/wasm-codegen/src/main/kotlin/util/WasiFunctionHandlersExt.kt | illarionov | 848,247,126 | false | {"Kotlin": 1343464, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89} | /*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.gradle.wasm.codegen.util
internal object WasiFunctionHandlersExt {
internal val WASI_MEMORY_READER_FUNCTIONS = setOf("fd_read", "fd_pread")
internal val WASI_MEMORY_WRITER_FUNCTIONS = setOf("fd_write", "fd_pwrite")
internal val NO_MEMORY_FUNCTIONS = setOf(
"fd_close",
"fd_datasync",
"fd_sync",
"proc_exit",
"sched_yield",
)
}
| 0 | Kotlin | 0 | 4 | 774f9d4fc1c05080636888c4fe03049fdb038a8d | 678 | wasi-emscripten-host | Apache License 2.0 |
infra/graphql/src/main/kotlin/io/bluetape4k/graphql/execution/AsyncPersistedQuerySupport.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.graphql.execution
import com.github.benmanes.caffeine.cache.AsyncCache
import graphql.ExecutionInput
import graphql.execution.preparsed.PreparsedDocumentEntry
import graphql.execution.preparsed.persisted.PersistedQuerySupport
import io.bluetape4k.logging.KLogging
import java.util.*
/**
* Preparsed document 를 Caffeine [AsyncCache]에 캐싱하는 Provider
*
* @see [graphql.execution.preparsed.persisted.ApolloPersistedQuerySupport]
* @see [graphql.execution.preparsed.persisted.AutomatedPersistedQueryCacheAdapter]
*
* @property cache
*/
class AsyncPersistedQuerySupport(
private val cache: AsyncCache<String, PreparsedDocumentEntry> = caffeineAsyncCacheOf(),
): PersistedQuerySupport(AutomatedPersistedQueryCaffeineAsyncCache(cache)) {
companion object: KLogging()
override fun getPersistedQueryId(executionInput: ExecutionInput): Optional<Any> {
return Optional.ofNullable(executionInput.query)
}
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 950 | bluetape4k | MIT License |
core/src/main/kotlin/materialui/components/menulist/menuList.kt | nikanorov | 275,884,338 | true | {"Kotlin": 473607} | package materialui.components.menulist
import kotlinx.html.Tag
import kotlinx.html.TagConsumer
import kotlinx.html.UL
import materialui.MenuList
import materialui.components.list.ListProps
import react.RBuilder
external interface MenuListProps : ListProps {
var disableListWrap: Boolean?
}
fun RBuilder.menuList(block: MenuListElementBuilder<UL>.() -> Unit)
= child(MenuListElementBuilder(MenuList, listOf()) { UL(mapOf(), it) }.apply(block).create())
fun <T: Tag> RBuilder.menuList(factory: (TagConsumer<Unit>) -> T, block: MenuListElementBuilder<T>.() -> Unit)
= child(MenuListElementBuilder(MenuList, listOf(), factory).apply(block).create())
| 0 | Kotlin | 0 | 1 | e4ece75415d9d844fbaa202ffc91f04c8415b4a4 | 662 | kotlin-material-ui | MIT License |
sisaku_12/app/src/main/java/com/example/sisaku_1/MainActivity.kt | n18020 | 214,353,921 | false | null | package com.example.sisaku_1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.view.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//1.画面遷移用ボタンの取得
val btnIntent = findViewById<Button>(R.id.bt_push)
//2.画面遷移用ボタンにリスナを登録
btnIntent.setOnClickListener (object : View.OnClickListener {
override fun onClick(v: View?) {
//3.Intentクラスのオブジェクトを生成
val intent = Intent(this@MainActivity, home::class.java)
//生成したオブジェクトを引数に画面を起動
startActivity(intent)
}
})
}
}
| 0 | Kotlin | 0 | 0 | 8d07dc753f72dda298e22ea3d1185e2952af9c3f | 887 | android | MIT License |
solar/src/main/java/com/chiksmedina/solar/lineduotone/naturetravel/Leaf.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.lineduotone.naturetravel
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.chiksmedina.solar.lineduotone.NatureTravelGroup
val NatureTravelGroup.Leaf: ImageVector
get() {
if (_leaf != null) {
return _leaf!!
}
_leaf = Builder(
name = "Leaf", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap =
Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 9.0f)
lineTo(16.5f, 4.5f)
moveTo(12.0f, 14.5f)
lineTo(18.5f, 8.0f)
moveTo(12.0f, 19.5f)
lineTo(19.5f, 12.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(12.0f, 22.0f)
curveTo(16.4183f, 22.0f, 20.0f, 18.3541f, 20.0f, 13.8567f)
curveTo(20.0f, 9.3945f, 17.4467f, 4.1876f, 13.4629f, 2.3256f)
curveTo(12.9986f, 2.1085f, 12.4993f, 2.0f, 12.0f, 2.0f)
moveTo(12.0f, 22.0f)
curveTo(7.5817f, 22.0f, 4.0f, 18.3541f, 4.0f, 13.8567f)
curveTo(4.0f, 9.3945f, 6.5533f, 4.1876f, 10.5371f, 2.3256f)
curveTo(11.0014f, 2.1085f, 11.5007f, 2.0f, 12.0f, 2.0f)
moveTo(12.0f, 22.0f)
verticalLineTo(2.0f)
}
}
.build()
return _leaf!!
}
private var _leaf: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 2,424 | SolarIconSetAndroid | MIT License |
src/main/kotlin/com/doblack/bot_library/analytics/models/ReferrerPair.kt | olejajew | 469,359,443 | false | null | package com.doblack.bot_library.analytics.models
data class ReferrerPair(
val referrer: String,
val referralId: Long,
val date: Long
) | 0 | Kotlin | 0 | 0 | 268d86ae417cf41bda22e633017bda0117630d60 | 147 | BotLibrary | Apache License 2.0 |
frontend/app/src/main/java/com/kasiry/app/models/data/Cart.kt | alfianandinugraha | 585,695,566 | false | null | package com.kasiry.app.models.data
import android.net.Uri
data class Cart(
val cartId: String,
val quantity: Int,
val product: Product
) {
override fun toString(): String {
return "Cart(cartId='$cartId', quantity=$quantity, product=$product)"
}
}
| 0 | Kotlin | 0 | 1 | 6dc3a367acc255e7c2b1fe75543311b4bbb38b17 | 277 | kasiry | MIT License |
video/src/main/java/com/yzc/video/arch/model/backup/BiliVideoAPI.kt | YeZC | 494,437,281 | false | {"Kotlin": 130549, "Java": 117682, "Python": 849} | package com.yzc.video.arch.model.backup
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.*
// https://app.bilibili.com/
const val video_detail = "x/v2/feed/index/story?actionKey=appkey&ad_extra=F6209EEC4D712ADB7AAF94480A782BC723B457F7EB38252387B036E1EBE7F78D51D7FE939D21CC86E48687C28F9AAA7C1DCF53A9144CDF263081F0AF5D506BE08AC4C8A6A4A2F3A62655CE248C64F5B448B8147B10A4B7968082E069DCEDD821DB33ACDD60F9F98E444D9F8EC759389E18DCA4265EB6864F4A29C40107FD74B8BF81DD5CC550B3F2E9F0F75A2BDCABFA5E9DDB2C82DFC1A9FA90D2025B968F2DD320596E111A69FD60631A44739C2C8A82C687BDFBAC59E25C2213128DBA9B33095F244022192780DE1A70B553C53A2E3BFA6AF6E5A15C6AC8D78391B64E5D7590F239A5ECDD681EB56F822E04CCCCE703F7A791997A48D3EA64E5665D70D99286D2816EC5750FA22F25428974AECA5692687020DB985528F2FCA2DEB5FDA32DA9FA1FE8A48E5AC4D9DBA5EDFEE054184FE9FF5AB0D36B10B6DA5A76D0186715109C011CB364134331572232B6B663379DD0936DB0DF375530C6388EF5F57CBCCD4DED7D2D06A630A9F65D4D3A2E8E7DBDCFC0BF7F8829F80954C25CAFDFCC117E0E8897AB34EEF7E6CAD329B305C2D5AF37E318BC1263140A5224C6B116CAD5907D23B25E21584DD8A14807D0C451C7D44368B3B847C02CF91816EF1FB6725E78DC0ADAF32123B9F1D27F91C51A2D128506D5C9F43E547F0005703895318B1F7C3AA7EA927ECF1DE63C21630D0B5B2AFADBAE145C299D86FBF1F58F93C73C6BE87DF9D5BC71AB736CEB70D7AC403329E6DF2ED522F16D2F7AF794DB0959441360AC0B30F05C202F3160B9817E979972B60FF4730B733FFC1C13E6C9E5D8ACF0311ABDCCC02BFE4C2F1AC2B474B82018CBBD37C30E7EFF40389EEF4333E0868CE8A0C28157432204B72EF6C67279250F46773D6B92B801877C4A83B1E8404DF0DDC710DBC5A01DC018ED9183CE7C1F6D2DACBB34A2E3B26E9226F23A9EC32A6D71F6EC031EAE4B05EE23190313F2988E6B2CA2018609E16422659F06E4027DD3464C25F3146106397090378A89E86197C252BB64A5246E052426533573B89E9F733EF88D856908B70A9B5244357844DC53210EDB81078506CC32DD07FFFF713DF0B64EE8DF854D3E7465D78778152C392E5699739FB85BD3B074371C61A8700864D9EE02CA8500D192E7032A13B29D62B07DAC14D89AEDC3C43E9282D10A0D78B212AD40F44BB6E6E573387895C559E53C569FB154FFC6CE87BB276A9338ED247C102B86B22D0301A42C291079ED461BD857E890D3238D71FA7BBA285931AC3A93595616FE8B09A1FBA2B911CE3A0F539BAB5B58E4<KEY>&appkey=<KEY>&auto_play=0&build=67500200&bvid=&c_locale=zh-Hans_CN&device=phone&disable_rcmd=0&display_id=1&fnval=400&fnver=0&force_host=0&fourk=1&from=7&from_spmid=tm.recommend.0.0&mobi_app=iphone&network=wifi&platform=ios&player_net=1&pull=0&qn=32&s_locale=zh-Hans_CN&sign=6557c5508d7103e6254344779a8cbb5f&spmid=main.ugc-video-detail-vertical.0.0&statistics=%7B%22appId%22%3A1%2C%22version%22%3A%226.75.0%22%2C%22abtest%22%3A%22%22%2C%22platform%22%3A1%7D&story_param=&trackid=all_15.shjd-ai-recsys-73.1655193938631.741&ts=1655194033"
interface BiliVideoAPI {
@GET(video_detail)
fun detailVideo(@Query("aid") aid: String): Call<ResponseBody>
@GET("{path}")
fun fetchRes(@Path("path") path: String,
@QueryMap map: Map<String, String>): Call<ResponseBody>
@HEAD("{path}")
fun getFileSize(@Path("path") path: String,
@QueryMap map: Map<String, String>): Call<Void>
@GET("{path}")
fun getVideoFlow(@Path("path") path: String,
@Header("RANGE") range: String,
@QueryMap map: Map<String, String>): Call<ResponseBody>
} | 0 | Kotlin | 0 | 1 | 70516dbd41dd4e1d65c73950524c9e159f0429d7 | 3,189 | bilibili | Apache License 2.0 |
errors/src/main/java/com/arch/error/handler/ExceptionMapper.kt | NeoSOFT-Technologies | 403,522,301 | false | {"Kotlin": 194331} |
package com.arch.error.handler
typealias ExceptionMapper<T> = (Throwable) -> T
| 3 | Kotlin | 2 | 3 | f29df20fc10acfeb64096e5b91b8e4246817e7d6 | 82 | mobile-android | Apache License 2.0 |
ble/src/main/java/com/bhm/ble/data/BleWriteQueueData.kt | buhuiming | 641,804,698 | false | {"Kotlin": 429267} | package com.bhm.ble.data
/**
* @description [com.bhm.ble.request.BleWriteRequest.writeQueueData]方法中队列存放的数据结构
* @author Buhuiming
* @date 2024/10/18/ 18:04
*/
internal data class BleWriteQueueData(
var operateRandomID: String,
var serviceUUID: String,
var writeUUID: String,
var data: ByteArray,
var skipErrorPacketData: Boolean,
var retryWriteCount: Int,
var retryDelayTime: Long,
var writeType: Int?,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BleWriteQueueData
if (operateRandomID != other.operateRandomID) return false
if (serviceUUID != other.serviceUUID) return false
if (writeUUID != other.writeUUID) return false
if (!data.contentEquals(other.data)) return false
if (skipErrorPacketData != other.skipErrorPacketData) return false
if (retryWriteCount != other.retryWriteCount) return false
if (retryDelayTime != other.retryDelayTime) return false
if (writeType != other.writeType) return false
return true
}
override fun hashCode(): Int {
var result = operateRandomID.hashCode()
result = 31 * result + serviceUUID.hashCode()
result = 31 * result + writeUUID.hashCode()
result = 31 * result + data.contentHashCode()
result = 31 * result + skipErrorPacketData.hashCode()
result = 31 * result + retryWriteCount
result = 31 * result + retryDelayTime.hashCode()
result = 31 * result + (writeType ?: 0)
return result
}
}
| 1 | Kotlin | 32 | 170 | 9d08d2466d7539b567b8d800b84f570eb957ebb4 | 1,640 | BleCore | The Unlicense |
swt/src/main/kotlin/com/apisw/swtrap/MainApp.kt | nu11ptr | 397,785,586 | false | null | package com.apisw.swtrap
import org.eclipse.swt.SWT
import org.eclipse.swt.layout.FillLayout
import org.eclipse.swt.widgets.Composite
import org.eclipse.swt.widgets.Display
import org.eclipse.swt.widgets.Shell
import org.jfree.chart.JFreeChart
import org.jfree.chart.swt.ChartComposite
private fun addChart(chart: JFreeChart, parent: Composite) {
ChartComposite(parent, SWT.NONE, chart, true)
}
fun main(args: Array<String>) {
val display = Display()
val shell = Shell(display).also {
it.setSize(640, 480)
it.layout = FillLayout()
it.text = "Swtrap"
MainView(it, ::addChart)
it.forceActive()
it.open()
}
while (!shell.isDisposed) {
if (!display.readAndDispatch()) {
display.sleep()
}
}
display.dispose()
}
| 0 | Kotlin | 0 | 1 | b5ee6117adeebb95354fdce52c25e2d4fef87e05 | 815 | swtrap | MIT License |
src/main/kotlin/kotlinx/kover/engines/commons/AgentsFactory.kt | Kotlin | 394,574,917 | false | null | package kotlinx.kover.engines.commons
import kotlinx.kover.api.*
import kotlinx.kover.engines.intellij.*
import kotlinx.kover.engines.jacoco.*
import org.gradle.api.*
internal object AgentsFactory {
fun createAgents(project: Project, koverExtension: KoverExtension): Map<CoverageEngine, CoverageAgent> {
return mapOf(
CoverageEngine.INTELLIJ to project.createIntellijAgent(koverExtension),
CoverageEngine.JACOCO to project.createJacocoAgent(koverExtension),
)
}
}
internal fun Map<CoverageEngine, CoverageAgent>.getFor(engine: CoverageEngine): CoverageAgent {
return this[engine] ?: throw GradleException("Coverage agent for Coverage Engine '$engine' not found")
}
| 34 | Kotlin | 14 | 520 | e1f3fbc4232216bf55b3c43ca0ad193e639afd68 | 720 | kotlinx-kover | Apache License 2.0 |
app/src/main/java/com/orionedutechfsm/features/stockCompetetorStock/api/AddCompStockRepository.kt | DebashisINT | 534,095,018 | false | {"Kotlin": 11238068, "Java": 960577} | package com.orionedutechfsm.features.stockCompetetorStock.api
import com.orionedutechfsm.base.BaseResponse
import com.orionedutechfsm.features.orderList.model.NewOrderListResponseModel
import com.orionedutechfsm.features.stockCompetetorStock.ShopAddCompetetorStockRequest
import com.orionedutechfsm.features.stockCompetetorStock.model.CompetetorStockGetData
import io.reactivex.Observable
class AddCompStockRepository(val apiService:AddCompStockApi){
fun addCompStock(shopAddCompetetorStockRequest: ShopAddCompetetorStockRequest): Observable<BaseResponse> {
return apiService.submShopCompStock(shopAddCompetetorStockRequest)
}
fun getCompStockList(sessiontoken: String, user_id: String, date: String): Observable<CompetetorStockGetData> {
return apiService.getCompStockList(sessiontoken, user_id, date)
}
} | 0 | Kotlin | 0 | 0 | cf44a58f7e930379e7c8dde546543665bc4f50b0 | 842 | OrionEdutech | Apache License 2.0 |
app/src/main/java/com/utim/weathertestapp/data/model/WeatherParamModel.kt | nullnullru | 245,515,387 | false | null | package com.utim.weathertestapp.data.model
data class WeatherParamModel(
val param: WeatherParamType, val value: Int
) | 0 | Kotlin | 0 | 0 | 878afc4c258aaf7d8046e67c3584fad80c8b3123 | 123 | weather_test_app | MIT License |
src/main/kotlin/io/github/bbortt/buessle/app/configuration/DevCorsConfiguration.kt | bbortt | 248,548,131 | false | {"JavaScript": 41819, "SCSS": 23178, "Kotlin": 14775, "Dockerfile": 260} | package io.github.bbortt.buessle.app.configuration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
import java.util.*
@Configuration
@Profile("dev")
class DevCorsConfiguration {
@Bean
fun corsConfiguration(): UrlBasedCorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowedOrigins = Collections.singletonList("http://localhost:3000")
configuration.allowedMethods = Arrays.asList("GET", "POST")
configuration.allowedHeaders = Collections.singletonList("content-type")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/api/**", configuration)
return source
}
@Bean
fun corsFilter(): CorsFilter = CorsFilter(corsConfiguration())
}
| 0 | JavaScript | 0 | 1 | 8a9fcfa2c910199b162663be928c45d759c9450d | 1,063 | buessle-app | Apache License 2.0 |
lib/src/test/kotlin/com/github/caay2000/ttk/lib/eventbus/impl/KTEventBusTest.kt | caay2000 | 489,137,393 | false | {"Kotlin": 177204, "Python": 1616} | package com.github.caay2000.ttk.lib.eventbus.impl
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class KTEventBusTest {
@Test
internal fun `event is published to event bus`() {
val eventBus = KTEventBus.init<String, String, String>()
val sut = KTEventPublisher<String>()
sut.publish("hi")
assertThat(eventBus.getAllEvents()).hasSize(1)
.isEqualTo(listOf("hi"))
}
@Test
internal fun `subscribers receive the published event`() {
KTEventBus.init<String, String, String>()
val sut = StringSubscriber()
KTEventPublisher<String>().publish("hi")
assertThat(sut.events).isEqualTo(listOf("hi"))
}
@Test
internal fun `multiple subscribers receive the published event`() {
val eventBus = KTEventBus.init<String, String, String>()
val subscriber1 = StringSubscriber()
val subscriber2 = StringSubscriber()
KTEventPublisher<String>().publish("hi")
assertThat(subscriber1.events).isEqualTo(listOf("hi"))
assertThat(subscriber2.events).isEqualTo(listOf("hi"))
assertThat(eventBus.getAllEvents()).isEqualTo(listOf("hi"))
}
@Test
internal fun `subscriber of different type does not receive the event`() {
val eventBus = KTEventBus.init<String, String, String>()
val sut = IntSubscriber()
KTEventPublisher<Number>().publish(Double.MAX_VALUE)
assertThat(eventBus.getAllEvents()).hasSize(1)
assertThat(sut.events).hasSize(0)
}
inner class StringSubscriber : KTEventSubscriber<String>(String::class) {
val events = mutableListOf<String>()
override fun handle(event: String) {
events.add(event)
}
}
inner class IntSubscriber : KTEventSubscriber<Int>(Int::class) {
val events = mutableListOf<Int>()
override fun handle(event: Int) {
events.add(event)
}
}
}
| 0 | Kotlin | 0 | 0 | 7691e2c8922aab61374b40481b945886401a77b9 | 2,004 | transport-tycoon-kata | MIT License |
archive/backups/hydrogen/hello-kotlin/src/main/kotlin/main.kt | roskenet | 295,683,964 | false | {"HTML": 708028, "Jupyter Notebook": 571597, "TeX": 547996, "Java": 447619, "Makefile": 214272, "JavaScript": 204557, "CMake": 113090, "Kotlin": 88563, "TypeScript": 61333, "Clojure": 36776, "CSS": 25303, "C++": 19374, "Red": 13104, "Python": 12901, "Shell": 12248, "SCSS": 5588, "Go": 4797, "Dockerfile": 2073, "C": 1687, "Vim Script": 1092, "PLpgSQL": 818, "Assembly": 384, "Rust": 308, "Gherkin": 207, "Procfile": 177, "C#": 147, "PHP": 94, "Less": 91, "Ruby": 73, "sed": 26, "Batchfile": 21, "Groovy": 21} | fun main(args: Array<String>) {
println(doSomething())
}
private fun doSomething(name: String = "Somebody"): String {
return name.toUpperCase()
}
| 0 | HTML | 1 | 0 | 39975a0248f2e390f799bdafde1170322267761b | 156 | playground | MIT License |
src/main/kotlin/com/gw2tb/apigen/schema/SchemaPrimitive.kt | GW2ToolBelt | 201,445,127 | false | {"Kotlin": 675601} | /*
* Copyright (c) 2019-2023 <NAME>
*
* 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.gw2tb.apigen.schema
/**
* A primitive schema type.
*
* @since 0.7.0
*/
public sealed class SchemaPrimitive : SchemaTypeUse(), SchemaPrimitiveOrAlias {
/**
* Always returns `false` as a primitive types on their own are never
* localized.
*
* @since 0.7.0
*/
override val isLocalized: Boolean get() = false
}
/**
* A primitive schema type that may serve as identifier.
*
* @since 0.7.0
*/
public sealed class SchemaPrimitiveIdentifier : SchemaPrimitive(), SchemaPrimitiveIdentifierOrAlias | 7 | Kotlin | 1 | 3 | 707d9035ca4219dd08ecb3b198e62995930f3317 | 1,665 | api-generator | MIT License |
app/src/main/java/com/bluehub/fastmixer/common/views/FileWaveView.kt | codecameo | 331,394,940 | true | {"Kotlin": 100962, "C++": 97824, "CMake": 5175, "C": 2407, "Shell": 1870} | package com.bluehub.fastmixer.common.views
import android.content.Context
import android.content.res.Configuration
import android.graphics.*
import android.os.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.BindingMethod
import androidx.databinding.BindingMethods
import com.bluehub.fastmixer.R
import com.bluehub.fastmixer.screens.mixing.AudioFileUiState
import com.bluehub.fastmixer.screens.mixing.FileWaveViewStore
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.functions.Function
import io.reactivex.rxjava3.subjects.BehaviorSubject
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.launch
import java.util.*
import kotlin.math.ceil
@BindingMethods(value = [
BindingMethod(type = FileWaveView::class, attribute = "samplesReader", method = "setSamplesReader"),
BindingMethod(type = FileWaveView::class, attribute = "audioFileUiState", method = "setAudioFileUiState"),
BindingMethod(type = FileWaveView::class, attribute = "fileWaveViewStore", method = "setFileWaveViewStore")
])
class FileWaveView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ViewGroup(context, attrs) {
companion object {
const val MAX_CLICK_DURATION = 200
}
private var mStartClickTime: Long = 0
private val mAudioFileUiState: BehaviorSubject<AudioFileUiState> = BehaviorSubject.create()
var mSamplesReader: BehaviorSubject<Function<Int, Deferred<Array<Float>>>> = BehaviorSubject.create()
private val mFileWaveViewStore: BehaviorSubject<FileWaveViewStore> = BehaviorSubject.create()
private lateinit var mAudioWidgetSlider: AudioWidgetSlider
var mRawPoints: BehaviorSubject<Array<Float>> = BehaviorSubject.create()
private lateinit var mPlotPoints: Array<Float>
private var attrsLoaded: BehaviorSubject<Boolean> = BehaviorSubject.create()
init {
attrsLoaded.subscribe {
if (it) {
setupObservers()
}
}
mAudioFileUiState.subscribe{ checkAttrs() }
mSamplesReader.subscribe { checkAttrs() }
mFileWaveViewStore.subscribe { checkAttrs() }
setWillNotDraw(false)
}
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
textAlign = Paint.Align.CENTER
textSize = 15.0f
typeface = Typeface.create("", Typeface.BOLD)
color = ContextCompat.getColor(context, R.color.colorAccent)
}
fun setAudioFileUiState(audioFileUiState: AudioFileUiState) {
mAudioFileUiState.onNext(audioFileUiState)
}
fun setSamplesReader(samplesReader: (Int) -> Deferred<Array<Float>>) {
mSamplesReader.onNext(samplesReader)
}
fun setFileWaveViewStore(fileWaveViewStore: FileWaveViewStore) {
mFileWaveViewStore.onNext(fileWaveViewStore)
}
fun zoomIn() {
if (mFileWaveViewStore.value.zoomIn(mAudioFileUiState.value)) {
handleZoom()
}
}
fun zoomOut() {
if (mFileWaveViewStore.value.zoomOut(mAudioFileUiState.value)) {
handleZoom()
}
}
private fun resetZoom() {
if (mFileWaveViewStore.hasValue() && mAudioFileUiState.hasValue()) {
mFileWaveViewStore.value.resetZoomLevel(mAudioFileUiState.value.path)
handleZoom()
}
}
private fun setupObservers() {
mRawPoints.subscribe { ptsArr ->
processPlotPoints(ptsArr)
}
mAudioFileUiState.value.displayPtsCount.subscribe {
requestLayout()
}
mAudioFileUiState.value.zoomLevel.subscribe {
handleZoom()
}
mAudioFileUiState.value.playSliderPosition
.observeOn(
AndroidSchedulers.mainThread()
)
.subscribe {
requestLayout()
}
}
private fun getNumPtsToPlot() = if (mAudioFileUiState.hasValue()) {
mAudioFileUiState.value.numPtsToPlot
} else 0
private fun fetchPointsToPlot() {
if (!attrsLoaded.hasValue()) return
val numPts = getNumPtsToPlot()
if (!mRawPoints.hasValue() || mRawPoints.value.size != numPts) {
mFileWaveViewStore.value.coroutineScope.launch {
mRawPoints.onNext(mSamplesReader.value.apply(numPts).await())
}
}
}
private fun processPlotPoints(rawPts: Array<Float>) {
if (rawPts.isEmpty()) {
return
}
val mean = rawPts.average()
val maximum = rawPts.maxOrNull()
val maxLevelInSamples = maximum ?: 3 * mean
val maxToScale = height * 0.95
mPlotPoints = rawPts.map { current ->
if (maxLevelInSamples != 0) {
((current / maxLevelInSamples.toFloat()) * maxToScale.toFloat())
} else 0.0f
}.toTypedArray()
invalidate()
}
private fun checkAttrs() {
if (mAudioFileUiState.hasValue()
&& mFileWaveViewStore.hasValue()) {
attrsLoaded.onNext(true)
}
}
private fun handleZoom() {
requestLayout()
}
private fun getSliderLeftPosition() = if (mAudioFileUiState.hasValue()) {
if (mAudioFileUiState.value.playSliderPosition.hasValue()) {
mAudioFileUiState.value.playSliderPosition.value
} else 0
} else 0
private fun vibrateDevice() {
val v = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(
VibrationEffect.createOneShot(
250,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
} else {
v.vibrate(250)
}
}
private fun handleLongClick(xPosition: Float) {
mFileWaveViewStore.value.setPlayHead(mAudioFileUiState.value.path, xPosition.toInt())
vibrateDevice()
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
event ?: return false
val x = event.x
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mStartClickTime = Calendar.getInstance().timeInMillis
}
MotionEvent.ACTION_UP -> {
val clickDuration = Calendar.getInstance().timeInMillis - mStartClickTime
return if (clickDuration > MAX_CLICK_DURATION) {
handleLongClick(x)
true
} else {
super.onTouchEvent(event)
}
}
}
return true
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
if (::mAudioWidgetSlider.isInitialized) {
val sliderLeft = getSliderLeftPosition()
val sliderTop = 0
if (mAudioWidgetSlider.visibility != GONE) {
mAudioWidgetSlider.layout(
sliderLeft,
sliderTop,
sliderLeft + mAudioWidgetSlider.measuredWidth,
sliderTop + mAudioWidgetSlider.measuredHeight
)
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (mFileWaveViewStore.hasValue()) {
mFileWaveViewStore.value.updateMeasuredWidth(measuredWidth)
}
if (!mAudioFileUiState.hasValue()) return
if (childCount == 1) {
val child = getChildAt(0)
if (child is AudioWidgetSlider && !::mAudioWidgetSlider.isInitialized) {
mAudioWidgetSlider = child
}
}
if (::mAudioWidgetSlider.isInitialized) {
val sliderWidth = context.resources.getDimension(R.dimen.audio_view_slider_line_width)
mAudioWidgetSlider.measure(
MeasureSpec.makeMeasureSpec(ceil(sliderWidth).toInt(), MeasureSpec.EXACTLY),
measuredHeight
)
}
val calculatedWidth = mAudioFileUiState.value.numPtsToPlot
val roundedWidth = if (measuredWidth == 0 || calculatedWidth < measuredWidth) measuredWidth else calculatedWidth
if (roundedWidth > 0) {
fetchPointsToPlot()
}
setMeasuredDimension(roundedWidth, measuredHeight)
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
resetZoom()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (!::mPlotPoints.isInitialized) {
return
}
val numPts = getNumPtsToPlot()
val widthPtRatio = numPts / mPlotPoints.size
val ptsDistance: Int = if (widthPtRatio >= 1) widthPtRatio else 1
var currentPoint = 0
mPlotPoints.forEach { item ->
canvas.drawLine(currentPoint.toFloat(), height.toFloat(), currentPoint.toFloat(), (height - item), paint)
currentPoint += ptsDistance
}
}
}
| 0 | null | 0 | 0 | 5f9403a61239984ce23b8250159a1e1913beda06 | 9,264 | fast-mixer | MIT License |
app/src/main/java/com/ng/ngleetcode/ui/page/code/widgets/CircularProgressLayout.kt | jiangzhengnan | 461,363,304 | false | {"Java": 1266106, "Kotlin": 298036, "CSS": 85875} | package com.ng.ngleetcode.ui.page.code.widgets
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.ng.ngleetcode.ui.page.code.mvi.CodeDrawerViewState
/**
* 进度圈圈图
*/
@Composable
fun CircularProgressLayout(viewData: CodeDrawerViewState) {
AndroidView(
modifier = Modifier.size(90.dp),
factory = { context ->
// Creates view
CircularProgressView(context).apply {
setValue(viewData)
}
},
update = { view ->
view.setValue(viewData)
}
)
} | 0 | Java | 4 | 23 | 58fe2721a7a2c04c5a8e0356248c1520200c526d | 663 | NgLeetCode | Apache License 2.0 |
server/src/main/kotlin/io/github/alessandrojean/tankobon/infrastructure/jms/ArtemisConfig.kt | alessandrojean | 609,405,137 | false | null | package io.github.alessandrojean.tankobon.infrastructure.jms
import jakarta.jms.ConnectionFactory
import mu.KotlinLogging
import org.apache.activemq.artemis.api.core.QueueConfiguration
import org.apache.activemq.artemis.api.core.RoutingType
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer
import org.springframework.boot.autoconfigure.jms.artemis.ArtemisConfigurationCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.jms.config.DefaultJmsListenerContainerFactory
import org.apache.activemq.artemis.core.config.Configuration as ArtemisConfiguration
private val logger = KotlinLogging.logger {}
const val TOPIC_EVENTS = "domain.events"
const val JMS_PROPERTY_TYPE = "type"
const val TOPIC_FACTORY = "topicJmsListenerContainerFactory"
@Configuration
class ArtemisConfig : ArtemisConfigurationCustomizer {
override fun customize(configuration: ArtemisConfiguration?) {
configuration?.let {
it.maxDiskUsage = 100
it.addQueueConfiguration(
QueueConfiguration(TOPIC_EVENTS)
.setAddress(TOPIC_EVENTS)
.setRoutingType(RoutingType.MULTICAST)
)
}
}
@Bean(TOPIC_FACTORY)
fun topicJmsListenerContainerFactory(
connectionFactory: ConnectionFactory,
configurer: DefaultJmsListenerContainerFactoryConfigurer,
): DefaultJmsListenerContainerFactory = DefaultJmsListenerContainerFactory().apply {
configurer.configure(this, connectionFactory)
setErrorHandler { logger.warn { it.message } }
setPubSubDomain(true)
}
} | 0 | Kotlin | 0 | 1 | cb28b68c0b6f3b1de7f77450122a609295396c28 | 1,635 | tankobon | MIT License |
app/src/main/java/com/tvmaze/challenge/utils/Constants.kt | rulomewsik | 587,548,799 | false | null | package com.tvmaze.challenge.utils
object Constants {
const val TV_MAZE_BASE_URL = "https://api.tvmaze.com/"
const val EXPANSION_TRANSITION_DURATION = 500
const val EXPAND_ANIMATION_DURATION = 500
} | 0 | Kotlin | 0 | 0 | 4d8f02f71ad84ed42b8b48489f76cf1f580aa8b3 | 212 | TVMazeChallenge | MIT License |
account-service/src/main/kotlin/com/onegravity/accountservice/persistence/model/Language.kt | 1gravity | 361,878,383 | false | null | package com.onegravity.accountservice.persistence.model
enum class Language(val languageLong: String) {
en("English"),
de("German")
}
| 0 | Kotlin | 4 | 34 | 0d31a4bee1b86a756371a42a2cf64e32213277c0 | 143 | Ktor-Template | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.