path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/xyz/heydarrn/githubuserwithapi/FollowingFragment.kt
|
naufalHaidar12342
| 512,125,897
| false
|
{"Kotlin": 25568}
|
package xyz.heydarrn.githubuserwithapi
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import xyz.heydarrn.githubuserwithapi.databinding.FragmentFollowingBinding
class FollowingFragment : Fragment() {
private var _bindingFollowing:FragmentFollowingBinding?=null
private val bindingFollowing get() = _bindingFollowing!!
private val viewModel by viewModels<FollowingViewModel>()
private val adapterFollowing by lazy { FollowingListAdapter() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_bindingFollowing= FragmentFollowingBinding.inflate(inflater,container,false)
return bindingFollowing.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val username=arguments?.getString(UserDetailActivity.EXTRA_USERNAME).toString()
bindingFollowing.apply {
recyclerViewFollowing.layoutManager=LinearLayoutManager(context)
recyclerViewFollowing.adapter=adapterFollowing
viewModel.getFollower(username)
viewModel.setFollowing().observe(viewLifecycleOwner){
if (it!=null){
adapterFollowing.submitList(it)
loadingAnimationFollowing.visibility=View.INVISIBLE
}
}
viewModel.viewModelScope.launch {
delay(1000)
loadingAnimationFollowing.visibility=View.INVISIBLE
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
280e82f7d35d151a2a4220e3f82fde1600088296
| 1,991
|
Discover-Github-API
|
Apache License 2.0
|
features/account/account-impl/src/commonMain/kotlin/io/spherelabs/accountimpl/ui/component/SendFeedback.kt
|
getspherelabs
| 687,455,894
| false
|
{"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048}
|
package io.spherelabs.accountimpl.ui.component
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import dev.icerock.moko.resources.compose.painterResource
import io.spherelabs.designsystem.fonts.LocalStrings
import io.spherelabs.resource.fonts.GoogleSansFontFamily
import io.spherelabs.resource.images.MR
@Composable
internal fun SendFeedback(
modifier: Modifier,
onOpenUrl: (String) -> Unit
) {
val strings = LocalStrings.current
Row(
modifier =
modifier
.padding(horizontal = 24.dp)
.fillMaxWidth()
.height(48.dp)
.clip(
RoundedCornerShape(16.dp),
)
.background(color = Color(0xff292933))
.clickable {
onOpenUrl.invoke("https://github.com/getspherelabs/anypass-kmp/issues/new/choose")
},
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
modifier = modifier.padding(start = 24.dp),
text = strings.sendFeedback,
fontSize = 16.sp,
color = Color.White,
fontFamily = GoogleSansFontFamily,
fontWeight = FontWeight.Medium,
)
Image(
modifier = modifier.padding(end = 24.dp).size(20.dp),
painter = painterResource(MR.images.message_square),
contentDescription = null,
colorFilter = ColorFilter.tint(color = Color.White),
)
}
}
| 15
|
Kotlin
|
27
| 236
|
902a0505c5eaf0f3848a5e06afaec98c1ed35584
| 2,361
|
anypass-kmp
|
Apache License 2.0
|
core-mvp-binding/lib-core-mvp-binding/src/main/java/ru/surfstudio/android/core/mvp/binding/rx/interfaces/ChangesInterface.kt
|
surfstudio
| 139,034,657
| false
|
{"Kotlin": 2966626, "Java": 1025166, "FreeMarker": 104337, "Groovy": 43020, "C++": 1542, "Ruby": 884, "CMake": 285, "Shell": 33, "Makefile": 25}
|
/*
* Copyright (c) 2019-present, SurfStudio LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.surfstudio.android.core.mvp.binding.rx.interfaces
import io.reactivex.Observable
/**
* Набор базовых интерфейсов для создаия кастомных вью и `ItemController`
*/
/**
* Интерфес для объекта с изменяющеся моделью
*/
interface RxChangesModel<T> {
fun modelChanges(): Observable<T>
}
/**
* Интерфес для объекта с изменяющимся состояниянием выбрано/невыбрано
*/
interface RxChangedChecked {
fun checkedChanges(): Observable<Boolean>
}
/**
* Интерфес для объекта который принимает клики.
* Используется там, где невозможно использовать [com.jakewharton.rxbinding2.view.RxView.clicks]
*/
interface RxClickable {
fun clicks(): Observable<Unit>
}
| 5
|
Kotlin
|
30
| 249
|
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
| 1,291
|
SurfAndroidStandard
|
Apache License 2.0
|
app/src/main/java/soup/stamp/ui/splash/SplashViewModel.kt
|
fornewid
| 362,494,946
| false
| null |
package soup.stamp.ui.splash
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.launch
import soup.stamp.data.repository.UserRepository
import soup.stamp.settings.AppSettings
import soup.stamp.ui.Screen
import javax.inject.Inject
@HiltViewModel
class SplashViewModel @Inject constructor(
appSettings: AppSettings,
userRepository: UserRepository
) : ViewModel() {
private val _navigateTo = BroadcastChannel<Screen>(1)
val navigateTo: Flow<Screen> = _navigateTo.asFlow()
init {
viewModelScope.launch {
delay(1000)
val screen = when {
appSettings.showOnBoarding -> Screen.OnBoarding
userRepository.isSignIn().not() -> Screen.Login
else -> Screen.Home
}
_navigateTo.send(screen)
}
}
}
| 1
|
Kotlin
|
0
| 2
|
39016bd5a81c1bc56b2fcb4fe59c3739552d96fb
| 1,082
|
stamp
|
Apache License 2.0
|
core/src/main/java/io/merculet/core/domain/ErrorEnvelope.kt
|
Merculet
| 160,765,571
| false
| null |
package io.merculet.core.domain
class ErrorEnvelope @JvmOverloads constructor(val code: Int, val message: String?, private val throwable: Throwable? = null) {
constructor(message: String?) : this(io.merculet.core.domain.Config.ErrorCode.UNKNOWN, message)
}
| 0
|
Kotlin
|
0
| 3
|
fa70d7d20de60a0745c4b77d0aadf3b7c2b77358
| 263
|
MerculetWalletBase
|
Apache License 2.0
|
app/src/main/java/com/fstyle/comparerxjava1vsrxjava2/transform/ScanFragment.kt
|
daolq3012
| 96,961,505
| false
| null |
package com.fstyle.comparerxjava1vsrxjava2.transform
import com.fstyle.comparerxjava1vsrxjava2.BaseFragment
import io.reactivex.Observable
/**
* Created by Sun on 7/13/2017.
*/
class ScanFragment : BaseFragment() {
override fun doSomething() {
val observable = getObservable()
val map = observable.scan() { s1, s2 ->
s1 + "-" + s2
}
// so the it gives the following list
// 1 - one
// 2 - one-two
// 3 - one-two-three
// 4 - one-two-three-four
// 5 - one-two-three-four-five
compositeDispose.add(subscribe(map))
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* *
* @return A new instance of fragment BufferFragment.
*/
fun newInstance(): ScanFragment {
val fragment = ScanFragment()
return fragment
}
}
}
| 0
|
Kotlin
|
1
| 3
|
fbb1b783e5315f51fdef6494dd01d4a9df160900
| 893
|
RxKotlin2Examples
|
Creative Commons Attribution 4.0 International
|
src/main/kotlin/io/github/viartemev/rabbitmq/channel/TxChannel.kt
|
viartemev
| 164,432,364
| false
|
{"Kotlin": 74301}
|
package io.github.viartemev.rabbitmq.channel
import com.rabbitmq.client.Channel
import io.github.viartemev.rabbitmq.consumer.ConfirmConsumer
import io.github.viartemev.rabbitmq.publisher.OutboundMessage
import mu.KotlinLogging
import java.util.concurrent.atomic.AtomicBoolean
private val logger = KotlinLogging.logger {}
@DslMarker
annotation class TxChannelDslMarker
@TxChannelDslMarker
open class TxChannel internal constructor(private val channel: Channel) : Channel by channel {
private val tx: Transaction // the only current tx associated with a channel
init {
channel.txSelect()
tx = Transaction()
}
@TxChannelDslMarker
inner class Transaction {
internal var active = AtomicBoolean(false)
internal var markForRollback = AtomicBoolean(false)
internal fun rollback() {
logger.debug { "marking for rolling back" }
markForRollback.set(true)
}
fun publish(message: OutboundMessage) {
message.apply {
this@TxChannel.channel.basicPublish(exchange, routingKey, properties, msg)
}
}
fun consumer(queue: String, prefetchSize: Int) =
ConfirmConsumer(this@TxChannel.channel, queue, prefetchSize)
}
suspend fun transaction(block: suspend Tx.() -> Unit) {
try {
if (!tx.active.compareAndSet(
false,
true
)
) throw TransactionException("another active tx on the channel is detected")
block(tx)
} catch (rollbackException: RuntimeException) {
if (tx.active.get()) {
logger.info("rolling back tx on runtime exception", rollbackException)
tx.rollback()
}
throw rollbackException
} finally {
if (tx.active.compareAndSet(true, false)) {
if (tx.markForRollback.get()) {
logger.debug { "rolling back tx" }
this@TxChannel.channel.txRollback()
//since we've decided to keep channels open, messages are still in unack state after rollback
this@TxChannel.channel.basicRecover()
} else {
logger.debug { "committing tx" }
this@TxChannel.channel.txCommit()
}
tx.markForRollback.set(false)
} else {
logger.debug { "finalize closed tx" }
}
}
}
}
typealias Tx = TxChannel.Transaction
class TransactionException(message: String) : RuntimeException(message)
suspend fun Tx.consume(queue: String, prefetchSize: Int = 0, block: suspend ConfirmConsumer.() -> Unit) =
this.consumer(queue, prefetchSize).use { block(it) }
| 8
|
Kotlin
|
5
| 99
|
83c2c8157134164dab770de7f28b539266d88c52
| 2,818
|
rabbitmq-kotlin
|
MIT License
|
app/src/main/java/com/youngsdeveloper/bus_murcia/io/ApiAdapter.kt
|
youngsdeveloper
| 542,304,717
| false
|
{"Kotlin": 129616, "Java": 7279}
|
package com.youngsdeveloper.bus_murcia.io
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class ApiAdapter {
companion object{
fun getApiService(): ApiService {
val logging = HttpLoggingInterceptor()
//logging.setLevel(HttpLoggingInterceptor.Level.NONE)
val client: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(logging)
.build()
return Retrofit
.Builder()
.baseUrl("https://api.latbus.com/latbusapp/rest/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
}
}
}
| 1
|
Kotlin
|
1
| 3
|
c9cf1daf20182eeb2ea82e8907c6529b8c574396
| 867
|
busmurcia-app
|
The Unlicense
|
examen-2b/app/src/main/java/com/example/adle_exam_2b/data/dao/DAOFactory.kt
|
2022B-Software-Computacion
| 569,303,681
| false
| null |
package com.example.adle_exam_2b.data.dao
import com.example.adle_exam_2b.data.firebase.FirebaseDAOFactory
abstract class DAOFactory {
companion object {
var factory: DAOFactory = FirebaseDAOFactory()
}
abstract fun getDeviceDAO(): DeviceDAO
abstract fun getComponentDAO(): ComponentDAO
}
| 0
|
Kotlin
|
0
| 0
|
47564429c2e7158b9d82735f3d4da10324a1c284
| 317
|
lozano-estrada-andres-david-mobile-apps
|
MIT License
|
java/compiler/tests/com/intellij/compiler/artifacts/propertybased/ArtifactTestUtils.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.compiler.artifacts.propertybased
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.packaging.artifacts.Artifact
import com.intellij.packaging.artifacts.ArtifactManager
import com.intellij.packaging.elements.CompositePackagingElement
import com.intellij.packaging.elements.PackagingElement
import com.intellij.packaging.impl.artifacts.workspacemodel.toElement
import com.intellij.packaging.impl.elements.ArtifactRootElementImpl
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.PackagingElementEntity
import org.junit.Assert
internal fun artifact(project: Project, name: String): Artifact {
val bridgeArtifact = runReadAction { ArtifactManager.getInstance(project).findArtifact(name) }
Assert.assertNotNull(bridgeArtifact)
return bridgeArtifact!!
}
internal fun artifactEntity(project: Project, name: String): ArtifactEntity {
val artifactEntities = WorkspaceModel.getInstance(project).entityStorage.current.entities(ArtifactEntity::class.java)
val artifactEntity = artifactEntities.find { it.name == name }
Assert.assertNotNull(artifactEntity)
return artifactEntity!!
}
internal fun assertTreesEquals(project: Project, left: PackagingElement<*>, right: PackagingElementEntity) {
val rightElement = right.toElement(project, WorkspaceEntityStorageBuilder.create())
assertElementsEquals(left, rightElement)
}
internal fun assertElementsEquals(left: PackagingElement<*>, right: PackagingElement<*>) {
if (left !is ArtifactRootElementImpl || right !is ArtifactRootElementImpl) {
if (!left.isEqualTo(right)) {
Assert.fail("Elements are not equals. $left <-> $right")
}
}
if (left is CompositePackagingElement<*> && right is CompositePackagingElement<*>) {
val leftChildren = left.children
val rightChildren = right.children
if (leftChildren.size != rightChildren.size) {
Assert.fail("Elements have different amount of children. Left: ${leftChildren} != right: ${rightChildren}")
}
if (leftChildren.size != left.nonWorkspaceModelChildren.size) {
Assert.fail("Element has different amount of children in store and internally.")
}
if (rightChildren.size != right.nonWorkspaceModelChildren.size) {
Assert.fail("Element has different amount of children in store and internally.")
}
for (i in leftChildren.indices) {
assertElementsEquals(leftChildren[i], rightChildren[i])
}
}
}
| 284
| null |
5162
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 2,820
|
intellij-community
|
Apache License 2.0
|
kotlin-node/src/jsMain/generated/node/test/MockFunctionOptions.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Generated by Karakum - do not modify it manually!
package node.test
sealed external interface MockFunctionOptions {
/**
* The number of times that the mock will use the behavior of `implementation`.
* Once the mock function has been called `times` times,
* it will automatically restore the behavior of `original`.
* This value must be an integer greater than zero.
* @default Infinity
*/
var times: Double?
}
| 40
|
Kotlin
|
165
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 453
|
kotlin-wrappers
|
Apache License 2.0
|
components/bridge/dao/impl/src/main/java/com/flipperdevices/bridge/dao/impl/api/delegates/KeyContentCleaner.kt
|
flipperdevices
| 288,258,832
| false
|
{"Kotlin": 2760721, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
|
package com.flipperdevices.bridge.dao.impl.api.delegates
/**
* Help delete unused files in internal storage
*/
interface KeyContentCleaner {
suspend fun deleteUnusedFiles()
}
| 13
|
Kotlin
|
131
| 999
|
ef27b6b6a78a59b603ac858de2c88f75b743f432
| 182
|
Flipper-Android-App
|
MIT License
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Incognito.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.Incognito: ImageVector
get() {
if (_incognito != null) {
return _incognito!!
}
_incognito = Builder(name = "Incognito", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.954f, 9.082f)
curveTo(19.5f, 1.45f, 15.529f, 0.0f, 14.984f, 0.0f)
arcTo(5.328f, 5.328f, 0.0f, false, false, 12.0f, 1.0f)
arcTo(5.186f, 5.186f, 0.0f, false, false, 9.067f, 0.0f)
curveTo(8.471f, 0.0f, 4.5f, 1.45f, 4.046f, 9.082f)
curveTo(1.57f, 9.7f, 0.0f, 10.605f, 0.0f, 11.613f)
curveTo(0.0f, 13.484f, 5.373f, 15.0f, 12.0f, 15.0f)
reflectiveCurveToRelative(12.0f, -1.516f, 12.0f, -3.387f)
curveTo(24.0f, 10.605f, 22.43f, 9.7f, 19.954f, 9.082f)
close()
moveTo(12.0f, 10.0f)
arcToRelative(21.435f, 21.435f, 0.0f, false, true, -4.975f, -0.486f)
curveToRelative(0.224f, -4.728f, 1.893f, -6.143f, 2.42f, -6.477f)
arcToRelative(1.8f, 1.8f, 0.0f, false, true, 1.222f, 0.95f)
lineTo(12.0f, 6.571f)
lineToRelative(1.333f, -2.584f)
arcToRelative(1.807f, 1.807f, 0.0f, false, true, 1.207f, -0.949f)
curveToRelative(0.575f, 0.363f, 2.213f, 1.8f, 2.435f, 6.475f)
arcTo(21.425f, 21.425f, 0.0f, false, true, 12.0f, 10.0f)
close()
moveTo(21.0f, 20.0f)
arcToRelative(3.989f, 3.989f, 0.0f, false, true, -7.8f, 1.193f)
arcTo(5.751f, 5.751f, 0.0f, false, false, 12.0f, 21.0f)
arcToRelative(5.751f, 5.751f, 0.0f, false, false, -1.2f, 0.193f)
arcToRelative(4.0f, 4.0f, 0.0f, true, true, -0.259f, -3.018f)
arcTo(7.526f, 7.526f, 0.0f, false, true, 12.0f, 18.0f)
arcToRelative(7.526f, 7.526f, 0.0f, false, true, 1.461f, 0.175f)
arcTo(3.987f, 3.987f, 0.0f, false, true, 21.0f, 20.0f)
close()
}
}
.build()
return _incognito!!
}
private var _incognito: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,053
|
icons
|
MIT License
|
app/src/main/java/com/pr0gramm/app/ui/intro/slides/CategoriesActionItemsSlide.kt
|
mopsalarm
| 30,804,448
| false
|
{"Kotlin": 1414351, "Shell": 6752, "Python": 1124}
|
package com.pr0gramm.app.ui.intro.slides
import com.pr0gramm.app.R
/**
*/
class CategoriesActionItemsSlide : ActionItemsSlide("CategoriesActionItemsSlide") {
override val introBackgroundResource: Int = R.color.pink_primary
override val introTitle: String = "Kategorien"
override val introDescription: String = "Die App bietet dir mehr als nur 'Top' und 'Neu' - welche Kategorien interessieren dich?"
override val introActionItems: List<ActionItem>
get() {
return listOf(
SettingActionItem("Zufall", "pref_show_category_random"),
SettingActionItem("Kontrovers", "pref_show_category_controversial"),
SettingActionItem("Stelz (nur pr0mium)", "pref_show_category_premium"))
}
}
| 39
|
Kotlin
|
38
| 284
|
d6917f3ec16b6664a90a4519843f3d3d4ccae2cf
| 784
|
Pr0
|
MIT License
|
uniflow-androidx/src/main/java/io/uniflow/androidx/flow/LiveDataPublisher.kt
|
niltsiar
| 318,138,716
| true
|
{"Kotlin": 106492, "Shell": 236}
|
package io.uniflow.androidx.flow
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import io.uniflow.core.flow.UIDataPublisher
import io.uniflow.core.flow.data.Event
import io.uniflow.core.flow.data.UIEvent
import io.uniflow.core.flow.data.UIState
import io.uniflow.core.threading.onMain
class LiveDataPublisher(defaultState: UIState) : UIDataPublisher {
private val _states = MutableLiveData<UIState>()
val states: LiveData<UIState> = _states
private val _events = MutableLiveData<Event<UIEvent>>()
val events: LiveData<Event<UIEvent>> = _events
init {
_states.value = defaultState
}
override suspend fun publishState(state: UIState) {
onMain(immediate = true) {
_states.value = state
}
}
override suspend fun publishEvent(event: UIEvent) {
onMain(immediate = true) {
_events.value = Event(content = event)
}
}
}
| 0
| null |
0
| 0
|
f2c9a7f57e2a08056cd15381a99bd88897c0adb1
| 950
|
uniflow-kt
|
Apache License 2.0
|
src/main/kotlin/me/jraynor/objects/item/SynthesizerItem.kt
|
MrManiacc
| 349,858,377
| false
| null |
package me.jraynor.objects.item
import net.minecraft.item.Item
import net.minecraft.item.ItemGroup
/**
* This is the go to item for the mod. It does all kinds of configurations.
* It is also required in order to link things with the utility block
*/
class SynthesizerItem : Item(Properties().group(ItemGroup.MISC).maxStackSize(1)) {
}
| 8
|
Kotlin
|
3
| 15
|
4334badd181215dccecb4f62be1f565ad8af5b09
| 344
|
Blueprints
|
MIT License
|
src/main/kotlin/me/jraynor/objects/item/SynthesizerItem.kt
|
MrManiacc
| 349,858,377
| false
| null |
package me.jraynor.objects.item
import net.minecraft.item.Item
import net.minecraft.item.ItemGroup
/**
* This is the go to item for the mod. It does all kinds of configurations.
* It is also required in order to link things with the utility block
*/
class SynthesizerItem : Item(Properties().group(ItemGroup.MISC).maxStackSize(1)) {
}
| 8
|
Kotlin
|
3
| 15
|
4334badd181215dccecb4f62be1f565ad8af5b09
| 344
|
Blueprints
|
MIT License
|
src/main/kotlin/io/github/dylmeadows/eontimer/util/javafx/spinner/SpinnerExtensions.kt
|
wuyaz
| 249,127,435
| true
|
{"Kotlin": 113770, "CSS": 4817}
|
package io.github.dylmeadows.eontimer.util.javafx.spinner
import io.github.dylmeadows.eontimer.util.asFlux
import javafx.beans.property.ObjectProperty
import javafx.beans.property.StringProperty
import javafx.scene.control.Spinner
import java.util.*
val <T> Spinner<T>.valueProperty: ObjectProperty<T>?
get() = valueFactory?.valueProperty()
val <T> Spinner<T>.textProperty: StringProperty
get() = editor.textProperty()
var <T> Spinner<T>.text: String
get() = editor.text
set(value) {
editor.text = value
}
fun <T> Spinner<T>.setValue(value: T) {
valueFactory?.value = value
}
fun <T> Spinner<T>.commitValue() {
Optional.ofNullable(valueFactory)
.map { it.converter }
.ifPresent { converter ->
setValue(converter.fromString(text))
}
}
fun <T> Spinner<T>.setOnFocusLost(onFocusLost: () -> Unit) {
focusedProperty().asFlux()
.filter { isFocused -> !isFocused }
.subscribe { onFocusLost() }
}
| 0
| null |
0
| 0
|
d868afe77ff39bf867e51b3b9280a263785bb41a
| 986
|
EonTimer
|
MIT License
|
src/main/kotlin/common/TileType.kt
|
leosongwei
| 476,196,000
| false
|
{"Kotlin": 33533, "GLSL": 670}
|
package common
enum class TileType(var typeCode: Int) {
Invalid(0),
Grass(1),
Sand(2),
Wall(3),
Water(4);
companion object {
fun fromNumber(typeCode: Int):TileType {
return when(typeCode) {
Grass.typeCode -> Grass
Sand.typeCode -> Sand
Wall.typeCode -> Wall
Water.typeCode -> Water
else -> Invalid
}
}
}
}
fun main() {
println(TileType.fromNumber(0))
println(TileType.fromNumber(1))
println(TileType.Sand.typeCode)
}
| 0
|
Kotlin
|
0
| 0
|
97b52cfdfa935d84c20e5f5c2d7143afdc9acac4
| 579
|
ecs-experiment
|
MIT License
|
vire-engine/src/main/kotlin/net/voxelpi/vire/engine/kernel/KernelInstanceConfig.kt
|
VoxelPi
| 700,036,011
| false
|
{"Kotlin": 336452}
|
package net.voxelpi.vire.engine.kernel
import net.voxelpi.vire.engine.kernel.variable.provider.SettingStateProvider
import net.voxelpi.vire.engine.kernel.variable.storage.SettingStateMap
import net.voxelpi.vire.engine.kernel.variable.storage.SettingStateStorage
import net.voxelpi.vire.engine.kernel.variable.storage.SettingStateStorageWrapper
internal data class KernelInstanceConfig(
val kernelVariant: KernelVariantImpl,
override val settingStateStorage: SettingStateStorage,
) : SettingStateStorageWrapper {
constructor(kernelVariant: KernelVariantImpl, settingStateProvider: SettingStateProvider) :
this(kernelVariant, SettingStateStorage(kernelVariant, settingStateProvider))
constructor(kernelVariant: KernelVariantImpl, settingStateMap: SettingStateMap) :
this(kernelVariant, SettingStateStorage(kernelVariant, settingStateMap))
}
| 2
|
Kotlin
|
0
| 0
|
a0d187668387520990923ec711d658bcacadf5da
| 875
|
Vire
|
MIT License
|
assemblyadapter-common-item/src/androidTest/java/com/github/panpf/assemblyadapter/common/item/test/ViewItemFactoryTest.kt
|
panpf
| 42,781,599
| false
| null |
/*
* Copyright (C) 2021 panpf <<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.github.panpf.assemblyadapter.common.item.test
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.test.platform.app.InstrumentationRegistry
import com.github.panpf.assemblyadapter.SimpleItemFactory
import com.github.panpf.assemblyadapter.ViewItemFactory
import org.junit.Assert
import org.junit.Test
class ViewItemFactoryTest {
@Test
fun test() {
val context = InstrumentationRegistry.getInstrumentation().context
val parent = FrameLayout(context)
val itemFactory = ViewItemFactory(String::class, R.layout.item_test)
val item = itemFactory.dispatchCreateItem(parent) as SimpleItemFactory.SimpleItem<String>
Assert.assertEquals(
"",
item.itemView.findViewById<TextView>(R.id.testItemTitleText).text
)
Assert.assertEquals(
14f,
item.itemView.findViewById<TextView>(R.id.testItemTitleText).textSize
)
item.dispatchBindData(0, 0, "hello")
Assert.assertEquals(
"",
item.itemView.findViewById<TextView>(R.id.testItemTitleText).text
)
val itemFactory2 = ViewItemFactory(
String::class,
LayoutInflater.from(context).inflate(R.layout.item_test, parent, false)
)
val item2 = itemFactory2.dispatchCreateItem(parent) as SimpleItemFactory.SimpleItem<String>
Assert.assertEquals(
"",
item2.itemView.findViewById<TextView>(R.id.testItemTitleText).text
)
Assert.assertEquals(
14f,
item2.itemView.findViewById<TextView>(R.id.testItemTitleText).textSize
)
item2.dispatchBindData(0, 0, "hello")
Assert.assertEquals(
"",
item2.itemView.findViewById<TextView>(R.id.testItemTitleText).text
)
val itemFactory3 = ViewItemFactory(String::class) { _, inflater, parent: ViewGroup ->
inflater.inflate(R.layout.item_test, parent, false)
}
val item3 = itemFactory3.dispatchCreateItem(parent) as SimpleItemFactory.SimpleItem<String>
Assert.assertEquals(
"",
item3.itemView.findViewById<TextView>(R.id.testItemTitleText).text
)
Assert.assertEquals(
14f,
item3.itemView.findViewById<TextView>(R.id.testItemTitleText).textSize
)
item3.dispatchBindData(0, 0, "hello")
Assert.assertEquals(
"",
item3.itemView.findViewById<TextView>(R.id.testItemTitleText).text
)
}
}
| 0
|
Kotlin
|
33
| 169
|
00cf02eb1b2be82685a2997d5473579246e256c8
| 3,261
|
assembly-adapter
|
Apache License 2.0
|
updater-mapper-standard/src/main/java/org/runestar/client/updater/mapper/std/classes/ClanChat.kt
|
widget-
| 246,016,204
| true
|
{"Kotlin": 1295734, "Java": 982488}
|
package org.runestar.client.updater.mapper.std.classes
import org.kxtra.lang.list.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.INT_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.annotations.DependsOn
import org.runestar.client.updater.mapper.annotations.MethodParameters
import org.runestar.client.updater.mapper.annotations.SinceVersion
import org.runestar.client.updater.mapper.extensions.and
import org.runestar.client.updater.mapper.extensions.predicateOf
import org.runestar.client.updater.mapper.extensions.type
import org.runestar.client.updater.mapper.tree.Class2
import org.runestar.client.updater.mapper.tree.Field2
import org.runestar.client.updater.mapper.tree.Instruction2
import org.runestar.client.updater.mapper.tree.Method2
import java.lang.reflect.Modifier
@SinceVersion(164)
@DependsOn(UserList::class, ClanMate::class)
class ClanChat : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<UserList>() }
.and { it.instanceMethods.flatMap { it.instructions.toList() }.any { it.opcode == NEW && it.typeType == type<ClanMate>() } }
@DependsOn(UserList.newInstance::class)
class newInstance : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newInstance>().mark }
}
@DependsOn(UserList.newTypedArray::class)
class newTypedArray : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newTypedArray>().mark }
}
@DependsOn(LoginType::class)
class loginType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<LoginType>() }
}
class name : OrderMapper.InConstructor.Field(ClanChat::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
class owner : OrderMapper.InConstructor.Field(ClanChat::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
@MethodParameters("buffer")
@DependsOn(Buffer::class)
class readUpdate : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<Buffer>()) }
.and { it.instructions.any { it.opcode == IINC } }
}
@DependsOn(Usernamed::class)
class localUser : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<Usernamed>() }
}
class rank : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE && Modifier.isPublic(it.access) }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsFriend::class)
class clearFriends : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsFriend>().id } }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsIgnored::class)
class clearIgnoreds : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsIgnored>().id } }
}
}
| 0
|
Kotlin
|
0
| 0
|
3e8846b00b649d716d7d4556b69beaf8a20355d2
| 3,673
|
client
|
MIT License
|
updater-mapper-standard/src/main/java/org/runestar/client/updater/mapper/std/classes/ClanChat.kt
|
widget-
| 246,016,204
| true
|
{"Kotlin": 1295734, "Java": 982488}
|
package org.runestar.client.updater.mapper.std.classes
import org.kxtra.lang.list.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.INT_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.annotations.DependsOn
import org.runestar.client.updater.mapper.annotations.MethodParameters
import org.runestar.client.updater.mapper.annotations.SinceVersion
import org.runestar.client.updater.mapper.extensions.and
import org.runestar.client.updater.mapper.extensions.predicateOf
import org.runestar.client.updater.mapper.extensions.type
import org.runestar.client.updater.mapper.tree.Class2
import org.runestar.client.updater.mapper.tree.Field2
import org.runestar.client.updater.mapper.tree.Instruction2
import org.runestar.client.updater.mapper.tree.Method2
import java.lang.reflect.Modifier
@SinceVersion(164)
@DependsOn(UserList::class, ClanMate::class)
class ClanChat : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<UserList>() }
.and { it.instanceMethods.flatMap { it.instructions.toList() }.any { it.opcode == NEW && it.typeType == type<ClanMate>() } }
@DependsOn(UserList.newInstance::class)
class newInstance : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newInstance>().mark }
}
@DependsOn(UserList.newTypedArray::class)
class newTypedArray : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<UserList.newTypedArray>().mark }
}
@DependsOn(LoginType::class)
class loginType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<LoginType>() }
}
class name : OrderMapper.InConstructor.Field(ClanChat::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
class owner : OrderMapper.InConstructor.Field(ClanChat::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == String::class.type }
}
@MethodParameters("buffer")
@DependsOn(Buffer::class)
class readUpdate : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<Buffer>()) }
.and { it.instructions.any { it.opcode == IINC } }
}
@DependsOn(Usernamed::class)
class localUser : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<Usernamed>() }
}
class rank : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == INT_TYPE && Modifier.isPublic(it.access) }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsFriend::class)
class clearFriends : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsFriend>().id } }
}
@MethodParameters()
@DependsOn(ClanMate.clearIsIgnored::class)
class clearIgnoreds : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE && it.arguments.isEmpty() }
.and { it.instructions.any { it.isMethod && it.methodId == method<ClanMate.clearIsIgnored>().id } }
}
}
| 0
|
Kotlin
|
0
| 0
|
3e8846b00b649d716d7d4556b69beaf8a20355d2
| 3,673
|
client
|
MIT License
|
sample/src/main/java/com/kangyee/locationselector/demo/util/PermissionUtils.kt
|
KangYee
| 636,330,875
| false
| null |
/*
* Copyright (C) 2023 KangYee
*
* 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.kangyee.locationselector.demo.util
import androidx.fragment.app.FragmentActivity
import com.permissionx.guolindev.PermissionX
object PermissionUtils {
fun requestPermission(activity: FragmentActivity, vararg permissions: String, request: Runnable) {
PermissionX.init(activity)
.permissions(*permissions)
.onExplainRequestReason { scope, deniedList ->
scope.showRequestReasonDialog(
deniedList, "你需要允许以下权限才可以继续", "我知道了", "我再想想"
)
}
.onForwardToSettings { scope, deniedList ->
scope.showForwardToSettingsDialog(
deniedList, "你需要在系统设置中,允许以下权限才可以继续", "立即设置", "我再想想"
)
}
.request { allGuard, _, _ ->
if (allGuard) {
request.run()
}
}
}
}
| 0
|
Kotlin
|
0
| 3
|
ee7d3ffd2f0163026188cf9627ced20d259ff291
| 2,014
|
LocationSelector
|
MIT License
|
app/src/main/java/com/chrynan/androidsearch/util/ContextUtils.kt
|
chRyNaN
| 161,237,148
| false
| null |
package com.chrynan.androidsearch.util
import android.content.Context
import android.content.Intent
fun Context.startIntentIfItExists(intent: Intent): Boolean {
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
return true
}
return false
}
| 0
|
Kotlin
|
0
| 0
|
ade50a4bda75e3e71d86457565e63573feaf597b
| 296
|
Android-Search
|
Apache License 2.0
|
kovibes/src/commonMain/kotlin/io/github/rubenquadros/kovibes/api/models/ImageInfo.kt
|
rubenquadros
| 758,569,353
| false
|
{"Kotlin": 193931}
|
package io.github.rubenquadros.kovibes.api.models
import io.github.rubenquadros.kovibes.api.ExcludeFromCoverage
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@ExcludeFromCoverage
@Serializable
internal data class ImageInfo(
@SerialName("height")
val height: Int?,
@SerialName("width")
val width: Int?,
@SerialName("url")
val url: String?
)
| 0
|
Kotlin
|
0
| 8
|
2c34ce95533b7fe1d119811ab4ba48d23245cb69
| 402
|
KoVibes
|
MIT License
|
app/src/main/java/com/expensivebelly/dagger2retaingraph/feature/di/MainComponent.kt
|
ExpensiveBelly
| 74,518,019
| false
| null |
package com.expensivebelly.dagger2retaingraph.feature.di
import com.expensivebelly.dagger2retaingraph.core.di.ActivityScope
import com.expensivebelly.dagger2retaingraph.feature.MainActivity
import dagger.Component
@ActivityScope
@Component
interface MainComponent {
fun inject(mainActivity: MainActivity)
}
| 1
| null |
1
| 1
|
b251d893068ba8ea82d4192a29f912585a90d3f3
| 312
|
Dagger2RetainGraph
|
Apache License 2.0
|
src/main/kotlin/com/cognifide/gradle/aem/instance/InstanceSync.kt
|
ergo123
| 137,851,057
| true
|
{"Kotlin": 236402, "Shell": 5207, "Java": 1813, "Batchfile": 233}
|
package com.cognifide.gradle.aem.instance
import com.cognifide.gradle.aem.api.AemConfig
import com.cognifide.gradle.aem.internal.Patterns
import com.cognifide.gradle.aem.internal.ProgressCountdown
import com.cognifide.gradle.aem.internal.http.PreemptiveAuthInterceptor
import com.cognifide.gradle.aem.pkg.PackagePlugin
import com.cognifide.gradle.aem.pkg.deploy.*
import org.apache.commons.io.IOUtils
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.HttpStatus
import org.apache.http.NameValuePair
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.HttpClient
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.message.BasicNameValuePair
import org.apache.http.ssl.SSLContextBuilder
import org.gradle.api.Project
import org.jsoup.Jsoup
import org.jsoup.parser.Parser
import org.zeroturnaround.zip.ZipUtil
import java.io.File
import java.io.FileNotFoundException
import java.util.*
class InstanceSync(val project: Project, val instance: Instance) {
companion object {
private const val PACKAGE_MANAGER_SERVICE_SUFFIX = "/crx/packmgr/service"
private const val PACKAGE_MANAGER_LIST_SUFFIX = "/crx/packmgr/list.jsp"
}
val config = AemConfig.of(project)
val logger = project.logger
val jsonTargetUrl = instance.httpUrl + PACKAGE_MANAGER_SERVICE_SUFFIX + "/.json"
val htmlTargetUrl = instance.httpUrl + PACKAGE_MANAGER_SERVICE_SUFFIX + "/.html"
val listPackagesUrl = instance.httpUrl + PACKAGE_MANAGER_LIST_SUFFIX
val bundlesUrl = "${instance.httpUrl}/system/console/bundles.json"
val componentsUrl = "${instance.httpUrl}/system/console/components.json"
val vmStatUrl = "${instance.httpUrl}/system/console/vmstat"
var basicUser = instance.user
var basicPassword = instance.password
var connectionTimeout = config.instanceConnectionTimeout
var connectionUntrustedSsl = config.instanceConnectionUntrustedSsl
var connectionRetries = true
var requestConfigurer: (HttpRequestBase) -> Unit = { _ -> }
var responseHandler: (HttpResponse) -> Unit = { _ -> }
fun get(url: String): String {
return fetch(HttpGet(normalizeUrl(url)))
}
fun postUrlencoded(url: String, params: Map<String, Any> = mapOf()): String {
return post(url, createEntityUrlencoded(params))
}
fun postMultipart(url: String, params: Map<String, Any> = mapOf()): String {
return post(url, createEntityMultipart(params))
}
private fun post(url: String, entity: HttpEntity): String {
return fetch(HttpPost(normalizeUrl(url)).apply { this.entity = entity })
}
/**
* Fix for HttpClient's: 'escaped absolute path not valid'
* https://stackoverflow.com/questions/13652681/httpclient-invalid-uri-escaped-absolute-path-not-valid
*/
private fun normalizeUrl(url: String): String {
return url.replace(" ", "%20")
}
fun fetch(method: HttpRequestBase): String {
return execute(method, { response ->
val body = IOUtils.toString(response.entity.content) ?: ""
if (response.statusLine.statusCode == HttpStatus.SC_OK) {
return@execute body
} else {
logger.debug(body)
throw DeployException("Unexpected instance response: ${response.statusLine}")
}
})
}
fun <T> execute(method: HttpRequestBase, success: (HttpResponse) -> T): T {
try {
requestConfigurer(method)
val client = createHttpClient()
val response = client.execute(method)
responseHandler(response)
return success(response)
} catch (e: Exception) {
throw DeployException("Failed instance request: ${e.message}", e)
} finally {
method.releaseConnection()
}
}
fun createHttpClient(): HttpClient {
val builder = HttpClientBuilder.create()
.addInterceptorFirst(PreemptiveAuthInterceptor())
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(connectionTimeout)
.build()
)
.setDefaultCredentialsProvider(BasicCredentialsProvider().apply {
setCredentials(AuthScope.ANY, UsernamePasswordCredentials(basicUser, basicPassword))
})
if (connectionUntrustedSsl) {
builder.setSSLSocketFactory(createSslConnectionSocketFactory())
}
if (!connectionRetries) {
builder.disableAutomaticRetries()
}
return builder.build()
}
private fun createSslConnectionSocketFactory(): SSLConnectionSocketFactory {
val sslContext = SSLContextBuilder()
.loadTrustMaterial(null, { _, _ -> true })
.build()
return SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)
}
private fun createEntityUrlencoded(params: Map<String, Any>): HttpEntity {
return UrlEncodedFormEntity(params.entries.fold(ArrayList<NameValuePair>(), { result, e ->
result.add(BasicNameValuePair(e.key, e.value.toString())); result
}))
}
private fun createEntityMultipart(params: Map<String, Any>): HttpEntity {
val builder = MultipartEntityBuilder.create()
for ((key, value) in params) {
if (value is File) {
if (value.exists()) {
builder.addBinaryBody(key, value)
}
} else {
val str = value.toString()
if (str.isNotBlank()) {
builder.addTextBody(key, str)
}
}
}
return builder.build()
}
fun determineRemotePackage(): ListResponse.Package? {
return resolveRemotePackage({ response ->
response.resolvePackage(project, ListResponse.Package(project))
}, true)
}
fun determineRemotePackagePath(): String {
if (!config.packageRemotePath.isBlank()) {
return config.packageRemotePath
}
val pkg = determineRemotePackage()
?: throw DeployException("Package is not uploaded on AEM instance.")
return pkg.path
}
fun determineRemotePackage(file: File, refresh: Boolean = true): ListResponse.Package? {
if (!ZipUtil.containsEntry(file, PackagePlugin.VLT_PROPERTIES)) {
throw DeployException("File is not a valid CRX package: $file")
}
val xml = ZipUtil.unpackEntry(file, PackagePlugin.VLT_PROPERTIES).toString(Charsets.UTF_8)
val doc = Jsoup.parse(xml, "", Parser.xmlParser())
val group = doc.select("entry[key=group]").text()
val name = doc.select("entry[key=name]").text()
val version = doc.select("entry[key=version]").text()
return resolveRemotePackage({ response ->
response.resolvePackage(project, ListResponse.Package(group, name, version))
}, refresh)
}
private fun resolveRemotePackage(resolver: (ListResponse) -> ListResponse.Package?, refresh: Boolean): ListResponse.Package? {
logger.debug("Asking AEM for uploaded packages using URL: '$listPackagesUrl'")
if (instance.packages == null || refresh) {
val json = postMultipart(listPackagesUrl)
instance.packages = try {
ListResponse.fromJson(json)
} catch (e: Exception) {
throw DeployException("Cannot ask AEM for uploaded packages!", e)
}
}
return resolver(instance.packages!!)
}
fun uploadPackage(file: File): UploadResponse {
lateinit var exception: DeployException
for (i in 0..config.uploadRetryTimes) {
try {
return uploadPackageOnce(file)
} catch (e: DeployException) {
exception = e
if (i < config.uploadRetryTimes) {
logger.warn("Cannot upload package to $instance.")
val header = "Retrying upload (${i + 1}/${config.uploadRetryTimes}) after delay."
val countdown = ProgressCountdown(project, header, config.uploadRetryDelay)
countdown.run()
}
}
}
throw exception
}
fun uploadPackageOnce(file: File): UploadResponse {
val url = "$jsonTargetUrl/?cmd=upload"
logger.info("Uploading package at path '{}' to URL '{}'", file.path, url)
try {
val json = postMultipart(url, mapOf(
"package" to file,
"force" to (config.uploadForce || isSnapshot(file))
))
val response = UploadResponse.fromJson(json)
if (response.isSuccess) {
logger.info(response.msg)
} else {
logger.error(response.msg)
throw DeployException(response.msg)
}
return response
} catch (e: FileNotFoundException) {
throw DeployException(String.format("Package file '%s' not found!", file.path), e)
} catch (e: Exception) {
throw DeployException("Cannot upload package", e)
}
}
fun installPackage(uploadedPackagePath: String): InstallResponse {
lateinit var exception: DeployException
for (i in 0..config.installRetryTimes) {
try {
return installPackageOnce(uploadedPackagePath)
} catch (e: DeployException) {
exception = e
if (i < config.installRetryTimes) {
logger.warn("Cannot install package on $instance.")
val header = "Retrying install (${i + 1}/${config.installRetryTimes}) after delay."
val countdown = ProgressCountdown(project, header, config.installRetryDelay)
countdown.run()
}
}
}
throw exception
}
fun installPackageOnce(uploadedPackagePath: String): InstallResponse {
val url = "$htmlTargetUrl$uploadedPackagePath/?cmd=install"
logger.info("Installing package using command: $url")
try {
val json = postMultipart(url, mapOf("recursive" to config.installRecursive))
val response = InstallResponse(json)
when (response.status) {
HtmlResponse.Status.SUCCESS -> if (response.errors.isEmpty()) {
logger.info("Package successfully installed.")
} else {
logger.warn("Package installed with errors")
response.errors.forEach { logger.error(it) }
throw DeployException("Installation completed with errors!")
}
HtmlResponse.Status.SUCCESS_WITH_ERRORS -> {
logger.error("Package installed with errors.")
response.errors.forEach { logger.error(it) }
throw DeployException("Installation completed with errors!")
}
HtmlResponse.Status.FAIL -> {
logger.error("Installation failed.")
response.errors.forEach { logger.error(it) }
throw DeployException("Installation incomplete!")
}
}
return response
} catch (e: Exception) {
throw DeployException("Cannot install package.", e)
}
}
fun isSnapshot(file: File): Boolean {
return Patterns.wildcard(file, config.packageSnapshots)
}
fun deployPackage(file: File) {
installPackage(uploadPackage(file).path)
}
fun distributePackage(file: File) {
val packagePath = uploadPackage(file).path
installPackage(packagePath)
activatePackage(packagePath)
}
fun activatePackage(path: String): UploadResponse {
val url = "$jsonTargetUrl$path/?cmd=replicate"
logger.info("Activating package using command: $url")
val json: String
try {
json = postMultipart(url)
} catch (e: Exception) {
throw DeployException("Cannot activate package", e)
}
val response = try {
UploadResponse.fromJson(json)
} catch (e: Exception) {
logger.error("Malformed JSON response", e)
throw DeployException("Package activation failed", e)
}
if (response.isSuccess) {
logger.info("Package activated")
} else {
logger.error("Package activation failed: + " + response.msg)
throw DeployException(response.msg)
}
return response
}
fun deletePackage(path: String) {
val url = "$htmlTargetUrl$path/?cmd=delete"
logger.info("Deleting package using command: $url")
try {
val rawHtml = postMultipart(url)
val response = DeleteResponse(rawHtml)
when (response.status) {
HtmlResponse.Status.SUCCESS,
HtmlResponse.Status.SUCCESS_WITH_ERRORS -> if (response.errors.isEmpty()) {
logger.info("Package successfully deleted.")
} else {
logger.warn("Package deleted with errors.")
response.errors.forEach { logger.error(it) }
throw DeployException("Package deleted with errors!")
}
HtmlResponse.Status.FAIL -> {
logger.error("Package deleting failed.")
response.errors.forEach { logger.error(it) }
throw DeployException("Package deleting failed!")
}
}
} catch (e: Exception) {
throw DeployException("Cannot delete package.", e)
}
}
fun uninstallPackage(installedPackagePath: String) {
val url = "$htmlTargetUrl$installedPackagePath/?cmd=uninstall"
logger.info("Uninstalling package using command: $url")
try {
val rawHtml = postMultipart(url, mapOf("recursive" to config.installRecursive))
val response = UninstallResponse(rawHtml)
when (response.status) {
HtmlResponse.Status.SUCCESS,
HtmlResponse.Status.SUCCESS_WITH_ERRORS -> if (response.errors.isEmpty()) {
logger.info("Package successfully uninstalled.")
} else {
logger.warn("Package uninstalled with errors.")
response.errors.forEach { logger.error(it) }
throw DeployException("Package uninstalled with errors!")
}
HtmlResponse.Status.FAIL -> {
logger.error("Package uninstalling failed.")
response.errors.forEach { logger.error(it) }
throw DeployException("Package uninstalling failed!")
}
}
} catch (e: Exception) {
throw DeployException("Cannot uninstall package.", e)
}
}
fun determineInstanceState(): InstanceState {
return InstanceState(this, instance)
}
fun determineBundleState(): BundleState {
logger.debug("Asking AEM for OSGi bundles using URL: '$bundlesUrl'")
return try {
BundleState.fromJson(get(bundlesUrl))
} catch (e: Exception) {
logger.debug("Cannot determine OSGi bundles state on $instance", e)
BundleState.unknown(e)
}
}
fun determineComponentState(): ComponentState {
logger.debug("Asking AEM for OSGi components using URL: '$bundlesUrl'")
return try {
ComponentState.fromJson(get(componentsUrl))
} catch (e: Exception) {
logger.debug("Cannot determine OSGi components state on $instance", e)
ComponentState.unknown()
}
}
fun reload() {
try {
logger.info("Triggering instance(s) shutdown")
postUrlencoded(vmStatUrl, mapOf("shutdown_type" to "Restart"))
} catch (e: DeployException) {
throw InstanceException("Cannot trigger shutdown for instance $instance", e)
}
}
}
fun Collection<Instance>.sync(project: Project, callback: (InstanceSync) -> Unit) {
return map { InstanceSync(project, it) }.parallelStream().forEach(callback)
}
| 0
|
Kotlin
|
0
| 0
|
0745e781c7a6b7aea6896b0a0618f52a855c68be
| 17,154
|
gradle-aem-plugin
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/timestream/SchemaPropertyDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.timestream
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.timestream.CfnTable
@Generated
public fun buildSchemaProperty(initializer: @AwsCdkDsl CfnTable.SchemaProperty.Builder.() -> Unit):
CfnTable.SchemaProperty = CfnTable.SchemaProperty.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
a1cf8fbfdfef9550b3936de2f864543edb76348b
| 415
|
aws-cdk-kt
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/timestream/SchemaPropertyDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.timestream
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.timestream.CfnTable
@Generated
public fun buildSchemaProperty(initializer: @AwsCdkDsl CfnTable.SchemaProperty.Builder.() -> Unit):
CfnTable.SchemaProperty = CfnTable.SchemaProperty.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
a1cf8fbfdfef9550b3936de2f864543edb76348b
| 415
|
aws-cdk-kt
|
Apache License 2.0
|
src/main/kotlin/org/caffeine/chaos/commands/Haste.kt
|
caffeine-moe
| 479,810,319
| false
|
{"Kotlin": 158081}
|
package org.caffeine.chaos.commands
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString
import org.caffeine.chaos.Command
import org.caffeine.chaos.CommandInfo
import org.caffeine.chaos.api.client.Client
import org.caffeine.chaos.api.client.message.MessageBuilder
import org.caffeine.chaos.api.client.message.MessageCreateEvent
import org.caffeine.chaos.api.json
import org.caffeine.chaos.api.normalHTTPClient
import java.nio.charset.MalformedInputException
class Haste : Command(arrayOf("haste"),
CommandInfo("Haste", "haste <Text> OR <file.txt>", "Uploads text OR a text document to Hastebin.")) {
@kotlinx.serialization.Serializable
private data class HasteResponse(
val key : String,
)
override suspend fun onCalled(
client : Client,
event : MessageCreateEvent,
args : MutableList<String>,
cmd : String,
) : Unit = coroutineScope {
event.channel.sendMessage(MessageBuilder().appendLine("Creating haste...").build()).thenAccept { message ->
launch {
var body = ""
if (args.isNotEmpty()) {
body = args.joinToString(" ")
}
if (event.message.attachments.isNotEmpty()) {
try {
body = normalHTTPClient.get(event.message.attachments.first().url).bodyAsText()
} catch (e : MalformedInputException) {
message.edit(error(client,
event,
"Unable to parse text from attached file. You must only upload text documents.",
commandInfo))
.thenAccept { this@coroutineScope.launch { onComplete(it, client, true) } }
return@launch
}
}
if (args.isEmpty() && event.message.attachments.isEmpty()) {
message.edit(error(client,
event,
"You must have at least one file attached OR other text written after the command.",
commandInfo))
.thenAccept { this@coroutineScope.launch { onComplete(it, client, true) } }
return@launch
}
val response = normalHTTPClient.post("https://www.toptal.com/developers/hastebin/documents") {
setBody(body)
}
val haste = json.decodeFromString<HasteResponse>(response.bodyAsText())
message.edit(MessageBuilder().appendLine("https://www.toptal.com/developers/hastebin/${haste.key}")
.build()).thenAccept { message ->
this.launch {
onComplete(message, client, client.config.auto_delete.bot.content_generation)
}
}
}
}
}
}
| 2
|
Kotlin
|
3
| 29
|
e378093a0694af80681f0433063e5b28a84086be
| 3,067
|
CHAOS
|
MIT License
|
src/main/kotlin/Mounting_Recursive.kt
|
cubesky
| 127,876,580
| false
| null |
import kefjs.Ef
import kefjs.kefconfig
import kefjs.prepareEf
import org.w3c.dom.events.Event
import kotlin.browser.document
class Mounting_Recursive {
lateinit var addItem : (state: Ef, value: String, e: Event) -> Unit
lateinit var removeItem : (state: Ef, value: String, e: Event) -> Unit
@JsName("main")
fun main() {
val _item = """
>div.item
.folder {{count = 0}}
>button
@click = addItem
.+
>button
@click = removeItem
.-
+list
""".prepareEf()
addItem = { state ,_, _ ->
state.editUserStore("ic", (state.getUserStore("ic",0)) + 1)
val ic = state.getUserStore<Int>("ic",0)
state.list("list").push(_item.newInstance(kefconfig {
data {
"count" setTo ic
}
methods {
"addItem" bind addItem
"removeItem" bind removeItem
}
}))
}
removeItem = { state ,_ , _ ->
state.umount()
}
_item.newInstance(kefconfig {
methods {
"addItem" bind addItem
"removeItem" bind removeItem
}
}).mount(document.body)
}
}
| 0
|
Kotlin
|
0
| 0
|
eb0b84ed1838afab40fe5379801463b5bbf49fb0
| 1,250
|
Kefjs_Demo
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/inspectorv2/CfnCisScanConfigurationSchedulePropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 70198112}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.inspectorv2
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import io.cloudshiftdev.awscdkdsl.common.MapBuilder
import kotlin.Any
import kotlin.Unit
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.inspectorv2.CfnCisScanConfiguration
/**
* The schedule the CIS scan configuration runs on.
*
* Each CIS scan configuration has exactly one type of schedule.
*
* 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.inspectorv2.*;
* Object oneTime;
* ScheduleProperty scheduleProperty = ScheduleProperty.builder()
* .daily(DailyScheduleProperty.builder()
* .startTime(TimeProperty.builder()
* .timeOfDay("timeOfDay")
* .timeZone("timeZone")
* .build())
* .build())
* .monthly(MonthlyScheduleProperty.builder()
* .day("day")
* .startTime(TimeProperty.builder()
* .timeOfDay("timeOfDay")
* .timeZone("timeZone")
* .build())
* .build())
* .oneTime(oneTime)
* .weekly(WeeklyScheduleProperty.builder()
* .days(List.of("days"))
* .startTime(TimeProperty.builder()
* .timeOfDay("timeOfDay")
* .timeZone("timeZone")
* .build())
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-inspectorv2-cisscanconfiguration-schedule.html)
*/
@CdkDslMarker
public class CfnCisScanConfigurationSchedulePropertyDsl {
private val cdkBuilder: CfnCisScanConfiguration.ScheduleProperty.Builder =
CfnCisScanConfiguration.ScheduleProperty.builder()
/** @param daily A daily schedule. */
public fun daily(daily: IResolvable) {
cdkBuilder.daily(daily)
}
/** @param daily A daily schedule. */
public fun daily(daily: CfnCisScanConfiguration.DailyScheduleProperty) {
cdkBuilder.daily(daily)
}
/** @param monthly A monthly schedule. */
public fun monthly(monthly: IResolvable) {
cdkBuilder.monthly(monthly)
}
/** @param monthly A monthly schedule. */
public fun monthly(monthly: CfnCisScanConfiguration.MonthlyScheduleProperty) {
cdkBuilder.monthly(monthly)
}
/** @param oneTime A one time schedule. */
public fun oneTime(oneTime: MapBuilder.() -> Unit = {}) {
val builder = MapBuilder()
builder.apply(oneTime)
cdkBuilder.oneTime(builder.map)
}
/** @param oneTime A one time schedule. */
public fun oneTime(oneTime: Any) {
cdkBuilder.oneTime(oneTime)
}
/** @param weekly A weekly schedule. */
public fun weekly(weekly: IResolvable) {
cdkBuilder.weekly(weekly)
}
/** @param weekly A weekly schedule. */
public fun weekly(weekly: CfnCisScanConfiguration.WeeklyScheduleProperty) {
cdkBuilder.weekly(weekly)
}
public fun build(): CfnCisScanConfiguration.ScheduleProperty = cdkBuilder.build()
}
| 0
|
Kotlin
|
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 3,193
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/mil/nga/msi/repository/asam/AsamLocalDataSource.kt
|
ngageoint
| 588,211,646
| false
| null |
package mil.nga.msi.repository.asam
import androidx.sqlite.db.SimpleSQLiteQuery
import mil.nga.msi.datasource.asam.Asam
import mil.nga.msi.datasource.asam.AsamDao
import javax.inject.Inject
class AsamLocalDataSource @Inject constructor(
private val dao: AsamDao
) {
fun observeAsams() = dao.observeAsams()
fun observeAsam(reference: String) = dao.observeAsam(reference)
fun observeAsamMapItems(query: SimpleSQLiteQuery) = dao.observeAsamMapItems(query)
fun observeAsamListItems(query: SimpleSQLiteQuery) = dao.getAsamListItems(query)
fun getAsams(query: SimpleSQLiteQuery) = dao.getAsams(query)
fun isEmpty() = dao.count() == 0
suspend fun getAsam(reference: String) = dao.getAsam(reference)
suspend fun getAsams(): List<Asam> = dao.getAsams()
suspend fun existingAsams(references: List<String>) = dao.getAsams(references)
suspend fun insert(asams: List<Asam>) = dao.insert(asams)
}
| 0
|
Kotlin
|
0
| 0
|
d7670ab5f73e2e89b741a56e418b49f2acc810a2
| 922
|
marlin-android
|
MIT License
|
app/src/main/java/tech/ascendio/mvvm/di/ViewModelModule.kt
|
MarianVasilca
| 134,163,908
| false
|
{"Kotlin": 83552}
|
/*
* Copyright (C) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.ascendio.mvvm.di
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
import tech.ascendio.mvvm.viewmodel.AppViewModelFactory
import tech.ascendio.mvvm.viewmodel.ImageViewModel
@Suppress("unused")
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(ImageViewModel::class)
abstract fun bindImageViewModel(imageViewModel: ImageViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(factory: AppViewModelFactory): ViewModelProvider.Factory
}
| 0
|
Kotlin
|
0
| 6
|
83788f2b5714c0e15cb9d034a5f6e437ef320071
| 1,215
|
android-mvvm-template
|
Apache License 2.0
|
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/message/abstracts/CommonMessage.kt
|
InsanusMokrassar
| 163,152,024
| false
| null |
package dev.inmo.tgbotapi.types.message.abstracts
import dev.inmo.tgbotapi.types.message.content.abstracts.MessageContent
interface CommonMessage<T: MessageContent> : Message,
PossiblyForwardedMessage,
PossiblyEditedMessage,
PossiblyReplyMessage,
PossiblyMarkedUp,
ContentMessage<T>
| 9
|
Kotlin
|
14
| 99
|
8206aefbb661db936d4078a8ef7cc9cecb5384e4
| 305
|
TelegramBotAPI
|
Apache License 2.0
|
wearApp/src/main/java/dev/johnoreilly/confetti/wear/sessions/SessionsScreen.kt
|
joreilly
| 436,024,503
| false
| null |
package dev.johnoreilly.confetti.wear.sessions
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.wear.compose.foundation.lazy.items
import androidx.wear.compose.ui.tooling.preview.WearPreviewDevices
import androidx.wear.compose.ui.tooling.preview.WearPreviewFontScales
import com.google.android.horologist.compose.layout.ScalingLazyColumn
import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults
import com.google.android.horologist.compose.layout.ScalingLazyColumnState
import com.google.android.horologist.compose.layout.ScreenScaffold
import com.google.android.horologist.compose.layout.rememberResponsiveColumnState
import dev.johnoreilly.confetti.decompose.SessionsUiState
import dev.johnoreilly.confetti.wear.components.SectionHeader
import dev.johnoreilly.confetti.wear.components.SessionCard
import dev.johnoreilly.confetti.wear.preview.TestFixtures
import dev.johnoreilly.confetti.wear.ui.ConfettiThemeFixed
import kotlinx.datetime.toKotlinLocalDateTime
@Composable
fun SessionsScreen(
uiState: SessionsUiState,
sessionSelected: (sessionId: String) -> Unit,
) {
val columnState: ScalingLazyColumnState = rememberResponsiveColumnState(
contentPadding = ScalingLazyColumnDefaults.padding(
first = ScalingLazyColumnDefaults.ItemType.Unspecified,
last = ScalingLazyColumnDefaults.ItemType.Unspecified
)
)
ScreenScaffold(scrollState = columnState) {
ScalingLazyColumn(
modifier = Modifier.fillMaxSize(),
columnState = columnState,
) {
when (uiState) {
is SessionsUiState.Success -> {
val sessions = uiState.sessionsByStartTimeList.firstOrNull().orEmpty()
sessions.forEach { (time, sessionsAtTime) ->
item {
SectionHeader(time)
}
items(sessionsAtTime) { session ->
SessionCard(
session,
sessionSelected = {
sessionSelected(it)
},
uiState.now
)
}
}
}
else -> {
// TODO
}
}
}
}
}
@WearPreviewDevices
@WearPreviewFontScales
@Composable
fun SessionListViewPreview() {
ConfettiThemeFixed {
SessionsScreen(
uiState = SessionsUiState.Success(
now = java.time.LocalDateTime.of(2022, 1, 1, 1, 1).toKotlinLocalDateTime(),
conferenceName = "wearconf",
venueLat = null,
venueLon = null,
confDates = listOf(),
formattedConfDates = listOf(),
sessionsByStartTimeList = listOf(
mapOf(
"14:00" to listOf(
TestFixtures.sessionDetails
)
)
),
speakers = listOf(),
rooms = listOf(),
bookmarks = setOf(),
isRefreshing = false,
searchString = "",
selectedSessionId = null,
),
sessionSelected = {},
)
}
}
| 51
| null |
91
| 784
|
d43e98fa3cd6eee949c3a0e57cf35d76dc49f083
| 3,536
|
Confetti
|
Apache License 2.0
|
app/src/main/java/com/jwhh/notekeeper/ui/NoteActivity.kt
|
Ibrahim-Mushtaha
| 424,583,013
| false
| null |
package com.bravedroid.notekeeper
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
private var notePosition = POSITION_NOT_SET
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val adapterCourses = ArrayAdapter<CourseInfo>(
this,
android.R.layout.simple_spinner_item,
DataManager.courses.values.toList()
)
adapterCourses.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerCourses.adapter = adapterCourses
notePosition =
savedInstanceState?.getInt(NOTE_POSITION, POSITION_NOT_SET) ?: intent.getIntExtra(
NOTE_POSITION,
POSITION_NOT_SET
)
if (notePosition != POSITION_NOT_SET)
displayNote()
else {
DataManager.notes.add(NoteInfo())
notePosition = DataManager.notes.lastIndex
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
if (notePosition >= DataManager.notes.lastIndex) {
val menuItem: MenuItem? = menu?.findItem(R.id.action_next)
if (menuItem != null) {
menuItem.icon = getDrawable(R.drawable.ic_not_interested_white_24dp)
menuItem.isEnabled = false
}
}
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
fun moveNext() {
++notePosition
displayNote()
invalidateOptionsMenu()
}
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
R.id.action_next -> {
moveNext()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun displayNote() {
val note = DataManager.notes[notePosition]
textNoteTitle.setText(note.title)
textNoteText.setText(note.text)
val courseposition = DataManager.courses.values.indexOf(note.course)
spinnerCourses.setSelection(courseposition)
}
override fun onPause() {
super.onPause()
saveNote()
}
private fun saveNote() {
val note = DataManager.notes[notePosition]
note.title = textNoteTitle.text.toString()
note.text = textNoteText.text.toString()
note.course = spinnerCourses.selectedItem as CourseInfo
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState?.putInt(NOTE_POSITION, notePosition)
}
}
| 1,092
| null |
1
| 4
|
b099dd261db1e6e26ace8383e816caa861353fac
| 3,400
|
NoteKeeper-Custom-Widgets
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com.macaosoftware.sdui.app/marketplace/amadeus/schedule/MySchedules.kt
|
pablichjenkov
| 701,156,284
| false
| null |
package com.macaosoftware.sdui.app.marketplace.amadeus.schedule
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.DateRange
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material3.Icon
import androidx.compose.material3.ShapeDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.macaosoftware.sdui.app.marketplace.amadeus.ui.screen.components.CustomBottomSheet
import com.macaosoftware.sdui.app.marketplace.amadeus.util.Util
import com.pablichj.incubator.amadeus.common.model.Address
import com.pablichj.incubator.amadeus.common.model.GeoCode
import io.kamel.core.Resource
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
@Composable
fun MySchedules() {
Row(
modifier = Modifier.fillMaxWidth()
.padding(start = 12.dp, end = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "My Schedule",
style = TextStyle(
fontSize = 16.sp,
lineHeight = 24.sp,
fontWeight = FontWeight(700),
color = Color(0xFF101010),
)
)
Text(
text = "See all",
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
fontWeight = FontWeight(500),
color = Color(0xFF4C4DDC),
)
)
}
val data1 = CityModel(
address = Address("123 Main St"),
chainCode = "ABC123",
dupeId = 1,
geoCode = GeoCode(12.34, 56.78),
hotelId = "H123",
iataCode = "IATA123",
lastUpdate = "2023-01-01",
name = "Hotel 1"
)
val data2 = CityModel(
address = Address("456 Oak St"),
chainCode = "DEF456",
dupeId = 2,
geoCode = GeoCode(23.45, 67.89),
hotelId = "H456",
iataCode = "IATA456",
lastUpdate = "2023-02-01",
name = "Hotel 2"
)
// Creating a list of ScheduleModel instances
val dataList = listOf(data1, data2)
// Printing the list
dataList.forEach { data ->
println(data)
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.CenterHorizontally
) {
items(dataList) { hotelDetails ->
repeat(10) {
MyScheduleItem(hotelDetails)
Spacer(modifier = Modifier.height(6.dp))
}
}
}
}
@Composable
fun MyScheduleItem(data: CityModel) {
//val navigator = LocalNavigator.current
val sheetState = rememberModalBottomSheetState()
val scope = rememberCoroutineScope()
val shape = ShapeDefaults.Medium
var visibility by remember { mutableStateOf(false) }
Row(
modifier = Modifier
.shadow(
elevation = 6.dp,
spotColor = Color(0x0A121212),
ambientColor = Color(0x0A121212)
)
.width(357.dp)
.height(108.dp)
.clickable {
visibility = !visibility
// navigator?.push(DetailScreen(data, Util.IMAGE))
}
.background(color = Color(0xFFFFFFFF), shape = RoundedCornerShape(size = 12.dp))
.padding(
end = 12.dp,
)
) {
// Image
val image: Resource<Painter> = asyncPainterResource(data = Util.IMAGE)
KamelImage(
resource = image,
contentDescription = null,
modifier = Modifier
.width(119.dp)
.height(108.dp)
.clip(
shape = RoundedCornerShape(topStart = 12.dp, bottomStart = 12.dp)
),
contentScale = ContentScale.FillBounds,
)
// Spacer
Spacer(modifier = Modifier.width(10.dp))
// Content Column
Column(
modifier = Modifier.fillMaxWidth()
.fillMaxHeight()
.padding(
start = 12.dp,
top = 12.dp,
end = 12.dp,
bottom = 12.dp
)
) {
// Title & Price
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(end = 2.dp) // Adjust end padding as needed
) {
Text(
modifier = Modifier.weight(0.65f),
text = data.name.toString(),
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
fontWeight = FontWeight(700),
color = Color(0xFF101010),
),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "$165.3 /night",
style = TextStyle(
fontSize = 14.sp,
lineHeight = 21.sp,
fontWeight = FontWeight(700),
color = Color(0xFF4C4DDC),
)
)
}
// Address
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
) {
Icon(
imageVector = Icons.Outlined.LocationOn,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = Color(0xFF4C4DDC),
)
Text(
text = "Wilora NT 0872, Australia",
style = TextStyle(
fontSize = 12.sp,
lineHeight = 18.sp,
fontWeight = FontWeight(500),
color = Color(0xFF878787),
),
modifier = Modifier.padding(top = 4.dp) // Adjust top padding as needed
)
}
// Rating
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
) {
Icon(
imageVector = Icons.Outlined.DateRange,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = Color(0xFF4C4DDC),
)
Text(
text = "19 October 2022",
style = TextStyle(
fontSize = 12.sp,
lineHeight = 18.sp,
fontWeight = FontWeight(500),
color = Color(0xFF878787),
)
)
}
if (visibility) {
CustomBottomSheet(
onRequestDismiss = { visibility = false },
sheetState = sheetState,
scope = scope,
modifier = Modifier.fillMaxWidth(),
containerColor = Color.White,
contentColor = Color.LightGray
)
}
}
}
}
| 0
| null |
2
| 9
|
228f663f7c53683d34528ea6fd437357bfe05a92
| 9,470
|
macao-marketplace
|
The Unlicense
|
src/commonMain/kotlin/dev/zacsweers/ReadMeUpdater.kt
|
ZacSweers
| 288,008,412
| false
|
{"Kotlin": 22893, "HTML": 202, "Shell": 86}
|
package dev.zacsweers
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlinx.serialization.json.Json
import nl.adaptivity.xmlutil.serialization.XML
class ReadMeUpdater {
private val client = httpClient {
install(HttpRequestRetry) {
retryOnExceptionOrServerErrors(maxRetries = 2)
exponentialDelay()
}
install(ContentNegotiation) {
json(json = Json { ignoreUnknownKeys = true })
xml(
format = XML { defaultPolicy { ignoreUnknownChildren() } },
contentType = ContentType.Text.Xml,
)
}
}
suspend fun generateReadme(): String {
return withContext(Dispatchers.Default) {
val githubActivity = async { fetchGithubActivity() }
val blogActivity = async { fetchBlogActivity() }
// Fetch in parallel
createReadMe(githubActivity.await(), blogActivity.await())
}
}
private suspend fun fetchBlogActivity(): List<ActivityItem> {
val blogApi = BlogApi.create(client)
val feed =
try {
blogApi.main()
} catch (e: Exception) {
println("Could not load blog content.")
e.printStackTrace()
return listOf(
ActivityItem("Could not load blog content. Please check back later.", Clock.System.now())
)
}
return feed.channel.items
.map { entry ->
ActivityItem(text = "[${entry.title}](${entry.link})", timestamp = entry.pubDate)
}
.take(10)
}
private suspend fun fetchGithubActivity(): List<ActivityItem> {
val githubApi = GitHubApi.create(client)
val events =
try {
githubApi.getUserActivity("ZacSweers")
} catch (e: Exception) {
println("Could not load GitHub activity.")
e.printStackTrace()
return listOf(
ActivityItem(
"Could not load GitHub activity. Please check back later.",
Clock.System.now(),
)
)
}
return events
.filter { it.public }
.mapNotNull { event ->
when (val payload = event.payload) {
UnknownPayload,
null -> return@mapNotNull null
is IssuesEventPayload -> {
ActivityItem(
"${payload.action} issue [#${payload.issue.number}](${payload.issue.htmlUrl}) on ${event.repo?.markdownUrl()}: \"${payload.issue.title}\"",
event.createdAt,
)
}
is IssueCommentEventPayload -> {
ActivityItem(
"commented on [#${payload.issue.number}](${payload.comment.htmlUrl}) in ${event.repo?.markdownUrl()}",
event.createdAt,
)
}
is PullRequestPayload -> {
val action = if (payload.pullRequest.merged == true) "merged" else payload.action
ActivityItem(
"$action PR [#${payload.number}](${payload.pullRequest.htmlUrl}) to ${event.repo?.markdownUrl()}: \"${payload.pullRequest.title}\"",
event.createdAt,
)
}
is CreateEvent -> {
ActivityItem(
"created ${payload.refType}${payload.ref?.let { " `$it`" } ?: ""} on ${event.repo?.markdownUrl()}",
event.createdAt,
)
}
is DeleteEvent -> {
if (payload.refType == "branch") {
// Filter out branch deletions
// https://github.com/ZacSweers/ZacSweers/issues/65
return@mapNotNull null
}
ActivityItem(
"deleted ${payload.refType}${payload.ref?.let { " `$it`" } ?: ""} on ${event.repo?.markdownUrl()}",
event.createdAt,
)
}
}
}
.take(10)
}
data class ActivityItem(val text: String, val timestamp: Instant) {
override fun toString() =
"**${timestamp.toLocalDateTime(TimeZone.of("America/New_York")).date}** — $text"
}
}
| 4
|
Kotlin
|
1
| 15
|
4c8e6ce86d7015ac4cd3847950f6ce7fa5d05fad
| 4,269
|
ZacSweers
|
Apache License 2.0
|
section8/android/app/src/main/kotlin/com/example/section8/MainActivity.kt
|
jiahaoliuliu
| 471,318,181
| false
|
{"Dart": 174507, "C++": 100484, "CMake": 82677, "HTML": 22900, "Ruby": 8055, "Swift": 6932, "C": 6434, "Java": 2243, "Objective-C": 2193, "Kotlin": 905}
|
package com.example.section8
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
a688de6bc68a9f498c0e86389f2efc9c8c106d44
| 125
|
FlutterAndDartTheCompleteGuide-2022Edition
|
Apache License 2.0
|
example/kotlin/jimmer-sql-graphql-kt/src/main/kotlin/org/babyfish/jimmer/example/kt/graphql/dal/BookStoreRepository.kt
|
babyfish-ct
| 488,154,823
| false
| null |
package org.babyfish.jimmer.example.kt.graphql.dal
import org.babyfish.jimmer.example.kt.graphql.entities.*
import org.babyfish.jimmer.spring.repository.KRepository
interface BookStoreRepository : KRepository<BookStore, Long> {
fun findByNameLikeOrderByName(name: String?): List<BookStore>
}
| 10
| null |
53
| 467
|
913955f5a97fda92567f6a727d3c3491e333cab9
| 298
|
jimmer
|
Apache License 2.0
|
knear-sdk/src/main/java/com/knear/android/service/AndroidKeyStore.kt
|
near
| 514,329,257
| false
| null |
package com.knear.android.service
import android.content.SharedPreferences
import com.knear.android.scheme.KeyPair
import com.knear.android.scheme.KeyPairEd25519
class AndroidKeyStore(sharedPreferences: SharedPreferences) {
private val sharedPreferences = sharedPreferences
private val editor: SharedPreferences.Editor
init {
sharedPreferences.edit().also { this.editor = it }
}
fun setAccountId(accountId: String) {
editor.putString("accountId", accountId)
editor.commit()
}
fun getAccountId() : String? {
return this.sharedPreferences.getString("accountId", "")
}
fun setNetworkId(networkId: String) {
editor.putString("networkId", networkId)
editor.commit()
}
fun getNetworkId(): String? {
return this.sharedPreferences.getString("networkId", "")
}
fun setKey(networkId: String, accountId: String, secretKey: KeyPairEd25519) {
editor.putString("$accountId:$networkId", secretKey.toString())
editor.putString("$accountId:$networkId:public", secretKey.publicKey.toString())
editor.commit()
}
fun getKey(networkId: String, accountId: String) : KeyPairEd25519? {
val secretKey = sharedPreferences.getString("$accountId:$networkId", "")
val publicKey = sharedPreferences.getString("$accountId:$networkId:public", "")
if(secretKey.isNullOrEmpty()) {
return null
}
if(publicKey.isNullOrEmpty()) {
return null
}
return KeyPair.fromStringKeyPair(secretKey, publicKey)
}
fun removeKey(networkId: String, accountId: String) {
editor.remove("$accountId:$networkId")
editor.remove("$accountId:$networkId:public")
editor.commit()
}
fun clear() {
editor.clear()
editor.commit()
}
override fun toString(): String {
return "AndroidKeyStore"
}
}
| 1
| null |
3
| 17
|
0f41802b2dcde996b4b0a9d369fc1ff3f8aede24
| 1,942
|
near-api-kotlin
|
MIT License
|
app/src/main/kotlin/jp/hotdrop/comlis/view/activity/CompanyRegisterActivity.kt
|
hotdrop
| 85,482,160
| false
| null |
package jp.hotdrop.comlis.view.activity
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.Fragment
import jp.hotdrop.comlis.R
import jp.hotdrop.comlis.databinding.ActivityCompanyRegisterBinding
import jp.hotdrop.comlis.view.fragment.CompanyRegisterFragment
class CompanyRegisterActivity : BaseActivity() {
companion object {
val EXTRA_TAB_NAME = "tabName"
fun startForResult(fragment: Fragment, tabName: String?, requestCode: Int) {
val intent = Intent(fragment.context, CompanyRegisterActivity::class.java).apply{
putExtra(EXTRA_TAB_NAME, tabName)
}
fragment.startActivityForResult(intent, requestCode)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityCompanyRegisterBinding>(this, R.layout.activity_company_register)
getComponent().inject(this)
setSupportActionBar(binding.toolbar)
supportActionBar?.run {
title = binding.toolbar.title
setDisplayHomeAsUpEnabled(true)
}
val tabName = intent.getStringExtra(EXTRA_TAB_NAME)
replaceFragment(CompanyRegisterFragment.create(tabName), R.id.content_view)
}
}
| 1
|
Kotlin
|
1
| 3
|
6530a21e691ac5c9af16e2de0c0020a5ea2956bb
| 1,365
|
comlis-android-app
|
Apache License 2.0
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/servicediscovery/CfnPublicDnsNamespace.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 140726596}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.servicediscovery
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.ITaggable
import io.cloudshiftdev.awscdk.TagManager
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import kotlin.Any
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* Creates a public namespace based on DNS, which is visible on the internet.
*
* The namespace defines your service naming scheme. For example, if you name your namespace
* `example.com` and name your service `backend` , the resulting DNS name for the service is
* `backend.example.com` . You can discover instances that were registered with a public DNS namespace
* by using either a `DiscoverInstances` request or using DNS. For the current quota on the number of
* namespaces that you can create using the same AWS account , see [AWS Cloud Map
* quotas](https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) in the *AWS Cloud Map
* Developer Guide* .
*
*
* The `CreatePublicDnsNamespace` API operation is not supported in the AWS GovCloud (US) Regions.
*
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.servicediscovery.*;
* CfnPublicDnsNamespace cfnPublicDnsNamespace = CfnPublicDnsNamespace.Builder.create(this,
* "MyCfnPublicDnsNamespace")
* .name("name")
* // the properties below are optional
* .description("description")
* .properties(PropertiesProperty.builder()
* .dnsProperties(PublicDnsPropertiesMutableProperty.builder()
* .soa(SOAProperty.builder()
* .ttl(123)
* .build())
* .build())
* .build())
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html)
*/
public open class CfnPublicDnsNamespace internal constructor(
internal override val cdkObject:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace,
) : CfnResource(cdkObject), IInspectable, ITaggable {
/**
* The Amazon Resource Name (ARN) of the public namespace.
*/
public open fun attrArn(): String = unwrap(this).getAttrArn()
/**
* The ID for the Route 53 hosted zone that AWS Cloud Map creates when you create a namespace.
*/
public open fun attrHostedZoneId(): String = unwrap(this).getAttrHostedZoneId()
/**
* The ID of the public namespace.
*/
public open fun attrId(): String = unwrap(this).getAttrId()
/**
* A description for the namespace.
*/
public open fun description(): String? = unwrap(this).getDescription()
/**
* A description for the namespace.
*/
public open fun description(`value`: String) {
unwrap(this).setDescription(`value`)
}
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector::unwrap))
}
/**
* The name that you want to assign to this namespace.
*/
public open fun name(): String = unwrap(this).getName()
/**
* The name that you want to assign to this namespace.
*/
public open fun name(`value`: String) {
unwrap(this).setName(`value`)
}
/**
* Properties for the public DNS namespace.
*/
public open fun properties(): Any? = unwrap(this).getProperties()
/**
* Properties for the public DNS namespace.
*/
public open fun properties(`value`: IResolvable) {
unwrap(this).setProperties(`value`.let(IResolvable::unwrap))
}
/**
* Properties for the public DNS namespace.
*/
public open fun properties(`value`: PropertiesProperty) {
unwrap(this).setProperties(`value`.let(PropertiesProperty::unwrap))
}
/**
* Properties for the public DNS namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("9f10d90a6a8a424f9a52868c9a8528cb61930a2dd90cedacc9edb450fd0dd1c6")
public open fun properties(`value`: PropertiesProperty.Builder.() -> Unit): Unit =
properties(PropertiesProperty(`value`))
/**
* Tag Manager which manages the tags for this resource.
*/
public override fun tags(): TagManager = unwrap(this).getTags().let(TagManager::wrap)
/**
* The tags for the namespace.
*/
public open fun tagsRaw(): List<CfnTag> = unwrap(this).getTagsRaw()?.map(CfnTag::wrap) ?:
emptyList()
/**
* The tags for the namespace.
*/
public open fun tagsRaw(`value`: List<CfnTag>) {
unwrap(this).setTagsRaw(`value`.map(CfnTag::unwrap))
}
/**
* The tags for the namespace.
*/
public open fun tagsRaw(vararg `value`: CfnTag): Unit = tagsRaw(`value`.toList())
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.servicediscovery.CfnPublicDnsNamespace].
*/
@CdkDslMarker
public interface Builder {
/**
* A description for the namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-description)
* @param description A description for the namespace.
*/
public fun description(description: String)
/**
* The name that you want to assign to this namespace.
*
*
* Do not include sensitive information in the name. The name is publicly available using DNS
* queries.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-name)
* @param name The name that you want to assign to this namespace.
*/
public fun name(name: String)
/**
* Properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-properties)
* @param properties Properties for the public DNS namespace.
*/
public fun properties(properties: IResolvable)
/**
* Properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-properties)
* @param properties Properties for the public DNS namespace.
*/
public fun properties(properties: PropertiesProperty)
/**
* Properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-properties)
* @param properties Properties for the public DNS namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("ec65c54f9f8faaa58126c9a09c8cc1d8e899fa1563d164d6f9e5bb2b1f0ac8b2")
public fun properties(properties: PropertiesProperty.Builder.() -> Unit)
/**
* The tags for the namespace.
*
* Each tag consists of a key and an optional value, both of which you define. Tag keys can have
* a maximum character length of 128 characters, and tag values can have a maximum length of 256
* characters.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-tags)
* @param tags The tags for the namespace.
*/
public fun tags(tags: List<CfnTag>)
/**
* The tags for the namespace.
*
* Each tag consists of a key and an optional value, both of which you define. Tag keys can have
* a maximum character length of 128 characters, and tag values can have a maximum length of 256
* characters.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-tags)
* @param tags The tags for the namespace.
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.Builder =
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.Builder.create(scope,
id)
/**
* A description for the namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-description)
* @param description A description for the namespace.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* The name that you want to assign to this namespace.
*
*
* Do not include sensitive information in the name. The name is publicly available using DNS
* queries.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-name)
* @param name The name that you want to assign to this namespace.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* Properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-properties)
* @param properties Properties for the public DNS namespace.
*/
override fun properties(properties: IResolvable) {
cdkBuilder.properties(properties.let(IResolvable::unwrap))
}
/**
* Properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-properties)
* @param properties Properties for the public DNS namespace.
*/
override fun properties(properties: PropertiesProperty) {
cdkBuilder.properties(properties.let(PropertiesProperty::unwrap))
}
/**
* Properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-properties)
* @param properties Properties for the public DNS namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("ec65c54f9f8faaa58126c9a09c8cc1d8e899fa1563d164d6f9e5bb2b1f0ac8b2")
override fun properties(properties: PropertiesProperty.Builder.() -> Unit): Unit =
properties(PropertiesProperty(properties))
/**
* The tags for the namespace.
*
* Each tag consists of a key and an optional value, both of which you define. Tag keys can have
* a maximum character length of 128 characters, and tag values can have a maximum length of 256
* characters.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-tags)
* @param tags The tags for the namespace.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag::unwrap))
}
/**
* The tags for the namespace.
*
* Each tag consists of a key and an optional value, both of which you define. Tag keys can have
* a maximum character length of 128 characters, and tag values can have a maximum length of 256
* characters.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicediscovery-publicdnsnamespace.html#cfn-servicediscovery-publicdnsnamespace-tags)
* @param tags The tags for the namespace.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace =
cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnPublicDnsNamespace {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnPublicDnsNamespace(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace):
CfnPublicDnsNamespace = CfnPublicDnsNamespace(cdkObject)
internal fun unwrap(wrapped: CfnPublicDnsNamespace):
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace = wrapped.cdkObject
}
/**
* DNS properties for the public DNS namespace.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.servicediscovery.*;
* PublicDnsPropertiesMutableProperty publicDnsPropertiesMutableProperty =
* PublicDnsPropertiesMutableProperty.builder()
* .soa(SOAProperty.builder()
* .ttl(123)
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-publicdnspropertiesmutable.html)
*/
public interface PublicDnsPropertiesMutableProperty {
/**
* Start of Authority (SOA) record for the hosted zone for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-publicdnspropertiesmutable.html#cfn-servicediscovery-publicdnsnamespace-publicdnspropertiesmutable-soa)
*/
public fun soa(): Any? = unwrap(this).getSoa()
/**
* A builder for [PublicDnsPropertiesMutableProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param soa Start of Authority (SOA) record for the hosted zone for the public DNS
* namespace.
*/
public fun soa(soa: IResolvable)
/**
* @param soa Start of Authority (SOA) record for the hosted zone for the public DNS
* namespace.
*/
public fun soa(soa: SOAProperty)
/**
* @param soa Start of Authority (SOA) record for the hosted zone for the public DNS
* namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("03c0db80c8d39476babdae6143d0dbe5590d56cafd6fd9ff6fe00a09291a2798")
public fun soa(soa: SOAProperty.Builder.() -> Unit)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty.Builder
=
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty.builder()
/**
* @param soa Start of Authority (SOA) record for the hosted zone for the public DNS
* namespace.
*/
override fun soa(soa: IResolvable) {
cdkBuilder.soa(soa.let(IResolvable::unwrap))
}
/**
* @param soa Start of Authority (SOA) record for the hosted zone for the public DNS
* namespace.
*/
override fun soa(soa: SOAProperty) {
cdkBuilder.soa(soa.let(SOAProperty::unwrap))
}
/**
* @param soa Start of Authority (SOA) record for the hosted zone for the public DNS
* namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("03c0db80c8d39476babdae6143d0dbe5590d56cafd6fd9ff6fe00a09291a2798")
override fun soa(soa: SOAProperty.Builder.() -> Unit): Unit = soa(SOAProperty(soa))
public fun build():
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty
= cdkBuilder.build()
}
private class Wrapper(
override val cdkObject:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty,
) : CdkObject(cdkObject), PublicDnsPropertiesMutableProperty {
/**
* Start of Authority (SOA) record for the hosted zone for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-publicdnspropertiesmutable.html#cfn-servicediscovery-publicdnsnamespace-publicdnspropertiesmutable-soa)
*/
override fun soa(): Any? = unwrap(this).getSoa()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}):
PublicDnsPropertiesMutableProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty):
PublicDnsPropertiesMutableProperty = Wrapper(cdkObject)
internal fun unwrap(wrapped: PublicDnsPropertiesMutableProperty):
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty
= (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PublicDnsPropertiesMutableProperty
}
}
/**
* Start of Authority (SOA) properties for a public or private DNS namespace.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.servicediscovery.*;
* SOAProperty sOAProperty = SOAProperty.builder()
* .ttl(123)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-soa.html)
*/
public interface SOAProperty {
/**
* The time to live (TTL) for purposes of negative caching.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-soa.html#cfn-servicediscovery-publicdnsnamespace-soa-ttl)
*/
public fun ttl(): Number? = unwrap(this).getTtl()
/**
* A builder for [SOAProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param ttl The time to live (TTL) for purposes of negative caching.
*/
public fun ttl(ttl: Number)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty.Builder
=
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty.builder()
/**
* @param ttl The time to live (TTL) for purposes of negative caching.
*/
override fun ttl(ttl: Number) {
cdkBuilder.ttl(ttl)
}
public fun build():
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty =
cdkBuilder.build()
}
private class Wrapper(
override val cdkObject:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty,
) : CdkObject(cdkObject), SOAProperty {
/**
* The time to live (TTL) for purposes of negative caching.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-soa.html#cfn-servicediscovery-publicdnsnamespace-soa-ttl)
*/
override fun ttl(): Number? = unwrap(this).getTtl()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): SOAProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty):
SOAProperty = Wrapper(cdkObject)
internal fun unwrap(wrapped: SOAProperty):
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty =
(wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.SOAProperty
}
}
/**
* Properties for the public DNS namespace.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.servicediscovery.*;
* PropertiesProperty propertiesProperty = PropertiesProperty.builder()
* .dnsProperties(PublicDnsPropertiesMutableProperty.builder()
* .soa(SOAProperty.builder()
* .ttl(123)
* .build())
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-properties.html)
*/
public interface PropertiesProperty {
/**
* DNS properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-properties.html#cfn-servicediscovery-publicdnsnamespace-properties-dnsproperties)
*/
public fun dnsProperties(): Any? = unwrap(this).getDnsProperties()
/**
* A builder for [PropertiesProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param dnsProperties DNS properties for the public DNS namespace.
*/
public fun dnsProperties(dnsProperties: IResolvable)
/**
* @param dnsProperties DNS properties for the public DNS namespace.
*/
public fun dnsProperties(dnsProperties: PublicDnsPropertiesMutableProperty)
/**
* @param dnsProperties DNS properties for the public DNS namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("24603897dd76d22da75f2f4b4a992f0dd56b12da7508ba55d2bf27269ca78942")
public fun dnsProperties(dnsProperties: PublicDnsPropertiesMutableProperty.Builder.() -> Unit)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty.Builder
=
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty.builder()
/**
* @param dnsProperties DNS properties for the public DNS namespace.
*/
override fun dnsProperties(dnsProperties: IResolvable) {
cdkBuilder.dnsProperties(dnsProperties.let(IResolvable::unwrap))
}
/**
* @param dnsProperties DNS properties for the public DNS namespace.
*/
override fun dnsProperties(dnsProperties: PublicDnsPropertiesMutableProperty) {
cdkBuilder.dnsProperties(dnsProperties.let(PublicDnsPropertiesMutableProperty::unwrap))
}
/**
* @param dnsProperties DNS properties for the public DNS namespace.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("24603897dd76d22da75f2f4b4a992f0dd56b12da7508ba55d2bf27269ca78942")
override
fun dnsProperties(dnsProperties: PublicDnsPropertiesMutableProperty.Builder.() -> Unit):
Unit = dnsProperties(PublicDnsPropertiesMutableProperty(dnsProperties))
public fun build():
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty
= cdkBuilder.build()
}
private class Wrapper(
override val cdkObject:
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty,
) : CdkObject(cdkObject), PropertiesProperty {
/**
* DNS properties for the public DNS namespace.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-publicdnsnamespace-properties.html#cfn-servicediscovery-publicdnsnamespace-properties-dnsproperties)
*/
override fun dnsProperties(): Any? = unwrap(this).getDnsProperties()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): PropertiesProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty):
PropertiesProperty = Wrapper(cdkObject)
internal fun unwrap(wrapped: PropertiesProperty):
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty
= (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.servicediscovery.CfnPublicDnsNamespace.PropertiesProperty
}
}
}
| 1
|
Kotlin
|
0
| 4
|
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
| 26,327
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
app/src/main/java/com/yazan98/autohub/utils/HomeViewPagerAdapter.kt
|
Yazan98
| 249,245,576
| false
| null |
package com.yazan98.autohub.utils
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.yazan98.autohub.fragments.main.FeedFragment
import com.yazan98.autohub.fragments.main.NotificationsFragment
import com.yazan98.autohub.fragments.main.ProfileFragment
class HomeViewPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> FeedFragment()
1 -> NotificationsFragment()
2 -> ProfileFragment()
else -> NotificationsFragment()
}
}
override fun getCount(): Int {
return 3
}
}
| 0
|
Kotlin
|
0
| 1
|
2f03f85f1be1af101029b8424a09ae241c03ef42
| 749
|
Github-Client
|
Apache License 2.0
|
app/src/main/java/me/hufman/androidautoidrive/phoneui/viewmodels/MusicAppsViewModel.kt
|
BimmerGestalt
| 164,273,785
| false
| null |
package me.hufman.androidautoidrive.phoneui.viewmodels
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import me.hufman.androidautoidrive.music.MusicAppInfo
import me.hufman.androidautoidrive.phoneui.MusicAppDiscoveryThread
class MusicAppsViewModel(val musicAppDiscoveryThread: MusicAppDiscoveryThread): ViewModel() {
class Factory(val appContext: Context): ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var model: MusicAppsViewModel? = null
val handler = Handler(Looper.getMainLooper()) // UI thread handler
val thread = MusicAppDiscoveryThread(appContext) { _ ->
handler.post {
model?.update()
}
}.apply { start() }
model = MusicAppsViewModel(thread)
return model as T
}
}
// TODO: Replace with https://github.com/evant/binding-collection-adapter
val allApps: ObservableList<MusicAppInfo> = ObservableArrayList()
val validApps: ObservableList<MusicAppInfo> = ObservableArrayList()
fun update() {
allApps.clear()
allApps.addAll(musicAppDiscoveryThread.discovery?.allApps ?: emptyList())
validApps.clear()
validApps.addAll(musicAppDiscoveryThread.discovery?.validApps ?: emptyList())
}
override fun onCleared() {
super.onCleared()
musicAppDiscoveryThread.callback = null
musicAppDiscoveryThread.stopDiscovery()
}
}
| 51
| null |
90
| 546
|
ea49ba17a18c353a8ba55f5040e8e4321bf14bd7
| 1,559
|
AAIdrive
|
MIT License
|
app/src/test/kotlin/net/rubygrapefruit/gen/builders/InternalLibrariesBuilderTest.kt
|
adammurdoch
| 430,814,411
| false
|
{"Kotlin": 181951}
|
package net.rubygrapefruit.gen.builders
import net.rubygrapefruit.gen.specs.InternalLibraryProductionSpec
import net.rubygrapefruit.gen.specs.Names
import net.rubygrapefruit.gen.specs.TypedNameProvider
import net.rubygrapefruit.gen.templates.Implementation
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class InternalLibrariesBuilderTest {
val names = Names()
val builder = InternalLibrariesBuilder(TypedNameProvider.of(names.names("top"), names.names("lib"), names.names("bottom")), Implementation.Java.librarySpecFactory)
@Test
fun canBeEmpty() {
assertEquals(0, builder.currentSize)
assertTrue(builder.exportedLibraries.libraries.isEmpty())
assertTrue(builder.contents.isEmpty())
assertTrue(builder.leaves.isEmpty())
}
@Test
fun canContainOne() {
builder.add(1)
assertEquals(1, builder.currentSize)
assertEquals(1, builder.contents.size)
assertEquals(listOf("bottom"), builder.contents.map { it.baseName.camelCase })
assertEquals(1, builder.exportedLibraries.libraries.size)
assertEquals(1, builder.leaves.size)
}
@Test
fun canContainTwo() {
builder.add(2)
assertEquals(2, builder.currentSize)
assertEquals(2, builder.contents.size)
assertEquals(1, builder.exportedLibraries.libraries.size)
assertEquals(listOf("top"), builder.exportedLibraries.libraries.map { it.baseName.camelCase })
assertEquals(1, builder.leaves.size)
assertEquals(listOf("bottom"), builder.leaves.map { it.baseName.camelCase })
}
@Test
fun canContainThree() {
builder.add(3)
assertEquals(3, builder.currentSize)
assertEquals(3, builder.contents.size)
assertEquals(1, builder.exportedLibraries.libraries.size)
assertEquals(listOf("top"), builder.exportedLibraries.libraries.map { it.baseName.camelCase })
assertEquals(2, builder.leaves.size) // internal dependency is only used by top
assertEquals(listOf("lib", "bottom"), builder.leaves.map { it.baseName.camelCase })
}
@Test
fun canContainFour() {
builder.add(4)
assertEquals(4, builder.currentSize)
assertEquals(4, builder.contents.size)
assertEquals(1, builder.exportedLibraries.libraries.size)
assertEquals(listOf("top"), builder.exportedLibraries.libraries.map { it.baseName.camelCase })
assertEquals(2, builder.leaves.size)
assertEquals(listOf("lib2", "bottom"), builder.leaves.map { it.baseName.camelCase })
}
@Test
fun canContainNine() {
builder.add(9)
assertEquals(9, builder.currentSize)
assertEquals(9, builder.contents.size)
assertEquals(2, builder.exportedLibraries.libraries.size)
assertEquals(listOf("top", "top2"), builder.exportedLibraries.libraries.map { it.baseName.camelCase })
assertEquals(4, builder.leaves.size)
assertEquals(listOf("lib5", "lib4", "lib2", "bottom"), builder.leaves.map { it.baseName.camelCase })
}
val InternalLibrariesBuilder.leaves: List<InternalLibraryProductionSpec> get() = contents.filter { it.usesImplementationLibraries.isEmpty() }
}
| 0
|
Kotlin
|
0
| 0
|
0d47884136b4764f7dc901009614cfe435de5dda
| 3,249
|
build-gen
|
Apache License 2.0
|
app/src/main/java/com/kylecorry/trail_sense/calibration/ui/CameraSettingsFragment.kt
|
kylecorry31
| 215,154,276
| false
|
{"Kotlin": 2452605, "Python": 20960, "HTML": 18863, "Shell": 5290, "CSS": 5120, "JavaScript": 3809, "Batchfile": 2553}
|
package com.kylecorry.trail_sense.calibration.ui
import android.os.Bundle
import com.kylecorry.andromeda.fragments.AndromedaPreferenceFragment
import com.kylecorry.trail_sense.R
import com.kylecorry.trail_sense.settings.infrastructure.AugmentedRealityPreferences
class CameraSettingsFragment : AndromedaPreferenceFragment() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.camera_preferences, rootKey)
// Set the projection type options
val names = mapOf(
AugmentedRealityPreferences.ProjectionType.EstimatedIntrinsics to "${getString(R.string.projection_estimated_intrinsics)} (${
getString(R.string.default_string)
})",
AugmentedRealityPreferences.ProjectionType.ManufacturerIntrinsics to getString(R.string.projection_manufacturer_intrinsics),
AugmentedRealityPreferences.ProjectionType.Perspective to getString(R.string.projection_perspective),
AugmentedRealityPreferences.ProjectionType.Linear to getString(R.string.projection_linear)
)
val ids = names.map { it.key.id }
val projectionType = list(R.string.pref_augmented_reality_mapper)
projectionType?.entries = names.values.toTypedArray()
projectionType?.entryValues = ids.toTypedArray()
}
}
| 446
|
Kotlin
|
66
| 911
|
c25a021b43cd0046d78ce70f727cd3bac0d4c276
| 1,369
|
Trail-Sense
|
MIT License
|
nebulosa-fits/src/main/kotlin/nebulosa/fits/FitsHelper.kt
|
tiagohm
| 568,578,345
| false
|
{"Kotlin": 2247410, "TypeScript": 359962, "HTML": 189644, "SCSS": 10196, "Python": 2817, "JavaScript": 1165}
|
@file:Suppress("NOTHING_TO_INLINE")
package nebulosa.fits
import nebulosa.io.SeekableSource
import nebulosa.math.Angle
import nebulosa.math.deg
import java.io.File
import java.nio.file.Path
import java.time.Duration
import java.time.LocalDateTime
inline fun Header.clone() = Header(this)
inline val Header.naxis
get() = getInt(Standard.NAXIS, -1)
inline fun Header.naxis(n: Int) = getInt(Standard.NAXISn.n(n), 0)
inline val Header.width
get() = getInt(Standard.NAXIS1, 0)
inline val Header.height
get() = getInt(Standard.NAXIS2, 0)
val Header.rightAscension
get() = Angle(getStringOrNull(Standard.RA), isHours = true, decimalIsHours = false).takeIf { it.isFinite() }
?: Angle(getStringOrNull(SBFitsExt.OBJCTRA), true).takeIf { it.isFinite() }
?: getDouble(NOAOExt.CRVAL1, Double.NaN).deg
val Header.declination
get() = Angle(getStringOrNull(Standard.DEC)).takeIf { it.isFinite() }
?: Angle(getStringOrNull(SBFitsExt.OBJCTDEC)).takeIf { it.isFinite() }
?: getDouble(NOAOExt.CRVAL2, Double.NaN).deg
inline val Header.binX
get() = getInt(SBFitsExt.XBINNING, 1)
inline val Header.binY
get() = getIntOrNull(SBFitsExt.YBINNING) ?: binX
inline val Header.exposureTimeInSeconds
get() = getDoubleOrNull(Standard.EXPTIME) ?: getDouble(Standard.EXPOSURE, 0.0)
inline val Header.exposureTime: Duration
get() = Duration.ofNanos((exposureTimeInSeconds * 1000000000.0).toLong())
inline val Header.exposureTimeInMicroseconds
get() = (exposureTimeInSeconds * 1000000.0).toLong()
const val INVALID_TEMPERATURE = 999.0
inline val Header.temperature
get() = getDoubleOrNull(NOAOExt.CCDTEM) ?: getDouble(SBFitsExt.CCD_TEMP, INVALID_TEMPERATURE)
inline val Header.gain
get() = getDouble(NOAOExt.GAIN, 0.0)
inline val Header.latitude
get() = (getDoubleOrNull(SBFitsExt.SITELAT) ?: getDoubleOrNull("LAT-OBS"))?.deg
inline val Header.longitude
get() = (getDoubleOrNull(SBFitsExt.SITELONG) ?: getDoubleOrNull("LONG-OBS"))?.deg
inline val Header.observationDate
get() = getStringOrNull(Standard.DATE_OBS)?.let(LocalDateTime::parse)
inline val Header.cfaPattern
get() = getStringOrNull(MaxImDLExt.BAYERPAT)?.ifBlank { null }?.trim()
inline val Header.filter
get() = getStringOrNull(Standard.FILTER)?.ifBlank { null }?.trim()
inline val Header.frame
get() = (getStringOrNull("FRAME") ?: getStringOrNull(SBFitsExt.IMAGETYP))?.ifBlank { null }?.trim()
inline val Header.instrument
get() = getStringOrNull(Standard.INSTRUME)?.ifBlank { null }?.trim()
inline fun SeekableSource.fits() = Fits().also { it.read(this) }
inline fun String.fits() = FitsPath(this).also(FitsPath::read)
inline fun Path.fits() = FitsPath(this).also(FitsPath::read)
inline fun File.fits() = FitsPath(this).also(FitsPath::read)
| 4
|
Kotlin
|
1
| 2
|
64201aa97326943b36f470c06a9ac4b5b57f0a14
| 2,805
|
nebulosa
|
MIT License
|
app/src/main/java/com/dart/campushelper/ui/component/Modifier.kt
|
founchoo
| 694,453,265
| false
|
{"Kotlin": 311228}
|
package com.dart.campushelper.ui.component
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
fun Modifier.fadingEdge(brush: Brush) = this
.graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)
.drawWithContent {
drawContent()
drawRect(brush = brush, blendMode = BlendMode.DstIn)
}
fun Modifier.defaultHorizontalFadingEdge() = this.fadingEdge(
Brush.horizontalGradient(
0f to Color.Transparent,
0.05f to Color.Black,
0.95f to Color.Black,
1f to Color.Transparent
)
)
fun Modifier.defaultVerticalFadingEdge() = this.fadingEdge(
Brush.verticalGradient(
0f to Color.Transparent,
0.05f to Color.Black,
0.95f to Color.Black,
1f to Color.Transparent
)
)
| 4
|
Kotlin
|
1
| 7
|
5cd4d008b9642eda11d3e7883748afa29af2a052
| 1,042
|
GongYun-for-Android
|
Apache License 2.0
|
src/main/kotlin/me/eetgeenappels/sugoma/module/modules/combat/KillAura.kt
|
eetgeenappels
| 631,292,117
| false
| null |
package me.eetgeenappels.sugoma.module.modules.combat
import me.eetgeenappels.sugoma.Sugoma
import me.eetgeenappels.sugoma.module.Category
import me.eetgeenappels.sugoma.module.Module
import me.eetgeenappels.sugoma.module.modules.settings.ModeSetting
import me.eetgeenappels.sugoma.module.modules.settings.SliderSetting
import me.eetgeenappels.sugoma.module.modules.settings.ToggleSetting
import me.eetgeenappels.sugoma.util.CombatUtil
import net.minecraft.entity.Entity
object KillAura : Module("KillAura", "An aura that kills stuff", Category.Combat) {
val targetMode : ModeSetting = ModeSetting("TargetMode", arrayOf("Closest", "Health"))
val reach: SliderSetting = SliderSetting("Reach", 3f, 5f, 4f)
val targetPlayers: ToggleSetting = ToggleSetting("TargetPlayers", true)
val targetMobs: ToggleSetting = ToggleSetting("TargetMobs", true)
val targetAnimals: ToggleSetting = ToggleSetting("TargetAnimals", true)
override fun onTick() {
val closestEntity: Entity = CombatUtil.findTarget(
targetMobs.value,
targetAnimals.value,
targetPlayers.value,
false,
when (targetMode.currentModeString) {
"Closest" -> {0}
"Health" -> {2}
else -> {0}
},
reach.value
) ?: return
(Sugoma.moduleManager.getModule("AutoEZ") as AutoEZ).addTarget(closestEntity)
CombatUtil.attack(closestEntity, true)
}
}
| 0
|
Kotlin
|
0
| 2
|
5f926bf2f31ddce330950310690aaf74e831b0da
| 1,486
|
Sugoma
|
MIT License
|
src/main/kotlin/no/nav/dagpenger/oppdrag/domene/DetaljertSimuleringResultat.kt
|
navikt
| 596,541,750
| false
|
{"Kotlin": 163567, "Dockerfile": 120}
|
package no.nav.dagpenger.oppdrag.domene
data class DetaljertSimuleringResultat(val simuleringMottaker: List<SimuleringMottaker>)
| 11
|
Kotlin
|
0
| 0
|
7d18e53c6e47d4b9ed1137d169db6aa8f34fdc29
| 130
|
dp-oppdrag
|
MIT License
|
core/network/src/main/java/com/eshc/goonersapp/core/network/api/TeamNetworkService.kt
|
eshc123
| 640,451,475
| false
|
{"Kotlin": 399981}
|
package com.eshc.goonersapp.core.network.api
import com.eshc.goonersapp.core.network.model.BaseResponse
import com.eshc.goonersapp.core.network.model.team.RemoteTeamDetail
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
const val TEAM_BASE_URL = "/apis/team"
interface TeamNetworkService {
@GET(value = "$TEAM_BASE_URL/detail")
suspend fun getTeamDetail(
@Query("teamId") teamId : Int = 2
) : Response<BaseResponse<RemoteTeamDetail>>
}
| 2
|
Kotlin
|
1
| 1
|
ff61b4a114c65b754a7fbc92887dea051bdedbd0
| 491
|
GoonersApp
|
Apache License 2.0
|
web/src/main/kotlin/no/nav/su/se/bakover/web/routes/revurdering/InstitusjonsoppholdRoutes.kt
|
navikt
| 227,366,088
| false
|
{"Kotlin": 9236522, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800}
|
package no.nav.su.se.bakover.web.routes.revurdering
import arrow.core.getOrElse
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.call
import io.ktor.server.routing.Route
import io.ktor.server.routing.post
import no.nav.su.se.bakover.common.audit.AuditLogEvent
import no.nav.su.se.bakover.common.brukerrolle.Brukerrolle
import no.nav.su.se.bakover.common.infrastructure.web.Resultat
import no.nav.su.se.bakover.common.infrastructure.web.audit
import no.nav.su.se.bakover.common.infrastructure.web.authorize
import no.nav.su.se.bakover.common.infrastructure.web.svar
import no.nav.su.se.bakover.common.infrastructure.web.withBody
import no.nav.su.se.bakover.common.infrastructure.web.withRevurderingId
import no.nav.su.se.bakover.domain.revurdering.service.RevurderingService
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.LeggTilInstitusjonsoppholdVilkårRequest
import no.nav.su.se.bakover.web.routes.vilkår.institusjonsopphold.LeggTilVurderingsperiodeInstitusjonsoppholdJson
import no.nav.su.se.bakover.web.routes.vilkår.institusjonsopphold.tilResultat
import vilkår.formue.domain.FormuegrenserFactory
import java.time.Clock
internal fun Route.institusjonsoppholdRoutes(
revurderingService: RevurderingService,
formuegrenserFactory: FormuegrenserFactory,
clock: Clock,
) {
post("$REVURDERING_PATH/{revurderingId}/institusjonsopphold") {
authorize(Brukerrolle.Saksbehandler) {
call.withRevurderingId { revurderingId ->
call.withBody<LeggTilVurderingsperiodeInstitusjonsoppholdJson> { body ->
call.svar(
body.toDomain(clock).map { vilkår ->
revurderingService.leggTilInstitusjonsoppholdVilkår(
request = LeggTilInstitusjonsoppholdVilkårRequest(
behandlingId = revurderingId,
vilkår = vilkår,
),
).fold(
{ it.tilResultat() },
{
call.audit(it.revurdering.fnr, AuditLogEvent.Action.UPDATE, it.revurdering.id)
Resultat.json(HttpStatusCode.Created, it.json(formuegrenserFactory))
},
)
}.getOrElse { it },
)
}
}
}
}
}
| 5
|
Kotlin
|
1
| 1
|
ed28832346c1f839ea3a489eae8cc623079a0a2f
| 2,515
|
su-se-bakover
|
MIT License
|
CaptureReceipt/src/main/java/com/mytiki/capture_receipt/receipt/CouponType.kt
|
tiki
| 710,742,774
| false
|
{"Kotlin": 60471}
|
package com.mytiki.capture_receipt.receipt
enum class CouponType{
UNKNOWN,
STORE,
MFGR,
}
| 0
|
Kotlin
|
0
| 0
|
5c3734b9f9e795b76fd7b5a9cfcafaa95859d216
| 103
|
capture-receipt-android
|
MIT License
|
src/main/java/utils/BlockDetector.kt
|
DavidPav123
| 670,749,975
| false
| null |
package utils
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.entity.Player
import org.bukkit.event.Listener
import org.bukkit.util.BlockIterator
object BlockDetector : Listener {
private const val RANGE = 12
private val passableBlocks = arrayOf(
Material.AIR, Material.CAVE_AIR, Material.ITEM_FRAME, Material.GRASS,
Material.TORCH
)
/**
* Return the first Block the vector of view hits. This method ignores air.
*
* @param player The player you want to get the view vector from.
* @return Returns the block the player is looking at, if there is no in range
* it returns an air block.
*/
fun getTargetBlock(player: Player?): Block {
val iter = BlockIterator(player!!, RANGE)
var lastBlock = iter.next()
while (iter.hasNext()) {
lastBlock = iter.next()
if (isBlockPassable(lastBlock) || lastBlock.type.name.contains("SIGN")
|| lastBlock.type.name.contains("CARPET") || lastBlock.isLiquid
) {
continue
}
break
}
return lastBlock
}
/**
* Returns the Block at the Location `loc`.
*
* @param loc The Location of the block.
* @return Returns the Block at the Location `loc`.
*/
fun getBlockByLocation(loc: Location): Block {
return loc.world.getBlockAt(loc)
}
private fun isBlockPassable(block: Block): Boolean {
for (m in passableBlocks) {
if (block.type == m) return true
}
return false
}
}
| 0
|
Kotlin
|
0
| 0
|
650f380535db7538f5ca5756ec9d8d7d1b56e3f6
| 1,637
|
DavidsInventorySorter
|
MIT License
|
marker/src/main/kotlin/spp/jetbrains/marker/SourceMarker.kt
|
sourceplusplus
| 173,253,271
| false
| null |
/*
* Source++, the continuous feedback platform for developers.
* Copyright (C) 2022-2024 CodeBrig, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spp.jetbrains.marker
import com.google.common.collect.ImmutableList
import com.google.common.collect.Lists
import com.google.common.collect.Maps
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiFile
import spp.jetbrains.marker.service.ArtifactNamingService
import spp.jetbrains.marker.service.SourceGuideProvider
import spp.jetbrains.marker.source.SourceFileMarker
import spp.jetbrains.marker.source.mark.api.SourceMark
import spp.jetbrains.marker.source.mark.api.event.SourceMarkEventListener
import spp.jetbrains.marker.source.mark.guide.GuideMark
import spp.jetbrains.marker.source.mark.gutter.GutterMark
import spp.jetbrains.marker.source.mark.inlay.InlayMark
import spp.jetbrains.status.SourceStatusService
import spp.protocol.artifact.ArtifactQualifiedName
/**
* Holds a collection of [SourceFileMarker]s for a given [Project].
*
* @since 0.1.0
* @author [<NAME>](mailto:<EMAIL>)
*/
class SourceMarker(private val project: Project) {
companion object {
var PLUGIN_NAME = "SourceMarker"
private val log = logger<SourceMarker>()
private val KEY = Key.create<SourceMarker>("SPP_SOURCE_MARKER")
@JvmStatic
@Synchronized
fun getInstance(project: Project): SourceMarker {
if (project.getUserData(KEY) == null) {
val sourceMarker = SourceMarker(project)
project.putUserData(KEY, sourceMarker)
}
return project.getUserData(KEY)!!
}
fun getSourceFileMarker(psiFile: PsiFile): SourceFileMarker? {
return getInstance(psiFile.project).getSourceFileMarker(psiFile)
}
}
val configuration: SourceMarkerConfiguration = SourceMarkerConfiguration()
private val availableSourceFileMarkers = Maps.newConcurrentMap<Int, SourceFileMarker>()
private val globalSourceMarkEventListeners = Lists.newArrayList<SourceMarkEventListener>()
fun getSourceFileMarkers(): List<SourceFileMarker> {
return availableSourceFileMarkers.values.toList()
}
fun clearAvailableSourceFileMarkers() {
availableSourceFileMarkers.forEach {
deactivateSourceFileMarker(it.value)
}
availableSourceFileMarkers.clear()
}
fun deactivateSourceFileMarker(sourceFileMarker: SourceFileMarker): Boolean {
if (availableSourceFileMarkers.remove(sourceFileMarker.hashCode()) != null) {
sourceFileMarker.clearSourceMarks()
sourceFileMarker.psiFile.putUserData(SourceFileMarker.KEY, null)
log.info("Deactivated source file marker: $sourceFileMarker")
return true
}
return false
}
fun getSourceFileMarkerIfExists(psiFile: PsiFile): SourceFileMarker? {
return psiFile.getUserData(SourceFileMarker.KEY)
}
fun getSourceFileMarker(psiFile: PsiFile): SourceFileMarker? {
var fileMarker = psiFile.getUserData(SourceFileMarker.KEY)
if (fileMarker != null) {
return fileMarker
} else if (!SourceFileMarker.isFileSupported(psiFile)) {
log.trace("File type not setup: ${psiFile.fileType.name}")
return null
} else if (psiFile.virtualFile == null || !psiFile.virtualFile.isInLocalFileSystem) {
log.trace("Skipping in-memory/non-local file: $psiFile")
return null
} else if (!ApplicationManager.getApplication().isUnitTestMode) {
if (!SourceStatusService.getInstance(project).isConnected()) {
log.warn("Not connected, skipping source file marker creation for: $psiFile")
return null
}
}
fileMarker = configuration.sourceFileMarkerProvider.createSourceFileMarker(psiFile)
availableSourceFileMarkers.putIfAbsent(psiFile.hashCode(), fileMarker)
fileMarker = availableSourceFileMarkers[psiFile.hashCode()]!!
psiFile.putUserData(SourceFileMarker.KEY, fileMarker)
SourceGuideProvider.determineGuideMarks(fileMarker)
return fileMarker
}
fun getSourceFileMarker(qualifiedClassNameOrFilename: String): SourceFileMarker? {
return ArtifactNamingService.findPsiFile(project, qualifiedClassNameOrFilename)
?.let { getSourceFileMarker(it) }
}
fun addGlobalSourceMarkEventListener(sourceMarkEventListener: SourceMarkEventListener) {
log.info("Adding global source mark event listener: $sourceMarkEventListener")
globalSourceMarkEventListeners.add(sourceMarkEventListener)
}
fun removeGlobalSourceMarkEventListener(sourceMarkEventListener: SourceMarkEventListener) {
log.info("Removing global source mark event listener: $sourceMarkEventListener")
globalSourceMarkEventListeners.remove(sourceMarkEventListener)
}
fun getGlobalSourceMarkEventListeners(): List<SourceMarkEventListener> {
return ImmutableList.copyOf(globalSourceMarkEventListeners)
}
fun clearGlobalSourceMarkEventListeners() {
globalSourceMarkEventListeners.clear()
}
fun getSourceMark(artifactQualifiedName: ArtifactQualifiedName, type: SourceMark.Type): SourceMark? {
availableSourceFileMarkers.values.forEach {
val sourceMark = it.getSourceMark(artifactQualifiedName, type)
if (sourceMark != null) {
return sourceMark
}
}
return null
}
fun getGuideMark(artifactQualifiedName: ArtifactQualifiedName): GuideMark? {
return getSourceMark(artifactQualifiedName, SourceMark.Type.GUIDE) as GuideMark?
}
fun getSourceMarks(artifactQualifiedName: ArtifactQualifiedName): List<SourceMark> {
availableSourceFileMarkers.values.forEach {
val sourceMarks = it.getSourceMarks(artifactQualifiedName)
if (sourceMarks.isNotEmpty()) {
return sourceMarks
}
}
return emptyList()
}
fun getSourceMarks(): List<SourceMark> {
return availableSourceFileMarkers.values.flatMap { it.getSourceMarks() }
}
fun getSourceMark(id: String): SourceMark? {
return getSourceMarks().find { it.id == id }
}
fun getInlayMarks(): List<InlayMark> {
return getSourceMarks().filterIsInstance<InlayMark>()
}
fun getGutterMarks(): List<GutterMark> {
return getSourceMarks().filterIsInstance<GutterMark>()
}
fun getGuideMarks(): List<GuideMark> {
return getSourceMarks().filterIsInstance<GuideMark>()
}
fun findByInstrumentId(instrumentId: String): List<SourceMark> {
return getSourceMarks().filter {
it.getUserData(SourceMarkerKeys.INSTRUMENT_ID) == instrumentId
}
}
fun findBySubscriptionId(subscriptionId: String): List<SourceMark> {
return getSourceMarks().filter {
it.getUserData(SourceMarkerKeys.VIEW_SUBSCRIPTION_ID) == subscriptionId
}
}
}
| 2
| null |
13
| 87
|
199006a410529d961dc184f0740a5d845bd87899
| 7,749
|
interface-jetbrains
|
Apache License 2.0
|
app/src/main/java/com/sik/guiddemo/MainActivity.kt
|
SilverIceKey
| 637,693,910
| false
| null |
package com.sik.guiddemo
import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.MotionEvent
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.PermissionUtils.SimpleCallback
import com.blankj.utilcode.util.ToastUtils
import com.sik.guid.GuidViewHelper
import com.sik.guid.onFinish
import com.sik.guid.onNotClear
import com.sik.guid.setGuidDataList
import com.sik.guid.setParentView
import com.sik.guiddemo.utils.guid.FirstGuidData
class MainActivity : AppCompatActivity() {
private lateinit var guidViewHelper: GuidViewHelper
private lateinit var mainContent: ConstraintLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainContent = findViewById(R.id.main_content)
findViewById<TextView>(R.id.start).setOnClickListener {
startAnimator()
}
if (!PermissionUtils.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.callback(object : SimpleCallback {
override fun onGranted() {
startAnimator()
}
override fun onDenied() {
}
}).request()
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
startAnimator()
} else {
startActivity(Intent().apply {
action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
})
}
} else {
startAnimator()
}
}
}
private fun startAnimator() {
guidViewHelper = GuidViewHelper(this)
.setParentView(mainContent)
.onFinish {
ToastUtils.showShort("引导完成")
}
.onNotClear {
ToastUtils.showShort("请根据动画完成引导")
}
.setGuidDataList(FirstGuidData())
guidViewHelper.start()
}
override fun onTouchEvent(event: MotionEvent): Boolean {
guidViewHelper.onTouchEvent(event)
return super.onTouchEvent(event)
}
}
| 0
|
Kotlin
|
0
| 0
|
7eb831a194d3e11e07275cf1f5f2c63f67d41367
| 2,611
|
LottieGuidViewHelper
|
MIT License
|
app/src/main/java/com/sik/guiddemo/MainActivity.kt
|
SilverIceKey
| 637,693,910
| false
| null |
package com.sik.guiddemo
import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.MotionEvent
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.PermissionUtils.SimpleCallback
import com.blankj.utilcode.util.ToastUtils
import com.sik.guid.GuidViewHelper
import com.sik.guid.onFinish
import com.sik.guid.onNotClear
import com.sik.guid.setGuidDataList
import com.sik.guid.setParentView
import com.sik.guiddemo.utils.guid.FirstGuidData
class MainActivity : AppCompatActivity() {
private lateinit var guidViewHelper: GuidViewHelper
private lateinit var mainContent: ConstraintLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainContent = findViewById(R.id.main_content)
findViewById<TextView>(R.id.start).setOnClickListener {
startAnimator()
}
if (!PermissionUtils.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.callback(object : SimpleCallback {
override fun onGranted() {
startAnimator()
}
override fun onDenied() {
}
}).request()
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
startAnimator()
} else {
startActivity(Intent().apply {
action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
})
}
} else {
startAnimator()
}
}
}
private fun startAnimator() {
guidViewHelper = GuidViewHelper(this)
.setParentView(mainContent)
.onFinish {
ToastUtils.showShort("引导完成")
}
.onNotClear {
ToastUtils.showShort("请根据动画完成引导")
}
.setGuidDataList(FirstGuidData())
guidViewHelper.start()
}
override fun onTouchEvent(event: MotionEvent): Boolean {
guidViewHelper.onTouchEvent(event)
return super.onTouchEvent(event)
}
}
| 0
|
Kotlin
|
0
| 0
|
7eb831a194d3e11e07275cf1f5f2c63f67d41367
| 2,611
|
LottieGuidViewHelper
|
MIT License
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WaitAction.kt
|
Waboodoo
| 34,525,124
| false
| null |
package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
class WaitAction(private val duration: Int) : BaseAction() {
override fun execute(executionContext: ExecutionContext): Completable =
Completable.timer(duration.toLong(), TimeUnit.MILLISECONDS, Schedulers.single())
}
| 23
|
Kotlin
|
87
| 547
|
09eaa8438d452f95e73d57183b198c4b52d05789
| 468
|
HTTP-Shortcuts
|
MIT License
|
push/src/main/java/com/ymy/push/ali/cus/huaiwei/CusHuaWeiRegister.kt
|
hybridappnest
| 409,475,593
| false
|
{"Java": 3496922, "Kotlin": 641137, "JavaScript": 5699}
|
package com.ymy.push.ali.cus.huaiwei
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister
import com.alibaba.sdk.android.push.impl.HuaweiMsgParseImpl
import com.alibaba.sdk.android.push.register.ThirdPushManager
import com.alibaba.sdk.android.push.register.ThirdPushManager.ThirdPushReportKeyword
import com.alibaba.sdk.android.push.utils.SysUtils
import com.alibaba.sdk.android.push.utils.ThreadUtil
import com.huawei.hms.aaid.HmsInstanceId
import com.jeremyliao.liveeventbus.LiveEventBus
import com.taobao.accs.utl.ALog
import com.ymy.push.ali.PushTokenData
/**
* Created on 2/4/21 13:50.
* @author:hanxueqiang
* @version: 1.0.0
* @desc:自定义的HuaWeiRegister,阿里移动推送不会吐出厂商token,只能通过重新阿里移动推送sdk中对应的类来获取token
* 因各个厂商渠道的token获取方式不一致,有的需重写对应的Register,有的需要重写对应的Service或receiver
*/
object CusHuaWeiRegister {
private val TAG = "MPS:CusHuaWeiRegister"
var isChannelRegister = false
fun register(application: Application): Boolean {
return registerBundle(application, false)
}
fun registerBundle(application: Application, channelRegister: Boolean): Boolean {
try {
isChannelRegister = channelRegister
if (!isChannelRegister && !SysUtils.isMainProcess(application)) {
ALog.e(
"MPS:HuaWeiRegister",
"register not in main process, return",
*arrayOfNulls(0)
)
return false
}
if (checkDevice() && Build.VERSION.SDK_INT >= 17) {
ThirdPushManager.registerImpl(HuaweiMsgParseImpl())
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({
ALog.i(
"MPS:HuaWeiRegister",
"register begin isChannel:" + HuaWeiRegister.isChannelRegister,
*arrayOfNulls(0)
)
getToken(application.applicationContext)
}, 5000L)
return true
}
ALog.i("MPS:HuaWeiRegister", "register checkDevice false", *arrayOfNulls(0))
} catch (var3: Throwable) {
ALog.e("MPS:HuaWeiRegister", "register", var3, *arrayOfNulls(0))
}
return false
}
private fun getToken(context: Context) {
ThreadUtil.getExecutor().execute {
try {
val appInfo = context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
val value = appInfo.metaData.getString("com.huawei.hms.client.appid")
var appId = ""
if (!TextUtils.isEmpty(value)) {
appId = value!!.replace("appid=", "")
}
ALog.i(
"MPS:HuaWeiRegister",
"onToken",
*arrayOf<Any>("appId", appId)
)
val token: String
token = if (TextUtils.isEmpty(appId)) {
HmsInstanceId.getInstance(context).token
} else {
HmsInstanceId.getInstance(context).getToken(appId, "HCM")
}
if (!TextUtils.isEmpty(token)) {
ALog.i(
"MPS:HuaWeiRegister",
"onToken",
*arrayOf<Any>("token", token)
)
token?.run {
LiveEventBus.get(PushTokenData::class.java)
.post(
PushTokenData(
ThirdPushReportKeyword.HUAWEI.thirdTokenKeyword,
token
)
)
}
ThirdPushManager.reportToken(
context,
ThirdPushReportKeyword.HUAWEI.thirdTokenKeyword,
token
)
}
} catch (var5: Exception) {
ALog.e(
"MPS:HuaWeiRegister",
"getToken failed.",
var5,
*arrayOfNulls(0)
)
}
}
}
private fun checkDevice(): Boolean {
var result = false
if (Build.BRAND.equals("huawei", ignoreCase = true) || Build.BRAND.equals(
"honor",
ignoreCase = true
)
) {
result = true
}
return result
}
}
| 0
|
Java
|
6
| 11
|
b1fd25a909463f631e4c98cdfdd27e77d82164f7
| 4,813
|
AppNestAndroid
|
Apache License 2.0
|
src/main/kotlin/no/nav/helse/sporenstreks/integrasjon/rest/oppgave/MockOppgaveKlient.kt
|
navikt
| 249,433,776
| false
| null |
package no.nav.helse.sporenstreks.integrasjon.rest.oppgave
import no.nav.helse.arbeidsgiver.integrasjoner.oppgave.*
import java.time.LocalDateTime.now
class MockOppgaveKlient : OppgaveKlient {
override suspend fun opprettOppgave(
opprettOppgaveRequest: OpprettOppgaveRequest,
callId: String
): OpprettOppgaveResponse {
return OpprettOppgaveResponse(
1234,
"2",
"SYK",
"ROB",
1,
now().toLocalDate(),
Prioritet.NORM,
Status.OPPRETTET
)
}
}
| 5
|
Kotlin
|
0
| 1
|
6fb71c2956e40f08e7eac109afa38d65f861d778
| 580
|
sporenstreks
|
MIT License
|
src/main/kotlin/net/starlegacy/feature/gear/powerarmor/PowerArmorManager.kt
|
hafarooki
| 437,384,015
| false
| null |
package net.starlegacy.feature.gear.powerarmor
import net.starlegacy.feature.misc.CustomItems
import net.starlegacy.feature.misc.getPower
import net.starlegacy.feature.misc.removePower
import net.starlegacy.listener.gear.hasMovedInLastSecond
import net.starlegacy.util.Tasks
import org.bukkit.Bukkit
import org.bukkit.Material.LEATHER_BOOTS
import org.bukkit.Material.LEATHER_CHESTPLATE
import org.bukkit.Material.LEATHER_HELMET
import org.bukkit.Material.LEATHER_LEGGINGS
import org.bukkit.Particle
import org.bukkit.Sound
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
import java.util.UUID
object PowerArmorManager {
private val glidingPlayers = mutableSetOf<UUID>()
fun init() {
Tasks.syncRepeat(20, 20) {
powerModuleTick()
}
Tasks.syncRepeat(1, 1) {
tickRocketBoosters()
}
}
private fun powerModuleTick() {
for (player in Bukkit.getOnlinePlayers()) {
for (item: ItemStack? in player.inventory.armorContents) {
if (item == null || !isPowerArmor(item) || getPower(item) == 0) {
continue
}
for (module in getModules(item)) {
when (module) {
PowerArmorModule.SPEED_BOOSTING -> {
player.addPotionEffect(
PotionEffect(PotionEffectType.SPEED, 20, 2)
)
if (hasMovedInLastSecond(player) && !player.world.name.lowercase().contains("arena")) {
removePower(item, 1)
}
}
PowerArmorModule.NIGHT_VISION -> {
player.addPotionEffect(
PotionEffect(PotionEffectType.NIGHT_VISION, 1000, 1)
)
}
PowerArmorModule.ROCKET_BOOSTING -> {
if (player.isGliding && !player.world.name.lowercase().contains("arena")) {
removePower(item, 5)
}
}
else -> {
}
}
}
}
}
}
private fun tickRocketBoosters() {
loop@ for (uuid in glidingPlayers.toList()) {
val player = Bukkit.getPlayer(uuid) ?: continue
if (player.isOnGround || !player.isSneaking) {
toggleGliding(player)
continue
}
for (item in player.inventory.armorContents) {
if (!isPowerArmor(item) || getPower(item) == 0) {
continue
}
for (module in getModules(item)) {
if (module != PowerArmorModule.ROCKET_BOOSTING) {
continue
}
player.isGliding = true
player.velocity = player.velocity.midpoint(player.location.direction.multiply(0.6))
player.world.spawnParticle(Particle.SMOKE_NORMAL, player.location, 5)
if (!player.world.name.lowercase().contains("arena")) {
removePower(item, 5)
}
player.world.playSound(player.location, Sound.BLOCK_FIRE_AMBIENT, 1.0f, 2.0f)
continue@loop
}
}
// no rocket boosting module was found
toggleGliding(player)
}
}
fun isPowerArmor(item: ItemStack?): Boolean = CustomItems[item] is CustomItems.PowerArmorItem
fun isModule(item: ItemStack?) = PowerArmorModule[item] != null
fun getPowerArmorType(item: ItemStack?): PowerArmorType? {
return if (item == null) null else when (item.type) {
LEATHER_HELMET -> PowerArmorType.HELMET
LEATHER_CHESTPLATE -> PowerArmorType.CHESTPLATE
LEATHER_LEGGINGS -> PowerArmorType.LEGGINGS
LEATHER_BOOTS -> PowerArmorType.BOOTS
else -> throw RuntimeException("Power armor can only be leather armor!")
}
}
fun getModules(item: ItemStack): Set<PowerArmorModule> {
return item.lore
?.filter { it.startsWith("Module: ") }
?.mapNotNull { PowerArmorModule[it.split(" ")[1]] }
?.toSet()
?: setOf()
}
fun hasModule(item: ItemStack, module: PowerArmorModule): Boolean {
return getModules(item).contains(module)
}
fun toggleGliding(player: Player) {
if (glidingPlayers.contains(player.uniqueId)) {
glidingPlayers.remove(player.uniqueId)
player.isGliding = false
} else {
if (player.isOnGround) return
glidingPlayers.add(player.uniqueId)
player.isGliding = true
}
}
}
| 0
|
Kotlin
|
5
| 4
|
c830eb40180c935e8bfff599da0f9310eeccfb5c
| 3,941
|
StarLegacy
|
MIT License
|
src/main/kotlin/no/nav/helse/fritakagp/web/api/resreq/validation/CustomValikatorConstraints.kt
|
navikt
| 301,987,870
| false
|
{"Kotlin": 499884, "Shell": 618, "Dockerfile": 297}
|
package no.nav.helse.fritakagp.web.api.resreq.validation
import no.nav.helse.fritakagp.domain.Arbeidsgiverperiode
import no.nav.helse.fritakagp.domain.FravaerData
import no.nav.helse.fritakagp.domain.GodkjenteFiletyper
import no.nav.helse.fritakagp.domain.KroniskSoeknad
import org.valiktor.Constraint
import org.valiktor.Validator
import java.time.LocalDate
import java.time.temporal.ChronoUnit
interface CustomConstraint : Constraint {
override val messageBundle: String
get() = "validation/validation-messages"
}
class RefusjonsdagerKanIkkeOverstigePeriodelengdenConstraint : CustomConstraint
fun <E> Validator<E>.Property<Int?>.refusjonsDagerIkkeOverstigerPeriodelengde(ap: Arbeidsgiverperiode) =
this.validate(RefusjonsdagerKanIkkeOverstigePeriodelengdenConstraint()) {
return@validate ChronoUnit.DAYS.between(ap.fom, ap.tom.plusDays(1)) >= it!!
}
class MåVæreVirksomhetContraint : CustomConstraint
fun <E> Validator<E>.Property<String?>.isVirksomhet(erVirksomhet: Boolean) =
this.validate(MåVæreVirksomhetContraint()) { erVirksomhet }
class FraDatoKanIkkeKommeEtterTomDato : CustomConstraint
fun <E> Validator<E>.Property<LocalDate?>.datoerHarRiktigRekkefolge(tom: LocalDate) =
this.validate(FraDatoKanIkkeKommeEtterTomDato()) { fom -> fom!!.isEqual(tom) || fom!!.isBefore(tom) }
class MaanedsInntektErStorreEnTiMil : CustomConstraint
fun <E> Validator<E>.Property<Double?>.maanedsInntektErMellomNullOgTiMil() =
this.validate(MaanedsInntektErStorreEnTiMil()) {
it!! > 0.0 && it!! <= TiMil
}
class AntallPerioderErMellomNullOgTreHundre() : CustomConstraint
fun <E> Validator<E>.Property<Iterable<KroniskSoeknad>?>.antallPerioderErMellomNullOgTreHundre() =
this.validate(AntallPerioderErMellomNullOgTreHundre()) { ps ->
ps!!.any { p -> p.antallPerioder >= 1 && p.antallPerioder < 300 }
}
class DataUrlExtensionConstraints : CustomConstraint
fun <E> Validator<E>.Property<String?>.isGodskjentFiletyper() =
this.validate(DataUrlExtensionConstraints()) {
return@validate enumContains<GodkjenteFiletyper>(extractFilExtDel(it!!.uppercase()))
}
class DataUrlBase64Constraints : CustomConstraint
fun <E> Validator<E>.Property<String?>.isAvStorrelse(minSize: Long, maxSize: Long) =
this.validate(DataUrlBase64Constraints()) {
return@validate extractBase64Del(it!!).toByteArray().size <= maxSize && extractBase64Del(it!!).toByteArray().size > minSize
}
class MaxAgeFravaersDataConstraint : CustomConstraint
fun <E> Validator<E>.Property<Iterable<FravaerData>?>.ingenDataEldreEnn(aar: Long) =
this.validate(MaxAgeFravaersDataConstraint()) { ps ->
val minDate = LocalDate.now().minusYears(aar).withDayOfMonth(1)
return@validate !ps!!.any {
LocalDate.parse("${it.yearMonth}-01").isBefore(minDate)
}
}
class NoFutureFravaersDataConstraint : CustomConstraint
fun <E> Validator<E>.Property<Iterable<FravaerData>?>.ingenDataFraFremtiden() =
this.validate(NoFutureFravaersDataConstraint()) { ps ->
val maxDate = LocalDate.now().withDayOfMonth(1)
return@validate !ps!!.any {
LocalDate.parse("${it.yearMonth}-01").isAfter(maxDate)
}
}
class MaxNumFravaersdagFravaersDataConstraint : CustomConstraint
fun <E> Validator<E>.Property<Iterable<FravaerData>?>.ikkeFlereFravaersdagerEnnDagerIMaanden() =
this.validate(MaxNumFravaersdagFravaersDataConstraint()) { ps ->
return@validate !ps!!.any {
LocalDate.parse("${it.yearMonth}-01").lengthOfMonth() < it.antallDagerMedFravaer
}
}
inline fun <reified T : Enum<T>> enumContains(name: String): Boolean {
return enumValues<T>().any { it.name == name }
}
fun extractBase64Del(dataUrl: String): String = dataUrl.substringAfter("base64,")
fun extractFilExtDel(dataUrl: String): String {
if (!dataUrl.contains(';'))
return ""
else
return dataUrl.substring(0, dataUrl.indexOf(';')).substringAfter('/')
}
class VirusCheckConstraint : CustomConstraint
const val TiMil = 10000000.0
| 6
|
Kotlin
|
0
| 0
|
db10634f777a3c30371433e00e1951986d851bf3
| 4,069
|
fritakagp
|
MIT License
|
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/dependency/JdkImageTransformDelegate.kt
|
RivanParmar
| 526,653,590
| false
| null |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.dependency
import com.android.SdkConstants
import com.android.build.gradle.internal.packaging.JarCreatorFactory
import com.android.ide.common.process.CachedProcessOutputHandler
import com.android.ide.common.process.LoggedProcessOutputHandler
import com.android.ide.common.process.ProcessExecutor
import com.android.ide.common.process.ProcessInfoBuilder
import com.android.utils.FileUtils
import com.android.utils.ILogger
import com.google.common.annotations.VisibleForTesting
import com.google.common.base.Preconditions
import java.io.File
import java.util.zip.Deflater
import java.util.zip.ZipFile
import kotlin.streams.toList
/**
* Processes a Jar containing the system module classes into a JDK Image,
* for use via the --system option of javac and other Java-related tools.
*
* As per the discussion in b/154357088, the input for this process is, properly, the
* core-for-system-modules.jar included starting in SDK 30. The steps taken to transform
* the Jar are discussed in b/63986449.
*/
class JdkImageTransformDelegate(
val systemModulesJar: File,
val workDir: File,
val outDir: File,
val jdkTools: JdkTools
) {
/**
* Links a JDK Image from [systemModulesJar] in [outDir], using [workDir]
* for the output of any intermediate operations. This is done via the "jlink" tool
* as exposed by [jdkTools].
*/
fun run() {
Preconditions.checkArgument(!outDir.exists() && outDir.parentFile.isDirectory)
// jlink takes a directory of JMOD files as inputs
val jmodFile = makeJmodFile()
val jmodDir = jmodFile.parentFile
jdkTools.linkJmodsIntoJdkImage(
jmodDir,
"java.base",
outDir
)
copyJrtFsJar(outDir, jdkTools)
}
/**
* Creates a "module-info.java" file describing the contents of [systemModulesJar]
*/
fun makeModuleDescriptorJava(): File {
val moduleInfoJavaContent = generateModuleDescriptor(
"java.base",
listOf(systemModulesJar)
)
val moduleInfoJava = workDir.resolve("module-info.java")
FileUtils.writeToFile(moduleInfoJava, moduleInfoJavaContent)
return moduleInfoJava
}
/**
* Creates and compiles a "module-info.class" file describing the contents of [systemModulesJar]
*/
@VisibleForTesting
internal fun makeModuleInfoClass(): File {
val moduleInfoJava = makeModuleDescriptorJava()
jdkTools.compileModuleDescriptor(
moduleInfoJava,
systemModulesJar,
workDir
)
val moduleInfoClass = workDir.resolve("module-info.class")
Preconditions.checkState(
moduleInfoClass.exists(),
"Expected compiled module descriptor file to be created at %s",
moduleInfoClass
)
return moduleInfoClass
}
/**
* Creates a Modular Jar from [systemModulesJar] by compiling and adding a module descriptor
*/
@VisibleForTesting
internal fun makeModuleJar(): File {
val moduleInfoClass = makeModuleInfoClass()
val moduleJar = workDir.resolve("module.jar")
createJar(moduleInfoClass, listOf(systemModulesJar), moduleJar)
return moduleJar
}
/**
* Transforms [systemModulesJar] into a JMOD file
*/
@VisibleForTesting
internal fun makeJmodFile(): File {
val moduleName = "java.base"
val jlinkVersion = jdkTools.jlinkVersion
val jmodDir = workDir.resolve("jmod")
FileUtils.mkdirs(jmodDir)
val jmodFile = FileUtils.join(jmodDir, "$moduleName.jmod")
val moduleJar = makeModuleJar()
jdkTools.createJmodFromModularJar(
jmodFile,
jlinkVersion,
moduleJar
)
return jmodFile
}
}
class JdkTools(
val javaHome: File,
val processExecutor: ProcessExecutor,
val logger: ILogger
) {
val jrtFsLocation: File = javaHome.resolve("lib").resolve("jrt-fs.jar")
val jlinkVersion: String by lazy {
val jlinkExecutable = javaHome.resolve("bin").resolve("jlink".optionalExe())
Preconditions.checkArgument(
jlinkExecutable.exists(),
"jlink executable %s does not exist.",
jlinkExecutable
)
val pib = ProcessInfoBuilder().apply {
setExecutable(jlinkExecutable)
addArgs("--version")
}
val processOutputHandler = CachedProcessOutputHandler()
processExecutor.execute(
pib.createProcess(),
processOutputHandler
).rethrowFailure().assertNormalExitValue()
processOutputHandler.processOutput.standardOutputAsString.trim()
}
fun compileModuleDescriptor(
moduleInfoJava: File,
systemModulesJar: File,
outDir: File
) {
val classpathArgValue = systemModulesJar.absolutePath
val javacExecutable = javaHome.resolve("bin").resolve("javac".optionalExe())
Preconditions.checkArgument(
javacExecutable.exists(),
"javac executable %s does not exist.",
javacExecutable
)
val pib = ProcessInfoBuilder().apply {
setExecutable(javacExecutable)
addArgs("--system=none")
addArgs("--patch-module=java.base=$classpathArgValue")
addArgs("-d", outDir.absolutePath)
addArgs(moduleInfoJava.absolutePath)
}
processExecutor.execute(
pib.createProcess(),
LoggedProcessOutputHandler(logger)
).rethrowFailure().assertNormalExitValue()
}
fun createJmodFromModularJar(
jmodFile: File,
jlinkVersion: String,
moduleJar: File
) {
val jmodExecutable = javaHome.resolve("bin").resolve("jmod".optionalExe())
Preconditions.checkArgument(
jmodExecutable.exists(),
"jmod executable %s does not exist.",
jmodExecutable
)
val pib = ProcessInfoBuilder().apply {
setExecutable(jmodExecutable)
addArgs("create")
addArgs("--module-version", jlinkVersion)
addArgs("--target-platform", "android")
addArgs("--class-path", moduleJar.absolutePath)
addArgs(jmodFile.absolutePath)
}
processExecutor.execute(
pib.createProcess(),
LoggedProcessOutputHandler(logger)
).rethrowFailure().assertNormalExitValue()
}
fun linkJmodsIntoJdkImage(jmodDir: File, moduleName: String, outDir: File) {
val jlinkExecutable = javaHome.resolve("bin").resolve("jlink".optionalExe())
Preconditions.checkArgument(
jlinkExecutable.exists(),
"jlink executable %s does not exist.",
jlinkExecutable
)
val pib = ProcessInfoBuilder().apply {
setExecutable(jlinkExecutable)
addArgs("--module-path", jmodDir.absolutePath)
addArgs("--add-modules", moduleName)
addArgs("--output", outDir.absolutePath)
addArgs("--disable-plugin", "system-modules")
}
processExecutor.execute(
pib.createProcess(),
LoggedProcessOutputHandler(logger)
).rethrowFailure().assertNormalExitValue()
}
}
/**
* Modeled after the Android platform build method for parsing module-info.java out of a list of Jars
* See b/63986449 for more info
*/
@VisibleForTesting
internal fun generateModuleDescriptor(
moduleName: String,
jars: List<File>
): String {
val stringBuilder = StringBuilder()
stringBuilder.appendln("module $moduleName {")
val packageNameRegex = Regex("(.*)/[^/]*.class")
jars.asSequence().flatMap { jar ->
ZipFile(jar).use { it.stream().map { zipEntry -> zipEntry.name }.toList() }.asSequence()
}
.mapNotNull { packageNameRegex.find(it)?.groupValues?.get(1)?.replace("/", ".") }
.toSortedSet()
.forEach { stringBuilder.appendln(" exports $it;") }
stringBuilder.appendln("}")
return stringBuilder.toString()
}
@VisibleForTesting
internal fun createJar(moduleInfoClass: File, inJars: List<File>, outputJar: File) {
JarCreatorFactory.make(outputJar.toPath()).use {
it.setCompressionLevel(Deflater.NO_COMPRESSION)
it.addFile(moduleInfoClass.name, moduleInfoClass.toPath())
inJars.forEach { inJar ->
it.addJar(inJar.toPath())
}
}
}
private fun copyJrtFsJar(outDir: File, jdkTools: JdkTools) {
val source = jdkTools.jrtFsLocation
val copiedLibsDir = FileUtils.mkdirs(outDir.resolve("lib"))
val destination = copiedLibsDir.resolve(source.name)
source.copyTo(destination)
}
internal fun String.optionalExe() =
if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) this + ".exe" else this
| 1
| null |
2
| 17
|
a497291d77bba1aa34271808088fe1e8aab5efe2
| 9,568
|
androlabs
|
Apache License 2.0
|
src/com/koxudaxi/htmpy/HtmpyTemplateHighlighter.kt
|
pauleveritt
| 288,542,769
| false
|
{"Kotlin": 64625, "Lex": 6725, "Java": 160}
|
package com.koxudaxi.htmpy
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.ex.util.LayerDescriptor
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter
import com.intellij.openapi.fileTypes.FileTypes.PLAIN_TEXT
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings
import com.jetbrains.python.PythonFileType
import com.koxudaxi.htmpy.psi.HtmpyTypes.*
class HtmpyTemplateHighlighter(project: Project?, virtualFile: VirtualFile?, colors: EditorColorsScheme) : LayeredLexerEditorHighlighter(HtmpyHighlighter(), colors) {
init {
val languageFileType = when {
project == null || virtualFile == null -> PLAIN_TEXT
else -> TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile)?.associatedFileType
?: HtmpyLanguage.defaultTemplateLang
}
SyntaxHighlighterFactory.getSyntaxHighlighter(languageFileType, project, virtualFile)?.let {
registerLayer(CONTENT, LayerDescriptor(it, ""))
}
SyntaxHighlighterFactory.getSyntaxHighlighter(PythonFileType.INSTANCE, project, virtualFile)?.let {
registerLayer(PYTHON_ELEMENT, LayerDescriptor(it, ""))
}
}
}
| 8
|
Kotlin
|
0
| 1
|
d2253eaa2d8a329b5757280765fb5c4586ed4797
| 1,416
|
htmpy-pycharm-plugin
|
MIT License
|
app/src/unitTest/kotlin/batect/execution/model/steps/runners/RunContainerStepRunnerSpec.kt
|
batect
| 102,647,061
| false
| null |
/*
Copyright 2017-2020 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.execution.model.steps.runners
import batect.config.Container
import batect.docker.DockerContainer
import batect.docker.DockerContainerRunResult
import batect.docker.DockerException
import batect.docker.client.DockerContainersClient
import batect.execution.CancellationContext
import batect.execution.model.events.ContainerRunFailedEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.RunningContainerExitedEvent
import batect.execution.model.events.TaskEventSink
import batect.execution.model.steps.RunContainerStep
import batect.os.Dimensions
import batect.testutils.createForEachTest
import batect.testutils.imageSourceDoesNotMatter
import batect.testutils.on
import batect.ui.containerio.ContainerIOStreamingOptions
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.doThrow
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import okio.Sink
import okio.Source
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object RunContainerStepRunnerSpec : Spek({
describe("running a 'run container' step") {
val container = Container("some-container", imageSourceDoesNotMatter())
val dockerContainer = DockerContainer("some-id")
val step = RunContainerStep(container, dockerContainer)
val stdout = mock<Sink>()
val stdin = mock<Source>()
val frameDimensions = Dimensions(20, 30)
val containersClient by createForEachTest { mock<DockerContainersClient>() }
val ioStreamingOptions by createForEachTest {
mock<ContainerIOStreamingOptions>() {
on { stdoutForContainer(container) } doReturn stdout
on { stdinForContainer(container) } doReturn stdin
on { this.frameDimensions } doReturn frameDimensions
}
}
val cancellationContext by createForEachTest { mock<CancellationContext>() }
val eventSink by createForEachTest { mock<TaskEventSink>() }
val runner by createForEachTest { RunContainerStepRunner(containersClient, ioStreamingOptions, cancellationContext) }
on("when running the container succeeds") {
beforeEachTest {
whenever(containersClient.run(any(), any(), any(), any(), any(), any())).doAnswer { invocation ->
@Suppress("UNCHECKED_CAST")
val onStartedHandler = invocation.arguments[5] as () -> Unit
onStartedHandler()
DockerContainerRunResult(123)
}
runner.run(step, eventSink)
}
it("runs the container with the stdin and stdout provided by the I/O streaming options") {
verify(containersClient).run(eq(dockerContainer), eq(stdout), eq(stdin), eq(cancellationContext), eq(frameDimensions), any())
}
it("emits a 'container started' event") {
verify(eventSink).postEvent(ContainerStartedEvent(container))
}
it("emits a 'running container exited' event") {
verify(eventSink).postEvent(RunningContainerExitedEvent(container, 123))
}
}
on("when running the container fails") {
beforeEachTest {
whenever(containersClient.run(any(), any(), any(), any(), any(), any())).doThrow(DockerException("Something went wrong"))
runner.run(step, eventSink)
}
it("emits a 'container run failed' event") {
verify(eventSink).postEvent(ContainerRunFailedEvent(container, "Something went wrong"))
}
}
}
})
| 12
| null |
47
| 620
|
1b6cb1d79d91a70a0cb038cc29b2db1c025fea9e
| 4,500
|
batect
|
Apache License 2.0
|
src/medium/_78Subsets.kt
|
ilinqh
| 390,190,883
| false
|
{"Kotlin": 395506, "Java": 32733}
|
package medium
class _78Subsets {
class Solution {
fun subsets(nums: IntArray): List<List<Int>> {
val result: MutableList<ArrayList<Int>> = ArrayList()
result.add(arrayListOf())
for (count in nums.indices) {
val tempList = ArrayList(result)
for (i in result.indices) {
val temp = ArrayList(tempList[i])
temp.add(nums[count])
result.add(temp)
}
// val size = result.size
// for (i in 0 until size) {
// val temp = ArrayList(result[i])
// temp.add(nums[count])
// result.add(temp)
// }
}
return result
}
}
class BestSolution {
fun subsets(nums: IntArray): List<List<Int>> {
val result = arrayListOf<ArrayList<Int>>()
result.add(arrayListOf())
for (i in nums) {
val c = ArrayList(result)
val n = c.size
for (j in 0 until n) {
val temp = ArrayList(c[j])
temp.add(i)
c.add(temp)
}
result.clear()
result.addAll(c)
}
return result
}
}
}
| 0
|
Kotlin
|
0
| 0
|
985f2f1a022a25d39782cd36ae3d0ab33fed8ac5
| 1,307
|
AlgorithmsProject
|
Apache License 2.0
|
koin-todoapp-mvp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailActivity.kt
|
eastar-dev
| 182,819,469
| false
|
{"Text": 1, "Gradle": 17, "Java Properties": 9, "Shell": 6, "Ignore List": 10, "Batchfile": 6, "Markdown": 5, "Proguard": 5, "Java": 51, "XML": 61, "Kotlin": 99, "INI": 3}
|
/*
* Copyright (C) 2017 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.example.android.architecture.blueprints.todoapp.taskdetail
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.util.replaceFragmentInActivity
import com.example.android.architecture.blueprints.todoapp.util.setupActionBar
import org.koin.android.ext.android.inject
/**
* Displays task details screen.
*/
class TaskDetailActivity : AppCompatActivity() {
private val taskDetailFragment: TaskDetailFragment by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.taskdetail_act)
// Set up the toolbar.
setupActionBar(R.id.toolbar) {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
supportFragmentManager
.findFragmentById(R.id.contentFrame) as TaskDetailFragment? ?:
taskDetailFragment.also {
replaceFragmentInActivity(it, R.id.contentFrame)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| 1
| null |
1
| 1
|
73b019c4cf4df58f7b6b4ad7325c99b84999462d
| 1,865
|
dagger_study
|
Apache License 2.0
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/platform/JvmIdePlatformKindTooling.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.platform.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.testIntegration.TestFramework
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.compiler.configuration.Kotlin2JvmCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.framework.JavaRuntimeDetectionUtil
import org.jetbrains.kotlin.idea.framework.JavaRuntimeLibraryDescription
import org.jetbrains.kotlin.idea.highlighter.KotlinTestRunLineMarkerContributor.Companion.getTestStateIcon
import org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling
import org.jetbrains.kotlin.idea.platform.isKotlinTestDeclaration
import org.jetbrains.kotlin.idea.platform.testintegration.LightTestFramework
import org.jetbrains.kotlin.idea.platform.testintegration.NoLightTestFrameworkResult
import org.jetbrains.kotlin.idea.platform.testintegration.ResolvedLightTestFrameworkResult
import org.jetbrains.kotlin.idea.platform.testintegration.UnsureLightTestFrameworkResult
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.utils.PathUtil
import javax.swing.Icon
class JvmIdePlatformKindTooling : IdePlatformKindTooling() {
override val kind = JvmIdePlatformKind
override fun compilerArgumentsForProject(project: Project) = Kotlin2JvmCompilerArgumentsHolder.getInstance(project).settings
override val mavenLibraryIds = listOf(
PathUtil.KOTLIN_JAVA_STDLIB_NAME,
PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME,
PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME,
PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME,
PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME
)
override val gradlePluginId = "kotlin-platform-jvm"
override val gradlePlatformIds: List<KotlinPlatform> get() = listOf(KotlinPlatform.JVM, KotlinPlatform.ANDROID)
override val libraryKind: PersistentLibraryKind<*>? = null
override fun getLibraryDescription(project: Project) = JavaRuntimeLibraryDescription(project)
override fun getLibraryVersionProvider(project: Project): (Library) -> String? {
return JavaRuntimeDetectionUtil::getJavaRuntimeVersion
}
private fun calculateUrlsToFramework(declaration: KtNamedDeclaration): Pair<List<String>, TestFramework>? {
for (lightTestFramework in LightTestFramework.EXTENSION_NAME.extensionList) {
val framework = when (val result = lightTestFramework.detectFramework(declaration)) {
is ResolvedLightTestFrameworkResult -> result.testFramework
is UnsureLightTestFrameworkResult -> continue
is NoLightTestFrameworkResult -> return null
}
val qualifiedName = lightTestFramework.qualifiedName(declaration) ?: return null
return when(declaration) {
is KtClassOrObject -> listOf("java:suite://$qualifiedName") to framework
is KtNamedFunction -> listOf(
"java:test://$qualifiedName/${declaration.name}",
"java:test://$qualifiedName.${declaration.name}"
) to framework
else -> null
}
}
return null
}
override fun getTestIcon(declaration: KtNamedDeclaration, descriptorProvider: () -> DeclarationDescriptor?): Icon? {
val (urls, framework) = calculateUrlsToFramework(declaration) ?: return null
framework?.let {
return getTestStateIcon(urls, declaration)
}
descriptorProvider()?.takeIf { it.isKotlinTestDeclaration() } ?: return null
return getTestStateIcon(urls, declaration)
}
override fun acceptsAsEntryPoint(function: KtFunction) = true
}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 4,222
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/zigis/paleontologas/quiz/fragments/QuizGameFragment.kt
|
edgar-zigis
| 240,962,785
| false
| null |
package com.zigis.paleontologas.quiz.fragments
import android.view.LayoutInflater
import android.view.ViewGroup
import com.zigis.paleontologas.application.android.BaseViewModelFragment
import com.zigis.paleontologas.quiz.data.entities.Question
import com.zigis.paleontologas.quiz.viewmodels.QuizGameViewModel
import com.zigis.paleontologas.quiz.views.QuizGameView
import com.zigis.paleontologas.quiz.views.QuizGameViewDelegate
class QuizGameFragment : BaseViewModelFragment<QuizGameViewModel, QuizGameView>(),
QuizGameViewDelegate {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?): QuizGameView {
return QuizGameView(inflater.context).also {
it.delegate = this
it.onBack = {
activity?.onBackPressed()
}
}.also {
viewModel.generateQuestions()
}
}
override fun observeChanges() {
viewModel.currentQuestion.observe(viewLifecycleOwner) {
contentView.setCurrentQuestion(it)
}
viewModel.endResult.observe(viewLifecycleOwner) { result ->
globalRouter.pushFragment(
QuizMarkFragment().also { it.mark = result.correctAnswers }
)
}
}
// QuizGameViewDelegate
override fun answerQuestion(question: Question, answer: Int) {
viewModel.answerQuestion(question, answer)
}
}
| 0
|
Kotlin
|
16
| 126
|
4ee09d3c6f29278aa1762e71f7db6a84d0ca3dea
| 1,403
|
Paleontologas
|
Apache License 2.0
|
app/src/main/java/com/zigis/paleontologas/quiz/fragments/QuizGameFragment.kt
|
edgar-zigis
| 240,962,785
| false
| null |
package com.zigis.paleontologas.quiz.fragments
import android.view.LayoutInflater
import android.view.ViewGroup
import com.zigis.paleontologas.application.android.BaseViewModelFragment
import com.zigis.paleontologas.quiz.data.entities.Question
import com.zigis.paleontologas.quiz.viewmodels.QuizGameViewModel
import com.zigis.paleontologas.quiz.views.QuizGameView
import com.zigis.paleontologas.quiz.views.QuizGameViewDelegate
class QuizGameFragment : BaseViewModelFragment<QuizGameViewModel, QuizGameView>(),
QuizGameViewDelegate {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?): QuizGameView {
return QuizGameView(inflater.context).also {
it.delegate = this
it.onBack = {
activity?.onBackPressed()
}
}.also {
viewModel.generateQuestions()
}
}
override fun observeChanges() {
viewModel.currentQuestion.observe(viewLifecycleOwner) {
contentView.setCurrentQuestion(it)
}
viewModel.endResult.observe(viewLifecycleOwner) { result ->
globalRouter.pushFragment(
QuizMarkFragment().also { it.mark = result.correctAnswers }
)
}
}
// QuizGameViewDelegate
override fun answerQuestion(question: Question, answer: Int) {
viewModel.answerQuestion(question, answer)
}
}
| 0
|
Kotlin
|
16
| 126
|
4ee09d3c6f29278aa1762e71f7db6a84d0ca3dea
| 1,403
|
Paleontologas
|
Apache License 2.0
|
app/src/main/java/com/example/visuallithuanian/interface/AdapterCallback.kt
|
klaus19
| 541,931,828
| false
|
{"Kotlin": 394608}
|
package com.example.visuallithuanian.`interface`
interface AdapterCallback {
fun onImageviewClicked(text:String)
}
| 10
|
Kotlin
|
4
| 9
|
184e0624f117a58e129dd395ff21a05e82ea05c8
| 120
|
Labas
|
Apache License 2.0
|
core/bluetooth/src/test/kotlin/edu/stanford/spezi/core/bluetooth/domain/BLEServiceTest.kt
|
StanfordSpezi
| 787,513,636
| false
|
{"Kotlin": 1195675, "Ruby": 1769, "Shell": 212}
|
package edu.stanford.spezi.core.bluetooth.domain
import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import com.google.common.truth.Truth.assertThat
import edu.stanford.spezi.core.bluetooth.data.model.BLEDevice
import edu.stanford.spezi.core.bluetooth.data.model.BLEServiceEvent
import edu.stanford.spezi.core.bluetooth.data.model.BLEServiceState
import edu.stanford.spezi.core.testing.SpeziTestScope
import edu.stanford.spezi.core.testing.runTestUnconfined
import edu.stanford.spezi.core.testing.verifyNever
import edu.stanford.spezi.core.utils.PermissionChecker
import edu.stanford.spezi.core.utils.UUID
import io.mockk.Called
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import org.junit.Before
import org.junit.Test
class BLEServiceTest {
private val bluetoothAdapter: BluetoothAdapter = mockk()
private val permissionChecker: PermissionChecker = mockk()
private val deviceScanner: BLEDeviceScanner = mockk()
private val deviceConnectorFactory: BLEDeviceConnector.Factory = mockk()
private val deviceConnector: BLEDeviceConnector = mockk()
private val deviceConnectorEvents = MutableSharedFlow<BLEServiceEvent>()
private val pairedDevicesStorage: BLEPairedDevicesStorage = mockk(relaxed = true)
private val bleDevicePairingNotifier: BLEDevicePairingNotifier = mockk(relaxed = true)
private val deviceScannerEvents = MutableSharedFlow<BLEDeviceScanner.Event>()
private val notifierEvents = MutableSharedFlow<BLEDevicePairingNotifier.Event>()
private val pairedDevicesState = MutableStateFlow(emptyList<BLEDevice>())
private val bluetoothDevice: BluetoothDevice = mockk {
every { address } returns "some device address"
}
private val device: BLEDevice = mockk()
private val services = listOf(UUID())
private val bleService by lazy {
BLEServiceImpl(
bluetoothAdapter = bluetoothAdapter,
permissionChecker = permissionChecker,
deviceScanner = deviceScanner,
scope = SpeziTestScope(),
deviceConnectorFactory = deviceConnectorFactory,
pairedDevicesStorage = pairedDevicesStorage,
bleDevicePairingNotifier = bleDevicePairingNotifier,
)
}
@Before
fun setup() {
every { deviceScanner.isScanning } returns false
every { bluetoothAdapter.isEnabled } returns true
every { permissionChecker.isPermissionGranted(any()) } returns true
every { deviceConnectorFactory.create(any()) } returns deviceConnector
with(deviceConnector) {
every { events } returns deviceConnectorEvents
every { connect() } just Runs
every { disconnect() } just Runs
}
with(deviceScanner) {
every { events } returns deviceScannerEvents
every { startScanning(services = services) } just Runs
every { stopScanning() } just Runs
}
every { pairedDevicesStorage.pairedDevices } returns pairedDevicesState
every { pairedDevicesStorage.isPaired(any()) } returns true
every { bleDevicePairingNotifier.events } returns notifierEvents
}
@Test
fun `it should have idle state initially`() {
// given
val sut = bleService
// when
val state = sut.state.value
// then
assertThat(state).isEqualTo(BLEServiceState.Idle)
}
@Test
fun `it should do nothing if device scanner is scanning`() {
// given
every { deviceScanner.isScanning } returns true
// when
bleService.startDiscovering(services = services)
// then
verify { permissionChecker wasNot Called }
verifyNever { deviceScanner.startScanning(services = services) }
}
@Test
fun `it should change state to BluetoothNotEnabled if adapter returns not enabled`() =
runTestUnconfined {
// given
every { bluetoothAdapter.isEnabled } returns false
// when
bleService.startDiscovering(services = services)
// then
verify { deviceScanner.stopScanning() }
assertState(state = BLEServiceState.BluetoothNotEnabled)
}
@Test
fun `it should notify missing permissions correctly`() = runTestUnconfined {
// given
every { permissionChecker.isPermissionGranted(any()) } returns false
val expectedPermissions = listOf(
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
)
// when
bleService.startDiscovering(services = services)
// then
assertState(state = BLEServiceState.MissingPermissions(permissions = expectedPermissions))
}
@Test
fun `it should handle start correctly given preconditions are met`() = runTestUnconfined {
// given
every { deviceScanner.isScanning } returns false
every { bluetoothAdapter.isEnabled } returns true
every { permissionChecker.isPermissionGranted(any()) } returns true
// when
bleService.startDiscovering(services = services)
// then
verify { bleDevicePairingNotifier.events }
verify { bleDevicePairingNotifier.start() }
verify { pairedDevicesStorage.pairedDevices }
verify { deviceScanner.events }
verify { deviceScanner.startScanning(services = services) }
}
@Test
fun `it should handle failure scanner event correctly`() = runTestUnconfined {
// given
val errorCode = 42
start()
// when
deviceScannerEvents.emit(BLEDeviceScanner.Event.Failure(errorCode = errorCode))
// then
assertEvent(event = BLEServiceEvent.ScanningFailed(errorCode = errorCode))
}
@Test
fun `it should handle device found event correctly`() = runTestUnconfined {
// given
val service = spyk(bleService)
start(service)
// when
emitDeviceFound()
// then
verify { service.pair(bluetoothDevice) }
}
@Test
fun `it should handle pair correctly`() = runTestUnconfined {
// when
bleService.pair(bluetoothDevice)
// then
verify { deviceConnectorFactory.create(device = bluetoothDevice) }
verify { deviceConnector.connect() }
verify { deviceConnector.events }
}
@Test
fun `it should handle device found correctly if device already paired`() =
runTestUnconfined {
// given
val service = spyk(bleService)
start(service)
every { pairedDevicesStorage.isPaired(bluetoothDevice) } returns true
// when
emitDeviceFound()
// then
verify { service.pair(bluetoothDevice) }
}
@Test
fun `it should handle connected event correctly`() = runTestUnconfined {
// given
val event = BLEServiceEvent.Connected(device = device)
// when
setupDeviceConnectorEvent(event = event)
// then
verify { pairedDevicesStorage.updateDeviceConnection(bluetoothDevice, true) }
}
@Test
fun `it should handle disconnected event correctly`() = runTestUnconfined {
// given
val event = BLEServiceEvent.Disconnected(device = device)
// when
setupDeviceConnectorEvent(event = event)
// then
assertEvent(event = event)
verify { pairedDevicesStorage.updateDeviceConnection(bluetoothDevice, false) }
}
@Test
fun `it should handle stop correctly`() = runTestUnconfined {
// given
setupDeviceConnectorEvent(BLEServiceEvent.Connected(device))
// when
bleService.stop()
// then
verify { deviceScanner.stopScanning() }
verify { pairedDevicesStorage.onStopped() }
verify { bleDevicePairingNotifier.stop() }
}
@Test
fun `it should update state correctly from the storage`() = runTestUnconfined {
// given
val devices = List(10) { device }
pairedDevicesState.update { devices }
// when
start()
// then
assertState(BLEServiceState.Scanning(devices))
}
@Test
fun `it should handle paired event correctly`() = runTestUnconfined {
// given
start()
// when
notifierEvents.emit(BLEDevicePairingNotifier.Event.DevicePaired(bluetoothDevice))
// then
assertEvent(BLEServiceEvent.DevicePaired(bluetoothDevice))
}
@Test
fun `it should handle unpaired event correctly`() = runTestUnconfined {
// given
start()
// when
notifierEvents.emit(BLEDevicePairingNotifier.Event.DeviceUnpaired(bluetoothDevice))
// then
assertEvent(BLEServiceEvent.DeviceUnpaired(bluetoothDevice))
}
private fun start(bleService: BLEServiceImpl? = null) {
every { deviceScanner.isScanning } returns false
every { bluetoothAdapter.isEnabled } returns true
every { permissionChecker.isPermissionGranted(any()) } returns true
(bleService ?: this.bleService).startDiscovering(services = services)
}
private suspend fun emitDeviceFound() {
deviceScannerEvents.emit(BLEDeviceScanner.Event.DeviceFound(device = bluetoothDevice))
}
private suspend fun setupDeviceConnectorEvent(event: BLEServiceEvent) {
start()
emitDeviceFound()
deviceConnectorEvents.emit(event)
}
private suspend fun assertEvent(event: BLEServiceEvent) {
assertThat(bleService.events.first()).isEqualTo(event)
}
private fun assertState(state: BLEServiceState) {
assertThat(bleService.state.value).isEqualTo(state)
}
}
| 16
|
Kotlin
|
2
| 8
|
9eae0b52bc631fa171b4873a739baddad8fe4b2c
| 10,187
|
SpeziKt
|
MIT License
|
src/main/java/it/andrearossi/mcitaliaapi/utils/html/APIObject.kt
|
Blovien
| 271,863,709
| false
|
{"Java": 23875, "Kotlin": 4269}
|
package it.andrearossi.mcitaliaapi.utils.html
import java.io.Serializable
interface APIObject : Serializable
| 1
| null |
1
| 1
|
6951d38d181b9770e4de7577d2bccf4280051555
| 111
|
MCItaliaAPI
|
MIT License
|
app/src/main/java/jp/juggler/subwaytooter/span/MisskeySpan.kt
|
BoFFire
| 146,865,117
| false
|
{"Java Properties": 2, "Perl": 4, "Text": 11, "JSON": 6, "Gradle": 9, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 8, "Git Config": 1, "Proguard": 6, "XML": 120, "Java": 34, "INI": 1, "Kotlin": 224}
|
package jp.juggler.subwaytooter.span
import android.graphics.Paint
import android.graphics.Typeface
import android.text.TextPaint
import android.text.style.MetricAffectingSpan
import java.lang.ref.WeakReference
class MisskeyBigSpan (
private val typeface : Typeface
): MetricAffectingSpan() ,AnimatableSpan{
private var invalidate_callback : AnimatableSpanInvalidator? = null
private var refDrawTarget : WeakReference<Any>? = null
override fun setInvalidateCallback(
draw_target_tag : Any,
invalidate_callback : AnimatableSpanInvalidator
) {
this.refDrawTarget = WeakReference(draw_target_tag)
this.invalidate_callback = invalidate_callback
}
private val textScalingMax = 1.5f
override fun updateMeasureState(paint : TextPaint) {
apply(paint,bDrawing=false)
}
override fun updateDrawState(drawState : TextPaint) {
apply(drawState,bDrawing=true)
}
private fun apply(paint : Paint, bDrawing:Boolean ) {
val textScaling = when{
!bDrawing -> textScalingMax
else -> {
invalidate_callback?.delayInvalidate(100L)
val t = (invalidate_callback?.timeFromStart ?: 0L) /500f
textScalingMax * ( Math.sin(t.toDouble()).toFloat() * 0.1f + 0.9f)
}
}
paint.textSize = paint.textSize * textScaling
val oldTypeface = paint.typeface
val oldStyle = oldTypeface?.style ?: 0
val fakeStyle = oldStyle and typeface.style.inv()
if(fakeStyle and Typeface.BOLD != 0) {
paint.isFakeBoldText = true
}
if(fakeStyle and Typeface.ITALIC != 0) {
paint.textSkewX = - 0.25f
}
paint.typeface = typeface
}
}
| 1
| null |
1
| 1
|
4f29ec06764f65fbc63ca59859f5afe826d5b417
| 1,593
|
SubwayTooter
|
Apache License 2.0
|
chooser-compose/src/main/java/net/mm2d/color/chooser/compose/ColorEvent.kt
|
ohmae
| 158,970,822
| false
|
{"Kotlin": 160321}
|
package net.mm2d.color.chooser.compose
import androidx.compose.ui.graphics.Color
internal data class ColorEvent(
val color: Color,
val source: ColorSource,
)
| 1
|
Kotlin
|
5
| 23
|
00a15b42ee16a2c0cc488a1a5c7d12e473a2819c
| 168
|
color-chooser
|
MIT License
|
src/main/kotlin/cz/startnet/utils/pgdiff/PgDiffPolicies.kt
|
lovelysystems
| 289,426,236
| false
|
{"Kotlin": 356018, "PLpgSQL": 56158, "Shell": 387, "Dockerfile": 156}
|
/**
* Copyright 2006 StartNet s.r.o.
*
* Distributed under MIT license
*/
package cz.startnet.utils.pgdiff
import cz.startnet.utils.pgdiff.schema.PgPolicy
import cz.startnet.utils.pgdiff.schema.PgSchema
import kotlin.text.StringBuilder
object PgDiffPolicies {
fun createPolicies(
writer: StringBuilder,
oldSchema: PgSchema?, newSchema: PgSchema?
) {
for (newTable in newSchema?.tables.orEmpty()) {
val newTableName = newTable.name
val oldTable = oldSchema?.getTable(newTableName)
for (policy in newTable.policies) {
val oldPolicy = oldTable?.getPolicy(policy.name)
if (oldPolicy == null) {
createPolicySQL(writer, policy)
}
}
}
}
fun alterPolicies(
writer: StringBuilder,
oldSchema: PgSchema?, newSchema: PgSchema?
) {
for (newTable in newSchema?.tables.orEmpty()) {
val newTableName = newTable.name
if (oldSchema != null) {
val oldTable = oldSchema.getTable(newTableName)
if (oldTable != null) {
for (policy in oldTable.policies) {
val newPolicy = newTable.getPolicy(policy.name)
if (newPolicy != null) {
// ALTER POLICY doesn't support changing command(ALL,
// SELECT..) so we drop it and create it
val newCommand = newPolicy.command
val oldCommand = policy.command
if (newCommand != null && oldCommand != null && newCommand != oldCommand) {
dropPolicySQL(writer, newPolicy)
createPolicySQL(writer, newPolicy)
} else if (policy.using == null && newPolicy.using != null
|| policy.using != null && newPolicy.using == null
|| policy.using != null && newPolicy.using != null && policy.using != newPolicy.using
) {
alterPolicySQL(writer, newPolicy)
} else if (policy.withCheck == null && newPolicy.withCheck != null
|| policy.withCheck != null && newPolicy.withCheck == null
|| policy.withCheck != null && newPolicy.withCheck != null && policy.withCheck != newPolicy.withCheck
) {
alterPolicySQL(writer, newPolicy)
} else {
val equalRoles = newPolicy.roles.containsAll(policy.roles) &&
policy.roles.containsAll(newPolicy.roles)
if (!equalRoles) {
alterPolicySQL(writer, newPolicy)
}
}
}
}
}
}
}
}
fun dropPolicies(
writer: StringBuilder,
oldSchema: PgSchema?, newSchema: PgSchema?
) {
for (newTable in newSchema?.tables.orEmpty()) {
val newTableName = newTable.name
if (oldSchema != null) {
val oldTable = oldSchema.getTable(newTableName)
if (oldTable != null) {
for (policy in oldTable.policies) {
if (newTable.getPolicy(policy.name) == null) {
dropPolicySQL(writer, policy)
}
}
}
}
}
}
private fun createPolicySQL(writer: StringBuilder, policy: PgPolicy) {
writer.append(
"CREATE POLICY "
+ PgDiffUtils.getQuotedName(policy.name)
+ " ON "
+ PgDiffUtils.getQuotedName(policy.tableName!!)
)
writer.append(" FOR " + policy.command)
var roles = ""
writer.append(" TO ")
val iterator: Iterator<String?> = policy.roles.iterator()
while (iterator.hasNext()) {
roles += iterator.next().toString() + if (iterator.hasNext()) ", " else ""
}
writer.append(roles)
if (policy.using != null) {
writer.println()
writer.appendLine("USING (")
writer.append(" ")
writer.println(policy.using)
writer.append(")")
}
if (policy.withCheck != null) {
writer.println()
writer.appendLine("WITH CHECK (")
writer.append(" ")
writer.println(policy.withCheck)
writer.append(")")
}
writer.appendLine(";")
}
private fun alterPolicySQL(writer: StringBuilder, policy: PgPolicy) {
writer.append(
"ALTER POLICY "
+ PgDiffUtils.getQuotedName(policy.name)
+ " ON "
+ PgDiffUtils.getQuotedName(policy.tableName!!)
)
var roles = ""
writer.append(" TO ")
val iterator: Iterator<String?> = policy.roles.iterator()
while (iterator.hasNext()) {
roles += iterator.next().toString() + if (iterator.hasNext()) ", " else ""
}
writer.append(roles)
if (policy.using != null) {
writer.println()
writer.appendLine("USING (")
writer.append(" ")
writer.println(policy.using)
writer.append(")")
}
if (policy.withCheck != null) {
writer.println()
writer.appendLine("WITH CHECK (")
writer.append(" ")
writer.println(policy.withCheck)
writer.append(")")
}
writer.appendLine(";")
}
private fun dropPolicySQL(writer: StringBuilder, policy: PgPolicy) {
writer.appendLine(
"DROP POLICY "
+ PgDiffUtils.getQuotedName(policy.name)
+ " ON "
+ PgDiffUtils.getQuotedName(policy.tableName!!)
+ ";"
)
}
}
| 3
|
Kotlin
|
0
| 0
|
add115b5aefdaf06719e43f2890f6767a44d363b
| 6,289
|
apgdiff
|
MIT License
|
Android/app/src/main/java/com/fglshm/instagramclone/profile/ProfileNoPostFragment.kt
|
fglshm
| 194,391,524
| false
| null |
package com.fglshm.instagramclone.profile
import com.fglshm.instagramclone.R
import com.fglshm.instagramclone.common.base.BaseFragment
class ProfileNoPostFragment : BaseFragment() {
override fun getLayout(): Int = R.layout.fragment_profile_no_post
companion object {
fun newInstance() = ProfileNoPostFragment()
}
}
| 0
|
Kotlin
|
0
| 0
|
eb83381aebf38244aa517fefe2636ba3c44cbe84
| 339
|
InstagramClone
|
MIT License
|
samples/RxFirebaseLogin/src/main/kotlin/br/com/rsicarelli/rxfirebaselogin/infra/di/component/ApplicationComponent.kt
|
fluentio
| 124,605,010
| false
| null |
package br.com.rsicarelli.rxfirebaselogin.infra.di.component
import android.app.Application
import br.com.rsicarelli.rxfirebaselogin.App
import br.com.rsicarelli.rxfirebaselogin.infra.di.module.ActivityBuilderModule
import br.com.rsicarelli.rxfirebaselogin.infra.di.module.ApplicationModule
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
@Singleton
@Component(modules = [
(AndroidSupportInjectionModule::class),
(ApplicationModule::class),
(ActivityBuilderModule::class)
])
interface ApplicationComponent : AndroidInjector<App> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): ApplicationComponent
}
}
| 7
|
Kotlin
|
7
| 31
|
43607b6b48d1ad870a752b3836ceaa3fb1172d25
| 834
|
Fluent
|
MIT License
|
app/src/main/java/com/example/minilydia/domain/model/User.kt
|
icodeyou
| 478,231,113
| false
| null |
package com.example.minilydia.domain.model
import java.io.Serializable
data class User(
val id: String,
val firstName: String,
val surname: String,
val gender: String,
val email: String,
val smallPicture: String,
val normalPicture: String,
val largePicture: String,
val phone: String,
val city: String,
val registered: Long
): Serializable {
fun getFullName(): String {
return "${this.firstName} ${this.surname}"
}
}
| 0
|
Kotlin
|
0
| 2
|
59f5126d0d8ace6c2cdad22a5456a9debf7b768d
| 478
|
minilydia
|
Apache License 2.0
|
src/main/kotlin/com/dp/advancedgunnerycontrol/weaponais/SpecificAIPluginBase.kt
|
DesperatePeter
| 361,380,141
| false
| null |
package com.dp.advancedgunnerycontrol.weaponais
// Notes:
// Initially I was unaware that the player ship's current velocity affects targeting, so some of the code here is a bit patchy
// Most of the time a "angular distance", i.e. the sin, is used instead of angles in calculations, as sin(x) ~= x for small angles
import com.dp.advancedgunnerycontrol.settings.Settings
import com.dp.advancedgunnerycontrol.typesandvalues.Values
import com.fs.starfarer.api.combat.*
import com.fs.starfarer.api.impl.campaign.ids.HullMods
import org.lazywizard.lazylib.combat.CombatUtils
import org.lazywizard.lazylib.ext.minus
import org.lazywizard.lazylib.ext.plus
import org.lwjgl.util.vector.Vector2f
import kotlin.math.PI
import kotlin.math.min
abstract class SpecificAIPluginBase(
val baseAI: AutofireAIPlugin,
private val customAIActive: Boolean = Settings.enableCustomAI()
) : AutofireAIPlugin {
protected var solution: FiringSolution? = null
private var lastTargetEntity: CombatEntityAPI? = null
private var forceOff = false
private val weapon = baseAI.weapon
private var weaponShouldFire = false
private var currentTgtLeadAcc = 1.0f
private var lastP0 = 0.0f
/**
* @return a value dependent on distance and velocity of target. Lower is better
* If this turns out to eat too much performance, picking a pseudo-random target might be better
* hint: use computeBasePriority
* simply use return 0f if isBaseAIOverwritable = false
*/
protected abstract fun computeTargetPriority(solution: FiringSolution): Float
/**
* @return all enemy entities within weapon range and arc
* hint: use something like:
* CombatUtils.getXYZWithinRange(...).filterNotNull()
* simply use emptyList() if isBaseAIOverwritable = false
*/
protected abstract fun getRelevantEntitiesWithinRange(): List<CombatEntityAPI>
protected abstract fun getRelevenEntitiesOutOfRange(): List<CombatEntityAPI>
/**
* @return true if the target selected by the baseAI matches what the weapon should target
*/
protected abstract fun isBaseAITargetValid(ship: ShipAPI?, missile: MissileAPI?): Boolean
/**
* @return true if the weapon should try to acquire a new target using custom AI if base AI fails
*/
protected abstract fun isBaseAIOverwritable(): Boolean
/**
* perform checks to see if this AI is compatible with the weapon
* if this returns false, the base AI will be used instead
*/
abstract fun isValid(): Boolean
/**
* gets called at start of every advancement frame
*/
private fun reset() {
determineTargetLeadingAccuracy(solution?.target, lastTargetEntity)
lastTargetEntity = solution?.target
solution = null
forceOff = false
weaponShouldFire = false
}
override fun advance(p0: Float) {
lastP0 = p0
reset()
if (!advanceBaseAI(p0) && customAIActive && isBaseAIOverwritable()) {
advanceWithCustomAI()
}
}
protected fun advanceBaseAI(p0: Float): Boolean {
if (Settings.forceCustomAI() && isBaseAIOverwritable()) return false
baseAI.advance(p0)
val ship = baseAI.targetShip
val missile = baseAI.targetMissile
val targetEntity = ship as? CombatEntityAPI ?: missile as? CombatEntityAPI
if (targetEntity != null && isBaseAITargetValid(ship, missile)) {
solution = FiringSolution(targetEntity, baseAI.target ?: computePointToAimAt(targetEntity))
weaponShouldFire = baseAI.shouldFire()
return true
}
return false
}
protected fun advanceWithCustomAI() {
var potentialTargets = calculateFiringSolutions(
getRelevantEntitiesWithinRange().filter { isHostile(it) }
).filter { isInRange(it.aimPoint, effectiveCollRadius(it.target)) } +
calculateFiringSolutions(getRelevenEntitiesOutOfRange().filter { isHostile(it) })
// TODO: It would be faster to get friendlies and foes in one go
if (Settings.customAIFriendlyFireComplexity() >= 2) {
// this is a deceptively expensive call (therefore locked behind opt-in setting)
potentialTargets = potentialTargets.filter { !isFriendlyFire(getFriendlies(), it.aimPoint) }
}
solution = potentialTargets.minByOrNull { computeTargetPriority(it) }
computeIfShouldFire(potentialTargets).let {
weaponShouldFire = it
}
}
protected open fun getFriendlies(): List<FiringSolution> {
return calculateFiringSolutions(
CombatUtils.getShipsWithinRange(weapon.location, weapon.range).filter { it != weapon.ship }.filter {
(it.isAlly || (it.owner == 0) || (it.owner == 100 && shouldConsiderNeutralsAsFriendlies())) && !it.isFighter
}).filter {
isInRange(it.aimPoint, effectiveCollRadius(it.target) * Settings.customAIFriendlyFireCaution())
&& isWithinArc(it.aimPoint, effectiveCollRadius(it.target) * Settings.customAIFriendlyFireCaution())
}
}
protected fun determineTargetLeadingAccuracy(currentTarget: CombatEntityAPI?, lastTarget: CombatEntityAPI?) {
if (Settings.customAIPerfectTargetLeading()) {
currentTgtLeadAcc = 1.0f
return
}
currentTgtLeadAcc = if (currentTarget == lastTarget) {
min(currentTgtLeadAcc + 0.2f * lastP0, 1.0f)
} else {
weapon.ship?.mutableStats?.autofireAimAccuracy?.modifiedValue ?: 1.0f
}
}
protected fun compensateTargetPointShipSpeed(tgt: Vector2f, ttt: Float): Vector2f {
val vel = weapon.ship?.velocity ?: Vector2f(0.0f, 0.0f)
return tgt - (vel times_ ttt)
}
// compensates for both player ship and target velocities
protected fun calculateFiringSolutions(potentialTargets: List<CombatEntityAPI>): List<FiringSolution> {
return potentialTargets.map {
FiringSolution(it, computePointToAimAt(it))
}
}
override fun forceOff() {
baseAI.forceOff()
forceOff = true
}
override fun getTarget(): Vector2f? {
return solution?.aimPoint ?: getNeutralPosition(weapon)
}
override fun getWeapon(): WeaponAPI {
return weapon
}
/**
* approximate position where the target will be after travel time
* based on player ship and target velocities.
* In a way, this transforms points from an absolute to a "relative" frame
* Some observations:
* - angles are in degrees
* - target ships can strafe, i.e. velocity direction =/= heading
* - acceleration refers to max possible acceleration, not current acceleration
* conclusion: Don't use acceleration or angular velocity, they are unreliable
*/
protected fun computePointToAimAt(tgt: CombatEntityAPI): Vector2f {
if (!isAimable(weapon)) {
return getNeutralPosition(weapon)
}
var tgtPoint = tgt.location
// no need to compute stuff for beam or non-aimable weapons
if (weapon.isBeam || weapon.isBurstBeam) {
return tgtPoint
}
for (i in 0 until Settings.customAIRecursionLevel()) {
val travelT = computeTimeToTravel(tgtPoint)
val velocityOffset = (tgt.velocity) times_ travelT
tgtPoint = compensateTargetPointShipSpeed(tgt.location + velocityOffset, travelT)
}
return tgtPoint
}
protected fun computeTimeToTravel(tgt: Vector2f): Float {
return computeTimeToTravel(weapon, tgt, (1.5f - 0.5f * currentTgtLeadAcc))
}
override fun getTargetShip(): ShipAPI? {
return solution?.target as? ShipAPI
}
override fun getTargetMissile(): MissileAPI? {
return solution?.target as? MissileAPI
}
protected fun isWithinArc(entity: CombatEntityAPI): Boolean {
if (!isAimable(weapon)) return true
return isWithinArc(entity.location, effectiveCollRadius(entity))
}
protected fun isWithinArc(position: Vector2f, radius: Float): Boolean {
// Note: This is using an approximated angle, which should be fine as angles should be rather small
return weapon.distanceFromArc(position) <=
(radius / (weapon.location - position).length()) * 180f / PI * aimingToleranceFactor
}
protected open fun shouldConsiderNeutralsAsFriendlies(): Boolean = true
// if aimPoint == null, the current weapon facing will be used
protected fun isFriendlyFire(friendlies: List<FiringSolution>, aimPoint: Vector2f? = null): Boolean = when {
weapon.spec.weaponId == "guardian" -> false // Paladin PD can shoot over friendlies
!isAimable(weapon) -> false // Guided missiles can shoot over friendlies
friendliesInDangerZone(friendlies, aimPoint).isEmpty() -> false
else -> true
}
protected fun friendliesInDangerZone(friendlies: List<FiringSolution>, aimPoint: Vector2f? = null):
List<FiringSolution> {
val ap = aimPoint ?: (vectorFromAngleDeg(weapon.currAngle) + weapon.location)
fun filterPred(firingSol: FiringSolution): Boolean{
val colRad = effectiveCollRadius(firingSol.target) * Settings.customAIFriendlyFireCaution()
val isCloserThanTgt = solution?.aimPoint?.let { tp ->
linearDistanceFromWeapon(
firingSol.aimPoint,
weapon
) < linearDistanceFromWeapon(tp, weapon)
} ?: true
val spread = weapon.getMaxSpreadForNextBurst()
if(spread < 5f){
return determineIfShotWillHit(
firingSol.aimPoint,
colRad,
weapon,
aimPoint
) && isCloserThanTgt
}else{
val enemyPos = solution?.aimPoint ?: return false
val enemyColRad = effectiveCollRadius(firingSol.target)
if(isCloserThanTgt){
val friendlyExposure = computeWeaponConeExposureRad(weapon.location, ap, spread, firingSol.aimPoint, colRad + 100f)
val enemyExposure = computeWeaponConeExposureRadWithEclipsingEntity(weapon.location, ap, spread, enemyPos, enemyColRad, firingSol.aimPoint, colRad)
return enemyExposure * 0.05f < friendlyExposure * Settings.customAIFriendlyFireCaution()
}else{
val friendlyExposure = computeWeaponConeExposureRadWithEclipsingEntity(weapon.location, ap, spread, firingSol.aimPoint, colRad + 30f, enemyPos, enemyColRad)
val enemyExposure = computeWeaponConeExposureRad(weapon.location, ap, spread, enemyPos, enemyColRad)
return enemyExposure * 0.1f < friendlyExposure * Settings.customAIFriendlyFireCaution()
}
}
}
return friendlies.filter { firingSol ->
filterPred(firingSol)
}
}
protected open fun computeIfShouldFire(potentialTargets: List<FiringSolution>): Boolean {
if (!isAimable(weapon)) {
return potentialTargets.isNotEmpty()
}
if (Settings.customAIFriendlyFireComplexity() >= 1) {
if (isFriendlyFire(getFriendlies())) return false
}
// Note: In a sequence, all calculations are done on the first element before moving to the next
potentialTargets.asSequence().filter { isInRange(it.aimPoint, effectiveCollRadius(it.target)) }.iterator()
.forEach {
val effectiveCollisionRadius =
effectiveCollRadius(it.target) * aimingToleranceFactor + aimingToleranceFlat
if (determineIfShotWillHitBySetting(it.target, it.aimPoint, effectiveCollisionRadius, weapon)) return true
}
return false
}
protected fun computePointCurrentlyAimedAt(): Vector2f {
val ship = weapon.ship ?: return Vector2f(0f, 0f)
return (vectorFromAngleDeg(weapon.currAngle) times_ weapon.range) + ship.location
}
/**
* @brief compute a priority number for a target based on lin/angular distance, whether it's the ship target etc
* @return low (>=0) number for high priority targets, high number for low priority targets
*/
protected fun computeBasePriority(solution: FiringSolution): Float {
val shipModifier = (solution.target as? ShipAPI)?.let { ship ->
1.0f *
(if(ship == weapon.ship.shipTarget) 0.05f else 1.0f) * // heavily incentivize targeting the ship target
(if(ship.isFighter) 1f else 0.8f) * // prioritize regular ships over other stuff
(if(ship.variant?.hasHullMod("do_not_fire_through") == true) 100f else 1f)
} ?: 1f
return solution.aimPoint.let {
angularDistanceFromWeapon(it, weapon) + Values.distToAngularDistEvaluationFactor * linearDistanceFromWeapon(
it,
weapon
) + 1.5f
} * (if (lastTargetEntity == solution.target) 0.5f else 1f) * // incentivize sticking to one target
shipModifier
}
override fun shouldFire(): Boolean {
return weaponShouldFire
}
protected fun isInRange(entity: Vector2f, radius: Float = 0f): Boolean {
return linearDistanceFromWeapon(entity, weapon) - radius <=
weapon.range + (0.25f * Settings.customAITriggerHappiness() * weapon.projectileFadeRange)
}
companion object {
protected val aimingToleranceFactor = 1.0f * Settings.customAITriggerHappiness()
protected val aimingToleranceFlat = 10f * Settings.customAITriggerHappiness()
}
}
| 2
| null |
3
| 9
|
514c3a1b9bd3f16ad6d0c602c9d9bdd9b50fb9fb
| 13,833
|
starsector-advanced-weapon-control
|
MIT License
|
compiler/ir/backend.jvm/codegen/src/org/jetbrains/kotlin/backend/jvm/codegen/JvmSignatureClashDetector.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.jvm.codegen
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
import org.jetbrains.kotlin.backend.jvm.JvmLoweredDeclarationOrigin
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.descriptors.toIrBasedDescriptor
import org.jetbrains.kotlin.ir.util.isFakeOverride
import org.jetbrains.kotlin.resolve.jvm.diagnostics.*
import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.org.objectweb.asm.Type
class JvmSignatureClashDetector(
private val irClass: IrClass,
private val type: Type,
private val context: JvmBackendContext
) {
private val methodsBySignature = HashMap<RawSignature, MutableSet<IrFunction>>()
private val fieldsBySignature = HashMap<RawSignature, MutableSet<IrField>>()
fun trackField(irField: IrField, rawSignature: RawSignature) {
fieldsBySignature.getOrPut(rawSignature) { SmartSet.create() }.add(irField)
}
fun trackMethod(irFunction: IrFunction, rawSignature: RawSignature) {
methodsBySignature.getOrPut(rawSignature) { SmartSet.create() }.add(irFunction)
}
fun trackFakeOverrideMethod(irFunction: IrFunction) {
if (irFunction.dispatchReceiverParameter != null) {
for (overriddenFunction in getOverriddenFunctions(irFunction as IrSimpleFunction)) {
trackMethod(irFunction, mapRawSignature(overriddenFunction))
}
} else {
trackMethod(irFunction, mapRawSignature(irFunction))
}
}
private fun mapRawSignature(irFunction: IrFunction): RawSignature {
val jvmSignature = context.methodSignatureMapper.mapSignatureSkipGeneric(irFunction)
return RawSignature(jvmSignature.asmMethod.name, jvmSignature.asmMethod.descriptor, MemberKind.METHOD)
}
private fun getOverriddenFunctions(irFunction: IrSimpleFunction): Set<IrFunction> {
val result = HashSet<IrFunction>()
collectOverridesOf(irFunction, result)
return result
}
private fun collectOverridesOf(irFunction: IrSimpleFunction, result: MutableSet<IrFunction>) {
for (overriddenSymbol in irFunction.overriddenSymbols) {
collectOverridesTree(overriddenSymbol.owner, result)
}
}
private fun collectOverridesTree(irFunction: IrSimpleFunction, visited: MutableSet<IrFunction>) {
if (!visited.add(irFunction)) return
collectOverridesOf(irFunction, visited)
}
private fun IrFunction.isSpecialOverride(): Boolean =
origin in SPECIAL_BRIDGES_AND_OVERRIDES
fun reportErrors(classOrigin: JvmDeclarationOrigin) {
// Class IFoo$DefaultImpls has conflicting signatures if and only if corresponding interface IFoo has conflicting signatures.
// Do not report these diagnostics twice.
if (irClass.origin == JvmLoweredDeclarationOrigin.DEFAULT_IMPLS) return
reportMethodSignatureConflicts(classOrigin)
reportPredefinedMethodSignatureConflicts(classOrigin)
reportFieldSignatureConflicts(classOrigin)
}
private fun reportMethodSignatureConflicts(classOrigin: JvmDeclarationOrigin) {
for ((rawSignature, methods) in methodsBySignature) {
if (methods.size <= 1) continue
val fakeOverridesCount = methods.count { it.isFakeOverride }
val specialOverridesCount = methods.count { it.isSpecialOverride() }
val realMethodsCount = methods.size - fakeOverridesCount - specialOverridesCount
val conflictingJvmDeclarationsData = getConflictingJvmDeclarationsData(classOrigin, rawSignature, methods)
when {
realMethodsCount == 0 && (fakeOverridesCount > 1 || specialOverridesCount > 1) ->
reportJvmSignatureClash(
ErrorsJvm.CONFLICTING_INHERITED_JVM_DECLARATIONS,
listOf(irClass),
conflictingJvmDeclarationsData
)
fakeOverridesCount == 0 && specialOverridesCount == 0 ->
reportJvmSignatureClash(
ErrorsJvm.CONFLICTING_JVM_DECLARATIONS,
methods,
conflictingJvmDeclarationsData
)
else ->
reportJvmSignatureClash(
ErrorsJvm.ACCIDENTAL_OVERRIDE,
methods.filter { !it.isFakeOverride && !it.isSpecialOverride() },
conflictingJvmDeclarationsData
)
}
}
}
private fun reportPredefinedMethodSignatureConflicts(classOrigin: JvmDeclarationOrigin) {
for (predefinedSignature in PREDEFINED_SIGNATURES) {
val knownMethods = methodsBySignature[predefinedSignature] ?: continue
val methods = knownMethods.filter { !it.isFakeOverride && !it.isSpecialOverride() }
if (methods.isEmpty()) continue
val conflictingJvmDeclarationsData = ConflictingJvmDeclarationsData(
type.internalName, classOrigin, predefinedSignature,
methods.map { it.getJvmDeclarationOrigin() } + JvmDeclarationOrigin(JvmDeclarationOriginKind.OTHER, null, null)
)
reportJvmSignatureClash(ErrorsJvm.ACCIDENTAL_OVERRIDE, methods, conflictingJvmDeclarationsData)
}
}
private fun reportFieldSignatureConflicts(classOrigin: JvmDeclarationOrigin) {
for ((rawSignature, fields) in fieldsBySignature) {
if (fields.size <= 1) continue
val conflictingJvmDeclarationsData = getConflictingJvmDeclarationsData(classOrigin, rawSignature, fields)
reportJvmSignatureClash(ErrorsJvm.CONFLICTING_JVM_DECLARATIONS, fields, conflictingJvmDeclarationsData)
}
}
private fun reportJvmSignatureClash(
diagnosticFactory1: DiagnosticFactory1<PsiElement, ConflictingJvmDeclarationsData>,
irDeclarations: Collection<IrDeclaration>,
conflictingJvmDeclarationsData: ConflictingJvmDeclarationsData
) {
val psiElements = irDeclarations.mapNotNullTo(HashSet()) { it.getElementForDiagnostics() }
for (psiElement in psiElements) {
context.psiErrorBuilder.at(psiElement)
.report(diagnosticFactory1, conflictingJvmDeclarationsData)
}
}
private fun IrDeclaration.findPsiElement() = context.psiSourceManager.findPsiElement(this)
private fun IrDeclaration.getElementForDiagnostics(): PsiElement? =
findPsiElement()
?: irClass.findPsiElement()
private fun getConflictingJvmDeclarationsData(
classOrigin: JvmDeclarationOrigin,
rawSignature: RawSignature,
methods: Collection<IrDeclaration>
): ConflictingJvmDeclarationsData =
ConflictingJvmDeclarationsData(
type.internalName,
classOrigin,
rawSignature,
methods.map { it.getJvmDeclarationOrigin() }
)
private fun IrDeclaration.getJvmDeclarationOrigin(): JvmDeclarationOrigin {
// It looks like 'JvmDeclarationOriginKind' is not really used in error reporting.
// However, if needed, we can provide more meaningful information regarding function origin.
return JvmDeclarationOrigin(
JvmDeclarationOriginKind.OTHER,
context.psiSourceManager.findPsiElement(this),
toIrBasedDescriptor()
)
}
companion object {
val SPECIAL_BRIDGES_AND_OVERRIDES = setOf(
IrDeclarationOrigin.BRIDGE,
IrDeclarationOrigin.BRIDGE_SPECIAL,
IrDeclarationOrigin.IR_BUILTINS_STUB,
JvmLoweredDeclarationOrigin.TO_ARRAY,
JvmLoweredDeclarationOrigin.DEFAULT_IMPLS_BRIDGE,
JvmLoweredDeclarationOrigin.DEFAULT_IMPLS_BRIDGE_FOR_COMPATIBILITY,
JvmLoweredDeclarationOrigin.DEFAULT_IMPLS_BRIDGE_TO_SYNTHETIC,
JvmLoweredDeclarationOrigin.DEFAULT_IMPLS_BRIDGE_FOR_COMPATIBILITY_SYNTHETIC
)
val PREDEFINED_SIGNATURES = listOf(
RawSignature("getClass", "()Ljava/lang/Class;", MemberKind.METHOD),
RawSignature("notify", "()V", MemberKind.METHOD),
RawSignature("notifyAll", "()V", MemberKind.METHOD),
RawSignature("wait", "()V", MemberKind.METHOD),
RawSignature("wait", "(J)V", MemberKind.METHOD),
RawSignature("wait", "(JI)V", MemberKind.METHOD)
)
}
}
| 157
| null |
5411
| 43,797
|
a8f547d080724fae3a45d675a16c5b3fc2f13b17
| 8,802
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/ti/sunrain/SunRainApplication.kt
|
bluebonnet27
| 317,797,469
| false
| null |
package com.ti.sunrain
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
/**
* @author: tihon
* @date: 2020/12/3
* @description:这个类的作用是提供全局的context
*/
class SunRainApplication:Application() {
/**
* 静态获取全局上下文的单例类
*/
companion object{
//确保注解通过 as 的静态审查,不带这个会报错 2020-12-01
@Suppress("StaticFieldLeak")
lateinit var context:Context
lateinit var settingsPreference:SharedPreferences
//彩云天气令牌值
const val TOKEN = "QTeX2n8AQjAhR9BV"
}
/**
* 全局调用 context
*/
override fun onCreate() {
super.onCreate()
context = applicationContext
settingsPreference = getSharedPreferences("settings",0)
}
}
| 1
| null |
2
| 6
|
68696f18320a86799e0b2243a92c7fa45df83272
| 767
|
SunRain
|
MIT License
|
app/src/main/java/com/ti/sunrain/SunRainApplication.kt
|
bluebonnet27
| 317,797,469
| false
| null |
package com.ti.sunrain
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
/**
* @author: tihon
* @date: 2020/12/3
* @description:这个类的作用是提供全局的context
*/
class SunRainApplication:Application() {
/**
* 静态获取全局上下文的单例类
*/
companion object{
//确保注解通过 as 的静态审查,不带这个会报错 2020-12-01
@Suppress("StaticFieldLeak")
lateinit var context:Context
lateinit var settingsPreference:SharedPreferences
//彩云天气令牌值
const val TOKEN = "QTeX2n8AQjAhR9BV"
}
/**
* 全局调用 context
*/
override fun onCreate() {
super.onCreate()
context = applicationContext
settingsPreference = getSharedPreferences("settings",0)
}
}
| 1
| null |
2
| 6
|
68696f18320a86799e0b2243a92c7fa45df83272
| 767
|
SunRain
|
MIT License
|
src/commonMain/kotlin/net/notjustanna/lin/ast/node/control/optimization/ScopeExpr.kt
|
annathelibri
| 280,314,655
| false
|
{"Kotlin": 323273}
|
package net.notjustanna.lin.ast.node.control.optimization
//data class ScopeExpr(val body: Expr, override val section: Section? = null) : Expr {
// /* @automation-disabled(ast.impl ScopeExpr,Expr)-start */
// override fun accept(visitor: NodeVisitor) = visitor.visitScopeExpr(this)
//
// override fun accept(visitor: NodeMapVisitor): Expr = visitor.visitScopeExpr(this)
//
// override fun <R> accept(visitor: NodeVisitorR<R>): R = visitor.visitScopeExpr(this)
//
// override fun <T> accept(visitor: NodeVisitor1<T>, param0: T) = visitor.visitScopeExpr(this, param0)
// /* @automation-end */
//}
| 17
|
Kotlin
|
0
| 7
|
b3b10f34e85bc7dec2d3b94d0d6fb2e51dcf1fbf
| 614
|
Lin
|
MIT License
|
amazon-chime-sdk/src/main/java/com/amazonaws/services/chime/sdk/meetings/utils/Versioning.kt
|
aws
| 249,543,698
| false
| null |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.services.chime.sdk.meetings.utils
import com.amazonaws.services.chime.sdk.BuildConfig
/**
* [Versioning] provides API to retrieve SDK version
*/
class Versioning {
companion object {
/**
* Return current version of Amazon Chime SDK for Android.
*/
fun sdkVersion(): String {
return BuildConfig.VERSION_NAME
}
}
}
| 33
| null |
53
| 99
|
eb9110d7d34a1a24d8e8162efa0ae1a094c421fd
| 518
|
amazon-chime-sdk-android
|
Apache License 2.0
|
src/main/kotlin/org/jetbrains/tinygoplugin/inspections/TinyGoInterfaceInspection.kt
|
JetBrains
| 334,932,962
| false
|
{"Go": 1625409, "Kotlin": 221745, "Lex": 7709, "JavaScript": 3972, "HTML": 3177, "CSS": 1140}
|
package org.jetbrains.tinygoplugin.inspections
import com.goide.inspections.core.GoInspectionBase
import com.goide.inspections.core.GoProblemsHolder
import com.goide.psi.GoConditionalExpr
import com.goide.psi.GoInterfaceType
import com.goide.psi.GoNamedElement
import com.goide.psi.GoVisitor
import com.goide.psi.impl.GoTypeUtil
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.psi.PsiElement
import org.jetbrains.tinygoplugin.configuration.tinyGoConfiguration
class TinyGoInterfaceInspection : GoInspectionBase() {
companion object {
const val INTERFACE_INSPECTION_MESSAGE_KEY = "inspection.interface.message"
}
override fun buildVisitor(holder: GoProblemsHolder, session: LocalInspectionToolSession): GoVisitor =
object : GoVisitor() {
override fun visitConditionalExpr(conditionalExpr: GoConditionalExpr) {
val tinyGoConfiguration = conditionalExpr.project.tinyGoConfiguration()
if (!tinyGoConfiguration.enabled) {
return
}
super.visitConditionalExpr(conditionalExpr)
if (conditionalExpr.eq != null || conditionalExpr.notEq != null) {
val arguments = conditionalExpr.children
if (arguments.size != 2) {
return
}
val interfaceComparison = arguments.all { isInterface(it) }
if (interfaceComparison) {
holder.registerProblem(
conditionalExpr,
inspectionMessage(INTERFACE_INSPECTION_MESSAGE_KEY)
)
}
}
}
}
}
@Suppress("ReturnCount")
private fun isInterface(element: PsiElement): Boolean {
val variableDeclaration = element.reference?.resolve() ?: return false
if (variableDeclaration !is GoNamedElement) {
return false
}
val goType = variableDeclaration.getGoType(null) ?: return false
// check if variable is declared with
// var a interface{}
if (goType is GoInterfaceType) {
return true
}
val typeSpec = GoTypeUtil.findTypeSpec(goType, null) ?: return false
return GoTypeUtil.isInterface(typeSpec)
}
| 1
|
Go
|
6
| 35
|
d3ae7d82e98da1aeb2eb875a040e96c76e9ab8f8
| 2,320
|
tinygo-plugin
|
Apache License 2.0
|
lib/src/test/kotlin/com/maltaisn/recurpicker/RecurrenceFinderTest.kt
|
maltaisn
| 116,074,300
| false
| null |
/*
* Copyright 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.
*/
@file:Suppress("MaxLineLength")
package com.maltaisn.recurpicker
import com.maltaisn.recurpicker.Recurrence.Period
import org.junit.Test
import java.util.TimeZone
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
internal class RecurrenceFinderTest {
// To validate events with RRule: http://jakubroztocil.github.io/rrule/
private val finder = RecurrenceFinder()
@Test
fun `should fail to find events with negative max amount`() {
val r = Recurrence(Period.DAILY)
assertFailsWith<IllegalArgumentException> {
finder.find(r, dateFor("2019-01-01"), -1)
}
}
@Test
fun `should fail to find events given no start date`() {
val r = Recurrence(Period.DAILY)
assertFailsWith<IllegalArgumentException> {
finder.find(r, Recurrence.DATE_NONE, 1)
}
}
@Test
fun `should return empty list with amount set to zero`() {
val r = Recurrence(Period.DAILY)
assertEquals(emptyList<Long>(), finder.find(r, dateFor("2019-01-01"), 0))
}
@Test
fun `should only find start date for 'does not repeat' recurrence`() {
val r = Recurrence.DOES_NOT_REPEAT
assertEquals(listOf(
dateFor("2019-01-01")
), finder.find(r, dateFor("2019-01-01"), 10))
}
@Test
fun `should only find start date for 'does not repeat' recurrence given a from date before start`() {
val r1 = Recurrence.DOES_NOT_REPEAT
assertEquals(listOf(
dateFor("2019-01-01")
), finder.find(r1, dateFor("2019-01-01"), 10, dateFor("2019-01-01")))
}
@Test
fun `should find no events for 'does not repeat' recurrence given a from date after start`() {
val r2 = Recurrence.DOES_NOT_REPEAT
assertEquals(emptyList<Long>(), finder.find(r2,
dateFor("2019-01-01"), 10, dateFor("2019-01-02")))
}
@Test
fun `should find no events for 'does not repeat' recurrence if start is excluded`() {
val r = Recurrence.DOES_NOT_REPEAT
assertEquals(emptyList<Long>(), finder.find(r,
dateFor("2019-01-01"), 10, dateFor("2019-01-01"), includeStart = false))
}
@Test
fun `should find events for daily recurrence`() {
val r = Recurrence(Period.DAILY)
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-02"),
dateFor("2019-01-03"),
dateFor("2019-01-04"),
dateFor("2019-01-05")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for daily recurrence from a specific date`() {
val r = Recurrence(Period.DAILY)
assertEquals(listOf(
dateFor("2019-01-03"),
dateFor("2019-01-04"),
dateFor("2019-01-05")
), finder.find(r, dateFor("2019-01-01"), 3, dateFor("2019-01-03")))
}
@Test
fun `should find events for daily recurrence with frequency 3`() {
val r = Recurrence(Period.DAILY) {
frequency = 3
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-04"),
dateFor("2019-01-07"),
dateFor("2019-01-10"),
dateFor("2019-01-13")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for daily recurrence stoppping at end date`() {
val r = Recurrence(Period.DAILY) {
endDate = dateFor("2019-01-03")
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-02"),
dateFor("2019-01-03")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for daily recurrence stopping at end count`() {
val r = Recurrence(Period.DAILY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-02"),
dateFor("2019-01-03"),
dateFor("2019-01-04"),
dateFor("2019-01-05")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for daily recurrence based on previous event (with end count)`() {
val r = Recurrence(Period.DAILY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-01-03"),
dateFor("2019-01-04"),
dateFor("2019-01-05")
), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-03"), 3, 1000))
}
@Test
fun `should find events for daily recurrence based on previous event (with end count and from date)`() {
val r = Recurrence(Period.DAILY) {
endCount = 6
}
assertEquals(listOf(
dateFor("2019-01-05"),
dateFor("2019-01-06")
), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-03"), 3, 1000, dateFor("2019-01-05")))
}
@Test
fun `should find events for daily recurrence excluding start date`() {
val r = Recurrence(Period.DAILY)
assertEquals(listOf(
dateFor("2019-01-02"),
dateFor("2019-01-03")
), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false))
}
@Test
fun `should find events for weekly recurrence (on the same day of the week as start date)`() {
val r = Recurrence(Period.WEEKLY)
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-08"),
dateFor("2019-01-15"),
dateFor("2019-01-22"),
dateFor("2019-01-29")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for weekly recurrence (on set days of the week)`() {
val r = Recurrence(Period.WEEKLY) {
setDaysOfWeek(Recurrence.SUNDAY, Recurrence.MONDAY, Recurrence.WEDNESDAY)
}
assertEquals(listOf(
dateFor("2019-01-02"),
dateFor("2019-01-06"),
dateFor("2019-01-07"),
dateFor("2019-01-09"),
dateFor("2019-01-13")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for weekly recurrence from a specific date`() {
val r = Recurrence(Period.WEEKLY) {
setDaysOfWeek(Recurrence.SUNDAY)
}
assertEquals(listOf(
dateFor("2019-01-06"),
dateFor("2019-01-13"),
dateFor("2019-01-20")
), finder.find(r, dateFor("2019-01-01"), 3, dateFor("2019-01-05")))
}
@Test
fun `should find events on every day of the week for weekly recurrence (frequency 2)`() {
val r = Recurrence(Period.WEEKLY) {
frequency = 2
setDaysOfWeek(Recurrence.EVERY_DAY_OF_WEEK)
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-02"),
dateFor("2019-01-03"),
dateFor("2019-01-04"),
dateFor("2019-01-05"),
dateFor("2019-01-13"),
dateFor("2019-01-14"),
dateFor("2019-01-15")
), finder.find(r, dateFor("2019-01-01"), 8))
}
@Test
fun `should find events for weekly recurrence with frequency 3`() {
val r = Recurrence(Period.WEEKLY) {
frequency = 3
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-22"),
dateFor("2019-02-12"),
dateFor("2019-03-05"),
dateFor("2019-03-26")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for weekly recurrence stopping at end date`() {
val r = Recurrence(Period.WEEKLY) {
endDate = dateFor("2019-01-15")
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-08"),
dateFor("2019-01-15")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for weekly recurrence stopping at end count`() {
val r = Recurrence(Period.WEEKLY) {
endCount = 4
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-01-08"),
dateFor("2019-01-15"),
dateFor("2019-01-22")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for weekly recurrence based on previous event (with end count)`() {
val r = Recurrence(Period.WEEKLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-01-15"),
dateFor("2019-01-22"),
dateFor("2019-01-29")
), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-15"), 3, 1000))
}
@Test
fun `should find events for weekly recurrence based on previous event (with end count and from date)`() {
val r = Recurrence(Period.WEEKLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-01-22"),
dateFor("2019-01-29")
), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-15"),
3, 1000, dateFor("2019-01-22")))
}
@Test
fun `should find events for weekly recurrence excluding start date`() {
val r = Recurrence(Period.WEEKLY)
assertEquals(listOf(
dateFor("2019-01-08"),
dateFor("2019-01-15")
), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false))
}
@Test
fun `should find events for weekly recurrence excluding start (with start date not being an event)`() {
val r = Recurrence(Period.WEEKLY) {
setDaysOfWeek(Recurrence.WEDNESDAY, Recurrence.THURSDAY)
}
assertEquals(listOf(
dateFor("2019-01-02"),
dateFor("2019-01-03")
), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false))
}
@Test
fun `should find events for monthly recurrence`() {
val r = Recurrence(Period.MONTHLY)
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-02-01"),
dateFor("2019-03-01"),
dateFor("2019-04-01"),
dateFor("2019-05-01")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for monthly recurrence from a specific date`() {
val r = Recurrence(Period.MONTHLY)
assertEquals(listOf(
dateFor("2020-06-01"),
dateFor("2020-07-01"),
dateFor("2020-08-01")
), finder.find(r, dateFor("2019-01-01"), 3, dateFor("2020-05-05")))
}
@Test
fun `should find events for monthly recurrence (on the 31st day)`() {
val r = Recurrence(Period.MONTHLY) {
frequency = 3
}
assertEquals(listOf(
dateFor("2019-01-31"),
dateFor("2019-07-31"),
dateFor("2019-10-31"),
dateFor("2020-01-31")
), finder.find(r, dateFor("2019-01-31"), 4))
}
@Test
fun `should find events for monthly recurrence (on the third tuesday)`() {
val r = Recurrence(Period.MONTHLY) {
setDayOfWeekInMonth(Recurrence.TUESDAY, 3)
}
assertEquals(listOf(
dateFor("2019-01-15"),
dateFor("2019-02-19"),
dateFor("2019-03-19"),
dateFor("2019-04-16"),
dateFor("2019-05-21")
), finder.find(r, dateFor("2019-01-15"), 5))
}
@Test
fun `should find events for monthly recurrence (on the last day)`() {
val r = Recurrence(Period.MONTHLY) {
dayInMonth = -1
}
assertEquals(listOf(
dateFor("2019-01-31"),
dateFor("2019-02-28"),
dateFor("2019-03-31"),
dateFor("2019-04-30"),
dateFor("2019-05-31")
), finder.find(r, dateFor("2019-01-15"), 5))
}
@Test
fun `should find events for monthly recurrence (on the 15th to last day)`() {
val r = Recurrence(Period.MONTHLY) {
dayInMonth = -15
}
assertEquals(listOf(
dateFor("2019-01-17"),
dateFor("2019-02-14"),
dateFor("2019-03-17"),
dateFor("2019-04-16"),
dateFor("2019-05-17")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for monthly recurrence (on the last thursday)`() {
val r = Recurrence(Period.MONTHLY) {
setDayOfWeekInMonth(Recurrence.THURSDAY, -1)
}
assertEquals(listOf(
dateFor("2019-01-31"),
dateFor("2019-02-28"),
dateFor("2019-03-28"),
dateFor("2019-04-25"),
dateFor("2019-05-30")
), finder.find(r, dateFor("2019-01-31"), 5))
}
@Test
fun `should find events for monthly recurrence with frequency 3`() {
val r = Recurrence(Period.MONTHLY) {
frequency = 3
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-04-01"),
dateFor("2019-07-01"),
dateFor("2019-10-01"),
dateFor("2020-01-01")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for monthly recurrence stopping at end date`() {
val r = Recurrence(Period.MONTHLY) {
endDate = dateFor("2019-03-01")
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-02-01"),
dateFor("2019-03-01")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for monthly recurrence stopping at end count`() {
val r = Recurrence(Period.MONTHLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2019-02-01"),
dateFor("2019-03-01"),
dateFor("2019-04-01"),
dateFor("2019-05-01")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for monthly recurrence based on previous event (with end count)`() {
val r = Recurrence(Period.MONTHLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-03-01"),
dateFor("2019-04-01"),
dateFor("2019-05-01")
), finder.findBasedOn(r, dateFor("2019-01-01"),
dateFor("2019-03-01"), 3, 1000))
}
@Test
fun `should find events for monthly recurrence based on previous event (with end count and from date)`() {
val r = Recurrence(Period.MONTHLY) {
endCount = 6
}
assertEquals(listOf(
dateFor("2019-05-01"),
dateFor("2019-06-01")
), finder.findBasedOn(r, dateFor("2019-01-01"),
dateFor("2019-03-01"), 3, 1000, dateFor("2019-05-01")))
}
@Test
fun `should find events for monthly recurrence on last day, starting from over one month after 1st event, but before 2nd`() {
val r = Recurrence(Period.MONTHLY) {
endCount = 6
byMonthDay = -1
}
assertEquals(listOf(
dateFor("2019-03-31"),
dateFor("2019-04-30"),
dateFor("2019-05-31")
), finder.find(r, dateFor("2019-02-28"), 3, dateFor("2019-03-30")))
}
@Test
fun `should find events for monthly recurrence excluding start`() {
val r = Recurrence(Period.MONTHLY)
assertEquals(listOf(
dateFor("2019-02-01"),
dateFor("2019-03-01")
), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false))
}
@Test
fun `should find events for yearly recurrence`() {
val r = Recurrence(Period.YEARLY)
assertEquals(listOf(
dateFor("2019-03-23"),
dateFor("2020-03-23"),
dateFor("2021-03-23"),
dateFor("2022-03-23"),
dateFor("2023-03-23")
), finder.find(r, dateFor("2019-03-23"), 5))
}
@Test
fun `should find events for yearly recurrence with frequency 3`() {
val r = Recurrence(Period.YEARLY) {
frequency = 3
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2022-01-01"),
dateFor("2025-01-01"),
dateFor("2028-01-01"),
dateFor("2031-01-01")
), finder.find(r, dateFor("2019-01-01"), 5))
}
@Test
fun `should find events for yearly recurrence stopping at end date`() {
val r = Recurrence(Period.YEARLY) {
endDate = dateFor("2021-01-01")
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2020-01-01"),
dateFor("2021-01-01")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for yearly recurrence stopping at end count`() {
val r = Recurrence(Period.YEARLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2019-01-01"),
dateFor("2020-01-01"),
dateFor("2021-01-01"),
dateFor("2022-01-01"),
dateFor("2023-01-01")
), finder.find(r, dateFor("2019-01-01"), 1000))
}
@Test
fun `should find events for yearly recurrence based on previous event (with end count)`() {
val r = Recurrence(Period.YEARLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2021-01-01"),
dateFor("2022-01-01"),
dateFor("2023-01-01")
), finder.findBasedOn(r, dateFor("2019-01-01"),
dateFor("2021-01-01"), 3, 1000))
}
@Test
fun `should find events for yearly recurrence based on previous event (with end count and from date)`() {
val r = Recurrence(Period.YEARLY) {
endCount = 5
}
assertEquals(listOf(
dateFor("2022-01-01"),
dateFor("2023-01-01")
), finder.findBasedOn(r, dateFor("2019-01-01"),
dateFor("2021-01-01"), 3, 1000, dateFor("2022-01-01")))
}
@Test
fun `should find events for yearly recurrence excluding start`() {
val r = Recurrence(Period.YEARLY)
assertEquals(listOf(
dateFor("2020-01-01"),
dateFor("2021-01-01")
), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false))
}
@Test
fun `should find events for yearly recurrence excluding start and based on previous event`() {
val r = Recurrence(Period.YEARLY)
assertEquals(listOf(
dateFor("2022-01-01"),
dateFor("2023-01-01")
), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2021-01-01"),
2, 2, includeStart = false))
}
@Test
fun `should find events for yearly recurrence on feb 29`() {
val r = Recurrence(Period.YEARLY)
assertEquals(listOf(
dateFor("2096-02-29"),
dateFor("2104-02-29"),
dateFor("2108-02-29"),
dateFor("2112-02-29")
), finder.find(r, dateFor("2096-02-29"), 4))
}
@Test
fun `should find events between two dates (daily recurrence)`() {
val r = Recurrence(Period.DAILY)
assertEquals(listOf(
dateFor("2019-01-27"),
dateFor("2019-01-28"),
dateFor("2019-01-29")
), finder.findBetween(r, dateFor("2019-01-01"),
dateFor("2019-01-27"), dateFor("2019-01-30")))
}
@Test
fun `should find events between two dates (recurrence with end count)`() {
val r = Recurrence(Period.DAILY) {
endCount = 7
}
assertEquals(listOf(
dateFor("2019-01-04"),
dateFor("2019-01-05"),
dateFor("2019-01-06"),
dateFor("2019-01-07")
), finder.findBetween(r, dateFor("2019-01-01"),
dateFor("2019-01-04"), dateFor("2019-01-10")))
}
@Test
fun `should find events between two dates (no events)`() {
val r = Recurrence(Period.MONTHLY)
assertEquals(emptyList<Long>(), finder.findBetween(r, dateFor("2019-01-01"),
dateFor("2019-01-04"), dateFor("2019-01-10")))
}
@Test
fun `should find events for recurrence using non-default timezone`() {
// This test should fail if not setting the timezone.
finder.timeZone = TimeZone.getTimeZone("GMT+07:00")
val r = Recurrence(Period.WEEKLY) {
setDaysOfWeek(Recurrence.THURSDAY)
}
assertEquals(listOf(
dateFor("2020-07-30T00:00:00.000+07:00"),
dateFor("2020-08-06T00:00:00.000+07:00")
), finder.find(r, dateFor("2020-07-29T00:00:00.000+07:00"), 2))
}
@Test
fun `should find events for recurrence until date with timezone`() {
finder.timeZone = TimeZone.getTimeZone("GMT-04:00")
val r = Recurrence(Period.DAILY) {
endDate = dateFor("2020-08-08T00:00:00.000+04:00")
}
assertEquals(listOf(
dateFor("2020-08-06T00:00:00.000+04:00"),
dateFor("2020-08-07T00:00:00.000+04:00"),
dateFor("2020-08-08T00:00:00.000+04:00")
), finder.find(r, dateFor("2020-08-06T00:00:00.000+04:00"), 1000))
}
@Test
fun `should find events for recurrence, keeping original time of the day`() {
val r = Recurrence(Period.DAILY)
assertEquals(listOf(
dateFor("2020-07-29T07:34:12.001"),
dateFor("2020-07-30T07:34:12.001"),
dateFor("2020-07-31T07:34:12.001")
), finder.find(r, dateFor("2020-07-29T07:34:12.001"), 3))
}
}
| 2
|
Kotlin
|
16
| 66
|
7f8c90a0efbf633e1265cee0303e1580bc9e672f
| 22,348
|
recurpickerlib
|
Apache License 2.0
|
app/src/main/java/com/linkerpad/linkerpad/Adapters/MembersListAdapter.kt
|
LinkerpadStartup
| 142,832,347
| false
| null |
package com.linkerpad.linkerpad.Adapters
import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.support.v4.app.ActivityCompat
import android.support.v7.widget.RecyclerView
import android.util.Base64
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.linkerpad.linkerpad.Data.MemberInformationData
import com.linkerpad.linkerpad.Data.ProjectInformationData
import kotlinx.android.synthetic.main.projetcs_items.view.*
import kotlinx.android.synthetic.main.team_items.*
import kotlinx.android.synthetic.main.team_items.view.*
import android.support.v4.content.ContextCompat.startActivity
import android.content.Intent.getIntent
import android.support.v4.content.ContextCompat.startActivity
import android.content.Intent.getIntent
import android.content.SharedPreferences
import android.graphics.drawable.BitmapDrawable
import android.support.annotation.NonNull
import android.support.v4.app.FragmentActivity
import android.widget.Toast
import com.linkerpad.linkerpad.*
import com.linkerpad.linkerpad.ApiData.output.RemoveMemberResponse
import com.linkerpad.linkerpad.Business.IUserApi
import com.linkerpad.linkerpad.Business.IWebApi
import com.linkerpad.linkerpad.Models.MemberViewModel
import com.linkerpad.linkerpad.Models.MemberViewModel.Companion.removeMember
import retrofit2.Call
import retrofit2.Response
/**
* Created by alihajiloo on 8/20/18.
*/
class MembersListAdapter(var context: Context,var activity:FragmentActivity, var data: ArrayList<MemberInformationData>, var projectId: String) : RecyclerView.Adapter<MembersListAdapter.ViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.team_items, viewGroup, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.bindModel(data[position], position)
/* viewHolder.itemView.deleteMemberImv.setOnClickListener {
AlertDialog.Builder(context)
.setMessage("آیا از حذف این عضو از پروژه مطمئن هستید؟")
.setPositiveButton("حذف شود", { dialog, view ->
dialog.dismiss()
removeMember(data[position].id, projectId)
}).setNegativeButton("خیر", { dialogInterface, i ->
dialogInterface.dismiss()
})
.create()
.show()
}*/
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@SuppressLint("MissingPermission")
@TargetApi(Build.VERSION_CODES.O)
fun bindModel(itemModel: MemberInformationData, position: Int) {
var i: Int = 0
itemView.nameLastNameTv.setText("${itemModel.firstName} ${itemModel.lastName}")
if (itemModel.profilePicture != "")
// itemView.userProfilePictureImv.setImageBitmap(BitmapFactory.decodeByteArray(java.util.Base64.getDecoder().decode(itemModel.profilePicture), 0, java.util.Base64.getDecoder().decode(itemModel.profilePicture).size))
itemView.memberCard.setOnClickListener {
if (i == 0) {
showViews(itemModel)
i = 1
} else {
clearViews()
i = 0
}
}
if (itemModel.profilePicture != "" && itemModel.profilePicture != null) {
val b = Base64.decode(itemModel.profilePicture, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(b, 0, b.size)
// var profileBitmap:Bitmap = BitmapFactory.decodeByteArray(Base64.getDecoder().decode(itemModel.projectPicture), 0, Base64.getDecoder().decode(itemModel.projectPicture).size)
itemView.userProfilePictureImv.setImageDrawable(BitmapDrawable(context.resources, bitmap))
}
itemView.callTeamImv.setOnClickListener {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
var phoneIntent: Intent = Intent(Intent.ACTION_CALL)
phoneIntent.setData(Uri.parse("tel:0${itemModel.mobileNumber.substring(2)}"))
context.startActivity(phoneIntent)
} else {
ActivityCompat.requestPermissions(activity, arrayOf(android.Manifest.permission.CALL_PHONE), 1)
}
}
itemView.emailTeamImv.setOnClickListener {
var emailIntent = Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", "${itemModel.emailAddress}", null))
context.startActivity(Intent.createChooser(emailIntent, "ارسال ایمیل با ..."))
}
/* itemView.memberCard.setOnLongClickListener {
var intent = Intent(context, EditMemberBottomSheetActivity::class.java)
// var option: ActivityOptions = ActivityOptions.makeCustomAnimation(context,R.anim.slide_top , R.anim.abc_fade_out)
intent.putExtra("id", data[position].id)
intent.putExtra("projectId", projectId)
context.startActivity(intent)
return@setOnLongClickListener true
}*/
itemView.deleteMemberImv.setOnClickListener {
// Toast.makeText(context,"${itemModel.firstName}" , Toast.LENGTH_LONG).show()
/* AlertDialog.Builder(context.applicationContext)
.setMessage("حذف این فرد از پروژه را تایید میکنید؟")
.setPositiveButton("بله", { dialog, view ->
dialog.dismiss()
removeMember(data[position].id, projectId)
}).setNegativeButton("خیر", { dialogInterface, i ->
dialogInterface.dismiss()
})
.create()
.show()*/
var intent = Intent(context, CustomAlertDialog::class.java)
// var option: ActivityOptions = ActivityOptions.makeCustomAnimation(context,R.anim.slide_top , R.anim.abc_fade_out)
intent.putExtra("id", data[position].id)
intent.putExtra("projectId", projectId)
intent.putExtra("message", "حذف این فرد از پروژه را تایید میکنید؟")
intent.putExtra("positive", "بله")
intent.putExtra("negative", "خیر")
context.startActivity(intent)
}
itemView.editMemberImv.setOnClickListener {
//Toast.makeText(context,"${itemModel.lastName}" , Toast.LENGTH_LONG).show()
var intent = Intent(context, EditMemberActivity::class.java)
// var option: ActivityOptions = ActivityOptions.makeCustomAnimation(context,R.anim.slide_top , R.anim.abc_fade_out)
intent.putExtra("userId", data[position].id)
intent.putExtra("projectId", projectId)
intent.putExtra("email", data[position].emailAddress)
intent.putExtra("userRole",data[position].userRole)
context.startActivity(intent)
}
}
fun showViews(itemModel: MemberInformationData) {
var llParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
itemView.firstTeamLL.layoutParams = llParams
itemView.secondTeamLL.layoutParams = llParams
itemView.thirdTeamLL.layoutParams = llParams
itemView.moreTeamImv.setImageDrawable(context.resources.getDrawable(R.drawable.ic_expand_less_gray))
/* */
/** reseption TextView **//*
val reseptionTv: TextView = TextView(context)
var reseptionTvParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
reseptionTv.layoutParams = reseptionTvParams
reseptionTv.setText("")
reseptionTv.setPadding(0, 0, 20, 0)
reseptionTv.setTextSize(14f)
reseptionTv.setTypeface(Typeface.createFromAsset(context!!.assets, "IRANSansWeb(FaNum).ttf"))
itemView.firstTeamLL.addView(reseptionTv)*/
/** access level TextView **/
val accessLevelTv: TextView = TextView(context)
accessLevelTv.setText(if (itemModel.userRole == 0) "مسئول" else if (itemModel.userRole == 1) "مدیر" else if (itemModel.userRole == 2) "سرپرست" else "کارشناس")
accessLevelTv.setPadding(35, 10, 35, 10)
accessLevelTv.setTextSize(14f)
accessLevelTv.gravity = Gravity.CENTER
accessLevelTv.setTextColor(context.resources.getColor(R.color.white))
accessLevelTv.background = context.resources.getDrawable(R.drawable.rounded_back_gray)
accessLevelTv.setTypeface(Typeface.createFromAsset(context!!.assets, "IRANSansWeb(FaNum).ttf"))
itemView.firstTeamLL.addView(accessLevelTv)
/** first LinearLayout Views added 👆 **/
/** company TextView **/
val companyTeamTv: TextView = TextView(context)
var companyTvParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
companyTeamTv.layoutParams = companyTvParams
companyTeamTv.setText(itemModel.company)
companyTeamTv.setPadding(15, 0, 20, 0)
companyTeamTv.setTextSize(16f)
companyTeamTv.gravity = Gravity.LEFT
companyTeamTv.setTypeface(Typeface.createFromAsset(context!!.assets, "IRANSansWeb(FaNum).ttf"))
itemView.firstTeamLL.addView(companyTeamTv)
/** skill TextView **/
var skillTvParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
val skillTv: TextView = TextView(context)
skillTv.layoutParams = skillTvParams
/* if (itemModel.skill != null) {
skillTv.setText("${itemModel.skill}")
}
if (itemModel.skill != "null") {
skillTv.setText("${itemModel.skill}")
}
skillTv.setText("${itemModel.skill}")
if (itemModel.skill == null) {
itemModel.skill = "بدون تخصص"
skillTv.setText("${itemModel.skill}")
}
if (itemModel.skill == "null") {
itemModel.skill = "بدون تخصص"
skillTv.setText("${itemModel.skill}")
}*/
if (itemModel.skill == null || itemModel.skill.toString().equals("") || itemModel.skill.toString().equals("null")) {
skillTv.setText("بدون تخصص")
} else {
skillTv.setText("${itemModel.skill}")
}
skillTv.setPadding(35, 10, 20, 10)
skillTv.setTextSize(16f)
skillTv.gravity = Gravity.RIGHT
skillTv.setTypeface(Typeface.createFromAsset(context!!.assets, "IRANSansWeb(FaNum).ttf"))
itemView.secondTeamLL.addView(skillTv)
/** phone number TextView **/
var phoneNumberTvParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
val phoneNumberTv: TextView = TextView(context)
phoneNumberTv.layoutParams = phoneNumberTvParams
phoneNumberTv.setText("0${itemModel.mobileNumber.substring(2)}")
phoneNumberTv.setPadding(15, 0, 0, 0)
phoneNumberTv.setTextSize(16f)
phoneNumberTv.gravity = Gravity.LEFT
phoneNumberTv.setTypeface(Typeface.createFromAsset(context!!.assets, "IRANSansWeb(FaNum).ttf"))
itemView.secondTeamLL.addView(phoneNumberTv)
var llParamsWrap: LinearLayout.LayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
var llParams2: LinearLayout.LayoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
/** Email TextView **/
itemView.emailTeamTv.layoutParams = llParams2
itemView.emailTeamTv.setText(itemModel.emailAddress)
itemView.emailTeamTv.setPadding(15, 0, 0, 10)
llParamsWrap.setMargins(0, 0, 0, 10)
itemView.deleteMemberImv.layoutParams = llParamsWrap
itemView.deleteMemberImv.setPadding(25, 25, 25, 25)
itemView.editMemberImv.layoutParams = llParamsWrap
itemView.editMemberImv.setPadding(25, 25, 25, 25)
}
fun clearViews() {
var llParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0)
itemView.firstTeamLL.layoutParams = llParams
itemView.firstTeamLL.removeAllViews()
itemView.secondTeamLL.layoutParams = llParams
itemView.secondTeamLL.removeAllViews()
itemView.emailTeamTv.layoutParams = llParams
itemView.deleteMemberImv.layoutParams = llParams
itemView.editMemberImv.layoutParams = llParams
itemView.moreTeamImv.setImageDrawable(context.resources.getDrawable(R.drawable.ic_expand_more_gray))
}
private fun getToken(): String {
var sharedPreferences: SharedPreferences = context.getSharedPreferences("userInformation", 0)
var token = sharedPreferences.getString("token", null)
return token
}
/*private fun removeMember(userId: String, projectId: String) {
var service: IUserApi = IWebApi.Factory.create()
var removeMemberBody = MemberViewModel.removeMember(projectId, userId)
var call = service.removeMember(getToken(), removeMemberBody)
call.enqueue(object : retrofit2.Callback<RemoveMemberResponse> {
override fun onFailure(call: Call<RemoveMemberResponse>?, t: Throwable?) {
// progressDialog.dismiss()
}
override fun onResponse(call: Call<RemoveMemberResponse>?, response: Response<RemoveMemberResponse>?) {
if (response!!.code() == 200) {
// progressDialog.dismiss()
AlertDialog.Builder(context)
.setMessage("عضو با موفقیت حذف گردید!")
.setPositiveButton("باشه", { dialog, view ->
dialog.dismiss()
})
.create()
.show()
} else if (response.code() == 400) {
// progressDialog.dismiss()
AlertDialog.Builder(context)
.setMessage("ایمیل وارد شده هم اکنون عضو تیم است!")
.setPositiveButton("باشه", { dialog, view ->
dialog.dismiss()
})
.create()
.show()
} else if (response.code() == 405) {
// progressDialog.dismiss()
AlertDialog.Builder(context)
.setMessage("باعرض پوزش شما امکان حذف عضو از پروژه را ندارید. از سازنده یا مدیر درخواست کنید!")
.setPositiveButton("باشه", { dialog, view ->
dialog.dismiss()
})
.create()
.show()
} else if (response.code() == 404) {
// progressDialog.dismiss()
AlertDialog.Builder(context)
.setMessage("ایمیل وارد شده وجود ندارد.شما میتوانید ایشان را به لینکرپد دعوت کنید!")
.setPositiveButton("باشه", { dialog, view ->
dialog.dismiss()
}).setNegativeButton("بعداً", { dialog, view ->
dialog.dismiss()
})
.create()
.show()
} else if (response.code() == 406) {
AlertDialog.Builder(context)
.setMessage("این دسترسی مجاز نمی باشد")
.setPositiveButton("باشه", { dialog, view ->
dialog.dismiss()
})
.create()
.show()
}
}
})
}*/
}
}
| 0
|
Kotlin
|
0
| 0
|
49b1645da41de6b631e3d526f44970449151baa5
| 17,871
|
Linkerpad-phase0-
|
MIT License
|
common_component/src/main/java/com/xyoye/common_component/network/Retrofit.kt
|
xyoye
| 138,993,190
| false
| null |
package com.xyoye.common_component.network
import com.xyoye.common_component.BuildConfig
import com.xyoye.common_component.network.helper.*
import com.xyoye.common_component.network.service.*
import com.xyoye.common_component.utils.JsonHelper
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by xyoye on 2020/4/14.
*/
class Retrofit private constructor() {
companion object {
private const val baseUrl = "https://api.acplay.net/"
private const val resUrl = "http://res.acplay.net/"
private const val shooterUrl = "http://api.assrt.net/"
private const val torrentUrl = "https://m2t.chinacloudsites.cn/"
private const val remoteUrl = "http://127.0.0.1:80/"
val service = Holder.instance.retrofitService
val resService = Holder.instance.resRetrofitService
val extService = Holder.instance.extRetrofitService
val torrentService = Holder.instance.torrentRetrofitService
val remoteService = Holder.instance.remoteRetrofitService
}
private var retrofitService: RetrofitService
private var resRetrofitService: ResRetrofitService
private var extRetrofitService: ExtRetrofitService
private var torrentRetrofitService: TorrentRetrofitService
private var remoteRetrofitService: RemoteService
private val moshiConverterFactory = MoshiConverterFactory.create(JsonHelper.MO_SHI)
init {
retrofitService = Retrofit.Builder()
.addConverterFactory(moshiConverterFactory)
.client(getOkHttpClient(needAuth = true))
.baseUrl(baseUrl)
.build()
.create(RetrofitService::class.java)
resRetrofitService = Retrofit.Builder()
.addConverterFactory(moshiConverterFactory)
.client(getOkHttpClient(needAuth = false, resDomain = true))
.baseUrl(resUrl)
.build()
.create(ResRetrofitService::class.java)
extRetrofitService = Retrofit.Builder()
.addConverterFactory(moshiConverterFactory)
.client(getOkHttpClient())
.baseUrl(shooterUrl)
.build()
.create(ExtRetrofitService::class.java)
torrentRetrofitService = Retrofit.Builder()
.addConverterFactory(moshiConverterFactory)
.client(getOkHttpClient())
.baseUrl(torrentUrl)
.build()
.create(TorrentRetrofitService::class.java)
remoteRetrofitService = Retrofit.Builder()
.addConverterFactory(moshiConverterFactory)
.client(getOkHttpClient(needAuth = false, resDomain = false, isRemote = true))
.baseUrl(remoteUrl)
.build()
.create(RemoteService::class.java)
}
private object Holder {
val instance = Retrofit()
}
private fun getOkHttpClient(
needAuth: Boolean = false,
resDomain: Boolean = false,
isRemote: Boolean = false
): OkHttpClient {
val builder = OkHttpClient.Builder()
builder.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(4, TimeUnit.SECONDS)
.hostnameVerifier { _, _ -> true }
.addInterceptor(AgentInterceptor())
//token验证、gzip压缩
if (needAuth) {
builder.addInterceptor(AuthInterceptor())
.addInterceptor(GzipInterceptor())
}
//远程连接
if (isRemote) {
builder.addInterceptor(RemoteInterceptor())
}
//自定义的资源节点
if (resDomain) {
builder.addInterceptor(ResDomainInterceptor())
}
//日志输出
if (BuildConfig.IS_DEBUG_MODE) {
builder.addInterceptor(LoggerInterceptor().retrofit())
}
return builder.build()
}
}
| 67
| null |
84
| 850
|
f752fdf8cd6457198cfe64493b4caf97b576d0e6
| 3,925
|
DanDanPlayForAndroid
|
Apache License 2.0
|
app/src/main/java/com/example/skillabus/modules/tutor/TutorScreen.kt
|
Raia17
| 622,374,334
| false
| null |
package com.example.skillabus.modules.tutor
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
@Composable
fun TutorScreen() {
Box(modifier = Modifier.fillMaxSize().background(MaterialTheme.colors.primaryVariant)) {
Text(
text = "TUTOR",
color = MaterialTheme.colors.onPrimary,
fontSize = MaterialTheme.typography.h3.fontSize,
fontWeight = FontWeight.Bold,
modifier = Modifier.align(Alignment.Center)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
53305d128ff50f59ff612fdf91cfec2525a303c3
| 836
|
Skillabus-Android
|
MIT License
|
app/src/main/java/com/plcoding/stockmarketapp/data/remote/dto/IntradayInfoDto.kt
|
shubham230523
| 533,838,711
| false
| null |
package com.plcoding.stockmarketapp.data.remote.dto
data class IntradayInfoDto (
val timestamp : String ,
val close : Double
)
| 0
|
Kotlin
|
0
| 0
|
fbe46892c71ebf6b6d4dfc266a43c5b807ce686a
| 135
|
JetPack_StockMarketApp
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/iot/CfnScheduledAuditDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 63959868}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.iot
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.services.iot.CfnScheduledAudit
import software.constructs.Construct
/**
* Use the `AWS::IoT::ScheduledAudit` resource to create a scheduled audit that is run at a
* specified time interval.
*
* For API reference, see
* [CreateScheduleAudit](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateScheduledAudit.html)
* and for general information, see
* [Audit](https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-audit.html) .
*
* 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.iot.*;
* CfnScheduledAudit cfnScheduledAudit = CfnScheduledAudit.Builder.create(this,
* "MyCfnScheduledAudit")
* .frequency("frequency")
* .targetCheckNames(List.of("targetCheckNames"))
* // the properties below are optional
* .dayOfMonth("dayOfMonth")
* .dayOfWeek("dayOfWeek")
* .scheduledAuditName("scheduledAuditName")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html)
*/
@CdkDslMarker
public class CfnScheduledAuditDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnScheduledAudit.Builder = CfnScheduledAudit.Builder.create(scope, id)
private val _tags: MutableList<CfnTag> = mutableListOf()
private val _targetCheckNames: MutableList<String> = mutableListOf()
/**
* The day of the month on which the scheduled audit is run (if the `frequency` is "MONTHLY").
*
* If days 29-31 are specified, and the month does not have that many days, the audit takes
* place on the "LAST" day of the month.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-dayofmonth)
*
* @param dayOfMonth The day of the month on which the scheduled audit is run (if the
* `frequency` is "MONTHLY").
*/
public fun dayOfMonth(dayOfMonth: String) {
cdkBuilder.dayOfMonth(dayOfMonth)
}
/**
* The day of the week on which the scheduled audit is run (if the `frequency` is "WEEKLY" or
* "BIWEEKLY").
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-dayofweek)
*
* @param dayOfWeek The day of the week on which the scheduled audit is run (if the `frequency`
* is "WEEKLY" or "BIWEEKLY").
*/
public fun dayOfWeek(dayOfWeek: String) {
cdkBuilder.dayOfWeek(dayOfWeek)
}
/**
* How often the scheduled audit occurs.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-frequency)
*
* @param frequency How often the scheduled audit occurs.
*/
public fun frequency(frequency: String) {
cdkBuilder.frequency(frequency)
}
/**
* The name of the scheduled audit.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-scheduledauditname)
*
* @param scheduledAuditName The name of the scheduled audit.
*/
public fun scheduledAuditName(scheduledAuditName: String) {
cdkBuilder.scheduledAuditName(scheduledAuditName)
}
/**
* Metadata that can be used to manage the scheduled audit.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-tags)
*
* @param tags Metadata that can be used to manage the scheduled audit.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* Metadata that can be used to manage the scheduled audit.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-tags)
*
* @param tags Metadata that can be used to manage the scheduled audit.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
/**
* Which checks are performed during the scheduled audit.
*
* Checks must be enabled for your account. (Use `DescribeAccountAuditConfiguration` to see the
* list of all checks, including those that are enabled or use `UpdateAccountAuditConfiguration`
* to select which checks are enabled.)
*
* The following checks are currently aviable:
* * `AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK`
* * `CA_CERTIFICATE_EXPIRING_CHECK`
* * `CA_CERTIFICATE_KEY_QUALITY_CHECK`
* * `CONFLICTING_CLIENT_IDS_CHECK`
* * `DEVICE_CERTIFICATE_EXPIRING_CHECK`
* * `DEVICE_CERTIFICATE_KEY_QUALITY_CHECK`
* * `DEVICE_CERTIFICATE_SHARED_CHECK`
* * `IOT_POLICY_OVERLY_PERMISSIVE_CHECK`
* * `IOT_ROLE_ALIAS_ALLOWS_ACCESS_TO_UNUSED_SERVICES_CHECK`
* * `IOT_ROLE_ALIAS_OVERLY_PERMISSIVE_CHECK`
* * `LOGGING_DISABLED_CHECK`
* * `REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK`
* * `REVOKED_DEVICE_CERTIFICATE_STILL_ACTIVE_CHECK`
* * `UNAUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-targetchecknames)
*
* @param targetCheckNames Which checks are performed during the scheduled audit.
*/
public fun targetCheckNames(vararg targetCheckNames: String) {
_targetCheckNames.addAll(listOf(*targetCheckNames))
}
/**
* Which checks are performed during the scheduled audit.
*
* Checks must be enabled for your account. (Use `DescribeAccountAuditConfiguration` to see the
* list of all checks, including those that are enabled or use `UpdateAccountAuditConfiguration`
* to select which checks are enabled.)
*
* The following checks are currently aviable:
* * `AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK`
* * `CA_CERTIFICATE_EXPIRING_CHECK`
* * `CA_CERTIFICATE_KEY_QUALITY_CHECK`
* * `CONFLICTING_CLIENT_IDS_CHECK`
* * `DEVICE_CERTIFICATE_EXPIRING_CHECK`
* * `DEVICE_CERTIFICATE_KEY_QUALITY_CHECK`
* * `DEVICE_CERTIFICATE_SHARED_CHECK`
* * `IOT_POLICY_OVERLY_PERMISSIVE_CHECK`
* * `IOT_ROLE_ALIAS_ALLOWS_ACCESS_TO_UNUSED_SERVICES_CHECK`
* * `IOT_ROLE_ALIAS_OVERLY_PERMISSIVE_CHECK`
* * `LOGGING_DISABLED_CHECK`
* * `REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK`
* * `REVOKED_DEVICE_CERTIFICATE_STILL_ACTIVE_CHECK`
* * `UNAUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-scheduledaudit.html#cfn-iot-scheduledaudit-targetchecknames)
*
* @param targetCheckNames Which checks are performed during the scheduled audit.
*/
public fun targetCheckNames(targetCheckNames: Collection<String>) {
_targetCheckNames.addAll(targetCheckNames)
}
public fun build(): CfnScheduledAudit {
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
if (_targetCheckNames.isNotEmpty()) cdkBuilder.targetCheckNames(_targetCheckNames)
return cdkBuilder.build()
}
}
| 4
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 8,104
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
ktor-server/ktor-server-jetty-jakarta/jvm/test/io/ktor/tests/server/jetty/jakarta/JettyStressTest.kt
|
ktorio
| 40,136,600
| false
|
{"Kotlin": 6007831, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.server.jetty.jakarta
import io.ktor.server.jetty.jakarta.*
import io.ktor.server.testing.suites.*
class JettyStressTest : EngineStressSuite<JettyApplicationEngine, JettyApplicationEngineBase.Configuration>(Jetty)
| 156
|
Kotlin
|
1051
| 12,926
|
f90f2edf11caca28a61dbe9973faae64c17a2842
| 363
|
ktor
|
Apache License 2.0
|
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/PipelineBranchesitempullRequestlinksTest.kt
|
oapicf
| 90,140,540
| false
|
{"Java": 12530173, "C++": 7972103, "PHP": 4475625, "TypeScript": 3228611, "Python": 3082826, "Rust": 2800453, "HTML": 2428440, "C#": 2318013, "JavaScript": 1592129, "Kotlin": 1468601, "R": 1219437, "Scala": 1119819, "Ada": 1009616, "C": 985434, "Perl": 962381, "Dart": 896698, "Crystal": 872405, "Haskell": 763757, "Apex": 741927, "PowerShell": 680505, "Xojo": 566494, "F#": 556012, "Objective-C": 465570, "Eiffel": 425526, "Shell": 394909, "Erlang": 373267, "Swift": 353672, "Go": 339356, "Lua": 323476, "Ruby": 321943, "Elm": 187340, "Elixir": 134551, "Clojure": 129017, "OCaml": 95013, "Groovy": 90212, "Nim": 66413, "CMake": 24930, "Batchfile": 13610, "Makefile": 12333, "Dockerfile": 7351, "QMake": 6915, "CSS": 4873, "Gherkin": 951, "Emacs Lisp": 191}
|
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import org.openapitools.client.models.ExtensionClassImpllinks
import org.openapitools.client.models.Link
class ExtensionClassImpllinksTest : ShouldSpec() {
init {
// uncomment below to create an instance of ExtensionClassImpllinks
//val modelInstance = ExtensionClassImpllinks()
// to test the property `self`
should("test self") {
// uncomment below to test the property
//modelInstance.self shouldBe ("TODO")
}
// to test the property `propertyClass`
should("test propertyClass") {
// uncomment below to test the property
//modelInstance.propertyClass shouldBe ("TODO")
}
}
}
| 30
|
Java
|
12
| 19
|
277d791c0d363a4d93832bec8a581d4c01297b18
| 1,083
|
swaggy-jenkins
|
MIT License
|
spotify-clone-frontend/app/src/main/java/com/spotifyclone/presentation/login/LoginActivity.kt
|
Ridersk
| 257,694,555
| false
|
{"Text": 1, "YAML": 1, "Markdown": 2, "SVG": 50, "INI": 2, "Java Properties": 3, "Gradle": 3, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "XML": 110, "Kotlin": 68, "Java": 5}
|
package com.spotifyclone.presentation.login
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import com.spotifyclone.R
import com.spotifyclone.presentation.base.BaseActivity
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_login.view.*
class LoginActivity : BaseActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_login)
super.onCreate(savedInstanceState)
}
override fun initComponents() {
val layout: ViewGroup = activityLogin
with(layout) {
spotifyBrand.text = getString(R.string.login_spotify_brand)
signUpButton.text = getString(R.string.login_button_sign_up)
facebookButton.text = getString(R.string.login_button_facebook)
loginButton.text = getString(R.string.login_button_login)
}
layout.loginButton.setOnClickListener{
val intent = Intent(this@LoginActivity, CredentialsActivity::class.java)
this@LoginActivity.startActivity(intent)
}
}
}
| 4
|
Kotlin
|
0
| 1
|
68617849bca5416100c85578ad42e12775c04865
| 1,140
|
spotify-music-player-kotlin
|
MIT License
|
src/test/kotlin/nl/dirkgroot/structurizr/dsl/editing/FoldingTest.kt
|
dirkgroot
| 561,786,663
| false
|
{"Kotlin": 75605, "Lex": 2479, "ASL": 463}
|
package nl.dirkgroot.structurizr.dsl.editing
import nl.dirkgroot.structurizr.dsl.support.StructurizrDSLCodeInsightTest
import org.junit.jupiter.api.Test
class FoldingTest : StructurizrDSLCodeInsightTest() {
@Test
fun `regular blocks`() {
fixture.testFolding(fixture.testDataPath + "/folding/regular_blocks.dsl")
}
@Test
fun `animation blocks`() {
fixture.testFolding(fixture.testDataPath + "/folding/animation_blocks.dsl")
}
@Test
fun `script blocks`() {
fixture.testFolding(fixture.testDataPath + "/folding/script_blocks.dsl")
}
@Test
fun `properties blocks`() {
fixture.testFolding(fixture.testDataPath + "/folding/properties_blocks.dsl")
}
}
| 7
|
Kotlin
|
1
| 37
|
5b6ea445348f6107dd98e52a1e891ce18c35ce5a
| 730
|
structurizr-dsl-intellij-plugin
|
MIT License
|
src/Day09.kt
|
proggler23
| 573,129,757
| false
|
{"Kotlin": 27990}
|
import kotlin.math.abs
import kotlin.math.sign
fun main() {
fun part1(input: List<String>) = RopeGrid().apply { move(input.parse9()) }.visited.size
fun part2(input: List<String>) = RopeGrid(10).apply { move(input.parse9()) }.visited.size
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
fun List<String>.parse9() = map { line ->
line.split(" ").let { (d, l) -> RopeMovement(Direction.values().first { it.name.startsWith(d) }, l.toInt()) }
}
enum class Direction(val dx: Int = 0, val dy: Int = 0) {
UP(dy = -1),
DOWN(dy = 1),
LEFT(dx = -1),
RIGHT(dx = 1)
}
data class RopeMovement(val direction: Direction, var length: Int)
class RopeGrid(val knotCount: Int = 2) {
private val knots = MutableList(knotCount) { 0 to 0 }
val visited = mutableSetOf(knots[knotCount - 1])
fun move(movements: List<RopeMovement>) {
movements.forEach { moveHead(it) }
}
private fun moveHead(movement: RopeMovement) {
repeat(movement.length) {
knots[0] = knots[0].first + movement.direction.dx to knots[0].second + movement.direction.dy
(1 until knotCount).forEach { moveKnot(it) }
visited.add(knots[knotCount - 1])
}
}
private fun moveKnot(i: Int) {
val (hx, hy) = knots[i - 1]
val (tx, ty) = knots[i]
val dx = hx - tx
val dy = hy - ty
if (abs(dx) > 1 || abs(dy) > 1) {
knots[i] = tx + dx.sign to ty + dy.sign
}
}
}
| 0
|
Kotlin
|
0
| 0
|
584fa4d73f8589bc17ef56c8e1864d64a23483c8
| 1,707
|
advent-of-code-2022
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.