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
common/src/main/kotlin/dev/erdragh/astralbot/handlers/FileWatcher.kt
Erdragh
723,352,761
false
{"Kotlin": 26227, "Java": 2141}
package dev.erdragh.astralbot.handlers import dev.erdragh.astralbot.LOGGER import kotlinx.coroutines.* import java.nio.file.* class FileWatcher(private val directoryPath: Path, private val handler: (event: WatchEvent<Path>) -> Unit) { private var job: Job? = null private var watchService: WatchService? = null fun startWatching() { job = GlobalScope.launch(Dispatchers.IO) { watchService = FileSystems.getDefault().newWatchService() directoryPath.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE ) try { while (isActive) { LOGGER.info("Waiting for watchService WatchKey") val key = watchService?.take() ?: break LOGGER.info("Got watchService WatchKey") for (event in key.pollEvents()) { LOGGER.info("Event: {}", event.kind()) // Send the event to the channel handler(event as WatchEvent<Path>) } key.reset() } } catch (_: ClosedWatchServiceException) { // Do nothing, this exception means we should just stop } LOGGER.info("WatchService ending") } } fun stopWatching() { watchService?.close() job?.cancel() } }
0
Kotlin
0
1
d589ddc6ca54e2af84b39e03c1af820d5eeead0d
1,552
AstralBot
MIT License
kmath-core/src/commonMain/kotlin/space/kscience/kmath/linear/MatrixWrapper.kt
SciProgCentre
129,486,382
false
{"Kotlin": 1988014, "ANTLR": 887}
/* * Copyright 2018-2024 KMath 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 space.kscience.kmath.linear import space.kscience.attributes.Attribute import space.kscience.attributes.Attributes import space.kscience.attributes.withAttribute import space.kscience.kmath.UnstableKMathAPI import space.kscience.kmath.operations.Ring /** * A [Matrix] that holds [MatrixAttribute] objects. * * @param T the type of items. */ public class MatrixWrapper<out T> internal constructor( public val origin: Matrix<T>, override val attributes: Attributes, ) : Matrix<T> by origin { override fun toString(): String = "MatrixWrapper(matrix=$origin, features=$attributes)" } /** * Return the original matrix. If this is a wrapper, return its origin. If not, this matrix. * Origin does not necessary store all features. */ @UnstableKMathAPI public val <T : Any> Matrix<T>.origin: Matrix<T> get() = (this as? MatrixWrapper)?.origin ?: this /** * Add a single feature to a [Matrix] */ public fun <T, A : Attribute<T>> Matrix<T>.withAttribute( attribute: A, attrValue: T, ): MatrixWrapper<T> = if (this is MatrixWrapper) { MatrixWrapper(origin, attributes.withAttribute(attribute, attrValue)) } else { MatrixWrapper(this, Attributes(attribute, attrValue)) } public fun <T, A : Attribute<Unit>> Matrix<T>.withAttribute( attribute: A, ): MatrixWrapper<T> = if (this is MatrixWrapper) { MatrixWrapper(origin, attributes.withAttribute(attribute)) } else { MatrixWrapper(this, Attributes(attribute, Unit)) } /** * Modify matrix attributes */ public fun <T> Matrix<T>.modifyAttributes(modifier: (Attributes) -> Attributes): MatrixWrapper<T> = if (this is MatrixWrapper) { MatrixWrapper(origin, modifier(attributes)) } else { MatrixWrapper(this, modifier(Attributes.EMPTY)) } /** * Diagonal matrix of ones. The matrix is virtual, no actual matrix is created. */ public fun <T> LinearSpace<T, Ring<T>>.one( rows: Int, columns: Int, ): MatrixWrapper<T> = VirtualMatrix(rows, columns) { i, j -> if (i == j) elementAlgebra.one else elementAlgebra.zero }.withAttribute(IsUnit) /** * A virtual matrix of zeroes */ public fun <T> LinearSpace<T, Ring<T>>.zero( rows: Int, columns: Int, ): MatrixWrapper<T> = VirtualMatrix(rows, columns) { _, _ -> elementAlgebra.zero }.withAttribute(IsZero)
88
Kotlin
55
645
3e8f44166c4a4ed6e99e1676a7200ed044645224
2,473
kmath
Apache License 2.0
app/src/main/java/com/melodie/parotia/ui/search/history/HistoryColor.kt
gejiaheng
284,195,510
false
null
package com.melodie.parotia.ui.search.history import androidx.annotation.ColorRes import com.melodie.parotia.R import kotlin.random.Random enum class HistoryColor(@ColorRes val color: Int, @ColorRes val colorBg: Int) { COLOR_0(R.color.search_history_color_0, R.color.search_history_color_0_20), COLOR_1(R.color.search_history_color_1, R.color.search_history_color_1_20), COLOR_2(R.color.search_history_color_2, R.color.search_history_color_2_20), COLOR_3(R.color.search_history_color_3, R.color.search_history_color_3_20); companion object { fun randColor() = HistoryColor.values()[Random.nextInt(4)] } }
0
Kotlin
1
2
f19459dac17f35cc26af5379764c292fef42be91
640
Parotia
Apache License 2.0
app/src/main/kotlin/com/muedsa/muaa/features/Aria2RpcWidget.kt
muedsa
703,390,470
false
{"Kotlin": 34391}
package com.muedsa.muaa.features import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.tv.foundation.lazy.list.TvLazyColumn import androidx.tv.material3.Button import androidx.tv.material3.ExperimentalTvMaterial3Api import androidx.tv.material3.MaterialTheme import com.muedsa.muaa.ui.CustomerColor import com.muedsa.muaa.viewmodel.MainViewModel @OptIn(ExperimentalTvMaterial3Api::class) @Composable fun Aria2RpcWidget( modifier: Modifier = Modifier, mainViewModel: MainViewModel = viewModel() ) { var rpcUrl by remember { mainViewModel.rpcUrlState } var rpcToken by remember { mainViewModel.rpcTokenState } var linkFileUrl by remember { mainViewModel.linkFileUrlState } TvLazyColumn(modifier = modifier) { item { OutlinedTextField( modifier = Modifier.fillMaxWidth(), textStyle = MaterialTheme.typography.bodyLarge, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = CustomerColor.outline, cursorColor = MaterialTheme.colorScheme.onSurface, focusedTextColor = MaterialTheme.colorScheme.onSurface, unfocusedTextColor = MaterialTheme.colorScheme.onSurfaceVariant, ), singleLine = true, value = linkFileUrl, onValueChange = { linkFileUrl = it }, label = { Text(text = "MAGNET LINK FILE URL") } ) Spacer(modifier = Modifier.height(10.dp)) } item { Button(onClick = { mainViewModel.aria2AddUriFromFileUrl() }) { Text(text = "aria2.addUri From URL") } Spacer(modifier = Modifier.height(10.dp)) } item { OutlinedTextField( modifier = Modifier.fillMaxWidth(), textStyle = MaterialTheme.typography.bodyLarge, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = CustomerColor.outline, cursorColor = MaterialTheme.colorScheme.onSurface, focusedTextColor = MaterialTheme.colorScheme.onSurface, unfocusedTextColor = MaterialTheme.colorScheme.onSurfaceVariant, ), singleLine = true, value = rpcUrl, onValueChange = { rpcUrl = it }, label = { Text(text = "RPC URL") } ) Spacer(modifier = Modifier.height(10.dp)) } item { OutlinedTextField( modifier = Modifier.fillMaxWidth(), textStyle = MaterialTheme.typography.bodyLarge, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = CustomerColor.outline, cursorColor = MaterialTheme.colorScheme.onSurface, focusedTextColor = MaterialTheme.colorScheme.onSurface, unfocusedTextColor = MaterialTheme.colorScheme.onSurfaceVariant, ), singleLine = true, value = rpcToken, onValueChange = { rpcToken = it }, label = { Text(text = "RPC TOKEN") } ) Spacer(modifier = Modifier.height(10.dp)) } item { Row { Button(onClick = { mainViewModel.saveSetting() }) { Text(text = "Save Setting") } Spacer(modifier = Modifier.width(10.dp)) Button(onClick = { mainViewModel.aria2TellActive() }) { Text(text = "aria2.tellActive") } } Spacer(modifier = Modifier.height(10.dp)) } item { Row { Button(onClick = { mainViewModel.aria2PauseAll() }) { Text(text = "aria2.pauseAll") } Spacer(modifier = Modifier.width(10.dp)) Button(onClick = { mainViewModel.aria2UnpauseAll() }) { Text(text = "aria2.unpauseAll") } } Spacer(modifier = Modifier.height(10.dp)) } item { Row { Button(onClick = { mainViewModel.aria2PurgeDownloadResult() }) { Text(text = "aria2.purgeDownloadResult") } Spacer(modifier = Modifier.width(10.dp)) Button(onClick = { mainViewModel.aria2SaveSession() }) { Text(text = "aria2.saveSession") } } Spacer(modifier = Modifier.height(10.dp)) } } }
0
Kotlin
0
0
ca6db399b0c3b3e298fde421b809d9f7a4f36a6f
5,816
MUAA
MIT License
app/src/main/java/com/skydoves/themovies/view/adapter/ReviewListAdapter.kt
paolorotolo
163,106,329
false
null
package com.skydoves.themovies.view.adapter import android.view.View import com.skydoves.baserecyclerviewadapter.BaseAdapter import com.skydoves.baserecyclerviewadapter.BaseViewHolder import com.skydoves.baserecyclerviewadapter.SectionRow import com.skydoves.themovies.R import com.skydoves.themovies.models.Resource import com.skydoves.themovies.models.Review import com.skydoves.themovies.view.viewholder.ReviewListViewHolder /** * Developed by skydoves on 2018-08-20. * Copyright (c) 2018 skydoves rights reserved. */ class ReviewListAdapter : BaseAdapter() { init { addSection(ArrayList<Review>()) } fun addReviewList(resource: Resource<List<Review>>) { resource.data?.let { sections[0].addAll(it) } notifyDataSetChanged() } override fun layout(sectionRow: SectionRow): Int { return R.layout.item_review } override fun viewHolder(layout: Int, view: View): BaseViewHolder { return ReviewListViewHolder(view) } }
0
null
0
2
f784a842ba15feaeb1e958e0267f550160554a5d
1,017
TheMovies
MIT License
app/src/androidTest/java/com/yury/lebowski/data/AccountDaoTest.kt
iliailemkov
143,139,061
true
{"Kotlin": 112583}
package com.yury.lebowski.data import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.room.Room import androidx.test.InstrumentationRegistry import androidx.test.runner.AndroidJUnit4 import com.yury.lebowski.data.local.dao.AccountDao import com.yury.lebowski.data.local.db.LebowskiDb import com.yury.lebowski.data.local.models.Account import com.yury.lebowski.data.local.models.enums.CurrencyType import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import androidx.arch.core.executor.testing.InstantTaskExecutorRule import org.junit.Rule import org.junit.rules.TestRule @RunWith(AndroidJUnit4::class) class AccountDaoTest { @JvmField @Rule var rule: TestRule = InstantTaskExecutorRule() private lateinit var accountDao: AccountDao private lateinit var db: LebowskiDb private val accounts = listOf( Account(1, "Card", 0.0, CurrencyType.Ruble), Account(2, "Cash", 0.0, CurrencyType.Dollar)) @Before fun setup() { val context = InstrumentationRegistry.getTargetContext() db = Room.inMemoryDatabaseBuilder(context, LebowskiDb::class.java!!).build() accountDao = db.accountDao() db.accountDao().insertAll(accounts) } @After fun closeDb() { db.close() } @Test fun getAll() { val liveData = accountDao.getAll() assertEquals(getBlockValue(liveData), accounts) } @Test fun getById() { val account = accountDao.findById(1) assertEquals(account, accounts[0]) } private fun <T> getBlockValue(liveData: LiveData<T>): T { val data = arrayOfNulls<Any>(1) val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(t: T?) { data[0] = t latch.countDown() liveData.removeObserver(this)//To change body of created functions use File | Settings | File Templates. } } liveData.observeForever(observer) latch.await(2, TimeUnit.SECONDS) return data[0] as T } }
0
Kotlin
0
0
aec038962531c5c1945ce4df71f3f93c15ebd4c1
2,396
Lebowski
Creative Commons Attribution 3.0 Unported
core/tests-core-arch/src/test/java/com/gabrielfv/core/arch/tests/recycler/ListDiffCallbackTest.kt
gfreivasc
286,602,068
false
null
/* * Copyright 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 com.gabrielfv.core.arch.tests.recycler import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListUpdateCallback import com.gabrielfv.core.arch.recycler.ListDiffCallback import io.mockk.mockk import io.mockk.verify import org.junit.Test class ListDiffCallbackTest { private val mockUpdateCallback = mockk<ListUpdateCallback>(relaxed = true) @Test fun insertionIsEvaluated() { val old = listOf<Int>() val new = listOf(1, 2) val subject = ListDiffCallback(old, new) DiffUtil.calculateDiff(subject) .dispatchUpdatesTo(mockUpdateCallback) verify { mockUpdateCallback.onInserted(eq(0), eq(2)) } } @Test fun removingIsEvaluated() { val old = listOf(1, 2) val new = listOf<Int>() val subject = ListDiffCallback(old, new) DiffUtil.calculateDiff(subject) .dispatchUpdatesTo(mockUpdateCallback) verify { mockUpdateCallback.onRemoved(eq(0), eq(2)) } } @Test fun movingIsEvaluated() { val old = listOf(1, 2, 3) val new = listOf(1, 3, 2) val subject = ListDiffCallback(old, new) DiffUtil.calculateDiff(subject) .dispatchUpdatesTo(mockUpdateCallback) verify { mockUpdateCallback.onMoved(eq(2), eq(1)) } } @Test fun changingValueIsEvaluated() { val old = listOf(IntWithId(0, 1), IntWithId(1, 2)) val new = listOf(IntWithId(0, 1), IntWithId(1, 3)) val subject = ListDiffCallback(old, new) { a, b -> a.id == b.id } DiffUtil.calculateDiff(subject) .dispatchUpdatesTo(mockUpdateCallback) verify { mockUpdateCallback.onChanged(eq(1), eq(1), isNull()) } } @Test fun noChangeDoesNotIssueAnUpdate() { val old = listOf<Int>() val new = listOf<Int>() val subject = ListDiffCallback(old, new) DiffUtil.calculateDiff(subject) .dispatchUpdatesTo(mockUpdateCallback) verify(exactly = 0) { mockUpdateCallback.onInserted(any(), any()) } verify(exactly = 0) { mockUpdateCallback.onChanged(any(), any(), any()) } verify(exactly = 0) { mockUpdateCallback.onMoved(any(), any()) } verify(exactly = 0) { mockUpdateCallback.onRemoved(any(), any()) } } data class IntWithId(val id: Int, val value: Int) }
0
Kotlin
0
1
00faf2da270e51d85e4a836cc314aac01bfbe6e4
2,997
biller-fragment
Apache License 2.0
url-gen/src/main/kotlin/com/cloudinary/transformation/ClippingPath.kt
baraka-gini
266,517,520
true
{"Kotlin": 589400, "Java": 7089}
package com.cloudinary.transformation class ClippingPath(private val action: Action) : Action by action { class Builder : TransformationComponentBuilder { private var index: Int? = null private var path: String? = null private var evenOdd: Boolean = false fun index(index: Int) = apply { this.index = index } fun path(path: String) = apply { this.path = path } fun evenOdd(evenOdd: Boolean) = apply { this.evenOdd = evenOdd } override fun build() = ClippingPath(buildAction(index ?: path, evenOdd)) } } fun clippingPath(clippingPath: (ClippingPath.Builder.() -> Unit)? = null): ClippingPath { val newBuilder = ClippingPath.Builder() if (clippingPath != null) newBuilder.clippingPath() return newBuilder.build() } // TODO simplify private fun buildAction(pageParamValue: Any?, evenOdd: Boolean): ParamsAction { val page = pageParamValue?.cldAsPage() val clip = FlagsParam(if (evenOdd) Flag.ClipEvenOdd() else Flag.Clip()) val clipPair = Pair(clip.key, clip) return ParamsAction(page, clip) }
0
Kotlin
0
0
4eedf1de1b7d784dff7232aa108f6a363364f205
1,090
cloudinary_kotlin
MIT License
app/src/main/java/me/hexile/odexpatcher/utils/LogUtils.kt
giacomoferretti
293,629,531
false
{"Kotlin": 97502, "Shell": 9943}
/* * Copyright 2020-2021 <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 me.hexile.odexpatcher.utils import android.util.Log import me.hexile.odexpatcher.BuildConfig const val TAG = "OdexPatcher" fun logi(tag: String, message: String) { if (BuildConfig.DEBUG) { Log.i(TAG, "[$tag] $message") } } fun loge(tag: String, message: String) { if (BuildConfig.DEBUG) { Log.e(TAG, "[$tag] $message") } } fun logd(tag: String, message: String) { if (BuildConfig.DEBUG) { Log.d(TAG, "[$tag] $message") } } fun logw(tag: String, message: String) { if (BuildConfig.DEBUG) { Log.w(TAG, "[$tag] $message") } } fun logv(tag: String, message: String) { if (BuildConfig.DEBUG) { Log.v(TAG, "[$tag] $message") } } fun logwtf(tag: String, message: String) { if (BuildConfig.DEBUG) { Log.wtf(TAG, "[$tag] $message") } }
10
Kotlin
12
70
fffee1ff0928c6c1cdadb1953bdd47d57c4c3588
1,434
odex-patcher
Apache License 2.0
plugins/git4idea/src/git4idea/index/ui/GitStageTree.kt
hieuprogrammer
284,920,751
true
null
// Copyright 2000-2020 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 git4idea.index.ui import com.intellij.ide.dnd.DnDActionInfo import com.intellij.ide.dnd.DnDDragStartBean import com.intellij.ide.dnd.DnDEvent import com.intellij.ide.util.treeView.TreeState import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.fileChooser.actions.VirtualFileDeleteProvider import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.ActiveIcon import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.changes.UnversionedViewDialog import com.intellij.openapi.vcs.changes.ui.* import com.intellij.openapi.vcs.impl.PlatformVcsPathPresenter import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ClickListener import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBLabel import com.intellij.util.FontUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.isEmpty import git4idea.conflicts.getConflictType import git4idea.i18n.GitBundle import git4idea.index.GitFileStatus import git4idea.index.GitStageTracker import git4idea.index.actions.StagingAreaOperation import git4idea.index.isRenamed import git4idea.index.ui.NodeKind.Companion.sortOrder import git4idea.repo.GitConflict import git4idea.status.GitStagingAreaHolder import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey import java.awt.event.MouseEvent import java.awt.event.MouseMotionListener import java.util.stream.Stream import javax.swing.Icon import javax.swing.JComponent import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreePath import kotlin.streams.toList val GIT_FILE_STATUS_NODES_STREAM = DataKey.create<Stream<GitFileStatusNode>>("GitFileStatusNodesStream") val GIT_STAGE_TREE = DataKey.create<GitStageTree>("GitStageTree") abstract class GitStageTree(project: Project, parentDisposable: Disposable) : ChangesTree(project, false, true) { private var hoverNode: ChangesBrowserNode<*>? = null set(value) { if (field != value) { field = value repaint() } } protected abstract val state: GitStageTracker.State protected abstract val operations: List<StagingAreaOperation> init { setCellRenderer(GitStageTreeRenderer(ChangesBrowserNodeRenderer(myProject, { isShowFlatten }, true))) addMouseMotionListener(MyMouseMotionListener()) MyClickListener().installOn(this) MyDnDSupport().install(parentDisposable) } abstract fun performStageOperation(nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) abstract fun getDndOperation(targetKind: NodeKind): StagingAreaOperation? abstract fun showMergeDialog(conflictedFiles: List<VirtualFile>); override fun getComponentWidth(path: TreePath): Int { val node = path.lastPathComponent as? ChangesBrowserNode<*> ?: return 0 return getFirstMatchingOperation(node)?.icon?.iconWidth ?: 0 } internal fun getFirstMatchingOperation(node: ChangesBrowserNode<*>): StagingAreaOperation? { val statusNode = node.userObject as? GitFileStatusNode ?: return null return operations.find { it.matches(statusNode) } } fun update() { val state = TreeState.createOn(this, root) state.setScrollToSelection(false) rebuildTree() state.applyTo(this) } override fun rebuildTree() { val builder = MyTreeModelBuilder(myProject, groupingSupport.grouping) builder.createKindNode(NodeKind.STAGED) builder.createKindNode(NodeKind.UNSTAGED) state.rootStates.forEach { (root, rootState) -> rootState.statuses.forEach { (_, status) -> NodeKind.values().forEach { kind -> if (kind.`is`(status)) { builder.insertStatus(root, status, kind) } } } } updateTreeModel(builder.build()) } override fun getData(dataId: String): Any? { return when { GIT_STAGE_TREE.`is`(dataId) -> this GIT_FILE_STATUS_NODES_STREAM.`is`(dataId) -> selectedStatusNodes() VcsDataKeys.FILE_PATH_STREAM.`is`(dataId) -> selectedStatusNodes().map { it.filePath } VcsDataKeys.VIRTUAL_FILE_STREAM.`is`(dataId) -> selectedStatusNodes().map { it.filePath.virtualFile }.filter { it != null } CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId) -> selectedStatusNodes().map { it.filePath.virtualFile }.filter { it != null } .toList().toTypedArray() CommonDataKeys.NAVIGATABLE_ARRAY.`is`(dataId) -> selectedStatusNodes().map { it.filePath.virtualFile }.filter { it != null } .map { OpenFileDescriptor(project, it!!) }.toList().toTypedArray() PlatformDataKeys.DELETE_ELEMENT_PROVIDER.`is`(dataId) -> if (!selectedStatusNodes().isEmpty()) VirtualFileDeleteProvider() else null else -> super.getData(dataId) } } fun selectedStatusNodes(): Stream<GitFileStatusNode> { return VcsTreeModelData.selected(this).userObjectsStream(GitFileStatusNode::class.java) } fun statusNodesListSelection(preferLimitedContext: Boolean): ListSelection<GitFileStatusNode> { val entries = VcsTreeModelData.selected(this).userObjects(GitFileStatusNode::class.java) if (entries.size > 1) { return ListSelection.createAt(entries, 0) } val selected = entries.singleOrNull() val selectedKind = selected?.kind val allEntriesData: VcsTreeModelData = when { preferLimitedContext && (selectedKind == NodeKind.UNSTAGED || selectedKind == NodeKind.UNTRACKED) -> { VcsTreeModelData.allUnderTag(this, NodeKind.UNSTAGED) } preferLimitedContext && selectedKind == NodeKind.STAGED -> { VcsTreeModelData.allUnderTag(this, NodeKind.STAGED) } else -> { VcsTreeModelData.all(this) } } val allEntries = allEntriesData.userObjects(GitFileStatusNode::class.java) return if (allEntries.size <= entries.size) { ListSelection.createAt(entries, 0) } else { ListSelection.create(allEntries, selected) } } private inner class MyTreeModelBuilder internal constructor(project: Project, grouping: ChangesGroupingPolicyFactory) : TreeModelBuilder(project, grouping) { private val parentNodes: MutableMap<NodeKind, ChangesBrowserKindNode> = mutableMapOf() private val untrackedFilesMap = mutableMapOf<VirtualFile, MutableCollection<GitFileStatus>>() fun insertStatus(root: VirtualFile, status: GitFileStatus, kind: NodeKind) { if (kind == NodeKind.UNTRACKED) { untrackedFilesMap.getOrPut(root) { mutableListOf() }.add(status) } else { insertFileStatusNode(GitFileStatusNode(root, status, kind), createKindNode(kind)) } } private fun insertFileStatusNode(node: GitFileStatusNode, subtreeRoot: ChangesBrowserNode<*>) { insertChangeNode(node.filePath, subtreeRoot, ChangesBrowserGitFileStatusNode(node)) } fun insertIntoRootNode(node: ChangesBrowserNode<*>) { myModel.insertNodeInto(node, myRoot, myRoot.childCount) } fun createKindNode(kind: NodeKind): ChangesBrowserKindNode { return parentNodes.getOrPut(kind) { ChangesBrowserKindNode(kind).also { insertIntoRootNode(it) } } } private fun createUntrackedNode() { val allUntrackedStatuses = untrackedFilesMap.values.flatten() if (allUntrackedStatuses.isEmpty()) return if (ChangesBrowserSpecificFilePathsNode.isManyFiles(allUntrackedStatuses)) { ChangesBrowserUntrackedNode(project, allUntrackedStatuses.map { it.path }).also { insertIntoRootNode(it) } } else { val unstagedNode = createKindNode(NodeKind.UNSTAGED) untrackedFilesMap.forEach { (root, untrackedInRoot) -> untrackedInRoot.forEach { insertFileStatusNode(GitFileStatusNode(root, it, NodeKind.UNTRACKED), unstagedNode) } } } } override fun build(): DefaultTreeModel { createUntrackedNode() return super.build() } } private class ChangesBrowserGitFileStatusNode(node: GitFileStatusNode) : AbstractChangesBrowserFilePathNode<GitFileStatusNode>(node, node.fileStatus) { private val movedRelativePath by lazy { getMovedRelativePath(getUserObject()) } private val conflict by lazy { getUserObject().createConflict() } override fun filePath(userObject: GitFileStatusNode): FilePath = userObject.filePath override fun originText(userObject: GitFileStatusNode): String? { val originalPath = userObject.origPath ?: return null if (movedRelativePath != null) { return VcsBundle.message("change.file.moved.from.text", movedRelativePath) } return VcsBundle.message("change.file.renamed.from.text", originalPath.name) } private fun getMovedRelativePath(userObject: GitFileStatusNode): String? { val origPath = userObject.origPath if (origPath == null || origPath.parentPath == userObject.filePath.parentPath) return null return PlatformVcsPathPresenter.getPresentableRelativePath(userObject.filePath, origPath) } override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { super.render(renderer, selected, expanded, hasFocus) conflict?.let { conflict -> renderer.append(FontUtil.spaceAndThinSpace() + getConflictType(conflict), SimpleTextAttributes.GRAYED_ATTRIBUTES) } } override fun appendParentPath(renderer: ChangesBrowserNodeRenderer, parentPath: FilePath?) { if (conflict == null) { super.appendParentPath(renderer, parentPath) } } } private open inner class ChangesBrowserKindNode(kind: NodeKind) : ChangesBrowserNode<NodeKind>(kind) { internal val kind: NodeKind get() = userObject as NodeKind init { markAsHelperNode() setAttributes(SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) } override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { if (kind == NodeKind.CONFLICTED) { renderer.append(textPresentation, attributes) renderer.append(FontUtil.spaceAndThinSpace(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) renderer.append(VcsBundle.message("changes.nodetitle.merge.conflicts.resolve.link.label"), SimpleTextAttributes.LINK_BOLD_ATTRIBUTES, Runnable { val conflictedFiles = getObjectsUnderStream(GitFileStatusNode::class.java).map { it.filePath.virtualFile }.filter { it != null }.toList() as List<VirtualFile> showMergeDialog(conflictedFiles) }) appendCount(renderer) } else { super.render(renderer, selected, expanded, hasFocus) } } @Nls override fun getTextPresentation(): String = GitBundle.message(kind.key) override fun compareUserObjects(o2: NodeKind?): Int { return Comparing.compare(sortOrder[kind], sortOrder[o2]) } } private class ChangesBrowserUntrackedNode(project: Project, files: List<FilePath>) : ChangesBrowserSpecificFilePathsNode<NodeKind>(NodeKind.UNTRACKED, files, { UnversionedViewDialog(project, files).show() }) { init { markAsHelperNode() setAttributes(SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) } @Nls override fun getTextPresentation(): String = GitBundle.message(NodeKind.UNTRACKED.key) override fun compareUserObjects(o2: NodeKind?): Int { return Comparing.compare(sortOrder[NodeKind.UNTRACKED], sortOrder[o2]) } } private class GitStageTreeRenderer(textRenderer: ChangesBrowserNodeRenderer) : ChangesTreeCellRenderer<JBLabel>(textRenderer, JBLabel()) { override fun JBLabel.prepare(tree: ChangesTree, node: ChangesBrowserNode<*>) { val baseIcon = (tree as? GitStageTree)?.getFirstMatchingOperation(node)?.icon isVisible = baseIcon != null icon = baseIcon?.let { it -> activeIcon(it, tree).apply { setActive(tree.hoverNode == node) } } } private fun activeIcon(icon: Icon, component: JComponent) = ActiveIcon(icon, IconLoader.getDisabledIcon(icon, component)) } private inner class MyMouseMotionListener : MouseMotionListener { override fun mouseMoved(e: MouseEvent?) { if (e == null) return val path = getPathIfInsideComponent(e.point) val node = path?.lastPathComponent as? ChangesBrowserNode<*> hoverNode = node if (node != null) { getFirstMatchingOperation(node)?.let { toolTipText = it.actionText.get() } } } override fun mouseDragged(e: MouseEvent?) = Unit } private inner class MyClickListener : ClickListener() { override fun onClick(event: MouseEvent, clickCount: Int): Boolean { val path: TreePath = getPathIfInsideComponent(event.point) ?: return false val node = path.lastPathComponent as? ChangesBrowserNode<*> ?: return false getFirstMatchingOperation(node)?.let { performStageOperation(listOf(node.userObject as GitFileStatusNode), it) } return false } } private inner class MyDnDSupport : ChangesTreeDnDSupport(this@GitStageTree) { override fun createDragStartBean(info: DnDActionInfo): DnDDragStartBean? { if (info.isMove) { val selection = selectedStatusNodes().toList() if (selection.isNotEmpty()) { return DnDDragStartBean(MyDragBean(this@GitStageTree, selection)) } } return null } override fun canHandleDropEvent(aEvent: DnDEvent, dropNode: ChangesBrowserNode<*>): Boolean { val dragBean = aEvent.attachedObject if (dragBean is MyDragBean) { if (dragBean.sourceComponent === this@GitStageTree && canAcceptDrop(dropNode, dragBean)) { dragBean.targetNode = dropNode return true } } return false } override fun drop(aEvent: DnDEvent) { val dragBean = aEvent.attachedObject if (dragBean is MyDragBean) { val changesBrowserNode = dragBean.targetNode changesBrowserNode?.let { acceptDrop(it, dragBean) } } } private fun canAcceptDrop(node: ChangesBrowserNode<*>, bean: MyDragBean): Boolean { val targetKind: NodeKind = node.userObject as? NodeKind ?: return false val operation = getDndOperation(targetKind) ?: return false return bean.nodes.all(operation::matches) } private fun acceptDrop(node: ChangesBrowserNode<*>, bean: MyDragBean) { val targetKind: NodeKind = node.userObject as? NodeKind ?: return val operation = getDndOperation(targetKind) ?: return performStageOperation(bean.nodes, operation) } } private class MyDragBean(val tree: ChangesTree, val nodes: List<GitFileStatusNode>) { var targetNode: ChangesBrowserNode<*>? = null val sourceComponent: JComponent get() = tree } } enum class NodeKind(@PropertyKey(resourceBundle = GitBundle.BUNDLE) @NonNls val key: String) { STAGED("stage.tree.node.staged") { override fun `is`(status: GitFileStatus) = status.getStagedStatus() != null override fun status(status: GitFileStatus) = status.getStagedStatus()!! override fun origPath(status: GitFileStatus): FilePath? = if (isRenamed(status.index)) status.origPath else null }, UNSTAGED("stage.tree.node.unstaged") { override fun `is`(status: GitFileStatus): Boolean = status.getUnStagedStatus() != null override fun status(status: GitFileStatus) = status.getUnStagedStatus()!! override fun origPath(status: GitFileStatus): FilePath? = if (isRenamed(status.workTree)) status.origPath else null }, CONFLICTED("stage.tree.node.unmerged") { override fun `is`(status: GitFileStatus): Boolean = status.isConflicted() override fun status(status: GitFileStatus) = FileStatus.MERGED_WITH_CONFLICTS }, UNTRACKED("stage.tree.node.untracked") { override fun `is`(status: GitFileStatus): Boolean = status.isUntracked() override fun status(status: GitFileStatus) = FileStatus.UNKNOWN }, IGNORED("stage.tree.node.ignored") { override fun `is`(status: GitFileStatus): Boolean = status.isIgnored() override fun status(status: GitFileStatus) = FileStatus.IGNORED }; abstract fun `is`(status: GitFileStatus): Boolean abstract fun status(status: GitFileStatus): FileStatus open fun origPath(status: GitFileStatus): FilePath? = null companion object { internal val sortOrder = listOf(CONFLICTED, STAGED, UNSTAGED, UNTRACKED, IGNORED).zip(values().indices).toMap() } } data class GitFileStatusNode(val root: VirtualFile, val status: GitFileStatus, val kind: NodeKind) { val filePath: FilePath get() = status.path val origPath: FilePath? get() = kind.origPath(status) val fileStatus: FileStatus get() = kind.status(status) override fun toString(): @NonNls String { return "GitFileStatusNode(root=$root, status=$fileStatus, kind=$kind)" } } internal fun GitFileStatusNode.createConflict(): GitConflict? { return GitStagingAreaHolder.createConflict(root, status) }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
17,674
intellij-community
Apache License 2.0
dsl/s3/src/main/kotlin/software/amazon/awscdk/dsl/services/s3/dsl.kt
aws-cdk-dsl
176,878,480
false
{"Kotlin": 3500307}
package software.amazon.awscdk.dsl.services.s3 /** * @see software.amazon.awscdk.services.s3.Bucket */ fun software.amazon.awscdk.Construct.bucket(id: String, props: software.amazon.awscdk.services.s3.BucketProps? = null, init: (software.amazon.awscdk.services.s3.Bucket.() -> Unit)? = null) : software.amazon.awscdk.services.s3.Bucket { val obj = software.amazon.awscdk.services.s3.Bucket(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.s3.BucketPolicy */ fun software.amazon.awscdk.Construct.bucketPolicy(id: String, props: software.amazon.awscdk.services.s3.BucketPolicyProps? = null, init: (software.amazon.awscdk.services.s3.BucketPolicy.() -> Unit)? = null) : software.amazon.awscdk.services.s3.BucketPolicy { val obj = software.amazon.awscdk.services.s3.BucketPolicy(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.s3.CfnBucket */ fun software.amazon.awscdk.Construct.cfnBucket(id: String, props: software.amazon.awscdk.services.s3.CfnBucketProps? = null, init: (software.amazon.awscdk.services.s3.CfnBucket.() -> Unit)? = null) : software.amazon.awscdk.services.s3.CfnBucket { val obj = software.amazon.awscdk.services.s3.CfnBucket(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.s3.CfnBucketPolicy */ fun software.amazon.awscdk.Construct.cfnBucketPolicy(id: String, props: software.amazon.awscdk.services.s3.CfnBucketPolicyProps? = null, init: (software.amazon.awscdk.services.s3.CfnBucketPolicy.() -> Unit)? = null) : software.amazon.awscdk.services.s3.CfnBucketPolicy { val obj = software.amazon.awscdk.services.s3.CfnBucketPolicy(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.s3.Bucket */ fun software.amazon.awscdk.Construct.bucket(id: String, init: (software.amazon.awscdk.services.s3.Bucket.() -> Unit)? = null) : software.amazon.awscdk.services.s3.Bucket { val obj = software.amazon.awscdk.services.s3.Bucket(this, id) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.s3.CfnBucket */ fun software.amazon.awscdk.Construct.cfnBucket(id: String, init: (software.amazon.awscdk.services.s3.CfnBucket.() -> Unit)? = null) : software.amazon.awscdk.services.s3.CfnBucket { val obj = software.amazon.awscdk.services.s3.CfnBucket(this, id) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder */ fun metricsConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.withId */ var software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.withTagFilters */ var software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.tagFilters: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on tagFilters is not supported.") set(value) { this.withTagFilters(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.withPrefix */ var software.amazon.awscdk.services.s3.CfnBucket.MetricsConfigurationProperty.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder */ fun inventoryConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.withId */ var software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.withDestination */ var software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.destination: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on destination is not supported.") set(value) { this.withDestination(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.withIncludedObjectVersions */ var software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.includedObjectVersions: String get() = throw NoSuchFieldException("Get on includedObjectVersions is not supported.") set(value) { this.withIncludedObjectVersions(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.withScheduleFrequency */ var software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.scheduleFrequency: String get() = throw NoSuchFieldException("Get on scheduleFrequency is not supported.") set(value) { this.withScheduleFrequency(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.withEnabled */ var software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.enabled: Boolean get() = throw NoSuchFieldException("Get on enabled is not supported.") set(value) { this.withEnabled(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.withPrefix */ var software.amazon.awscdk.services.s3.CfnBucket.InventoryConfigurationProperty.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder */ fun commonPipelineSourceActionProps(init: software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps { val builder = software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.withOutputArtifactName */ var software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.outputArtifactName: String get() = throw NoSuchFieldException("Get on outputArtifactName is not supported.") set(value) { this.withOutputArtifactName(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.withPollForSourceChanges */ var software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.pollForSourceChanges: Boolean get() = throw NoSuchFieldException("Get on pollForSourceChanges is not supported.") set(value) { this.withPollForSourceChanges(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.withActionName */ var software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.actionName: String get() = throw NoSuchFieldException("Get on actionName is not supported.") set(value) { this.withActionName(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.withRunOrder */ var software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.runOrder: Number get() = throw NoSuchFieldException("Get on runOrder is not supported.") set(value) { this.withRunOrder(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.withBucketKey */ var software.amazon.awscdk.services.s3.CommonPipelineSourceActionProps.Builder.bucketKey: String get() = throw NoSuchFieldException("Get on bucketKey is not supported.") set(value) { this.withBucketKey(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty.Builder */ fun encryptionConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty.Builder.withReplicaKmsKeyId */ var software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty.Builder.replicaKmsKeyId: String get() = throw NoSuchFieldException("Get on replicaKmsKeyId is not supported.") set(value) { this.withReplicaKmsKeyId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty.Builder */ fun bucketEncryptionProperty(init: software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty.Builder.withServerSideEncryptionConfiguration */ var software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty.Builder.serverSideEncryptionConfiguration: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on serverSideEncryptionConfiguration is not supported.") set(value) { this.withServerSideEncryptionConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AbortIncompleteMultipartUploadProperty.Builder */ fun abortIncompleteMultipartUploadProperty(init: software.amazon.awscdk.services.s3.CfnBucket.AbortIncompleteMultipartUploadProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.AbortIncompleteMultipartUploadProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.AbortIncompleteMultipartUploadProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AbortIncompleteMultipartUploadProperty.Builder.withDaysAfterInitiation */ var software.amazon.awscdk.services.s3.CfnBucket.AbortIncompleteMultipartUploadProperty.Builder.daysAfterInitiation: Number get() = throw NoSuchFieldException("Get on daysAfterInitiation is not supported.") set(value) { this.withDaysAfterInitiation(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder */ fun notificationConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.withLambdaConfigurations */ var software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.lambdaConfigurations: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on lambdaConfigurations is not supported.") set(value) { this.withLambdaConfigurations(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.withQueueConfigurations */ var software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.queueConfigurations: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on queueConfigurations is not supported.") set(value) { this.withQueueConfigurations(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.withTopicConfigurations */ var software.amazon.awscdk.services.s3.CfnBucket.NotificationConfigurationProperty.Builder.topicConfigurations: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on topicConfigurations is not supported.") set(value) { this.withTopicConfigurations(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder */ fun loggingConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder.withLogFilePrefix */ var software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder.logFilePrefix: String get() = throw NoSuchFieldException("Get on logFilePrefix is not supported.") set(value) { this.withLogFilePrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder.withDestinationBucketName */ var software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty.Builder.destinationBucketName: String get() = throw NoSuchFieldException("Get on destinationBucketName is not supported.") set(value) { this.withDestinationBucketName(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder */ fun destinationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.withFormat */ var software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.format: String get() = throw NoSuchFieldException("Get on format is not supported.") set(value) { this.withFormat(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.withBucketAccountId */ var software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.bucketAccountId: String get() = throw NoSuchFieldException("Get on bucketAccountId is not supported.") set(value) { this.withBucketAccountId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.withBucketArn */ var software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.bucketArn: String get() = throw NoSuchFieldException("Get on bucketArn is not supported.") set(value) { this.withBucketArn(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.withPrefix */ var software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder */ fun replicationDestinationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.withStorageClass */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.storageClass: String get() = throw NoSuchFieldException("Get on storageClass is not supported.") set(value) { this.withStorageClass(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.withAccount */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.account: String get() = throw NoSuchFieldException("Get on account is not supported.") set(value) { this.withAccount(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.withBucket */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.bucket: String get() = throw NoSuchFieldException("Get on bucket is not supported.") set(value) { this.withBucket(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.withEncryptionConfiguration */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.encryptionConfiguration: software.amazon.awscdk.services.s3.CfnBucket.EncryptionConfigurationProperty get() = throw NoSuchFieldException("Get on encryptionConfiguration is not supported.") set(value) { this.withEncryptionConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.withAccessControlTranslation */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty.Builder.accessControlTranslation: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on accessControlTranslation is not supported.") set(value) { this.withAccessControlTranslation(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder */ fun routingRuleConditionProperty(init: software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder.withKeyPrefixEquals */ var software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder.keyPrefixEquals: String get() = throw NoSuchFieldException("Get on keyPrefixEquals is not supported.") set(value) { this.withKeyPrefixEquals(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder.withHttpErrorCodeReturnedEquals */ var software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty.Builder.httpErrorCodeReturnedEquals: String get() = throw NoSuchFieldException("Get on httpErrorCodeReturnedEquals is not supported.") set(value) { this.withHttpErrorCodeReturnedEquals(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder */ fun corsRuleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder.withId */ var software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder.withMaxAge */ var software.amazon.awscdk.services.s3.CfnBucket.CorsRuleProperty.Builder.maxAge: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on maxAge is not supported.") set(value) { this.withMaxAge(value) } /** * @see software.amazon.awscdk.services.s3.Transition.Builder */ fun transition(init: software.amazon.awscdk.services.s3.Transition.Builder.() -> Unit): software.amazon.awscdk.services.s3.Transition { val builder = software.amazon.awscdk.services.s3.Transition.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.Transition.Builder.withTransitionInDays */ var software.amazon.awscdk.services.s3.Transition.Builder.transitionInDays: Number get() = throw NoSuchFieldException("Get on transitionInDays is not supported.") set(value) { this.withTransitionInDays(value) } /** * @see software.amazon.awscdk.services.s3.Transition.Builder.withTransitionDate */ var software.amazon.awscdk.services.s3.Transition.Builder.transitionDate: java.time.Instant get() = throw NoSuchFieldException("Get on transitionDate is not supported.") set(value) { this.withTransitionDate(value) } /** * @see software.amazon.awscdk.services.s3.Transition.Builder.withStorageClass */ var software.amazon.awscdk.services.s3.Transition.Builder.storageClass: software.amazon.awscdk.services.s3.StorageClass get() = throw NoSuchFieldException("Get on storageClass is not supported.") set(value) { this.withStorageClass(value) } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder */ fun pipelineSourceActionProps(init: software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.PipelineSourceActionProps { val builder = software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.withOutputArtifactName */ var software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.outputArtifactName: String get() = throw NoSuchFieldException("Get on outputArtifactName is not supported.") set(value) { this.withOutputArtifactName(value) } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.withPollForSourceChanges */ var software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.pollForSourceChanges: Boolean get() = throw NoSuchFieldException("Get on pollForSourceChanges is not supported.") set(value) { this.withPollForSourceChanges(value) } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.withBucket */ var software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.bucket: software.amazon.awscdk.services.s3.IBucket get() = throw NoSuchFieldException("Get on bucket is not supported.") set(value) { this.withBucket(value) } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.withActionName */ var software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.actionName: String get() = throw NoSuchFieldException("Get on actionName is not supported.") set(value) { this.withActionName(value) } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.withRunOrder */ var software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.runOrder: Number get() = throw NoSuchFieldException("Get on runOrder is not supported.") set(value) { this.withRunOrder(value) } /** * @see software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.withBucketKey */ var software.amazon.awscdk.services.s3.PipelineSourceActionProps.Builder.bucketKey: String get() = throw NoSuchFieldException("Get on bucketKey is not supported.") set(value) { this.withBucketKey(value) } /** * @see software.amazon.awscdk.services.s3.BucketPolicyProps.Builder */ fun bucketPolicyProps(init: software.amazon.awscdk.services.s3.BucketPolicyProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.BucketPolicyProps { val builder = software.amazon.awscdk.services.s3.BucketPolicyProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.BucketPolicyProps.Builder.withBucket */ var software.amazon.awscdk.services.s3.BucketPolicyProps.Builder.bucket: software.amazon.awscdk.services.s3.IBucket get() = throw NoSuchFieldException("Get on bucket is not supported.") set(value) { this.withBucket(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionRuleProperty.Builder */ fun serverSideEncryptionRuleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionRuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionRuleProperty.Builder.withServerSideEncryptionByDefault */ var software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionRuleProperty.Builder.serverSideEncryptionByDefault: software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty get() = throw NoSuchFieldException("Get on serverSideEncryptionByDefault is not supported.") set(value) { this.withServerSideEncryptionByDefault(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder */ fun filterRuleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder.withValue */ var software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder.value: String get() = throw NoSuchFieldException("Get on value is not supported.") set(value) { this.withValue(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder.withName */ var software.amazon.awscdk.services.s3.CfnBucket.FilterRuleProperty.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder */ fun queueConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.withQueue */ var software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.queue: String get() = throw NoSuchFieldException("Get on queue is not supported.") set(value) { this.withQueue(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.withEvent */ var software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.event: String get() = throw NoSuchFieldException("Get on event is not supported.") set(value) { this.withEvent(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.withFilter */ var software.amazon.awscdk.services.s3.CfnBucket.QueueConfigurationProperty.Builder.filter: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on filter is not supported.") set(value) { this.withFilter(value) } /** * @see software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder */ fun noncurrentVersionTransition(init: software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder.() -> Unit): software.amazon.awscdk.services.s3.NoncurrentVersionTransition { val builder = software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder.withTransitionInDays */ var software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder.transitionInDays: Number get() = throw NoSuchFieldException("Get on transitionInDays is not supported.") set(value) { this.withTransitionInDays(value) } /** * @see software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder.withStorageClass */ var software.amazon.awscdk.services.s3.NoncurrentVersionTransition.Builder.storageClass: software.amazon.awscdk.services.s3.StorageClass get() = throw NoSuchFieldException("Get on storageClass is not supported.") set(value) { this.withStorageClass(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder */ fun tagFilterProperty(init: software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder.withKey */ var software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder.key: String get() = throw NoSuchFieldException("Get on key is not supported.") set(value) { this.withKey(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder.withValue */ var software.amazon.awscdk.services.s3.CfnBucket.TagFilterProperty.Builder.value: String get() = throw NoSuchFieldException("Get on value is not supported.") set(value) { this.withValue(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder */ fun replicationConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder.withRole */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder.role: String get() = throw NoSuchFieldException("Get on role is not supported.") set(value) { this.withRole(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder.withRules */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty.Builder.rules: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on rules is not supported.") set(value) { this.withRules(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder */ fun publicAccessBlockConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.withIgnorePublicAcls */ var software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.ignorePublicAcls: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on ignorePublicAcls is not supported.") set(value) { this.withIgnorePublicAcls(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.withRestrictPublicBuckets */ var software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.restrictPublicBuckets: Boolean get() = throw NoSuchFieldException("Get on restrictPublicBuckets is not supported.") set(value) { this.withRestrictPublicBuckets(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.withBlockPublicAcls */ var software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.blockPublicAcls: Boolean get() = throw NoSuchFieldException("Get on blockPublicAcls is not supported.") set(value) { this.withBlockPublicAcls(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.withBlockPublicPolicy */ var software.amazon.awscdk.services.s3.CfnBucket.PublicAccessBlockConfigurationProperty.Builder.blockPublicPolicy: Boolean get() = throw NoSuchFieldException("Get on blockPublicPolicy is not supported.") set(value) { this.withBlockPublicPolicy(value) } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder */ fun pipelineDeployActionProps(init: software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.PipelineDeployActionProps { val builder = software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.withInputArtifact */ var software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.inputArtifact: software.amazon.awscdk.services.codepipeline.api.Artifact get() = throw NoSuchFieldException("Get on inputArtifact is not supported.") set(value) { this.withInputArtifact(value) } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.withBucket */ var software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.bucket: software.amazon.awscdk.services.s3.IBucket get() = throw NoSuchFieldException("Get on bucket is not supported.") set(value) { this.withBucket(value) } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.withActionName */ var software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.actionName: String get() = throw NoSuchFieldException("Get on actionName is not supported.") set(value) { this.withActionName(value) } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.withRunOrder */ var software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.runOrder: Number get() = throw NoSuchFieldException("Get on runOrder is not supported.") set(value) { this.withRunOrder(value) } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.withObjectKey */ var software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.objectKey: String get() = throw NoSuchFieldException("Get on objectKey is not supported.") set(value) { this.withObjectKey(value) } /** * @see software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.withExtract */ var software.amazon.awscdk.services.s3.PipelineDeployActionProps.Builder.extract: Boolean get() = throw NoSuchFieldException("Get on extract is not supported.") set(value) { this.withExtract(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty.Builder */ fun corsConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty.Builder.withCorsRules */ var software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty.Builder.corsRules: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on corsRules is not supported.") set(value) { this.withCorsRules(value) } /** * @see software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder */ fun blockPublicAccessOptions(init: software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.() -> Unit): software.amazon.awscdk.services.s3.BlockPublicAccessOptions { val builder = software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.withIgnorePublicAcls */ var software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.ignorePublicAcls: Boolean get() = throw NoSuchFieldException("Get on ignorePublicAcls is not supported.") set(value) { this.withIgnorePublicAcls(value) } /** * @see software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.withRestrictPublicBuckets */ var software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.restrictPublicBuckets: Boolean get() = throw NoSuchFieldException("Get on restrictPublicBuckets is not supported.") set(value) { this.withRestrictPublicBuckets(value) } /** * @see software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.withBlockPublicAcls */ var software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.blockPublicAcls: Boolean get() = throw NoSuchFieldException("Get on blockPublicAcls is not supported.") set(value) { this.withBlockPublicAcls(value) } /** * @see software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.withBlockPublicPolicy */ var software.amazon.awscdk.services.s3.BlockPublicAccessOptions.Builder.blockPublicPolicy: Boolean get() = throw NoSuchFieldException("Get on blockPublicPolicy is not supported.") set(value) { this.withBlockPublicPolicy(value) } /** * @see software.amazon.awscdk.services.s3.BucketImportProps.Builder */ fun bucketImportProps(init: software.amazon.awscdk.services.s3.BucketImportProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.BucketImportProps { val builder = software.amazon.awscdk.services.s3.BucketImportProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.BucketImportProps.Builder.withBucketName */ var software.amazon.awscdk.services.s3.BucketImportProps.Builder.bucketName: String get() = throw NoSuchFieldException("Get on bucketName is not supported.") set(value) { this.withBucketName(value) } /** * @see software.amazon.awscdk.services.s3.BucketImportProps.Builder.withBucketArn */ var software.amazon.awscdk.services.s3.BucketImportProps.Builder.bucketArn: String get() = throw NoSuchFieldException("Get on bucketArn is not supported.") set(value) { this.withBucketArn(value) } /** * @see software.amazon.awscdk.services.s3.BucketImportProps.Builder.withBucketWebsiteUrl */ var software.amazon.awscdk.services.s3.BucketImportProps.Builder.bucketWebsiteUrl: String get() = throw NoSuchFieldException("Get on bucketWebsiteUrl is not supported.") set(value) { this.withBucketWebsiteUrl(value) } /** * @see software.amazon.awscdk.services.s3.BucketImportProps.Builder.withBucketDomainName */ var software.amazon.awscdk.services.s3.BucketImportProps.Builder.bucketDomainName: String get() = throw NoSuchFieldException("Get on bucketDomainName is not supported.") set(value) { this.withBucketDomainName(value) } /** * @see software.amazon.awscdk.services.s3.BucketImportProps.Builder.withBucketWebsiteNewUrlFormat */ var software.amazon.awscdk.services.s3.BucketImportProps.Builder.bucketWebsiteNewUrlFormat: Boolean get() = throw NoSuchFieldException("Get on bucketWebsiteNewUrlFormat is not supported.") set(value) { this.withBucketWebsiteNewUrlFormat(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder */ fun serverSideEncryptionByDefaultProperty(init: software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder.withKmsMasterKeyId */ var software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder.kmsMasterKeyId: String get() = throw NoSuchFieldException("Get on kmsMasterKeyId is not supported.") set(value) { this.withKmsMasterKeyId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder.withSseAlgorithm */ var software.amazon.awscdk.services.s3.CfnBucket.ServerSideEncryptionByDefaultProperty.Builder.sseAlgorithm: String get() = throw NoSuchFieldException("Get on sseAlgorithm is not supported.") set(value) { this.withSseAlgorithm(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder */ fun ruleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.RuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withId */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withStatus */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.status: String get() = throw NoSuchFieldException("Get on status is not supported.") set(value) { this.withStatus(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withTagFilters */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.tagFilters: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on tagFilters is not supported.") set(value) { this.withTagFilters(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withPrefix */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withAbortIncompleteMultipartUpload */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.abortIncompleteMultipartUpload: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on abortIncompleteMultipartUpload is not supported.") set(value) { this.withAbortIncompleteMultipartUpload(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withExpirationDate */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.expirationDate: java.time.Instant get() = throw NoSuchFieldException("Get on expirationDate is not supported.") set(value) { this.withExpirationDate(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withExpirationInDays */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.expirationInDays: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on expirationInDays is not supported.") set(value) { this.withExpirationInDays(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withNoncurrentVersionExpirationInDays */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.noncurrentVersionExpirationInDays: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on noncurrentVersionExpirationInDays is not supported.") set(value) { this.withNoncurrentVersionExpirationInDays(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withNoncurrentVersionTransition */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.noncurrentVersionTransition: software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty get() = throw NoSuchFieldException("Get on noncurrentVersionTransition is not supported.") set(value) { this.withNoncurrentVersionTransition(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withNoncurrentVersionTransitions */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.noncurrentVersionTransitions: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on noncurrentVersionTransitions is not supported.") set(value) { this.withNoncurrentVersionTransitions(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withTransition */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.transition: software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty get() = throw NoSuchFieldException("Get on transition is not supported.") set(value) { this.withTransition(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.withTransitions */ var software.amazon.awscdk.services.s3.CfnBucket.RuleProperty.Builder.transitions: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on transitions is not supported.") set(value) { this.withTransitions(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder */ fun dataExportProperty(init: software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder.withDestination */ var software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder.destination: software.amazon.awscdk.services.s3.CfnBucket.DestinationProperty get() = throw NoSuchFieldException("Get on destination is not supported.") set(value) { this.withDestination(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder.withOutputSchemaVersion */ var software.amazon.awscdk.services.s3.CfnBucket.DataExportProperty.Builder.outputSchemaVersion: String get() = throw NoSuchFieldException("Get on outputSchemaVersion is not supported.") set(value) { this.withOutputSchemaVersion(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder */ fun lifecycleRule(init: software.amazon.awscdk.services.s3.LifecycleRule.Builder.() -> Unit): software.amazon.awscdk.services.s3.LifecycleRule { val builder = software.amazon.awscdk.services.s3.LifecycleRule.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withId */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withEnabled */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.enabled: Boolean get() = throw NoSuchFieldException("Get on enabled is not supported.") set(value) { this.withEnabled(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withPrefix */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withExpirationDate */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.expirationDate: java.time.Instant get() = throw NoSuchFieldException("Get on expirationDate is not supported.") set(value) { this.withExpirationDate(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withExpirationInDays */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.expirationInDays: Number get() = throw NoSuchFieldException("Get on expirationInDays is not supported.") set(value) { this.withExpirationInDays(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withNoncurrentVersionExpirationInDays */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.noncurrentVersionExpirationInDays: Number get() = throw NoSuchFieldException("Get on noncurrentVersionExpirationInDays is not supported.") set(value) { this.withNoncurrentVersionExpirationInDays(value) } /** * @see software.amazon.awscdk.services.s3.LifecycleRule.Builder.withAbortIncompleteMultipartUploadAfterDays */ var software.amazon.awscdk.services.s3.LifecycleRule.Builder.abortIncompleteMultipartUploadAfterDays: Number get() = throw NoSuchFieldException("Get on abortIncompleteMultipartUploadAfterDays is not supported.") set(value) { this.withAbortIncompleteMultipartUploadAfterDays(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder */ fun cfnBucketProps(init: software.amazon.awscdk.services.s3.CfnBucketProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucketProps { val builder = software.amazon.awscdk.services.s3.CfnBucketProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withBucketName */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.bucketName: String get() = throw NoSuchFieldException("Get on bucketName is not supported.") set(value) { this.withBucketName(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withAccelerateConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.accelerateConfiguration: software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty get() = throw NoSuchFieldException("Get on accelerateConfiguration is not supported.") set(value) { this.withAccelerateConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withAccessControl */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.accessControl: String get() = throw NoSuchFieldException("Get on accessControl is not supported.") set(value) { this.withAccessControl(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withAnalyticsConfigurations */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.analyticsConfigurations: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on analyticsConfigurations is not supported.") set(value) { this.withAnalyticsConfigurations(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withBucketEncryption */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.bucketEncryption: software.amazon.awscdk.services.s3.CfnBucket.BucketEncryptionProperty get() = throw NoSuchFieldException("Get on bucketEncryption is not supported.") set(value) { this.withBucketEncryption(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withCorsConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.corsConfiguration: software.amazon.awscdk.services.s3.CfnBucket.CorsConfigurationProperty get() = throw NoSuchFieldException("Get on corsConfiguration is not supported.") set(value) { this.withCorsConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withInventoryConfigurations */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.inventoryConfigurations: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on inventoryConfigurations is not supported.") set(value) { this.withInventoryConfigurations(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withLifecycleConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.lifecycleConfiguration: software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty get() = throw NoSuchFieldException("Get on lifecycleConfiguration is not supported.") set(value) { this.withLifecycleConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withLoggingConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.loggingConfiguration: software.amazon.awscdk.services.s3.CfnBucket.LoggingConfigurationProperty get() = throw NoSuchFieldException("Get on loggingConfiguration is not supported.") set(value) { this.withLoggingConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withMetricsConfigurations */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.metricsConfigurations: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on metricsConfigurations is not supported.") set(value) { this.withMetricsConfigurations(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withNotificationConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.notificationConfiguration: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on notificationConfiguration is not supported.") set(value) { this.withNotificationConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withPublicAccessBlockConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.publicAccessBlockConfiguration: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on publicAccessBlockConfiguration is not supported.") set(value) { this.withPublicAccessBlockConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withReplicationConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.replicationConfiguration: software.amazon.awscdk.services.s3.CfnBucket.ReplicationConfigurationProperty get() = throw NoSuchFieldException("Get on replicationConfiguration is not supported.") set(value) { this.withReplicationConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withVersioningConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.versioningConfiguration: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on versioningConfiguration is not supported.") set(value) { this.withVersioningConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketProps.Builder.withWebsiteConfiguration */ var software.amazon.awscdk.services.s3.CfnBucketProps.Builder.websiteConfiguration: software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty get() = throw NoSuchFieldException("Get on websiteConfiguration is not supported.") set(value) { this.withWebsiteConfiguration(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder */ fun redirectAllRequestsToProperty(init: software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder.withProtocol */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder.protocol: String get() = throw NoSuchFieldException("Get on protocol is not supported.") set(value) { this.withProtocol(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder.withHostName */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectAllRequestsToProperty.Builder.hostName: String get() = throw NoSuchFieldException("Get on hostName is not supported.") set(value) { this.withHostName(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.VersioningConfigurationProperty.Builder */ fun versioningConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.VersioningConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.VersioningConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.VersioningConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.VersioningConfigurationProperty.Builder.withStatus */ var software.amazon.awscdk.services.s3.CfnBucket.VersioningConfigurationProperty.Builder.status: String get() = throw NoSuchFieldException("Get on status is not supported.") set(value) { this.withStatus(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty.Builder */ fun sourceSelectionCriteriaProperty(init: software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty.Builder.withSseKmsEncryptedObjects */ var software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty.Builder.sseKmsEncryptedObjects: software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty get() = throw NoSuchFieldException("Get on sseKmsEncryptedObjects is not supported.") set(value) { this.withSseKmsEncryptedObjects(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.S3KeyFilterProperty.Builder */ fun s3KeyFilterProperty(init: software.amazon.awscdk.services.s3.CfnBucket.S3KeyFilterProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.S3KeyFilterProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.S3KeyFilterProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.S3KeyFilterProperty.Builder.withRules */ var software.amazon.awscdk.services.s3.CfnBucket.S3KeyFilterProperty.Builder.rules: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on rules is not supported.") set(value) { this.withRules(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder */ fun lambdaConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.withEvent */ var software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.event: String get() = throw NoSuchFieldException("Get on event is not supported.") set(value) { this.withEvent(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.withFilter */ var software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.filter: software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty get() = throw NoSuchFieldException("Get on filter is not supported.") set(value) { this.withFilter(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.withFunction */ var software.amazon.awscdk.services.s3.CfnBucket.LambdaConfigurationProperty.Builder.function: String get() = throw NoSuchFieldException("Get on function is not supported.") set(value) { this.withFunction(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.StorageClassAnalysisProperty.Builder */ fun storageClassAnalysisProperty(init: software.amazon.awscdk.services.s3.CfnBucket.StorageClassAnalysisProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.StorageClassAnalysisProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.StorageClassAnalysisProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.StorageClassAnalysisProperty.Builder.withDataExport */ var software.amazon.awscdk.services.s3.CfnBucket.StorageClassAnalysisProperty.Builder.dataExport: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on dataExport is not supported.") set(value) { this.withDataExport(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder */ fun cfnBucketPolicyProps(init: software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucketPolicyProps { val builder = software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder.withPolicyDocument */ var software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder.policyDocument: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on policyDocument is not supported.") set(value) { this.withPolicyDocument(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder.withBucket */ var software.amazon.awscdk.services.s3.CfnBucketPolicyProps.Builder.bucket: String get() = throw NoSuchFieldException("Get on bucket is not supported.") set(value) { this.withBucket(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AccessControlTranslationProperty.Builder */ fun accessControlTranslationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.AccessControlTranslationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.AccessControlTranslationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.AccessControlTranslationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AccessControlTranslationProperty.Builder.withOwner */ var software.amazon.awscdk.services.s3.CfnBucket.AccessControlTranslationProperty.Builder.owner: String get() = throw NoSuchFieldException("Get on owner is not supported.") set(value) { this.withOwner(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder */ fun transitionProperty(init: software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.withTransitionInDays */ var software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.transitionInDays: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on transitionInDays is not supported.") set(value) { this.withTransitionInDays(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.withTransitionDate */ var software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.transitionDate: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on transitionDate is not supported.") set(value) { this.withTransitionDate(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.withStorageClass */ var software.amazon.awscdk.services.s3.CfnBucket.TransitionProperty.Builder.storageClass: String get() = throw NoSuchFieldException("Get on storageClass is not supported.") set(value) { this.withStorageClass(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty.Builder */ fun sseKmsEncryptedObjectsProperty(init: software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty.Builder.withStatus */ var software.amazon.awscdk.services.s3.CfnBucket.SseKmsEncryptedObjectsProperty.Builder.status: String get() = throw NoSuchFieldException("Get on status is not supported.") set(value) { this.withStatus(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder */ fun topicConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.withEvent */ var software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.event: String get() = throw NoSuchFieldException("Get on event is not supported.") set(value) { this.withEvent(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.withTopic */ var software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.topic: String get() = throw NoSuchFieldException("Get on topic is not supported.") set(value) { this.withTopic(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.withFilter */ var software.amazon.awscdk.services.s3.CfnBucket.TopicConfigurationProperty.Builder.filter: software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty get() = throw NoSuchFieldException("Get on filter is not supported.") set(value) { this.withFilter(value) } /** * @see software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder */ fun notificationKeyFilter(init: software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder.() -> Unit): software.amazon.awscdk.services.s3.NotificationKeyFilter { val builder = software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder.withSuffix */ var software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder.suffix: String get() = throw NoSuchFieldException("Get on suffix is not supported.") set(value) { this.withSuffix(value) } /** * @see software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder.withPrefix */ var software.amazon.awscdk.services.s3.NotificationKeyFilter.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder */ fun websiteConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.withRoutingRules */ var software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.routingRules: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on routingRules is not supported.") set(value) { this.withRoutingRules(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.withErrorDocument */ var software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.errorDocument: String get() = throw NoSuchFieldException("Get on errorDocument is not supported.") set(value) { this.withErrorDocument(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.withIndexDocument */ var software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.indexDocument: String get() = throw NoSuchFieldException("Get on indexDocument is not supported.") set(value) { this.withIndexDocument(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.withRedirectAllRequestsTo */ var software.amazon.awscdk.services.s3.CfnBucket.WebsiteConfigurationProperty.Builder.redirectAllRequestsTo: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on redirectAllRequestsTo is not supported.") set(value) { this.withRedirectAllRequestsTo(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty.Builder */ fun accelerateConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty.Builder.withAccelerationStatus */ var software.amazon.awscdk.services.s3.CfnBucket.AccelerateConfigurationProperty.Builder.accelerationStatus: String get() = throw NoSuchFieldException("Get on accelerationStatus is not supported.") set(value) { this.withAccelerationStatus(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder */ fun replicationRuleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.withId */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.withDestination */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.destination: software.amazon.awscdk.services.s3.CfnBucket.ReplicationDestinationProperty get() = throw NoSuchFieldException("Get on destination is not supported.") set(value) { this.withDestination(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.withStatus */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.status: String get() = throw NoSuchFieldException("Get on status is not supported.") set(value) { this.withStatus(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.withPrefix */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.withSourceSelectionCriteria */ var software.amazon.awscdk.services.s3.CfnBucket.ReplicationRuleProperty.Builder.sourceSelectionCriteria: software.amazon.awscdk.services.s3.CfnBucket.SourceSelectionCriteriaProperty get() = throw NoSuchFieldException("Get on sourceSelectionCriteria is not supported.") set(value) { this.withSourceSelectionCriteria(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty.Builder */ fun notificationFilterProperty(init: software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty.Builder.withS3Key */ var software.amazon.awscdk.services.s3.CfnBucket.NotificationFilterProperty.Builder.s3Key: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on s3Key is not supported.") set(value) { this.withS3Key(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder */ fun redirectRuleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.withProtocol */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.protocol: String get() = throw NoSuchFieldException("Get on protocol is not supported.") set(value) { this.withProtocol(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.withHostName */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.hostName: String get() = throw NoSuchFieldException("Get on hostName is not supported.") set(value) { this.withHostName(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.withReplaceKeyPrefixWith */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.replaceKeyPrefixWith: String get() = throw NoSuchFieldException("Get on replaceKeyPrefixWith is not supported.") set(value) { this.withReplaceKeyPrefixWith(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.withReplaceKeyWith */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.replaceKeyWith: String get() = throw NoSuchFieldException("Get on replaceKeyWith is not supported.") set(value) { this.withReplaceKeyWith(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.withHttpRedirectCode */ var software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty.Builder.httpRedirectCode: String get() = throw NoSuchFieldException("Get on httpRedirectCode is not supported.") set(value) { this.withHttpRedirectCode(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty.Builder */ fun lifecycleConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty.Builder.withRules */ var software.amazon.awscdk.services.s3.CfnBucket.LifecycleConfigurationProperty.Builder.rules: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on rules is not supported.") set(value) { this.withRules(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder */ fun noncurrentVersionTransitionProperty(init: software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder.withTransitionInDays */ var software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder.transitionInDays: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on transitionInDays is not supported.") set(value) { this.withTransitionInDays(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder.withStorageClass */ var software.amazon.awscdk.services.s3.CfnBucket.NoncurrentVersionTransitionProperty.Builder.storageClass: String get() = throw NoSuchFieldException("Get on storageClass is not supported.") set(value) { this.withStorageClass(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder */ fun routingRuleProperty(init: software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder.withRoutingRuleCondition */ var software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder.routingRuleCondition: software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleConditionProperty get() = throw NoSuchFieldException("Get on routingRuleCondition is not supported.") set(value) { this.withRoutingRuleCondition(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder.withRedirectRule */ var software.amazon.awscdk.services.s3.CfnBucket.RoutingRuleProperty.Builder.redirectRule: software.amazon.awscdk.services.s3.CfnBucket.RedirectRuleProperty get() = throw NoSuchFieldException("Get on redirectRule is not supported.") set(value) { this.withRedirectRule(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder */ fun analyticsConfigurationProperty(init: software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.() -> Unit): software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty { val builder = software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.withId */ var software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.id: String get() = throw NoSuchFieldException("Get on id is not supported.") set(value) { this.withId(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.withTagFilters */ var software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.tagFilters: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on tagFilters is not supported.") set(value) { this.withTagFilters(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.withPrefix */ var software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.prefix: String get() = throw NoSuchFieldException("Get on prefix is not supported.") set(value) { this.withPrefix(value) } /** * @see software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.withStorageClassAnalysis */ var software.amazon.awscdk.services.s3.CfnBucket.AnalyticsConfigurationProperty.Builder.storageClassAnalysis: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on storageClassAnalysis is not supported.") set(value) { this.withStorageClassAnalysis(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder */ fun commonPipelineDeployActionProps(init: software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps { val builder = software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.withInputArtifact */ var software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.inputArtifact: software.amazon.awscdk.services.codepipeline.api.Artifact get() = throw NoSuchFieldException("Get on inputArtifact is not supported.") set(value) { this.withInputArtifact(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.withActionName */ var software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.actionName: String get() = throw NoSuchFieldException("Get on actionName is not supported.") set(value) { this.withActionName(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.withRunOrder */ var software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.runOrder: Number get() = throw NoSuchFieldException("Get on runOrder is not supported.") set(value) { this.withRunOrder(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.withObjectKey */ var software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.objectKey: String get() = throw NoSuchFieldException("Get on objectKey is not supported.") set(value) { this.withObjectKey(value) } /** * @see software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.withExtract */ var software.amazon.awscdk.services.s3.CommonPipelineDeployActionProps.Builder.extract: Boolean get() = throw NoSuchFieldException("Get on extract is not supported.") set(value) { this.withExtract(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder */ fun bucketProps(init: software.amazon.awscdk.services.s3.BucketProps.Builder.() -> Unit): software.amazon.awscdk.services.s3.BucketProps { val builder = software.amazon.awscdk.services.s3.BucketProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withEncryptionKey */ var software.amazon.awscdk.services.s3.BucketProps.Builder.encryptionKey: software.amazon.awscdk.services.kms.IEncryptionKey get() = throw NoSuchFieldException("Get on encryptionKey is not supported.") set(value) { this.withEncryptionKey(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withBucketName */ var software.amazon.awscdk.services.s3.BucketProps.Builder.bucketName: String get() = throw NoSuchFieldException("Get on bucketName is not supported.") set(value) { this.withBucketName(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withVersioned */ var software.amazon.awscdk.services.s3.BucketProps.Builder.versioned: Boolean get() = throw NoSuchFieldException("Get on versioned is not supported.") set(value) { this.withVersioned(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withWebsiteErrorDocument */ var software.amazon.awscdk.services.s3.BucketProps.Builder.websiteErrorDocument: String get() = throw NoSuchFieldException("Get on websiteErrorDocument is not supported.") set(value) { this.withWebsiteErrorDocument(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withBlockPublicAccess */ var software.amazon.awscdk.services.s3.BucketProps.Builder.blockPublicAccess: software.amazon.awscdk.services.s3.BlockPublicAccess get() = throw NoSuchFieldException("Get on blockPublicAccess is not supported.") set(value) { this.withBlockPublicAccess(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withPublicReadAccess */ var software.amazon.awscdk.services.s3.BucketProps.Builder.publicReadAccess: Boolean get() = throw NoSuchFieldException("Get on publicReadAccess is not supported.") set(value) { this.withPublicReadAccess(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withRemovalPolicy */ var software.amazon.awscdk.services.s3.BucketProps.Builder.removalPolicy: software.amazon.awscdk.RemovalPolicy get() = throw NoSuchFieldException("Get on removalPolicy is not supported.") set(value) { this.withRemovalPolicy(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withEncryption */ var software.amazon.awscdk.services.s3.BucketProps.Builder.encryption: software.amazon.awscdk.services.s3.BucketEncryption get() = throw NoSuchFieldException("Get on encryption is not supported.") set(value) { this.withEncryption(value) } /** * @see software.amazon.awscdk.services.s3.BucketProps.Builder.withWebsiteIndexDocument */ var software.amazon.awscdk.services.s3.BucketProps.Builder.websiteIndexDocument: String get() = throw NoSuchFieldException("Get on websiteIndexDocument is not supported.") set(value) { this.withWebsiteIndexDocument(value) }
2
Kotlin
0
31
054694dc9793b7455c517af6afd666ec742594d4
87,673
aws-cdk-kotlin-dsl
MIT License
src/main/kotlin/lt/neworld/vd2svg/processor/Processor.kt
neworld
114,039,773
false
null
package lt.neworld.vd2svg.processor import com.xenomachina.argparser.SystemExitException import lt.neworld.vd2svg.converter.Converter import lt.neworld.vd2svg.logProgress import java.io.File import java.io.FileOutputStream import java.io.OutputStream import java.nio.file.PathMatcher /** * @author Andrius Semionovas * @since 2017-11-22 */ class Processor(val converter: Converter, val input: List<PathMatcher>, val output: File?) { fun process() { prepareOutput(output) File(".").walkTopDown() .filter { file -> input.any { it.matches(file.relativeTo(File(".")).toPath()) } } .filter { file -> file.readText().contains("<vector") } .forEach { file -> logProgress("Processing: $file") val outputStream = createOutputStream(file) converter.convert(file.inputStream(), outputStream) outputStream.close() } } private fun createOutputStream(input: File): OutputStream { val filename = input.nameWithoutExtension val outputDir = output ?: input.parentFile val fileOutput = File(outputDir, "$filename.svg") logProgress("Save to: $fileOutput") return FileOutputStream(fileOutput) } private fun prepareOutput(output: File?) { output ?: return if (output.isFile) { throw SystemExitException("output is not directory", 1) } if (!output.exists()) { logProgress("Creating output dir: ${output.path}") output.mkdirs() || throw SystemExitException("Failed create output dir", 1) } } }
0
Kotlin
13
98
a81d4612352a1447efaefbed01d23c4633cb527a
1,683
vd2svg
Apache License 2.0
ChallengeUI/src/main/java/com/drivequant/drivekit/challenge/ui/challengedetail/viewmodel/ChallengeDetailViewModel.kt
DriveQuantPublic
216,339,559
false
{"Kotlin": 1650199, "Java": 8753}
package com.drivequant.drivekit.challenge.ui.challengedetail.viewmodel import android.content.Context import android.graphics.Typeface.BOLD import android.text.Spannable import android.text.SpannableString import android.view.View import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.drivequant.drivekit.challenge.ChallengeDetailQueryListener import com.drivequant.drivekit.challenge.ChallengeDetailSyncStatus import com.drivequant.drivekit.challenge.DriveKitChallenge import com.drivequant.drivekit.challenge.ui.R import com.drivequant.drivekit.common.ui.DriveKitUI import com.drivequant.drivekit.common.ui.component.ranking.viewmodel.DriverProgression import com.drivequant.drivekit.common.ui.component.triplist.TripData import com.drivequant.drivekit.common.ui.extension.capitalizeFirstLetter import com.drivequant.drivekit.common.ui.extension.format import com.drivequant.drivekit.common.ui.extension.removeZeroDecimal import com.drivequant.drivekit.common.ui.extension.resSpans import com.drivequant.drivekit.common.ui.utils.* import com.drivequant.drivekit.common.ui.utils.DKDataFormatter.formatMeterDistanceInKm import com.drivequant.drivekit.core.DriveKit import com.drivequant.drivekit.core.SynchronizationType import com.drivequant.drivekit.databaseutils.entity.Challenge import com.drivequant.drivekit.databaseutils.entity.ChallengeDetail import com.drivequant.drivekit.databaseutils.entity.Trip import com.drivequant.drivekit.dbchallengeaccess.DbChallengeAccess import kotlin.math.roundToInt class ChallengeDetailViewModel(private val challengeId: String) : ViewModel() { var syncChallengeDetailError: MutableLiveData<Boolean> = MutableLiveData() var challengeDetailData: ChallengeDetail? = null var challengeDetailTrips = listOf<Trip>() lateinit var challenge: Challenge init { DbChallengeAccess.findChallengeById(challengeId)?.let { challenge = it } } fun getChallengeId() = challengeId fun getLocalChallengeDetail() : ChallengeDetail? = DbChallengeAccess.findChallengeDetailById(challengeId) fun fetchChallengeDetail(synchronizationType: SynchronizationType = SynchronizationType.DEFAULT) { if (DriveKit.isConfigured()) { DriveKitChallenge.getChallengeDetail( challengeId, object : ChallengeDetailQueryListener { override fun onResponse( challengeDetailSyncStatus: ChallengeDetailSyncStatus, challengeDetail: ChallengeDetail?, trips: List<Trip> ) { if (challengeDetailSyncStatus != ChallengeDetailSyncStatus.CHALLENGE_NOT_FOUND) { challengeDetailData = challengeDetail challengeDetailTrips = trips } val value = when (challengeDetailSyncStatus) { ChallengeDetailSyncStatus.CACHE_DATA_ONLY, ChallengeDetailSyncStatus.SUCCESS, ChallengeDetailSyncStatus.SYNC_ALREADY_IN_PROGRESS -> true ChallengeDetailSyncStatus.CHALLENGE_NOT_FOUND, ChallengeDetailSyncStatus.FAILED_TO_SYNC_CHALLENGE_DETAIL_CACHE_ONLY -> false } syncChallengeDetailError.postValue(value) } }, synchronizationType) } else { syncChallengeDetailError.postValue(false) } } fun getTripData() = when (challenge.themeCode) { in 101..104 -> TripData.ECO_DRIVING in 201..216 -> TripData.SAFETY in 301..305 -> TripData.DISTANCE in 306..309 -> TripData.DURATION 221 -> TripData.DISTRACTION 401 -> TripData.SPEEDING else -> TripData.SAFETY } fun getDriverProgress() : Int { var progress = 0 challengeDetailData?.let { if (it.challengeStats.maxScore == it.challengeStats.minScore || it.challengeStats.maxScore == it.driverStats.score) { progress = 100 } else { progress = when (challenge.themeCode) { in 101..301, in 306..309, 401 -> ((it.driverStats.score - it.challengeStats.minScore) * 100).div( it.challengeStats.maxScore - it.challengeStats.minScore ).roundToInt() in 302..305 -> { val duration = (it.driverStats.score * 3600 / 60).roundToInt() val minDuration = (it.challengeStats.minScore * 3600 / 60).roundToInt() val numeratorDuration = (duration - minDuration) * 100 val maxDuration = (it.challengeStats.maxScore * 3600 / 60).roundToInt() numeratorDuration / (maxDuration - minDuration) } else -> 0 } } } return progress.let { if (it <= 0) { 1 } else { it } } } fun getBestPerformance(context: Context): String { return challengeDetailData?.let { return when (challenge.themeCode) { in 101..221, 401 -> { val score = if (it.challengeStats.maxScore == 10.0) { it.challengeStats.maxScore.removeZeroDecimal() } else { it.challengeStats.maxScore.format(2) } "$score/10" } in 306..309 ->formatChallengeDuration(it.challengeStats.maxScore, context).convertToString() in 302..305 -> formatChallengeDistance(it.challengeStats.maxScore, context).convertToString() 301 -> "${it.challengeStats.maxScore.removeZeroDecimal()} ${context.resources.getQuantityString( R.plurals.trip_plural, it.challengeStats.numberTrip )}" else -> "-" } } ?: "" } fun getWorstPerformance(context: Context): String { return challengeDetailData?.let { return when (challenge.themeCode) { in 101..221, 401 -> "${it.challengeStats.minScore.format(2)}/10" in 306..309, in 302..305, 301 -> "${it.challengeStats.minScore.removeZeroDecimal()} ${context.resources.getQuantityString( R.plurals.trip_plural, it.challengeStats.numberTrip )}" else -> "-" } } ?: "" } fun getMainScore(context: Context): Spannable { return challengeDetailData?.let { return when (challenge.themeCode) { in 101..221, 401 -> { val score = if (it.driverStats.score == 10.0) { it.driverStats.score.removeZeroDecimal() } else { it.driverStats.score.format(2) } DKSpannable().append(score, context.resSpans { color(DriveKitUI.colors.primaryColor()) size(R.dimen.dk_text_xxxbig) typeface(BOLD) }).append(" /10", context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_big) typeface(BOLD) }).toSpannable() } in 306..309 -> { val spannable = DKSpannable() formatChallengeDuration(it.driverStats.score, context).forEach { formatType -> when (formatType) { is FormatType.VALUE -> spannable.append( formatType.value, context.resSpans { color(DriveKitUI.colors.primaryColor()) typeface(BOLD) size(R.dimen.dk_text_xxxbig) }) is FormatType.UNIT -> spannable.append( formatType.value, context.resSpans { color(DriveKitUI.colors.primaryColor()) typeface(BOLD) size(R.dimen.dk_text_xxxbig) }) is FormatType.SEPARATOR -> spannable.append(formatType.value) } } spannable.toSpannable() } in 302..305 -> { val spannable = DKSpannable() formatChallengeDistance(it.driverStats.score, context).forEach { formatType -> when (formatType) { is FormatType.VALUE -> spannable.append( formatType.value, context.resSpans { color(DriveKitUI.colors.primaryColor()) typeface(BOLD) size(R.dimen.dk_text_xxxbig) }) is FormatType.UNIT -> spannable.append( formatType.value, context.resSpans { color(DriveKitUI.colors.mainFontColor()) typeface(BOLD) size(R.dimen.dk_text_big) }) is FormatType.SEPARATOR -> spannable.append(formatType.value) } } spannable.toSpannable() } 301 -> DKSpannable().append("${it.driverStats.numberTrip} ", context.resSpans { color(DriveKitUI.colors.primaryColor()) size(R.dimen.dk_text_xxxbig) typeface(BOLD) }).append( context.resources.getQuantityString( R.plurals.trip_plural, it.driverStats.numberTrip ), context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_big) typeface(BOLD) }).toSpannable() else -> SpannableString("") } } ?: SpannableString("") } fun challengeGlobalRank(context: Context) = if (challengeDetailData?.driverStats?.rank?.toInt() == 0) { "-" } else { "${challengeDetailData?.driverStats?.rank?.toInt()}" }.let { val pseudo = challengeDetailData?.let { challengeDetail -> challengeDetail.driversRanked?.let { drivers -> val pseudo = drivers[challengeDetail.userIndex].pseudo if (drivers.isNotEmpty() && !pseudo?.trim().isNullOrBlank()) { pseudo } else { "" } } } ?: "-" DKSpannable().append(pseudo, context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_normal) typeface(BOLD) }).append(" ") .append(it, context.resSpans { color(DriveKitUI.colors.secondaryColor()) size(R.dimen.dk_text_xxbig) typeface(BOLD) }).append(" / ", context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_medium) typeface(BOLD) }).append( "${challengeDetailData?.nbDriverRanked}", context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_normal) typeface(BOLD) }).toSpannable() } fun getChallengeResultScoreTitle() = when (challenge.themeCode) { in 101..104 -> "dk_challenge_eco_driving_score" in 201..204 -> "dk_challenge_safety_score" in 205..208 -> "dk_challenge_braking_score" in 209..212 -> "dk_challenge_acceleration_score" in 213..216 -> "dk_challenge_adherence_score" 221 -> "dk_challenge_distraction_score" 301 -> "dk_challenge_nb_trip" in 306..309 -> "dk_challenge_driving_time" in 302..305 -> "dk_challenge_traveled_distance" 401 -> "dk_challenge_speeding_score" else -> "-" } private fun computeRankPercentage(): Int = challengeDetailData?.let { 100 - (it.driverStats.rank.div(it.nbDriverRanked.toDouble()) * 100).roundToInt() } ?: kotlin.run { 0 } fun isUserTheFirst() = challengeDetailData?.let { it.driverStats.rank.roundToInt() == 1 || computeRankPercentage() == 100 || it.challengeStats.maxScore == it.driverStats.score } ?: run { false } fun shouldDisplayMinScore(): Boolean = challengeDetailData?.let { it.challengeStats.maxScore == it.challengeStats.minScore } ?: run { false } fun shouldDisplayDistanceCard() = when(challenge.themeCode) { in 302..305 -> View.GONE else -> View.VISIBLE } fun shouldDisplayTripsCard() = when(challenge.themeCode) { 301 -> View.GONE else -> View.VISIBLE } fun shouldDisplayDurationCard() = when(challenge.themeCode) { in 306..309 -> View.GONE else -> View.VISIBLE } fun computeRatingStartCount(): Float { val value = computeRankPercentage() return if (isUserTheFirst() || value >= 100) { 4 } else { when (value) { in 76..100 -> 4 in 51..75 -> 3 in 26..50 -> 2 in 0..25 -> 1 else -> 0 } }.toFloat() } fun getScoreTitle(context: Context) = when(challenge.themeCode) { in 101..221 -> "dk_common_ranking_score" in 306..309 -> "dk_common_duration" in 302..305 -> "dk_common_distance" 301 -> "dk_common_trip_plural" else -> "dk_common_ranking_score" }.let { DKResource.convertToString(context, it).capitalizeFirstLetter() } fun getDriverDistance(context: Context) = challengeDetailData?.let { formatChallengeDistance(it.driverStats.distance, context).convertToString() } ?: "-" fun getCompetitorDistance(context: Context): String = challengeDetailData?.let { formatChallengeDistance(it.challengeStats.distance, context).convertToString() } ?: "-" fun getDriverDuration(context: Context) = challengeDetailData?.let { formatChallengeDuration(it.driverStats.duration, context).convertToString() } ?: "-" fun getCompetitorDuration(context: Context) = challengeDetailData?.let { formatChallengeDuration(it.challengeStats.duration, context).convertToString() } ?: "-" fun getDriverTripsNumber(context: Context): String { return challengeDetailData?.let { "${it.driverStats.numberTrip} ${context.resources.getQuantityString( R.plurals.trip_plural, it.driverStats.numberTrip )}" } ?: "-" } fun getCompetitorTripsNumber(context: Context): String { return challengeDetailData?.let { "${it.challengeStats.numberTrip} ${context.resources.getQuantityString( R.plurals.trip_plural, it.challengeStats.numberTrip )}" } ?: "-" } fun getRankingHeaderIcon(context: Context) = when (challenge.themeCode) { in 101..104 -> "dk_challenge_leaderboard_ecodriving" in 201..204, in 205..208, in 209..212, in 213..216 -> "dk_challenge_leaderboard_safety" 221 -> "dk_challenge_leaderboard_distraction" 301 -> "dk_challenge_leaderboard_trips_number" in 306..309 -> "dk_challenge_leaderboard_duration" in 302..305 -> "dk_challenge_leaderboard_distance" 401 -> "dk_challenge_leaderboard_speeding" else -> "-" }.let { DKResource.convertToDrawable(context, it) } fun getRankingList(): List<ChallengeRankingItem> { val listOfRanking = mutableListOf<ChallengeRankingItem>() challengeDetailData?.let { challengeDetail -> challengeDetail.driversRanked?.let { driversRanking -> for (driver in driversRanking) { listOfRanking.add( ChallengeRankingItem( this, driver.rank, driver.pseudo, driver.distance, driver.score ) ) } } } return listOfRanking } fun getRankingProgression(): DriverProgression? = challengeDetailData?.let { return it.driversRanked?.let { driversRanked -> val previousRank = driversRanked[it.userIndex].previousRank val rank = driversRanked[it.userIndex].rank return if (rank > 0 && previousRank > 0) { val delta = previousRank - rank return when { delta > 0 -> DriverProgression.GOING_UP delta == 0 -> null else -> DriverProgression.GOING_DOWN } } else { null } } } fun geRankingGlobalRank(context: Context) = if (challengeDetailData?.driverStats?.rank?.toInt() == 0) { "-" } else { "${challengeDetailData?.driverStats?.rank?.toInt()}" }.let { DKSpannable().append(it, context.resSpans { color(DriveKitUI.colors.secondaryColor()) size(R.dimen.dk_text_xbig) typeface(BOLD) }).append(" / ", context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_xbig) typeface(BOLD) }).append( "${challengeDetailData?.nbDriverRanked}", context.resSpans { color(DriveKitUI.colors.mainFontColor()) size(R.dimen.dk_text_xbig) typeface(BOLD) }).toSpannable() } fun formatChallengeDistance(distance:Double, context: Context): List<FormatType> = formatMeterDistanceInKm( context, distance * 1000, minDistanceToRemoveFractions = 10.0 ) fun formatChallengeDuration(duration: Double, context: Context): List<FormatType> = DKDataFormatter.formatDuration( context, DKDataFormatter.ceilDuration(duration * 3600, 600), DurationUnit.HOUR ) @Suppress("UNCHECKED_CAST") class ChallengeDetailViewModelFactory(private val challengeId: String) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { return ChallengeDetailViewModel(challengeId) as T } } }
1
Kotlin
2
9
596a46ce63257f5aad5f5b8eddd57de4e5454ef7
20,120
drivekit-ui-android
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/delegates/kt41982.kt
JetBrains
3,432,266
false
null
// ISSUE: KT-41982 import kotlin.reflect.KProperty class Delegate<R, T> { operator fun getValue(thisRef: R, property: KProperty<*>): T = null!! operator fun setValue(thisRef: R, property: KProperty<*>, value: T) {} } abstract class DelegateProvider<in Type> fun <Type : Base, Base : DelegateProvider<Base>> Type.long(initializer: (() -> Long?)? = null): Delegate<Type, Long> = null!! class Test : DelegateProvider<Any>() { var start by long { 0 } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
467
kotlin
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/delegates/kt41982.kt
JetBrains
3,432,266
false
null
// ISSUE: KT-41982 import kotlin.reflect.KProperty class Delegate<R, T> { operator fun getValue(thisRef: R, property: KProperty<*>): T = null!! operator fun setValue(thisRef: R, property: KProperty<*>, value: T) {} } abstract class DelegateProvider<in Type> fun <Type : Base, Base : DelegateProvider<Base>> Type.long(initializer: (() -> Long?)? = null): Delegate<Type, Long> = null!! class Test : DelegateProvider<Any>() { var start by long { 0 } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
467
kotlin
Apache License 2.0
sensitivewords/src/main/kotlin/top/shenluw/nsfn/sensitivewords/WordStore.kt
shenluw
190,761,968
false
null
package top.shenluw.nsfn.sensitivewords import java.io.File import java.io.FileInputStream import java.io.InputStreamReader import java.util.* import java.util.function.Consumer /** * 敏感词数据中心,可以是内存,文件,在线获取 * * @author Shenluw * created:2019/6/6 22:35 */ abstract class WordStore { companion object; private val listeners = arrayListOf<Consumer<WordStore>>() abstract fun get(): Set<String> @Synchronized fun addListener(listener: Consumer<WordStore>) { this.listeners.add(listener) } @Synchronized fun notifyListen() { this.listeners.forEach { it.accept(this) } } } fun WordStore.Companion.load(reader: InputStreamReader): SortedSet<String> { val lines = reader.readLines() return lines .filter { !it.isBlank() } .map { it.trim() } .toSortedSet() } fun WordStore.Companion.load(file: File): SortedSet<String> { return load(InputStreamReader(FileInputStream(file))) } fun WordStore.Companion.load(dir: String): SortedSet<String> { val f = File(dir) if (!f.exists() || f.isFile) { throw NsfnException("sensitive words dir is not valid") } val set = sortedSetOf<String>() val files = f.listFiles() if (files.isNullOrEmpty()) { return set } files.forEach { if (it.isFile && it.canRead()) { set.addAll(load(it)) } } return set }
0
Kotlin
0
0
2db9d00d3c59ba4434322e4002e851324b22ea3e
1,287
spring-nsfn-validation-starter
MIT License
utils/adapter/src/main/java/com/g985892345/android/utils/adapter/vp/FragmentVpAdapter.kt
985892345
677,411,791
false
{"Kotlin": 151318, "Shell": 5228}
package com.g985892345.android.utils.adapter.vp import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter /** * * 正确的 FragmentStateAdapter 用法 * ``` * // 下面这种封装是错误的 !!! * * class FragmentVpAdapter(activity: FragmentActivity, list: List<Fragment>) : FragmentStateAdapter(activity) { * override fun createFragment(position: Int): Fragment = list[position] * } * * val list = listOf(Fragment1(), Fragment2()) * FragmentVpAdapter(this, list) * ``` * * ## 原因 * createFragment() 方法并不是每次都会回调,如果经历了屏幕旋转等,Activity 恢复后创建的 Vp2 他会自动帮你还原 Fragment, * 此时就不会再回调 createFragment() * * 你传进来的 list 就创建了多余的 Fragment,如果你还直接拿来用,就会导致一系列的问题 * * 所以需要使用接口延迟创建 Fragment,正确的创建时机是在 createFragment() 回调时 * * @author 985892345 (<NAME>) * @email <EMAIL> * @date 2022/7/25 18:22 */ open class FragmentVpAdapter private constructor( fragmentManager: FragmentManager, lifecycle: Lifecycle ) : FragmentStateAdapter(fragmentManager, lifecycle) { constructor(activity: FragmentActivity) : this(activity.supportFragmentManager, activity.lifecycle) constructor(fragment: Fragment) : this(fragment.childFragmentManager, fragment.lifecycle) protected val mFragments = arrayListOf<() -> Fragment>() open fun add(fragment: () -> Fragment): FragmentVpAdapter { mFragments.add(fragment) return this } open fun add(fragment: Class<out Fragment>): FragmentVpAdapter { // 官方源码中在恢复 Fragment 时就是调用的这个反射方法,该方法应该不是很耗性能 :) mFragments.add { fragment.getDeclaredConstructor().newInstance() } return this } override fun getItemCount(): Int = mFragments.size override fun createFragment(position: Int): Fragment = mFragments[position].invoke() }
0
Kotlin
0
2
55ddf14ee78f7ea0ef19aac546f9f5f3756584b1
1,839
AndroidWheel
Apache License 2.0
json-logic/src/test/kotlin/io/github/ayushmaanbhav/jsonLogic/operations/numeric/AdditionTest.kt
ayushmaanbhav
633,602,472
false
{"Kotlin": 739672, "Shell": 1175, "Dockerfile": 1119}
package io.github.ayushmaanbhav.jsonLogic.operations.numeric import io.github.ayushmaanbhav.jsonLogic.JsonLogicEngine import io.github.ayushmaanbhav.jsonLogic.JsonLogicResult import io.github.ayushmaanbhav.jsonLogic.stdlib.TestInput import io.github.ayushmaanbhav.jsonLogic.utils.toBigDecimalDefaultContext import io.github.ayushmaanbhav.jsonLogic.valueShouldBe import io.kotest.core.spec.style.FunSpec import io.kotest.datatest.withData class AdditionTest : FunSpec({ val logicEngine = JsonLogicEngine.Builder().build() withData( nameFn = { input -> "Should evaluated ${input.expression} with given ${input.data} result in ${input.result}" }, ts = listOf( TestInput( expression = mapOf("+" to listOf(1, 2)), result = JsonLogicResult.Success(3.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf("5"), listOf("5"), listOf("5"))), result = JsonLogicResult.Success(15.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf("5", listOf("5")), listOf("5"), listOf("5"))), result = JsonLogicResult.Success(15.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf("5"), 6)), result = JsonLogicResult.Success(11.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf(listOf("5")), 6)), result = JsonLogicResult.Success(11.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf(listOf("5")), listOf(6))), result = JsonLogicResult.Success(11.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf(listOf("5"), listOf(6)))), result = JsonLogicResult.Success(5.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf("5"), listOf("6"))), result = JsonLogicResult.Success(11.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(2, 2, 2)), result = JsonLogicResult.Success(6.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(1)), result = JsonLogicResult.Success(1.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to emptyList<Double>()), result = JsonLogicResult.Success(0.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf("1", 1)), result = JsonLogicResult.Success(2.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf("1", 1.5)), result = JsonLogicResult.Success(2.5.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(12.6543534, 1.1)), result = JsonLogicResult.Success(13.7543534.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(9, .9, .09, .009, .0009, .00009)), result = JsonLogicResult.Success(9.99999.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(Int.MAX_VALUE, 3)), result = JsonLogicResult.Success((Int.MAX_VALUE + 3L).toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(Int.MIN_VALUE, -3)), result = JsonLogicResult.Success((Int.MIN_VALUE - 3L).toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf(2, 2), 2)), result = JsonLogicResult.Success(4.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(listOf(2, "a"), 2)), result = JsonLogicResult.Success(4.toBigDecimalDefaultContext()) ), TestInput( expression = mapOf("+" to listOf(2, 2, null)), result = JsonLogicResult.Failure.NullResult ), TestInput( expression = mapOf("+" to listOf("1", 1.5, "banana")), result = JsonLogicResult.Failure.NullResult ), TestInput( expression = mapOf("+" to listOf("1", 1, listOf("banana"))), result = JsonLogicResult.Failure.NullResult ), TestInput(expression = mapOf("+" to listOf("a", 2)), result = JsonLogicResult.Failure.NullResult), TestInput( expression = mapOf("+" to listOf(listOf("a", 2), 2)), result = JsonLogicResult.Failure.NullResult ), TestInput( expression = mapOf("+" to listOf(listOf(2, "a"), listOf("a", 2))), result = JsonLogicResult.Failure.NullResult ), TestInput(expression = mapOf("+" to listOf(null, 5)), result = JsonLogicResult.Failure.NullResult), TestInput(expression = mapOf("+" to listOf(5, null)), result = JsonLogicResult.Failure.NullResult), TestInput( expression = mapOf("+" to listOf(null, null)), result = JsonLogicResult.Failure.NullResult ), TestInput(expression = mapOf("+" to listOf(null)), result = JsonLogicResult.Failure.NullResult), TestInput( expression = mapOf("+" to listOf(true, false)), result = JsonLogicResult.Failure.NullResult ), TestInput(expression = mapOf("+" to listOf(true)), result = JsonLogicResult.Failure.NullResult), TestInput(expression = mapOf("+" to listOf(false)), result = JsonLogicResult.Failure.NullResult), TestInput( expression = mapOf("+" to listOf(true, null)), result = JsonLogicResult.Failure.NullResult ), TestInput( expression = mapOf("+" to listOf(false, null)), result = JsonLogicResult.Failure.NullResult ), TestInput( expression = mapOf("+" to listOf(false, true)), result = JsonLogicResult.Failure.NullResult ), TestInput(expression = mapOf("+" to listOf(0, true)), result = JsonLogicResult.Failure.NullResult), TestInput(expression = mapOf("+" to listOf(1, true)), result = JsonLogicResult.Failure.NullResult), TestInput( expression = mapOf("+" to listOf(emptyList<String>(), 2)), result = JsonLogicResult.Failure.NullResult ), ) // given ) { testInput: TestInput -> // when val evaluationResult = logicEngine.evaluate(testInput.expression, testInput.data) // then evaluationResult valueShouldBe testInput.result } })
0
Kotlin
0
0
28cfa17f9eb435d149a97d6b08f1eff7d1a54854
7,337
product-farm
Apache License 2.0
src/main/kotlin/ar/edu/unq/arqs1/MercadilloLibreBack/lib/ProductSpecificatoinsBuilder.kt
ArqSoft-Unq
406,999,376
false
{"Kotlin": 136681, "Dockerfile": 132}
package ar.edu.unq.arqs1.MercadilloLibreBack.lib import ar.edu.unq.arqs1.MercadilloLibreBack.models.Product import org.springframework.data.jpa.domain.Specification class ProductSpecificationsBuilder(private val specification: Specification<Product>? = null) { private val params: MutableList<ProductSpecification> = arrayListOf() fun with(searchCriteria: SearchCriteria): ProductSpecificationsBuilder { params.add(ProductSpecification(searchCriteria)) return this } fun build(): Specification<Product>? { if (params.isEmpty()) { return null } val startingValue: Specification<Product>? if (specification == null) { startingValue = Specification.where(params[0]) params.remove(startingValue) } else { startingValue = specification } return params.fold(startingValue) { result, param -> result.and(param) } } }
0
Kotlin
0
0
e3ded142d9194166dc1d24050e972f05e16a3daf
956
MercadilloLibreBack
MIT License
src/main/kotlin/com/tobiadeyinka/jenkinsci/plugins/builddashboard/BuildDashboard.kt
beverlyRoadGoose
189,773,283
false
null
/* * MIT License * * Copyright (c) 2019 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.tobiadeyinka.jenkinsci.plugins.builddashboard import java.io.IOException import javax.servlet.ServletException import hudson.Extension import hudson.Functions import hudson.Util.filter import hudson.model.Job import hudson.model.ListView import hudson.model.Descriptor.FormException import org.kohsuke.stapler.StaplerRequest import org.kohsuke.stapler.DataBoundConstructor import org.kohsuke.stapler.bind.JavaScriptMethod import com.tobiadeyinka.jenkinsci.plugins.builddashboard.job.MonitoredJob import com.tobiadeyinka.jenkinsci.plugins.builddashboard.build.Installation import com.tobiadeyinka.jenkinsci.plugins.builddashboard.build.entities.Build import com.tobiadeyinka.jenkinsci.plugins.builddashboard.build.BuildInfoLoader import com.tobiadeyinka.jenkinsci.plugins.builddashboard.security.csrf.RemoteRequestCrumb import com.tobiadeyinka.jenkinsci.plugins.builddashboard.serialization.SerializationUtils import net.sf.json.JSONArray import net.sf.json.JSONObject import net.sf.json.JSONSerializer.toJSON /** * Main entity definition of the plugin. * * @property[name] The name of the dashboard * @property[title] An optional title for the dashboard. Defaults to the name when not set. */ class BuildDashboard @DataBoundConstructor constructor(private val name: String?, private var title: String?) : ListView(name) { private val installation: Installation = Installation() private val build: Build = installation.build /** * Handles the dashboard settings form data on submit */ @Throws(ServletException::class, IOException::class, FormException::class) override fun submit(request: StaplerRequest) { super.submit(request) title = request.getParameter("title") } /** * @return The title of the dashboard if it exists, if not, return the name. */ fun getTitle(): String = title ?: displayName /** * @return true when then there are no jobs added to the dashboard */ fun isEmpty(): Boolean = allItems.isEmpty() /** * @return true when there are no jobs configured on the jenkins instance */ fun jenkinsInstanceHasNoJobsConfigured(): Boolean = Functions.getAllTopLevelItems(owner.itemGroup).isEmpty() /** * @return The installed version of the plugin */ fun getBuildVersion(): String = build.version /** * @return The number of jobs on the board */ fun getNumberOfJobs(): Int = getMonitoredJobs().size /** * Used by the vue webapp to retrieve JSON data of the jobs on the board. The javascript method annotation exposes * the method to javascript calls. * * @return A JSON object representation of all the jobs on the board along with their status data */ @JavaScriptMethod fun getMonitoredJobsAsJSON(): JSONArray = toJSON( SerializationUtils.getObjectWriter().writeValueAsString(getMonitoredJobs()) ) as JSONArray @JavaScriptMethod fun getInstallationAsJSON(): JSONObject = toJSON( SerializationUtils.getObjectWriter().writeValueAsString(installation) ) as JSONObject fun getRemoteRequestCrumb(): JSONObject = toJSON( SerializationUtils.getObjectWriter().writeValueAsString( RemoteRequestCrumb() ) ) as JSONObject /** * Creates [MonitoredJob] instances of all the jobs on the * board and returns a list of these instances */ private fun getMonitoredJobs(): List<MonitoredJob> { val monitoredJobs: MutableList<MonitoredJob> = mutableListOf() filter(allItems, Job::class.java).forEach { monitoredJobs.add(MonitoredJob(it)) } return monitoredJobs } /** * Integration point with jenkins */ @Extension class BuildDashboardDescriptor : hudson.model.ListView.DescriptorImpl() { /** * Sets the display name that jenkins identifies the plugin with */ override fun getDisplayName(): String = BuildInfoLoader() .buildInfo .build!! .pluginName } }
0
Kotlin
0
1
49c5ff3ca07d01c81ee6204dba8f3d60cfeff1b9
5,034
jenkins-build-dashboard
MIT License
plugins/terminal/src/org/jetbrains/plugins/terminal/exp/completion/TerminalCompletionUtil.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.terminal.exp.completion import com.intellij.icons.AllIcons import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.fileTypes.UnknownFileType import com.intellij.terminal.completion.spec.* import com.intellij.terminal.completion.spec.ShellSuggestionType.* import org.jetbrains.plugins.terminal.TerminalIcons import org.jetbrains.plugins.terminal.util.ShellType import javax.swing.Icon internal object TerminalCompletionUtil { fun getNextSuggestionsString(suggestion: ShellCompletionSuggestion): String { val result = when (suggestion) { is ShellCommandSpec -> getNextOptionsAndArgumentsString(suggestion) is ShellOptionSpec -> getNextArgumentsString(suggestion.arguments) else -> "" } return if (result.isNotEmpty()) " $result" else "" } /** Returns required options and all arguments */ private fun getNextOptionsAndArgumentsString(spec: ShellCommandSpec): String { return buildString { // Search required options only from static options. // Searching all the options requires running ShellRuntimeDataGenerator, that can be slow. for (option in spec.options.filter { it.isRequired }) { append(option.name) val arguments = getNextArgumentsString(option.arguments) if (arguments.isNotEmpty()) { append(' ') append(arguments) } append(' ') } append(getNextArgumentsString(spec.arguments)) }.trim() } private fun getNextArgumentsString(args: List<ShellArgumentSpec>): String { val argStrings = args.mapIndexed { index, arg -> arg.asSuggestionString(index) } return argStrings.joinToString(" ") } private fun ShellArgumentSpec.asSuggestionString(index: Int): String { val name = displayName ?: "arg${index + 1}" return if (isOptional) "[$name]" else "<$name>" } fun findIconForSuggestion(name: String, type: ShellSuggestionType): Icon? { return when (type) { COMMAND -> TerminalIcons.Command OPTION -> TerminalIcons.Option FOLDER -> AllIcons.Nodes.Folder FILE -> getFileIcon(name) ARGUMENT -> TerminalIcons.Other else -> null } } fun getFileIcon(fileName: String): Icon { val fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName) val fileIcon = fileType.icon ?: TerminalIcons.OtherFile return if (fileType is UnknownFileType) TerminalIcons.OtherFile else fileIcon } fun ShellType.toShellName(): ShellName { return ShellName(this.toString().lowercase()) } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
2,693
intellij-community
Apache License 2.0
app/src/main/java/alexandre/ladriere/thegeneralculturequiz/HistoryActivity.kt
AlexandreLadriere
226,545,398
false
null
package alexandre.ladriere.thegeneralculturequiz import alexandre.ladriere.thegeneralculturequiz.questions.AppDatabase import alexandre.ladriere.thegeneralculturequiz.questions.Question import alexandre.ladriere.thegeneralculturequiz.questionsreview.QuestionReviewAdapter import alexandre.ladriere.thegeneralculturequiz.utils.SpinnerItem import alexandre.ladriere.thegeneralculturequiz.utils.SpinnerItemArrayAdapter import alexandre.ladriere.thegeneralculturequiz.utils.ViewAnimation import android.content.Context import android.os.Bundle import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.Spinner import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.android.synthetic.main.activity_history.* /** * Custom activity to display all questions answered since the installation of the app */ class HistoryActivity : AppCompatActivity() { private var questionArray: ArrayList<Question> = ArrayList() private var adapter = QuestionReviewAdapter( questionArray, ::favQuestion ) private val questionDao = AppDatabase.getAppDatabase(this).getQuestionDao() private var isRotate = false private lateinit var categorySpinner: Spinner private lateinit var fab: FloatingActionButton private lateinit var fabSort: FloatingActionButton private lateinit var fabFav: FloatingActionButton private lateinit var fabCorrect: FloatingActionButton private lateinit var fabFalse: FloatingActionButton private lateinit var fabClear: FloatingActionButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_history) setQuestionList(questionDao.getAll().reversed() as ArrayList<Question>) val recyclerView = findViewById<RecyclerView>(R.id.a_history_rcv) val layoutManager = LinearLayoutManager(this) adapter = QuestionReviewAdapter( questionArray, ::favQuestion ) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter val backB = a_history_image_button_back.setOnClickListener { this.finish() } val searchView = a_history_search_view searchView.setOnQueryTextListener(object : android.widget.SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { adapter.filter(query!!) return true } override fun onQueryTextChange(newText: String?): Boolean { adapter.filter(newText!!) return true } }) searchView.setOnClickListener { val imm = baseContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY) searchView.isFocusable = true searchView.isIconified = false searchView.clearFocus() searchView.requestFocusFromTouch() } categorySpinner = a_history_category_spinner initCategorySpinner() fab = a_history_fab fabSort = a_history_fab_sort fabFav = a_history_fab_fav fabCorrect = a_history_fab_correct fabFalse = a_history_fab_false fabClear = a_history_fab_clear ViewAnimation().init(fabSort) ViewAnimation().init(fabFav) ViewAnimation().init(fabCorrect) ViewAnimation().init(fabFalse) ViewAnimation().init(fabClear) fab.setOnClickListener { view -> rotateFab(view) } fabSort.setOnClickListener { view -> categorySpinner.performClick() rotateFab(fab) } fabFav.setOnClickListener { view -> adapter.filterFav(true) rotateFab(fab) } fabCorrect.setOnClickListener { view -> adapter.filterCorrect(true) rotateFab(fab) } fabFalse.setOnClickListener { view -> adapter.filterCorrect(false) rotateFab(fab) } fabClear.setOnClickListener { view -> adapter.filter("") rotateFab(fab) searchView.setQuery("", false) } categorySpinner.onItemSelectedListener = object : OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onItemSelected( parentView: AdapterView<*>?, selectedItemView: View, position: Int, id: Long ) { val category = categorySpinner.adapter.getItem(position) as SpinnerItem if(category.code == "") { adapter.filter(category.code) } else { Toast.makeText(baseContext, category.title, Toast.LENGTH_SHORT).show() adapter.filterCategory(category.title) } } } } private fun rotateFab(view: View) { isRotate = ViewAnimation().rotateFab(view, !isRotate) if(isRotate){ showInAllFab() }else{ showOutAllFab() } } private fun showInAllFab() { ViewAnimation().showIn(fabSort) ViewAnimation().showIn(fabFav) ViewAnimation().showIn(fabCorrect) ViewAnimation().showIn(fabFalse) ViewAnimation().showIn(fabClear) } private fun showOutAllFab() { ViewAnimation().showOut(fabSort) ViewAnimation().showOut(fabFav) ViewAnimation().showOut(fabCorrect) ViewAnimation().showOut(fabFalse) ViewAnimation().showOut(fabClear) } private fun setQuestionList(questionList: ArrayList<Question>) { this.questionArray.clear() this.questionArray.addAll(questionList) adapter.notifyDataSetChanged() } private fun favQuestion(position: Int) { val tmpQuestion = this.questionArray[position] tmpQuestion.favorite = !this.questionArray[position].favorite questionDao.updateQuestionFav(tmpQuestion.question, tmpQuestion.favorite) questionArray[position] = tmpQuestion adapter.notifyItemChanged(position) } private fun initCategorySpinner() { categorySpinner.adapter = SpinnerItemArrayAdapter( this, listOf( SpinnerItem( "", "Any Category" ), SpinnerItem( "9", "General Knowledge" ), SpinnerItem( "10", "Entertainment: Books" ), SpinnerItem( "11", "Entertainment: Film" ), SpinnerItem( "12", "Entertainment: Music" ), SpinnerItem( "13", "Entertainment: Musicals & Theatres" ), SpinnerItem( "14", "Entertainment: Television" ), SpinnerItem( "15", "Entertainment: Video Games" ), SpinnerItem( "16", "Entertainment: Board Games" ), SpinnerItem( "17", "Science & Nature" ), SpinnerItem( "18", "Science: Computers" ), SpinnerItem( "19", "Science: Mathematics" ), SpinnerItem( "20", "Mythology" ), SpinnerItem( "21", "Sports" ), SpinnerItem( "22", "Geography" ), SpinnerItem( "23", "History" ), SpinnerItem( "24", "Politics" ), SpinnerItem( "25", "Art" ), SpinnerItem( "26", "Celebrities" ), SpinnerItem( "27", "Animals" ), SpinnerItem( "28", "Vehicles" ), SpinnerItem( "29", "Entertainment: Comics" ), SpinnerItem( "30", "Science: Gadgets" ), SpinnerItem( "31", "Entertainment: Japanese Anime & Manga" ), SpinnerItem( "32", "Entertainment: Cartoon & Animations" ) ) ) } private fun hideSystemUI() { // Enables regular immersive mode. // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE. // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) } private fun showSystemUI() { window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (hasFocus) hideSystemUI() } }
0
Kotlin
0
1
966b008ae95090224d70dae8020b8928ec22383d
11,466
Android_The-general-culture-quiz
MIT License
src/test/kotlin/org/rust/lang/core/psi/RsCodeFragmentCompletionTestBase.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi import com.intellij.openapi.project.Project import com.intellij.psi.util.parentOfType import com.intellij.testFramework.fixtures.CodeInsightTestFixture import org.intellij.lang.annotations.Language import org.rust.InlineFile import org.rust.RsTestBase import org.rust.lang.core.completion.RsCompletionTestFixtureBase import org.rust.lang.core.psi.RsCodeFragmentCompletionTestFixture.Data import org.rust.lang.core.psi.ext.RsElement abstract class RsCodeFragmentCompletionTestBase( private val fragmentConstructor: (Project, String, RsElement) -> RsCodeFragment ) : RsTestBase() { private lateinit var completionFixture: RsCodeFragmentCompletionTestFixture override fun setUp() { super.setUp() completionFixture = RsCodeFragmentCompletionTestFixture(myFixture, fragmentConstructor) completionFixture.setUp() } override fun tearDown() { completionFixture.tearDown() super.tearDown() } protected fun checkContainsCompletion(@Language("Rust") context: String, fragment: String, variant: String) { completionFixture.checkContainsCompletion(Data(context, fragment), listOf(variant)) } protected fun checkNotContainsCompletion(@Language("Rust") context: String, fragment: String, variant: String) { completionFixture.checkNotContainsCompletion(Data(context, fragment), setOf(variant)) } } private class RsCodeFragmentCompletionTestFixture( fixture: CodeInsightTestFixture, private val fragmentConstructor: (Project, String, RsElement) -> RsCodeFragment ) : RsCompletionTestFixtureBase<Data>(fixture) { override fun prepare(code: Data) { val (context, fragment) = code InlineFile(myFixture, context, "main.rs").withCaret() check("<caret>" in fragment) { "Please, add `<caret>` marker to\n$fragment" } val contextElement = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<RsElement>()!! val codeFragment = fragmentConstructor(project, fragment, contextElement) myFixture.configureFromExistingVirtualFile(codeFragment.virtualFile) } data class Data(val context: String, val fragment: String) }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
2,334
intellij-rust
MIT License
app/src/main/java/com/rokoblak/chatbackup/ui/commonui/ChatDisplay.kt
oblakr24
598,672,859
false
null
package com.rokoblak.chatbackup.commonui import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.rokoblak.chatbackup.ui.theme.ChatBackupTheme import com.rokoblak.chatbackup.ui.theme.LocalTypography data class ChatDisplayData( val id: String, val content: String, val date: String, val alignedLeft: Boolean, val avatar: AvatarData?, ) @Composable fun ChatDisplay(modifier: Modifier = Modifier, data: ChatDisplayData) { val alignment = if (data.alignedLeft) Alignment.Start else Alignment.End val backgroundColor = if (data.alignedLeft) Color.LightGray else Color.Blue val textColor = if (data.alignedLeft) Color.Black else Color.White Column( modifier = modifier.fillMaxWidth(), horizontalAlignment = alignment ) { Row(modifier = Modifier.wrapContentWidth()) { if (data.avatar != null) { AvatarBadge( data = data.avatar, modifier = Modifier .padding(top = 4.dp) .size(28.dp), textStyle = LocalTypography.current.subheadSemiBold ) } Column( modifier = Modifier .wrapContentWidth() .padding(4.dp) ) { Text( modifier = Modifier .background(backgroundColor, RoundedCornerShape(12.dp)) .align(alignment) .widthIn(min = 20.dp, max = 220.dp) .padding(8.dp), text = data.content, style = LocalTypography.current.bodyRegular, color = textColor, ) Text( modifier = Modifier.padding(2.dp), text = data.date, style = LocalTypography.current.subheadRegular ) } } } } @Preview @Composable fun ChatDisplayOtherPreview() { ChatBackupTheme { ChatDisplay( modifier = Modifier, data = ChatDisplayData( id = "id1", content = "Content Looong Content Looooong Looong Looong", date = "Sun 14th Dec 2022, 13:44:55", alignedLeft = true, avatar = AvatarData.Initials("AB", Color.Blue), ) ) } } @Preview @Composable fun ChatDisplayMinePreview() { ChatBackupTheme { ChatDisplay( modifier = Modifier, data = ChatDisplayData( id = "id1", content = "Content", date = "Sun 14th Dec 2022, 13:44:55", alignedLeft = false, avatar = null, ) ) } }
0
Kotlin
0
1
c35b0c214aa58d11497037bb66f44ed42f2e8de4
3,215
chat-backup-app
Apache License 2.0
shared/src/iosMain/kotlin/main.ios.kt
yoshimuratakuma0
642,908,865
false
null
import androidx.compose.ui.window.ComposeUIViewController import domain.usecases.GetSampleTextUseCase actual fun getPlatformName(): String = "iOS" fun MainViewController(getSampleTextUseCase: GetSampleTextUseCase) = ComposeUIViewController { App(getSampleTextUseCase) }
0
Kotlin
0
0
f4df4360a90b6cf3bfecce520729f85e566dcd73
276
compose-multiplatform-di-template
Apache License 2.0
client/android/app/src/main/java/org/devtcg/robotrc/robotview/ui/RobotViewFragment.kt
jasta
462,495,183
false
null
package org.devtcg.robotrc.robotview.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class RobotViewFragment: Fragment() { private lateinit var layoutAgent: RobotLayoutAgent override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { layoutAgent = RobotLayoutAgent(requireActivity()) return layoutAgent.onCreateView(inflater, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { layoutAgent.onViewCreated() } override fun onPause() { super.onPause() layoutAgent.onPause() } override fun onResume() { super.onResume() layoutAgent.onResume() } }
0
Kotlin
0
0
8f2a755e1ff6b745f934a56ccfaea12b8a91c418
804
ev3-remote-control
MIT License
compiler/testData/codegen/box/coroutines/featureIntersection/callableReference/bound/emptyLHS.kt
JetBrains
3,432,266
false
null
// WITH_STDLIB // WITH_COROUTINES import helpers.* import kotlin.coroutines.* var result = "" class A { suspend fun memberFunction() { result += "A.mf," } suspend fun aMemberFunction() { result += "A.amf," } suspend fun test(): String { (::memberFunction)() (::aExtensionFunction)() return result } inner class B { suspend fun memberFunction() { result += "B.mf," } suspend fun test(): String { (::aMemberFunction)() (::aExtensionFunction)() (::memberFunction)() (::bExtensionFunction)() return result } } } suspend fun A.aExtensionFunction() { result += "A.ef," } suspend fun A.B.bExtensionFunction() { result += "B.ef," } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var a = "FAIL 1" builder { a = A().test() } if (a != "A.mf,A.ef,") return "Fail $a" result = "" var b = "FAIL 2" builder { b = A().B().test() } if (b != "A.amf,A.ef,B.mf,B.ef,") return "Fail $b" result = "" builder { with(A()) { (::memberFunction)() (::aExtensionFunction)() } } if (result != "A.mf,A.ef,") return "Fail $result" result = "" builder { with(A()) { with(B()) { (::aMemberFunction)() (::aExtensionFunction)() (::memberFunction)() (::bExtensionFunction)() } } } if (result != "A.amf,A.ef,B.mf,B.ef,") return "Fail $result" return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,709
kotlin
Apache License 2.0
mylibrary/src/main/java/com/esp/library/utilities/data/lookup/LookupInfoListDAO.kt
ahsan1122
255,336,932
false
null
package utilities.data.lookup class ESP_LIB_LookupInfoListDAO { var id: Int = 0 var titleCustomFieldId: Int = 0 var fieldsCount: Int = 0 lateinit var name: String lateinit var createdOn: String var isVisible: Boolean = false var isMain: Boolean = false var isShowToApplicant: Boolean = false var isVariable: Boolean = false }
1
null
1
1
6e962b8507eb55d5bfb646d230517ae93be14aa7
364
ISP_Library
MIT License
app/src/androidTest/java/com/atiurin/espressopageobjectexample/pages/ChatPage.kt
yurykalash
284,529,836
true
{"Kotlin": 104494, "Java": 13380}
package com.atiurin.espressopageobjectexample.pages import android.view.View import androidx.core.view.size import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import com.atiurin.espressopageobjectexample.R import com.atiurin.espressopageobjectexample.framework.* import com.atiurin.espressopageobject.extensions.click import com.atiurin.espressopageobject.extensions.hasText import com.atiurin.espressopageobject.extensions.isDisplayed import com.atiurin.espressopageobject.extensions.typeText import com.atiurin.espressopageobject.recyclerview.RecyclerViewItem import com.atiurin.espressopageobject.recyclerview.withRecyclerView import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf import org.junit.Assert class ChatPage : Page { override fun assertPageDisplayed() = apply { step("Assert friends list page displayed") { messagesList.isDisplayed() } } val messagesList = withId(R.id.messages_list) val clearHistoryBtn = withText("Clear history") val inputMessageText = withId(R.id.message_input_text) val sendMessageBtn = withId(R.id.send_button) fun getListItem(text: String): ChatRecyclerItem { return ChatRecyclerItem( messagesList, ViewMatchers.hasDescendant( allOf( withId(R.id.message_text), withText(text) ) ) ) } private fun getListItemAtPosition(position: Int): ChatRecyclerItem { return ChatRecyclerItem(messagesList, position) } fun getTitle(title: String): Matcher<View> { return allOf(withId(R.id.toolbar_title), withText(title)) } class ChatRecyclerItem : RecyclerViewItem { constructor(list: Matcher<View>, item: Matcher<View>) : super(list, item) constructor(list: Matcher<View>, position: Int) : super(list, position) val text = getChildMatcher(withId(R.id.message_text)) } fun sendMessage(text: String) = apply { step("Send message with text '$text") { inputMessageText.typeText(text) sendMessageBtn.click() this.getListItem(text).text .isDisplayed() .hasText(text) } } fun assertMessageTextAtPosition(position: Int, text: String) = apply { this.getListItemAtPosition(position).text.isDisplayed().hasText(text) } fun clearHistory() = apply { step("Clear chat history") { openOptionsMenu() clearHistoryBtn.click() Assert.assertEquals(0, withRecyclerView(messagesList).getSize()) } } fun assertMessageDisplayed(text: String) { getListItem(text).text .isDisplayed() .hasText(text) } }
0
null
0
0
631c66758a431ef2c1d355cc8cf3b87ab85e140c
2,895
espresso-page-object
Apache License 2.0
app/src/main/java/com/reift/movieapp/data/MovieRepository.kt
ReihanFatilla
523,763,069
false
{"Kotlin": 65738}
package com.reift.movieapp.data import android.content.Context import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import com.reift.movieapp.data.remote.ApiClient import com.reift.movieapp.data.response.CreditResponse import com.reift.movieapp.data.response.DetailResponse import com.reift.movieapp.data.response.ReviewResponse import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.schedulers.Schedulers class MovieRepository(context: Context) { private val ai: ApplicationInfo = context.packageManager .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) private val apiKey = "<KEY>" // ai.metaData["apiKey"].toString() private val apiService = ApiClient.getApiService() fun getMovieTVList( responseHandler: (MovieResponse) -> Unit, errorHandler: (Throwable) -> Unit, media: String, type: String, region: String, page: String ){ apiService.getMovieTVList(media, type, apiKey, region, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun getSimilarList( responseHandler: (MovieResponse) -> Unit, errorHandler: (Throwable) -> Unit, media: String, id: String, region: String, page: String ){ apiService.getSimilarList(media, id, apiKey, region, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun getReviewList( responseHandler: (ReviewResponse) -> Unit, errorHandler: (Throwable) -> Unit, media: String, id: String, page: String, ){ apiService.getReviewList(media, id, apiKey, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun getCreditList( responseHandler: (CreditResponse) -> Unit, errorHandler: (Throwable) -> Unit, media: String, id: String, region: String, ){ apiService.getCreditList(media, id, apiKey, region) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun getTrendingList( responseHandler: (MovieResponse) -> Unit, errorHandler: (Throwable) -> Unit, media: String, region: String, page: String ){ apiService.getTrendingList(media, apiKey, region, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun getDetail( responseHandler: (DetailResponse) -> Unit, errorHandler: (Throwable) -> Unit, media: String, id: String ){ apiService.getDetail(media, id, apiKey) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun getMovieRecommendationsById( responseHandler: (MovieResponse) -> Unit, errorHandler: (Throwable) -> Unit, id: String, region: String, page: String ){ apiService.getMovieRecommendationsById(id, apiKey, region, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) } ) } fun getMovieSortBY( responseHandler: (MovieResponse) -> Unit, errorHandler: (Throwable) -> Unit, sortBy: String, region: String, page: String ){ apiService.getMovieSortBy(apiKey, sortBy, region, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } fun searchMovieBy( responseHandler: (MovieResponse) -> Unit, errorHandler: (Throwable) -> Unit, searchBy: String, query: String, region: String, page: String ){ apiService.searchMovieBy(searchBy, apiKey, query, region, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ responseHandler(it) },{ errorHandler(it) }) } }
0
Kotlin
2
4
fad24a7548e0ba5407e4a3a5c4bea8fa4b171d57
5,213
Movo
MIT License
src/main/kotlin/jetbrains/buildServer/server/querylang/ast/abstractFilters.kt
JetBrains
285,547,183
false
{"Kotlin": 340073, "ANTLR": 10846, "Java": 10814}
package jetbrains.buildServer.server.querylang.ast import jetbrains.buildServer.server.querylang.ast.wrappers.AllElementsVisitor import jetbrains.buildServer.server.querylang.ast.wrappers.AnyElementValidator import jetbrains.buildServer.server.querylang.ast.wrappers.ElementValidator import jetbrains.buildServer.server.querylang.ast.wrappers.MAllContainer abstract class MultipleObjectsConditionFilter<Obj, NestedObj> : MAllContainer, ConditionFilter<Obj, NestedObj>() { override var searchAll: ElementValidator<*> = AnyElementValidator<NestedObj>() override fun buildVisitorFrom(subVisitor: RealObjectFilter<NestedObj>): RealObjectFilter<Obj> { val oldElementValidator = this.searchAll this.searchAll = AllElementsVisitor<NestedObj>() return buildFrom(subVisitor).also { this.searchAll = oldElementValidator } } } abstract class SingleObjectConditionFilter<Obj, NestedObj> : ConditionFilter<Obj, NestedObj>() { override fun buildVisitorFrom(subVisitor: RealObjectFilter<NestedObj>) = buildFrom(subVisitor) } abstract class StringFilter: Filter<String> { var isCaseSensitive = false }
4
Kotlin
5
3
5f83223c23bc282b2cec4a04c736de91716e72be
1,133
teamcity-search-ql
Apache License 2.0
app/src/main/java/com/vietnam/corona/api/globalData/GlobalDataHolder.kt
18HCB
277,356,246
false
{"Java": 125778, "Kotlin": 1446}
package com.vietnam.corona.api.globalData import retrofit2.Call import retrofit2.http.GET interface GlobalDataHolder { @GET("/api") fun getGlobalData(): Call<GlobalData> }
1
Java
1
1
8bc8156840e40791be23c8a9cc11082f1538c13b
183
corona
MIT License
src/main/kotlin/com/exactpro/th2/codec/EncodeProcessor.kt
jean-michel-perli-sonsin
315,864,047
true
{"Kotlin": 57695, "Dockerfile": 290}
/* * Copyright 2020-2020 Exactpro (Exactpro Systems Limited) * * 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.exactpro.th2.codec import com.exactpro.sf.externalapi.codec.IExternalCodecFactory import com.exactpro.sf.externalapi.codec.IExternalCodecSettings import com.exactpro.th2.codec.util.toCodecContext import com.exactpro.th2.common.grpc.Message import com.exactpro.th2.common.grpc.MessageBatch import com.exactpro.th2.common.grpc.RawMessage import com.exactpro.th2.common.grpc.RawMessageBatch import com.exactpro.th2.common.grpc.RawMessageMetadata import com.exactpro.th2.sailfish.utils.ProtoToIMessageConverter import com.google.protobuf.ByteString import com.google.protobuf.util.JsonFormat import mu.KotlinLogging class EncodeProcessor( codecFactory: IExternalCodecFactory, codecSettings: IExternalCodecSettings, private val converter: ProtoToIMessageConverter ) : AbstractCodecProcessor<MessageBatch, RawMessageBatch>(codecFactory, codecSettings) { private val logger = KotlinLogging.logger { } override fun process(source: MessageBatch): RawMessageBatch { val rawMessageBatchBuilder = RawMessageBatch.newBuilder() for (protoMessage in source.messagesList) { val convertedSourceMessage = converter.fromProtoMessage(protoMessage, true).also { logger.debug { "converted source message '${it.name}': $it" } } val encodedMessageData = getCodec().encode(convertedSourceMessage, protoMessage.toCodecContext()) rawMessageBatchBuilder.addMessages(RawMessage.newBuilder() .setBody(ByteString.copyFrom(encodedMessageData)) .setMetadata(toRawMessageMetadataBuilder(protoMessage).also { logger.debug { val jsonRawMessage = JsonFormat.printer().omittingInsignificantWhitespace().print(it) "message metadata: $jsonRawMessage" } }) ) } return rawMessageBatchBuilder.build() } private fun toRawMessageMetadataBuilder(sourceMessage: Message): RawMessageMetadata { return RawMessageMetadata.newBuilder() .setId(sourceMessage.metadata.id) .setTimestamp(sourceMessage.metadata.timestamp) .putAllProperties(sourceMessage.metadata.propertiesMap) .build() } }
0
null
0
0
00c253f0ae9848650b4684e8a84452b80d1ad227
2,920
th2-codec
Apache License 2.0
app/src/main/java/com/ithebk/tasks/ui/addtask/AddTaskBottomDialogFragment.kt
ithebk
197,948,569
false
null
package com.ithebk.tasks.ui.addtask import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.cardview.widget.CardView import androidx.core.os.bundleOf import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.ithebk.tasks.R import com.ithebk.tasks.utils.Utils import com.ithebk.tasks.callbacks.ActionCallback import com.ithebk.tasks.db.Task import com.ithebk.tasks.models.EXTRA_ACTION import com.ithebk.tasks.models.TaskAction enum class ACTION { NEW, UPDATE, DELETE } class AddTaskBottomDialogFragment : BottomSheetDialogFragment() { private lateinit var mListener: AddTaskBottomSheetListener private lateinit var editWordView: EditText private lateinit var btDeleteTask: CardView private lateinit var textAddOrUpdate: TextView private var action: ACTION = ACTION.NEW private var currentTask: Task? = null private lateinit var recyclerAction: RecyclerView private lateinit var taskActionAdapter: TaskActionAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val rootView = inflater.inflate(R.layout.add_task_bottom_layout_sheet, container, true) editWordView = rootView.findViewById(R.id.edit_word) btDeleteTask = rootView.findViewById(R.id.bt_delete_task) textAddOrUpdate = rootView.findViewById(R.id.text_view_add_or_update) recyclerAction = rootView.findViewById(R.id.recycler_view_action) rootView.findViewById<CardView>(R.id.bt_add_task).setOnClickListener { dismiss() } if ((arguments?.get(TASK)) != null) { currentTask = (arguments?.get(TASK)) as Task; if(currentTask!=null) { textAddOrUpdate.text = getString(R.string.update) action = ACTION.UPDATE editWordView.setText(currentTask!!.info) btDeleteTask.visibility = View.VISIBLE } } btDeleteTask.setOnClickListener { action = ACTION.DELETE dismiss() } setActionAdapter() return rootView } private fun setActionAdapter() { var taskActions = mutableListOf<TaskAction>() for (i in 0..3) { taskActions.add(TaskAction( EXTRA_ACTION.NOTIFICATION, "ADD Notification", R.drawable.ic_add_notification, false )) } taskActionAdapter = TaskActionAdapter(context!!, Utils.ACTIONS, object : ActionCallback { override fun onItemClick(position: Int, taskAction: TaskAction) { } }) recyclerAction.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) adapter = taskActionAdapter itemAnimator = DefaultItemAnimator() } } companion object { private const val TASK = "task" const val TAG = "MAIN_BOTTOM_DIALOG_FRAGMENT" fun newInstance(task: Task? = null) = AddTaskBottomDialogFragment() .apply { arguments = bundleOf( TASK to task ) } } override fun onDismiss(dialog: DialogInterface) { mListener.onSave( editWordView.text.toString(), action, currentTask ) super.onDismiss(dialog) } override fun onAttach(context: Context) { super.onAttach(context) if (context is AddTaskBottomSheetListener) { mListener = context } else { throw RuntimeException( "$context must implement ItemClickListener" ) } } interface AddTaskBottomSheetListener { fun onSave(name: String, action: ACTION, prevTask: Task?) } }
0
Kotlin
0
1
343493a889e61afa06e44b9ce858a5e447075269
4,298
task_app
Apache License 2.0
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt
react-native-tvos
177,633,560
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<77fc4d6577fc0e2e9a0500cc762bba77>> */ /** * IMPORTANT: Do NOT modify this file directly. * * To change the definition of the flags, edit * packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js. * * To regenerate this code, run the following script from the repo root: * yarn featureflags-update */ package com.facebook.react.internal.featureflags class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAccessor { private var currentProvider: ReactNativeFeatureFlagsProvider = ReactNativeFeatureFlagsDefaults() private val accessedFeatureFlags = mutableSetOf<String>() private var commonTestFlagCache: Boolean? = null private var useModernRuntimeSchedulerCache: Boolean? = null private var enableMicrotasksCache: Boolean? = null private var batchRenderingUpdatesInEventLoopCache: Boolean? = null private var enableSpannableBuildingUnificationCache: Boolean? = null private var enableCustomDrawOrderFabricCache: Boolean? = null private var enableFixForClippedSubviewsCrashCache: Boolean? = null override fun commonTestFlag(): Boolean { var cached = commonTestFlagCache if (cached == null) { cached = currentProvider.commonTestFlag() accessedFeatureFlags.add("commonTestFlag") commonTestFlagCache = cached } return cached } override fun useModernRuntimeScheduler(): Boolean { var cached = useModernRuntimeSchedulerCache if (cached == null) { cached = currentProvider.useModernRuntimeScheduler() accessedFeatureFlags.add("useModernRuntimeScheduler") useModernRuntimeSchedulerCache = cached } return cached } override fun enableMicrotasks(): Boolean { var cached = enableMicrotasksCache if (cached == null) { cached = currentProvider.enableMicrotasks() accessedFeatureFlags.add("enableMicrotasks") enableMicrotasksCache = cached } return cached } override fun batchRenderingUpdatesInEventLoop(): Boolean { var cached = batchRenderingUpdatesInEventLoopCache if (cached == null) { cached = currentProvider.batchRenderingUpdatesInEventLoop() accessedFeatureFlags.add("batchRenderingUpdatesInEventLoop") batchRenderingUpdatesInEventLoopCache = cached } return cached } override fun enableSpannableBuildingUnification(): Boolean { var cached = enableSpannableBuildingUnificationCache if (cached == null) { cached = currentProvider.enableSpannableBuildingUnification() accessedFeatureFlags.add("enableSpannableBuildingUnification") enableSpannableBuildingUnificationCache = cached } return cached } override fun enableCustomDrawOrderFabric(): Boolean { var cached = enableCustomDrawOrderFabricCache if (cached == null) { cached = currentProvider.enableCustomDrawOrderFabric() accessedFeatureFlags.add("enableCustomDrawOrderFabric") enableCustomDrawOrderFabricCache = cached } return cached } override fun enableFixForClippedSubviewsCrash(): Boolean { var cached = enableFixForClippedSubviewsCrashCache if (cached == null) { cached = currentProvider.enableFixForClippedSubviewsCrash() accessedFeatureFlags.add("enableFixForClippedSubviewsCrash") enableFixForClippedSubviewsCrashCache = cached } return cached } override fun override(provider: ReactNativeFeatureFlagsProvider) { if (accessedFeatureFlags.isNotEmpty()) { val accessedFeatureFlagsStr = accessedFeatureFlags.joinToString(separator = ", ") { it } throw IllegalStateException( "Feature flags were accessed before being overridden: $accessedFeatureFlagsStr") } currentProvider = provider } override fun dangerouslyReset() { // We don't need to do anything here because `ReactNativeFeatureFlags` will // just create a new instance of this class. } }
18
null
141
897
f8904c210b1be562d3e141b083c7c24b6fc85750
4,110
react-native-tvos
MIT License
analysis/analysis-api-platform-interface/src/org/jetbrains/kotlin/analysis/api/platform/declarations/KotlinDirectInheritorsProvider.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.platform.declarations import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.analysis.api.platform.KotlinPlatformComponent import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject public interface KotlinDirectInheritorsProvider : KotlinPlatformComponent { /** * Returns all direct *Kotlin* inheritors of [ktClass] that can be found in the given [scope]. * * The implementor of [getDirectKotlinInheritors] is allowed to lazy-resolve symbols up to the `SUPER_TYPES` phase. This is required to * check subtyping for potential inheritors. Hence, if [getDirectKotlinInheritors] is invoked during lazy resolution, it requires a * phase of `SEALED_CLASS_INHERITORS` or later. * * @param includeLocalInheritors If `false`, only non-local inheritors will be searched and returned. */ public fun getDirectKotlinInheritors( ktClass: KtClass, scope: GlobalSearchScope, includeLocalInheritors: Boolean = true, ): Iterable<KtClassOrObject> public companion object { public fun getInstance(project: Project): KotlinDirectInheritorsProvider = project.service() } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,540
kotlin
Apache License 2.0
yetutil/src/main/java/yet/ui/widget/TabBarItemView.kt
yangentao
64,828,822
false
null
package yet.ui.widget import android.content.Context import android.graphics.Color import android.graphics.drawable.Drawable import android.widget.RelativeLayout import android.widget.TextView import yet.ext.RGB import yet.theme.Colors import yet.ui.ext.* import yet.ui.res.D import yet.ui.res.Res import yet.ui.res.sized import yet.ui.res.tinted import yet.ui.viewcreator.textView /** * Created by <EMAIL> on 2018-04-18. */ open class TabBarItemView(context: Context) : RelativeLayout(context) { val textView: TextView val indicateView: TextView var autoTintDrawable = true init { genId() backColorWhite() textView = this.textView(RParam.CenterInParent.Wrap) { compoundDrawablePadding = 0 textSizeD() gravityCenter() padding(1, 4, 1, 1) textColor(D.listColor(Colors.TextColorMajor, Colors.Theme)) } indicateView = textView(RParam.ParentTop.ParentRight.margins(0, 5, 5, 0)) { textColor(Color.WHITE) textSizeSp(10) gravityCenter() backDrawable { fillColor = RGB(255, 80, 80) cornerPx = dp(7) } padding(2, 0, 2, 0) minimumWidth = dp(14) gone() } } //0: 不显示; <0 只显示红点; >0显示红点和数字 fun setIndicate(n: Int) { if (n == 0) { indicateView.gone() return } if (n > 0) { indicateView.text = "$n" indicateView.visiable() return } indicateView.text = "" indicateView.visiable() } fun setText(text: String) { textView.textS = text } fun setIcon(res: Int) { if (res != 0) { setIcon(Res.drawable(res)) } } fun setIcon(d: Drawable) { val dd = if (autoTintDrawable) { d.tinted(Colors.Unselected, Colors.Theme) } else { d.mutate() } textView.topImage(dd.sized(24), 0) } val text: String get() = textView.textS }
0
Kotlin
0
0
e5f048899e88d34e0fbc331b76cdd5d897495438
1,726
klib
Apache License 2.0
yabapi-core/src/commonMain/kotlin/moe/sdl/yabapi/connect/LiveMessageConnection.kt
SDLMoe
437,756,989
false
null
package moe.sdl.yabapi.connect import io.ktor.client.HttpClient import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession import io.ktor.client.plugins.websocket.wss import io.ktor.http.HttpMethod import io.ktor.utils.io.core.buildPacket import io.ktor.utils.io.core.readUInt import io.ktor.utils.io.core.toByteArray import io.ktor.utils.io.core.writeFully import io.ktor.websocket.Frame import io.ktor.websocket.FrameType.BINARY import kotlinx.atomicfu.atomic import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.onClosed import kotlinx.coroutines.channels.onFailure import kotlinx.coroutines.channels.onSuccess import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import moe.sdl.yabapi.Platform import moe.sdl.yabapi.data.live.CertificatePacketBody import moe.sdl.yabapi.data.live.CertificatePacketResponse import moe.sdl.yabapi.data.live.LiveDanmakuHost import moe.sdl.yabapi.data.live.commands.LiveCommand import moe.sdl.yabapi.data.live.commands.RawLiveCommand import moe.sdl.yabapi.packet.LiveMsgPacket import moe.sdl.yabapi.packet.LiveMsgPacketProtocol.SPECIAL_NO_COMPRESSION import moe.sdl.yabapi.packet.LiveMsgPacketType.CERTIFICATE import moe.sdl.yabapi.packet.LiveMsgPacketType.CERTIFICATE_RESPONSE import moe.sdl.yabapi.packet.LiveMsgPacketType.COMMAND import moe.sdl.yabapi.packet.LiveMsgPacketType.HEARTBEAT import moe.sdl.yabapi.packet.LiveMsgPacketType.HEARTBEAT_RESPONSE import moe.sdl.yabapi.util.Logger import moe.sdl.yabapi.util.string.findJson import kotlin.coroutines.CoroutineContext import kotlin.native.concurrent.SharedImmutable @SharedImmutable private val logger by lazy { Logger("LiveMessageConnection") } private typealias Wss = DefaultClientWebSocketSession internal class LiveMessageConnection( private val loginUserMid: Long, private val realRoomId: Long, private val token: String, private val host: LiveDanmakuHost, private val client: HttpClient, private val jsonParser: Json, private val context: CoroutineContext = Platform.ioDispatcher + CoroutineName("yabapi-live-msg-connect"), config: LiveDanmakuConnectConfig.() -> Unit = {}, ) { private val configInstance = LiveDanmakuConnectConfig() init { configInstance.config() } private val sequence = atomic(0L) suspend fun start() = coroutineScope { launch(context) { requireNotNull(host.host) requireNotNull(host.wssPort) client.wss(HttpMethod.Get, host = host.host, host.wssPort, "/sub") { val isSuccess = sendCertificatePacket() if (isSuccess) { launch { doHeartbeatJob() } handleIncoming() } } } } private suspend inline fun Wss.sendLiveDanmakuPacket( packet: LiveMsgPacket, ): Boolean { var isSuccess = false outgoing.trySend(Frame.byType(true, BINARY, packet.encode(), rsv1 = false, rsv2 = false, rsv3 = false)).also { logger.debug { "Try to send ${packet.header.type} packet." } }.onFailure { if (it is CancellationException) throw it logger.debug { "Failed to send ${packet.header.type} packet: $packet" } logger.verbose(it) { "stacktrace:" } }.onSuccess { logger.debug { "Sent ${packet.header.type} packet: $packet" } sequence.getAndIncrement() logger.verbose { "Now Sequence: $sequence" } isSuccess = true }.onClosed { if (it is CancellationException) throw it logger.debug { "Outgoing Channel closed" } cancel("Remote closed", it) } return isSuccess } private suspend inline fun Wss.handleIncoming() { incoming.consumeAsFlow().collect { frame -> when (frame) { is Frame.Binary -> { try { LiveMsgPacket.decode(frame.data).also { packet -> logger.debug { "Decoded Packet Head: ${packet.header}" } handleBinaryPacket(packet) } } catch (e: NotImplementedError) { logger.warn(e) { "Not Implemented Compression" } } } is Frame.Text -> logger.debug { "Received Text: ${frame.data.contentToString()}" } is Frame.Close -> cancel("Remote closed.") else -> { // DO NOTHING } } } } private suspend inline fun Wss.handleBinaryPacket( packet: LiveMsgPacket, ) = when (packet.header.type) { HEARTBEAT_RESPONSE -> { val popular = buildPacket { writeFully(packet.body) }.readUInt() logger.debug { "Decoded popular value: $popular" } configInstance.onHeartbeatResponse( this, channelFlow { this.send(popular) } ) } CERTIFICATE_RESPONSE -> { val data: CertificatePacketResponse = jsonParser.decodeFromString(packet.body.decodeToString()) logger.debug { "Decoded Certificate Response: $data" } configInstance.onCertificateResponse( this, channelFlow { this.send(data) } ) } COMMAND -> { val flow = packet.body.decodeToString().also { logger.verbose { "Raw Received body decoded to string: $it" } }.findJson().asFlow() flow.map { parsed -> // String -> RawLiveCommand logger.verbose { "Decoded weired json string: $parsed" } RawLiveCommand(jsonParser.decodeFromString(parsed)) }.collect { raw -> // Send Raw to downstream logger.debug { "Decoded RawLiveCommand $raw" } configInstance.onRawCommandResponse(this, channelFlow { send(raw) }) val data = try { raw.data } catch (e: SerializationException) { logger.warn(e) { "Unexpected Serialization Exception, raw decoded: $raw" } null } logger.debug { "Decoded LiveCommand $data" } configInstance.onCommandResponse( this, channelFlow { data?.let { this.send(it) } } ) } } else -> error("Decoded Unexpected Incoming Packet: $packet") } private suspend inline fun Wss.doHeartbeatJob() { while (isActive) { sendHeartbeatPacket() delay(30_000) } } private suspend inline fun Wss.sendCertificatePacket(): Boolean { val body = jsonParser.encodeToString( CertificatePacketBody( mid = loginUserMid, roomId = realRoomId, key = token ) ).toByteArray() return sendLiveDanmakuPacket( LiveMsgPacket( protocol = SPECIAL_NO_COMPRESSION, type = CERTIFICATE, sequence = sequence, body = body ) ) } private suspend inline fun Wss.sendHeartbeatPacket() = sendLiveDanmakuPacket( LiveMsgPacket( protocol = SPECIAL_NO_COMPRESSION, type = HEARTBEAT, sequence = sequence, body = "[object Object]".toByteArray() ) ) } private typealias Config = LiveDanmakuConnectConfig /** * 直播弹幕信息流的配置 * * 将函数存储为值以供调用, 默认为空 * * 流是通过 `channelFlow` 构造的, 上流是 `channel` 下流是 `flow`. * 因此, 并不具备冷流特性, 详见官方文档 * @see channelFlow * @see Flow */ public class LiveDanmakuConnectConfig { public var onHeartbeatResponse: suspend Wss.(popular: Flow<UInt>) -> Unit = {} public var onCertificateResponse: suspend Wss.(response: Flow<CertificatePacketResponse>) -> Unit = {} public var onCommandResponse: suspend Wss.(command: Flow<LiveCommand>) -> Unit = {} public var onRawCommandResponse: suspend Wss.(command: Flow<RawLiveCommand>) -> Unit = {} } @Suppress("NOTHING_TO_INLINE") public inline fun Config.onHeartbeatResponse(noinline block: suspend Wss.(popular: Flow<UInt>) -> Unit) { onHeartbeatResponse = block } @Suppress("NOTHING_TO_INLINE") public inline fun Config.onCertificateResponse(noinline block: suspend Wss.(response: Flow<CertificatePacketResponse>) -> Unit) { onCertificateResponse = block } @Suppress("NOTHING_TO_INLINE") public inline fun Config.onCommandResponse(noinline block: suspend Wss.(command: Flow<LiveCommand>) -> Unit) { onCommandResponse = block } @Suppress("NOTHING_TO_INLINE") public inline fun Config.onRawCommandResponse(noinline block: suspend Wss.(command: Flow<RawLiveCommand>) -> Unit) { onRawCommandResponse = block }
0
null
1
26
c8be46f9b5e4db1e429c33b0821643fd94789fa1
9,648
Yabapi
Creative Commons Zero v1.0 Universal
app/src/main/java/com/zaneschepke/wireguardautotunnel/service/tunnel/WireGuardTunnel.kt
zaneschepke
644,710,160
false
{"Kotlin": 225248, "HTML": 1349}
package com.zaneschepke.wireguardautotunnel.service.tunnel import com.wireguard.android.backend.Backend import com.wireguard.android.backend.BackendException import com.wireguard.android.backend.Statistics import com.wireguard.android.backend.Tunnel import com.wireguard.crypto.Key import com.zaneschepke.wireguardautotunnel.Constants import com.zaneschepke.wireguardautotunnel.repository.model.TunnelConfig import com.zaneschepke.wireguardautotunnel.util.NumberUtils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject class WireGuardTunnel @Inject constructor(private val backend : Backend, ) : VpnService { private val _tunnelName = MutableStateFlow("") override val tunnelName get() = _tunnelName.asStateFlow() private val _state = MutableSharedFlow<Tunnel.State>( onBufferOverflow = BufferOverflow.DROP_OLDEST, replay = 1) private val _handshakeStatus = MutableSharedFlow<HandshakeStatus>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) override val state get() = _state.asSharedFlow() private val _statistics = MutableSharedFlow<Statistics>(replay = 1) override val statistics get() = _statistics.asSharedFlow() private val _lastHandshake = MutableSharedFlow<Map<Key, Long>>(replay = 1) override val lastHandshake get() = _lastHandshake.asSharedFlow() override val handshakeStatus: SharedFlow<HandshakeStatus> get() = _handshakeStatus.asSharedFlow() private val scope = CoroutineScope(Dispatchers.IO); private lateinit var statsJob : Job override suspend fun startTunnel(tunnelConfig: TunnelConfig) : Tunnel.State{ return try { if(getState() == Tunnel.State.UP && _tunnelName.value != tunnelConfig.name) { stopTunnel() } _tunnelName.emit(tunnelConfig.name) val config = TunnelConfig.configFromQuick(tunnelConfig.wgQuick) val state = backend.setState( this, Tunnel.State.UP, config) _state.emit(state) state; } catch (e : Exception) { Timber.e("Failed to start tunnel with error: ${e.message}") Tunnel.State.DOWN } } override fun getName(): String { return _tunnelName.value } override suspend fun stopTunnel() { try { if(getState() == Tunnel.State.UP) { val state = backend.setState(this, Tunnel.State.DOWN, null) _state.emit(state) scope.cancel() } } catch (e : BackendException) { Timber.e("Failed to stop tunnel with error: ${e.message}") } } override fun getState(): Tunnel.State { return backend.getState(this) } override fun onStateChange(state : Tunnel.State) { val tunnel = this; _state.tryEmit(state) if(state == Tunnel.State.UP) { statsJob = scope.launch { val handshakeMap = HashMap<Key, Long>() var neverHadHandshakeCounter = 0 while (true) { val statistics = backend.getStatistics(tunnel) _statistics.emit(statistics) statistics.peers().forEach { val handshakeEpoch = statistics.peer(it)?.latestHandshakeEpochMillis ?: 0L handshakeMap[it] = handshakeEpoch if(handshakeEpoch == 0L) { if(neverHadHandshakeCounter >= HandshakeStatus.NEVER_CONNECTED_TO_UNHEALTHY_TIME_LIMIT_SEC) { _handshakeStatus.emit(HandshakeStatus.NEVER_CONNECTED) } else { _handshakeStatus.emit(HandshakeStatus.NOT_STARTED) } if(neverHadHandshakeCounter <= HandshakeStatus.NEVER_CONNECTED_TO_UNHEALTHY_TIME_LIMIT_SEC) { neverHadHandshakeCounter += 10 } return@forEach } if(NumberUtils.getSecondsBetweenTimestampAndNow(handshakeEpoch) >= HandshakeStatus.UNHEALTHY_TIME_LIMIT_SEC) { _handshakeStatus.emit(HandshakeStatus.UNHEALTHY) } else { _handshakeStatus.emit(HandshakeStatus.HEALTHY) } } _lastHandshake.emit(handshakeMap) delay(Constants.VPN_STATISTIC_CHECK_INTERVAL) } } } if(state == Tunnel.State.DOWN) { if(this::statsJob.isInitialized) { statsJob.cancel() } _handshakeStatus.tryEmit(HandshakeStatus.NOT_STARTED) _lastHandshake.tryEmit(emptyMap()) } } }
8
Kotlin
8
96
79583e0e61b69312a2c317abbea09409107c8d3e
5,374
wgtunnel
MIT License
browser-kotlin/src/jsMain/kotlin/web/crypto/Algorithm.kt
karakum-team
393,199,102
false
{"Kotlin": 6328455}
// Automatically generated - do not modify! package web.crypto import kotlinx.js.JsPlainObject @JsPlainObject external interface Algorithm { var name: String }
1
Kotlin
8
35
6c553c67c6cbf77a802c137d010b143895c7da60
167
types-kotlin
Apache License 2.0
app/src/main/java/io/github/aloussase/booksdownloader/behaviors/BottomNavigationViewBehavior.kt
aloussase
759,640,931
false
{"Kotlin": 76283}
package io.github.aloussase.booksdownloader.behaviors import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.google.android.material.bottomnavigation.BottomNavigationView class BottomNavigationViewBehavior : CoordinatorLayout.Behavior<BottomNavigationView>() { var height = 0f override fun onLayoutChild( parent: CoordinatorLayout, child: BottomNavigationView, layoutDirection: Int ): Boolean { height = child.height.toFloat() return super.onLayoutChild(parent, child, layoutDirection) } override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: BottomNavigationView, directTargetChild: View, target: View, axes: Int, type: Int ): Boolean { return axes == ViewCompat.SCROLL_AXIS_VERTICAL } override fun onNestedScroll( coordinatorLayout: CoordinatorLayout, child: BottomNavigationView, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray ) { if (dyConsumed > 0) { slideDown(child) } else if (dyConsumed < 0) { slideUp(child); } } private fun slideUp(child: BottomNavigationView) { child.clearAnimation() child.animate().translationY(0f).setDuration(200) } private fun slideDown(child: BottomNavigationView) { child.clearAnimation() child.animate().translationY(height).setDuration(200) } }
3
Kotlin
4
60
010dcdcb3cca09cff1e01f4166cb015c29b20762
1,662
AlexandriaApp
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/locationsinsideprison/resource/PrisonerLocationResource.kt
ministryofjustice
738,978,080
false
null
package uk.gov.justice.digital.hmpps.locationsinsideprison.resource import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.tags.Tag import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.locationsinsideprison.service.PrisonerLocationService import java.util.* @RestController @Validated @RequestMapping("/prisoner-locations", produces = [MediaType.APPLICATION_JSON_VALUE]) @Tag( name = "Prisoner locations", description = "Returns the locations prisoners", ) class PrisonerLocationResource( private val prisonerLocationService: PrisonerLocationService, ) { @GetMapping("/id/{id}") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('VIEW_PRISONER_LOCATIONS')") @Operation( summary = "Returns a map of prisoners in cells within this location", description = "Requires role VIEW_PRISONER_LOCATIONS", responses = [ ApiResponse( responseCode = "200", description = "Returns location", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Missing required role. Requires the VIEW_PRISONER_LOCATIONS role", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun getPrisonersInLocationById( @Schema(description = "Location Id, can be a wing, landing or cell", example = "de91dfa7-821f-4552-a427-bf2f32eafeb0", required = true) @PathVariable id: UUID, ) = prisonerLocationService.prisonersInLocations(id) @GetMapping("/key/{key}") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('VIEW_PRISONER_LOCATIONS')") @Operation( summary = "Returns a map of prisoners in cells within this location", description = "Requires role VIEW_PRISONER_LOCATIONS", responses = [ ApiResponse( responseCode = "200", description = "Returns location", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Missing required role. Requires the VIEW_PRISONER_LOCATIONS role", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun getPrisonersInLocationByKey( @Schema(description = "Full location key, can be a wing, landing or cell, prisonId must be included", examples = ["MDI-1", "LEI-A-1-001", "PVI-1-2"], required = true) @PathVariable key: String, ) = prisonerLocationService.prisonersInLocations(key) @GetMapping("/prison/{prisonId}") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('VIEW_PRISONER_LOCATIONS')") @Operation( summary = "Returns a map of prisoners in cells within this prison", description = "Requires role VIEW_PRISONER_LOCATIONS", responses = [ ApiResponse( responseCode = "200", description = "Returns location", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Missing required role. Requires the VIEW_PRISONER_LOCATIONS role", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun getPrisonersInLocationByPrison( @Schema(description = "Prison ID", examples = ["MDI", "LEI", "PVI"], required = true) @PathVariable prisonId: String, ) = prisonerLocationService.prisonersInPrison(prisonId = prisonId) }
3
null
0
2
9946a37ef6ee0301ce3bd626015f5a927e991007
4,730
hmpps-locations-inside-prison-api
MIT License
reflekt-plugin/src/main/kotlin/org/jetbrains/reflekt/plugin/generation/ir/ReflektIrTransformer.kt
JetBrains-Research
293,503,377
false
null
package org.jetbrains.reflekt.plugin.generation.ir import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.util.* import org.jetbrains.reflekt.plugin.analysis.analyzer.IrReflektQueriesAnalyzer import org.jetbrains.reflekt.plugin.analysis.common.ReflektEntity import org.jetbrains.reflekt.plugin.analysis.ir.toFunctionInfo import org.jetbrains.reflekt.plugin.analysis.models.ir.IrInstances import org.jetbrains.reflekt.plugin.analysis.models.ir.LibraryArguments import org.jetbrains.reflekt.plugin.analysis.processor.ir.reflektArguments.getReflektInvokeParts import org.jetbrains.reflekt.plugin.utils.Util.log /** * Replaces Reflekt invoke calls with their results. * * @property pluginContext * @property irInstances * @property messageCollector * @property analyzer [IrReflektQueriesAnalyzer] to extract Reflekt queries arguments, * e.g. supertypes, annotations, functions signatures * @property libraryArguments TODO: use for ReflektImpl generation */ @Suppress("KDOC_NO_CLASS_BODY_PROPERTIES_IN_HEADER", "KDOC_EXTRA_PROPERTY", "UnusedPrivateMember") class ReflektIrTransformer( pluginContext: IrPluginContext, private val irInstances: IrInstances, private val libraryArguments: LibraryArguments, private val messageCollector: MessageCollector? = null, storageClassGenerator: StorageClassGenerator = StorageClassGenerator(pluginContext), ) : BaseReflektIrTransformer(pluginContext, messageCollector, storageClassGenerator) { private val analyzer = IrReflektQueriesAnalyzer(irInstances, pluginContext) /** * Visit [IrCall] and replace IR to found entities if it is a Reflekt query * * @param expression [IrCall] */ @Suppress("ReturnCount") override fun visitCall(expression: IrCall): IrExpression { messageCollector?.log("[IR] CURRENT EXPRESSION:\n${expression.dump()}") val filteredInstances = expression.filterInstances() messageCollector?.log("[IR] FILTERED INSTANCES: $filteredInstances") val invokeParts = expression.getReflektInvokeParts() ?: return super.visitCall(expression) messageCollector?.log("[IR] INVOKE PARTS: $invokeParts") // TODO: delete duplicate with SmartReflektIrTransformer val call = when (invokeParts.entityType) { ReflektEntity.OBJECTS, ReflektEntity.CLASSES -> resultIrCall( currentFile.module, invokeParts, filteredInstances.mapNotNull { (it as? IrClass)?.fqNameWhenAvailable?.asString() }, expression.type, ) ReflektEntity.FUNCTIONS -> functionResultIrCall( invokeParts, filteredInstances.mapNotNull { (it as? IrFunction)?.toFunctionInfo() }, expression.type, ) } messageCollector?.log("[IR] FOUND CALL (${invokeParts.entityType}):\n${expression.dump()}") messageCollector?.log("[IR] GENERATE CALL:\n${call.dump()}") return call } /** * Filters instances according to [IrCall]. * If [irInstances] is empty we don't need to process [IrCall]. * If [IrCall] is a Reflekt call then extract all query arguments and filter instances. */ private fun IrCall.filterInstances() = if (irInstances.isEmpty()) { emptyList() } else { analyzer.processWithCurrentResult(this, currentFile) } }
13
null
9
325
6ad9ebf8a4591c6fd729deea56063406b8c72612
3,644
reflekt
Apache License 2.0
app/src/main/java/com/example/crudloginpage/di/RepostioryModule.kt
hardigerz
787,808,754
false
{"Kotlin": 53449}
package com.example.crudloginpage.di import com.example.crudloginpage.repository.PhotoRepository import com.example.crudloginpage.repository.PhotoRepositoryImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Binds abstract fun providePhotoRepository(photoRepository: PhotoRepositoryImpl): PhotoRepository }
0
Kotlin
0
0
f1ddebf69d4f5028da3f333c8f92d1858110cf12
470
CRUDLoginPage
Apache License 2.0
app/src/main/java/de/lemke/sudoku/domain/GetDailySudokusUseCase.kt
Lemkinator
539,200,477
false
{"Kotlin": 307941}
package de.lemke.sudoku.domain import de.lemke.sudoku.data.database.SudokusRepository import de.lemke.sudoku.domain.model.Sudoku import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.time.LocalDate import javax.inject.Inject class GetDailySudokusUseCase @Inject constructor( private val sudokusRepository: SudokusRepository, private val saveSudoku: SaveSudokuUseCase, private val generateDailySudoku: GenerateDailySudokuUseCase, ) { suspend operator fun invoke(includeUncompleted: Boolean, date: LocalDate = LocalDate.now()): List<Pair<Sudoku?, LocalDate>> = withContext(Dispatchers.Default) { var dailySudokus = sudokusRepository.getAllDailySudokus() if (dailySudokus.none { it.created.toLocalDate() == LocalDate.now() }) { saveSudoku(generateDailySudoku()) dailySudokus = sudokusRepository.getAllDailySudokus() } val sudokuDatePairs: MutableList<Pair<Sudoku?, LocalDate>> = dailySudokus.filter { if (includeUncompleted) true else { it.completed } || it.created.toLocalDate() == date }.map { it to it.created.toLocalDate() }.toMutableList() val sudokuDatePairsCopy = sudokuDatePairs.toMutableList() var offset = 0 var oldDate: LocalDate? = null sudokuDatePairsCopy.forEachIndexed { index, pair -> // add a null entry for date separator if (oldDate == null || oldDate?.month != pair.second.month) { sudokuDatePairs.add(index + offset, Pair(null, pair.second)) oldDate = pair.second offset++ } } return@withContext sudokuDatePairs } }
0
Kotlin
1
8
2b61114ed2912c1886d1be88b0dc7be72cde34e5
1,826
Sudoku
MIT License
.teamcity/src/templates/KibanaTemplate.kt
vincent-fuchs
330,519,717
true
{"TypeScript": 82483297, "JavaScript": 11701547, "SCSS": 366647, "Shell": 217254, "CSS": 208671, "HTML": 139006, "Groovy": 105359, "Kotlin": 43154, "Perl": 12787, "Handlebars": 10144, "ANTLR": 9216, "Python": 8657, "Dockerfile": 7359, "Batchfile": 3782, "Gherkin": 1716}
package templates import StandardAgents import co.elastic.teamcity.common.requireAgent import getProjectBranch import isReportingEnabled import vcs.Kibana import jetbrains.buildServer.configs.kotlin.v2019_2.BuildStep import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay import jetbrains.buildServer.configs.kotlin.v2019_2.Template import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.PullRequests import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.perfmon import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.pullRequests import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.placeholder import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script object KibanaTemplate : Template({ name = "Kibana Template" description = "For builds that need to check out kibana and execute against the repo using node" vcs { root(Kibana) checkoutDir = "kibana" // checkoutDir = "/dev/shm/%system.teamcity.buildType.id%/%system.build.number%/kibana" } requireAgent(StandardAgents["2"]!!) features { perfmon { } pullRequests { vcsRootExtId = "${Kibana.id}" provider = github { authType = token { token = "credentialsJSON:07d22002-12de-4627-91c3-672bdb23b55b" } filterTargetBranch = "refs/heads/${getProjectBranch()}" filterAuthorRole = PullRequests.GitHubRoleFilter.MEMBER } } } failureConditions { executionTimeoutMin = 160 testFailure = false } params { param("env.CI", "true") param("env.TEAMCITY_CI", "true") param("env.HOME", "/var/lib/jenkins") // TODO once the agent images are sorted out // TODO remove these param("env.GCS_UPLOAD_PREFIX", "INVALID_PREFIX") param("env.CI_PARALLEL_PROCESS_NUMBER", "1") param("env.TEAMCITY_URL", "%teamcity.serverUrl%") param("env.TEAMCITY_BUILD_URL", "%teamcity.serverUrl%/build/%teamcity.build.id%") param("env.TEAMCITY_JOB_ID", "%system.teamcity.buildType.id%") param("env.TEAMCITY_BUILD_ID", "%build.number%") param("env.TEAMCITY_BUILD_NUMBER", "%teamcity.build.id%") param("env.GIT_BRANCH", "%vcsroot.branch%") param("env.GIT_COMMIT", "%build.vcs.number%") param("env.branch_specifier", "%vcsroot.branch%") param("env.CI_REPORTING_ENABLED", isReportingEnabled().toString()) password("env.KIBANA_CI_STATS_CONFIG", "", display = ParameterDisplay.HIDDEN) password("env.CI_STATS_TOKEN", "<PASSWORD>", display = ParameterDisplay.HIDDEN) password("env.CI_STATS_HOST", "credentialsJSON:933ba93e-4b06-44c1-8724-8c536651f2b6", display = ParameterDisplay.HIDDEN) // TODO move these to vault once the configuration is finalized // password("env.CI_STATS_TOKEN", "%vault:kibana-issues:secret/kibana-issues/dev/kibana_ci_stats!/api_token%", display = ParameterDisplay.HIDDEN) // password("env.CI_STATS_HOST", "%vault:kibana-issues:secret/kibana-issues/dev/kibana_ci_stats!/api_host%", display = ParameterDisplay.HIDDEN) // TODO remove this once we are able to pull it out of vault and put it closer to the things that require it if(isReportingEnabled()) { password( "env.GITHUB_TOKEN", "credentialsJSON:<PASSWORD>", display = ParameterDisplay.HIDDEN ) password("env.KIBANA_CI_REPORTER_KEY", "", display = ParameterDisplay.HIDDEN) password( "env.KIBANA_CI_REPORTER_KEY_BASE64", "credentialsJSON:86878779-4cf7-4434-82af-5164a1b992fb", display = ParameterDisplay.HIDDEN ) } } steps { script { name = "Setup Environment" scriptContent = """ #!/bin/bash ./.ci/teamcity/setup_env.sh """.trimIndent() } script { name = "Setup Node and Yarn" scriptContent = """ #!/bin/bash ./.ci/teamcity/setup_node.sh """.trimIndent() } script { name = "Setup CI Stats" scriptContent = """ #!/bin/bash node .ci/teamcity/setup_ci_stats.js """.trimIndent() } script { name = "Bootstrap" scriptContent = """ #!/bin/bash ./.ci/teamcity/bootstrap.sh """.trimIndent() } placeholder {} script { name = "Set Build Status Success" scriptContent = """ #!/bin/bash echo "##teamcity[setParameter name='env.BUILD_STATUS' value='SUCCESS']" """.trimIndent() executionMode = BuildStep.ExecutionMode.RUN_ON_SUCCESS } script { name = "CI Stats Complete" scriptContent = """ #!/bin/bash node .ci/teamcity/ci_stats_complete.js """.trimIndent() executionMode = BuildStep.ExecutionMode.RUN_ON_FAILURE } } })
0
null
0
0
e4b89d42d8bd16d92f94cff6ade7abd221ea0594
4,894
kibana
Apache License 2.0
Notes/app/src/main/java/com/example/notes/ui/screens/registration/LogInFragment.kt
trypuzz
590,908,174
false
null
package com.example.notes.ui.screeens.registration import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import com.example.notes.* import com.example.notes.databinding.FragmentLogInBinding import com.example.notes.repositories.SharePreferencesRepository import com.example.notes.ui.screeens.TaskFragment class LogInFragment : Fragment() { private lateinit var binding: FragmentLogInBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentLogInBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnLogin.setOnClickListener { onLogIn() } binding.btnSignUpReturn.setOnClickListener { onClickReturnSignUp() } } private fun validate(): Boolean { val isPasswordValid = validatePassword() val isEmailValid = validateEmail() return isPasswordValid == null && isEmailValid == null } private fun validatePassword(): String? { val passwordInputLayout = binding.passwordContainer passwordInputLayout.editText?.let { val result = validatePasswords(it.text.toString()) return when (result) { is Invalid -> { passwordInputLayout.error = this.getString(result.textError) this.getString(result.textError) } else -> { passwordInputLayout.error = null null } } } ?: return null } private fun validateEmail(): String? { val emailInputLayout = binding.emailContainer emailInputLayout.editText?.let { val result = validateEmails(it.text.toString()) return when (result) { is Invalid -> { emailInputLayout.error = this.getString(result.textError) this.getString(result.textError) } else -> { emailInputLayout.error = null null } } } ?: return null } fun onLogIn() { val sharedPreferencesRepository = SharePreferencesRepository(requireContext()) if (validate()) { if ((sharedPreferencesRepository.getUserEmail() != null) && (sharedPreferencesRepository.getUserEmail() .equals(binding.emailEditText.text.toString())) ) { parentFragmentManager.beginTransaction() .replace(R.id.container, TaskFragment()) .addToBackStack("") .commit() } else if (!(sharedPreferencesRepository.getUserEmail() .equals(binding.emailEditText.text.toString())) || (sharedPreferencesRepository.getUserEmail() == null) ) { Toast.makeText(requireContext(), R.string.user_no_registration, Toast.LENGTH_SHORT) .show() } } } fun onClickReturnSignUp() { parentFragmentManager.beginTransaction() .replace(R.id.container, SignUpFragment()) .addToBackStack("") .commit() } }
0
Kotlin
0
9
088cd66c2bba97ea1cfd62d35b2d70c4837a6d09
3,502
pet-projects
MIT License
03_ANDROID/02_ANDROID_COMPOSE_UI/03_STOCKS_APP/app/src/main/java/com/aryan/stockmarketapp/StockApplication.kt
singhtwenty2
743,251,401
false
{"Kotlin": 215510}
package com.aryan.stockmarketapp import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class StockApplication: Application() { }
0
Kotlin
0
1
9830286cba16130d236cf834d22d390de0bb3594
165
AndroidWithKotlinJourney
MIT License
test_runner/src/test/kotlin/ftl/doctor/DoctorTest.kt
rashiq
267,499,333
false
{"Markdown": 10, "INI": 2, "Gradle Kotlin DSL": 6, "Go": 1, "Shell": 7, "Java": 68, "JavaScript": 2, "HTML": 2, "CSS": 2, "TypeScript": 1, "Java Properties": 1, "Batchfile": 1, "Kotlin": 123}
package ftl.doctor import com.google.common.truth.Truth.assertThat import ftl.args.AndroidArgs import ftl.args.IosArgs import ftl.test.util.FlankTestRunner import java.nio.file.Paths import org.junit.Test import org.junit.runner.RunWith @RunWith(FlankTestRunner::class) class DoctorTest { @Test fun androidDoctorTest() { val lint = Doctor.validateYaml(AndroidArgs, Paths.get("src/test/kotlin/ftl/fixtures/flank.local.yml")) assertThat(lint).isEmpty() } @Test fun androidDoctorTest2() { val lint = Doctor.validateYaml( AndroidArgs, """ hi: . foo: bar: 1 gcloud: results-bucket: . record-video: . timeout: . async: . results-history-name: . app: . test: . auto-google-login: . use-orchestrator: . environment-variables: clearPackageData: . directories-to-pull: - . performance-metrics: . test-targets: - . device: - model: . version: . locale: . orientation: . two: . flank: max-test-shards: 7 num-test-runs: 8 test-targets-always-run: - . three: . project: . """.trimIndent() ) assertThat(lint).isEqualTo( """ Unknown top level keys: [hi, foo] Unknown keys in gcloud -> [two] Unknown keys in flank -> [three] """.trimIndent() ) } @Test fun androidDoctorTest3() { val lint = Doctor.validateYaml( AndroidArgs, """ gcloud: app: . test: . flank: project: . """.trimIndent() ) assertThat(lint).isEqualTo("") } @Test fun iosDoctorTest() { val lint = Doctor.validateYaml(IosArgs, Paths.get("src/test/kotlin/ftl/fixtures/flank.ios.yml")) assertThat(lint).isEmpty() } @Test fun iosDoctorTest2() { val lint = Doctor.validateYaml( IosArgs, """ hi: . foo: bar: 1 gcloud: results-bucket: . record-video: . timeout: . async: . results-history-name: . test: . xctestrun-file: . device: - model: . version: . locale: . orientation: . two: . flank: max-test-shards: . num-test-runs: . test-targets-always-run: - . test-targets: - . three: . project: . """.trimIndent() ) assertThat(lint).isEqualTo( """ Unknown top level keys: [hi, foo] Unknown keys in gcloud -> [two] Unknown keys in flank -> [three] """.trimIndent() ) } @Test fun iosDoctorTest3() { val lint = Doctor.validateYaml( IosArgs, """ gcloud: test: . xctestrun-file: . flank: project: . """.trimIndent() ) assertThat(lint).isEqualTo("") } }
1
null
1
1
bd8dd925f6f10a61fe583b03b63228daa0f6a885
2,636
flank
MIT License
telegram/src/main/kotlin/com/github/kotlintelegrambot/entities/HideKeyboardReplyMarkup.kt
kotlin-telegram-bot
121,235,631
false
null
package com.github.kotlintelegrambot.entities import com.google.gson.Gson import com.google.gson.annotations.SerializedName as Name data class HideKeyboardReplyMarkup( @Name("hide_keyboard") val hideKeyboard: Boolean = true, val selective: Boolean? = null ) : ReplyMarkup { private companion object { val GSON = Gson() } override fun toString(): String = GSON.toJson(this) }
67
null
161
794
18013912c6a8c395b6491c2323a8f5eb7288b4f5
406
kotlin-telegram-bot
Apache License 2.0
ktoml-core/src/commonTest/kotlin/com/akuleshov7/ktoml/encoders/TomlDocsEncoderTest.kt
orchestr7
330,720,838
false
{"Kotlin": 453507, "Shell": 606}
package com.akuleshov7.ktoml.encoders import com.akuleshov7.ktoml.Toml import com.akuleshov7.ktoml.TomlIndentation import com.akuleshov7.ktoml.TomlOutputConfig import com.akuleshov7.ktoml.annotations.TomlInlineTable import com.akuleshov7.ktoml.annotations.TomlLiteral import kotlinx.datetime.Instant import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toInstant import kotlinx.serialization.* import kotlinx.serialization.descriptors.StructureKind import kotlinx.serialization.descriptors.buildSerialDescriptor import kotlinx.serialization.descriptors.element import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.encoding.encodeCollection import kotlin.test.Ignore import kotlin.test.Test class TomlDocsEncoderTest { @Serializable data class ReadMe( val title: String = "TOML Example", val owner: Owner = Owner(), val database: Database = Database(), val servers: Servers = Servers() ) @Serializable data class Owner( val name: String = "Tom Preston-Werner", val dob: Instant = LocalDateTime(1979, 5, 27, 15, 32, 0) .toInstant(TimeZone.UTC) ) @Serializable data class Database( val enabled: Boolean = true, val ports: List<Long> = listOf(8000, 8001, 8002), @Serializable(with = DataSerializer::class) val data: List<List<@Contextual Any>> = listOf(listOf("delta", "phi"), listOf(3.14)), @SerialName("temp_targets") @TomlInlineTable val tempTargets: Map<String, Double> = mapOf("cpu" to 79.5, "case" to 72.0) ) { // Serializing this as a hard-coded list instead of making Any @Polymorphic // because these would be serialized as [ "kotlin.<type>", <value> ] rather // than as primitives. Making an exception for primitives in the encoder // works, but could make types difficult to resolve on deserialization. @OptIn(ExperimentalSerializationApi::class) object DataSerializer : KSerializer<List<List<Any>>> { @OptIn(InternalSerializationApi::class) override val descriptor = buildSerialDescriptor("data", StructureKind.LIST) { element<List<String>>("0") element<List<Double>>("1") } @Suppress("UNCHECKED_CAST") override fun serialize(encoder: Encoder, value: List<List<Any>>) { encoder.encodeCollection(descriptor, 2) { encodeSerializableElement(descriptor, 0, serializer<_>(), value[0] as List<String>) encodeSerializableElement(descriptor, 1, serializer<_>(), value[1] as List<Double>) } } override fun deserialize(decoder: Decoder): List<List<Any>> { throw IllegalStateException() } } } @Serializable data class Servers( val alpha: Entry = Entry("10.0.0.1", "frontend"), val beta: Entry = Entry("10.0.0.2", "backend") ) { @Serializable data class Entry(val ip: String, val role: String) } @Test fun readMeTest() { assertEncodedEquals( value = ReadMe(), expectedToml = """ title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T15:32:00Z [database] enabled = true ports = [ 8000, 8001, 8002 ] data = [ [ "delta", "phi" ], [ 3.14 ] ] temp_targets = { cpu = 79.5, case = 72.0 } [servers] [servers.alpha] ip = "10.0.0.1" role = "frontend" [servers.beta] ip = "10.0.0.2" role = "backend" """.trimIndent(), tomlInstance = Toml( outputConfig = TomlOutputConfig.compliant( indentation = TomlIndentation.NONE, explicitTables = true ) ) ) } @Test fun basicStringTest() { @Serializable data class File( val str1: String = "I'm a string.", val str2: String = "You can \"quote\" me.", val str3: String = "Name\tJos\u00E9\nLoc\tSF." ) assertEncodedEquals( value = File(), expectedToml = """ str1 = "I'm a string." str2 = "You can \"quote\" me." str3 = "Name José\nLoc SF." """.trimIndent() ) } @Test fun literalStringTest() { @Serializable data class File( @TomlLiteral val winpath: String = """C:\Users\nodejs\templates""", @TomlLiteral val winpath2: String = """\\ServerX\admin${'$'}\system32\""", @TomlLiteral val quoted: String = """Tom "Dubs" Preston-Werner""", @TomlLiteral val regex: String = """<\i\c*\s*>""" ) assertEncodedEquals( value = File(), expectedToml = """ winpath = 'C:\Users\nodejs\templates' winpath2 = '\\ServerX\admin${'$'}\system32\' quoted = 'Tom "Dubs" Preston-Werner' regex = '<\i\c*\s*>' """.trimIndent() ) } }
36
Kotlin
23
450
b22969a093d3a1f062d3b9840c9195c09951d8b2
5,575
ktoml
MIT License
compiler/testData/diagnostics/testsWithJsStdLib/dynamicTypes/supertypesAndBounds.kt
JakeWharton
99,388,807
false
null
// FIR_IDENTICAL interface Tr : <!DYNAMIC_SUPERTYPE!>dynamic<!> fun <T: <!DYNAMIC_UPPER_BOUND!>dynamic<!>> foo() {} class C<T> where T : <!DYNAMIC_UPPER_BOUND!>dynamic<!>
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
173
kotlin
Apache License 2.0
detail/api/src/main/java/com/novina/navigation/lib/detail/api/domain/data/DetailTransitionData.kt
mohammad8135
542,037,428
false
null
package com.novina.navigation.lib.detail.api.domain.data data class DetailTransitionData(val id: Int)
0
Kotlin
1
2
9bbf65a8e90feedf98748bd750e32ede292389f3
102
Modularisation-and-Navigation
Apache License 2.0
roboquant-server/src/main/kotlin/org/roboquant/server/PausablePolicy.kt
neurallayer
406,929,056
false
null
/* * Copyright 2020-2024 Neural Layer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.roboquant.server import org.roboquant.brokers.Account import org.roboquant.feeds.Event import org.roboquant.orders.Order import org.roboquant.policies.Policy import org.roboquant.strategies.Signal import java.time.Instant /** * Policy that can be paused and also captures a number of metrics */ internal class PausablePolicy(private val policy: Policy, var pause: Boolean = false) : Policy by policy { internal var sellSignals = 0 internal var holdSignals = 0 internal var buySignals = 0 internal var totalOrders = 0 internal var totalEvents = 0 internal var emptyEvents = 0 internal var totalActions = 0 internal var lastUpdate: Instant = Instant.MIN override fun act(signals: List<Signal>, account: Account, event: Event): List<Order> { // Still invoke the policy so any state can be updated if required. val orders = policy.act(signals, account, event) buySignals += signals.filter { it.isBuy }.size sellSignals += signals.filter { it.isSell }.size holdSignals += signals.filter { it.rating == 0.0 }.size totalEvents++ if (event.items.isEmpty()) emptyEvents++ totalActions += event.items.size lastUpdate = event.time return if (!pause) { totalOrders += orders.size orders } else { emptyList() } } override fun reset() { sellSignals = 0 holdSignals = 0 buySignals = 0 totalOrders = 0 totalEvents = 0 emptyEvents = 0 totalActions = 0 } }
8
null
42
316
769f1aade1e8e95817591866faad4561f7768071
2,204
roboquant
Apache License 2.0
composables/src/androidTest/java/dev/medzik/android/composables/navigation/NavigationTests.kt
M3DZIK
698,762,035
false
{"Kotlin": 61620}
package dev.medzik.android.components import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import org.junit.Rule import org.junit.Test enum class Argument : NavArgument { ID, Name } enum class Screen(override val args: Array<NavArgument>? = null) : NavScreen { Home, Example(arrayOf(Argument.ID, Argument.Name)) } class NavigationTests { @get:Rule val composeTestRule = createComposeRule() @Test fun testNavigation() { composeTestRule.setContent { val navController = rememberNavController() NavHost(navController = navController, startDestination = Screen.Home.getRoute()) { composable(Screen.Home.getRoute()) { Column { Text("Home Screen") Button(onClick = { navController.navigate( screen = Screen.Example, args = arrayOf( Argument.ID to "test id", Argument.Name to "test name" ) ) }) { Text("Click me to go to Example screen") } } } composable(Screen.Example.getRoute()) { val id = navController.getString(Argument.ID) val name = navController.getString(Argument.Name) Column { Text("Example Screen") Text("ID: $id") Text("Name: $name") } } } } composeTestRule.onNodeWithText("Home Screen").assertExists() // go to example screen composeTestRule.onNodeWithText("Click me to go to Example screen").performClick() composeTestRule.onNodeWithText("Example Screen").assertExists() // check arguments composeTestRule.onNodeWithText("ID: test id").assertExists() composeTestRule.onNodeWithText("Name: test name").assertExists() } }
0
Kotlin
0
1
f12fcb6dc99fd66f2857a8d9ae0904496d9cbe99
2,608
android-utils
MIT License
camera/camera-camera2-pipe-integration/src/androidTest/java/androidx/camera/camera2/pipe/integration/InitializationTest.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.integration import androidx.annotation.OptIn import androidx.camera.lifecycle.ExperimentalCameraProviderConfiguration import androidx.camera.lifecycle.ProcessCameraProvider import androidx.concurrent.futures.await import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class InitializationTest { @OptIn(ExperimentalCameraProviderConfiguration::class) @Test fun initializeCameraX_withCameraPipeConfig() = runBlocking { ProcessCameraProvider.configureInstance(CameraPipeConfig.defaultConfig()) // Retrieve camera provider initialized with CameraPipeConfig val cameraProvider = ProcessCameraProvider.getInstance(ApplicationProvider.getApplicationContext()).await() assertThat(cameraProvider).isNotNull() // Ensure retrieved provider is shut down cameraProvider.shutdown().await() return@runBlocking } }
29
null
823
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
1,810
androidx
Apache License 2.0
app/src/main/java/com/sgtech/wendysclear/MainActivity.kt
DSieghard
380,814,690
false
null
package com.sgtech.wendysclear import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get reference to all views val et_user_name = findViewById<EditText>(R.id.et_user_name) val et_password = findViewById<EditText>(R.id.et_password) val btn_reset = findViewById<Button>(R.id.btn_reset) val btn_submit = findViewById<Button>(R.id.btn_submit) btn_reset.setOnClickListener { // clearing user_name and password edit text views on reset button click et_user_name.setText("") et_password.setText("") } // set on-click listener btn_submit.setOnClickListener { val username = et_user_name.text; val password = et_password.text; Toast.makeText(this@MainActivity, username, Toast.LENGTH_LONG).show() // your code to validate the user_name and password combination // and verify the same } } }
0
Kotlin
0
0
f5d373a7abd650cababaf2bb3936374218d54b1d
1,230
WendysClear2021
Creative Commons Zero v1.0 Universal
app/src/main/kotlin/com/dot/gallery/core/util/MediaStoreBuckets.kt
IacobIonut01
614,314,251
false
{"Kotlin": 1381485, "Shell": 455}
/* * SPDX-FileCopyrightText: 2023 The LineageOS Project * SPDX-License-Identifier: Apache-2.0 */ package com.dot.gallery.core.util enum class MediaStoreBuckets { /** * Favorites album. */ MEDIA_STORE_BUCKET_FAVORITES, /** * Trash album. */ MEDIA_STORE_BUCKET_TRASH, /** * Timeline, contains all medias. */ MEDIA_STORE_BUCKET_TIMELINE, /** * Reserved bucket ID for placeholders, throw an exception if this value is used. */ MEDIA_STORE_BUCKET_PLACEHOLDER, /** * Timeline, contains only photos. */ MEDIA_STORE_BUCKET_PHOTOS, /** * Timeline, contains only videos. */ MEDIA_STORE_BUCKET_VIDEOS; val id = (-0x0000DEAD - ((ordinal + 1) shl 16)).toLong() }
87
Kotlin
66
1,292
261ceb8c5ade6ede7b295536b9384ac12d77f572
771
Gallery
Apache License 2.0
frogosdk/src/main/java/com/frogobox/sdk/core/IFrogoFragment.kt
frogobox
293,762,352
false
null
package com.frogobox.nutritionframework.core import android.view.View import androidx.fragment.app.Fragment /* * Created by faisalamir on 28/07/21 * FrogoSDK * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2021 FrogoBox Inc. * All rights reserved * */ interface INutriFragment { fun setupChildFragment(frameId: Int, fragment: Fragment) fun checkArgument(argsKey: String): Boolean fun setupEventEmptyView(view: View, isEmpty: Boolean) fun setupEventProgressView(view: View, progress: Boolean) fun showToast(message: String) fun <Model> baseNewInstance(argsKey: String, data: Model) // Please Add Your Code Under This Line -------------------------------------------------------- }
1
null
4
8
427d5a98ef5027f000fab91d8e563a606bbb0462
866
frogo-android-sdk
Apache License 2.0
kira/src/main/java/com/popovanton0/kira/suppliers/OneOfManySupplier.kt
popovanton0
489,662,148
false
{"Kotlin": 294584}
package com.popovanton0.kira.suppliers import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.tooling.preview.Preview import com.popovanton0.kira.suppliers.base.ClassType import com.popovanton0.kira.suppliers.base.NamedValue.Companion.withName import com.popovanton0.kira.suppliers.base.NamedValue import com.popovanton0.kira.suppliers.base.PropertyBasedSupplier import com.popovanton0.kira.suppliers.base.ReflectionUsage import com.popovanton0.kira.suppliers.base.Supplier import com.popovanton0.kira.suppliers.base.SupplierBuilder import com.popovanton0.kira.suppliers.base.Type import com.popovanton0.kira.suppliers.base.Ui import com.popovanton0.kira.suppliers.base.toClassType import com.popovanton0.kira.suppliers.compound.KiraScope import com.popovanton0.kira.ui.Dropdown @ReflectionUsage public inline fun <reified T : Any> KiraScope.oneOfMany( paramName: String, values: Collection<NamedValue<T>>, defaultOptionIndex: Int = 0, ): OneOfManySupplierBuilder<T> = oneOfMany( paramName, values, T::class.toClassType(nullable = false), defaultOptionIndex, ) @ReflectionUsage public inline fun <reified T : Any> KiraScope.nullableOneOfMany( paramName: String, values: Collection<NamedValue<T>>, defaultOptionIndex: Int = 0, ): OneOfManySupplierBuilder<T?> = nullableOneOfMany( paramName, values, T::class.toClassType(nullable = true), defaultOptionIndex, ) public fun <T> KiraScope.oneOfMany( paramName: String, values: Collection<NamedValue<T>>, type: Type, defaultOptionIndex: Int = 0, ): OneOfManySupplierBuilder<T> { require(defaultOptionIndex < values.size) { "Index should be less that values.size" } return OneOfManySupplierBuilder(paramName, type.notNullable(), values, defaultOptionIndex) .also(::addSupplierBuilder) } public fun <T : Any> KiraScope.nullableOneOfMany( paramName: String, values: Collection<NamedValue<T>>, type: Type, defaultOptionIndex: Int? = null, ): OneOfManySupplierBuilder<T?> { if (defaultOptionIndex != null) { require(defaultOptionIndex < values.size) { "Index should be less that values.size" } } return OneOfManySupplierBuilder( paramName = paramName, type = type.nullable(), values = buildList { add(null withName "null") addAll(values) }, defaultOptionIndex = defaultOptionIndex?.plus(1) ?: 0, ).also(::addSupplierBuilder) } public class OneOfManySupplierBuilder<T> internal constructor( public var paramName: String, public var type: Type, public var values: Collection<NamedValue<T>>, public var defaultOptionIndex: Int, ) : SupplierBuilder<T>() { override fun provideSupplier(): Supplier<T> = OneOfManySupplier(paramName, type, values.toList(), defaultOptionIndex) } private class OneOfManySupplier<T>( private val paramName: String, private val type: Type, private val values: List<NamedValue<T>>, defaultOptionIndex: Int, ) : PropertyBasedSupplier<T> { override var currentValue: T by mutableStateOf(values[defaultOptionIndex].value) private var selectedOptionIndex by mutableStateOf(defaultOptionIndex) private val displayNames: List<String> = values.map { it.displayName } @Composable override fun Ui(params: Any?) { Dropdown( selectedOptionIndex = selectedOptionIndex, onSelect = { selectedOptionIndex = it currentValue = values[it].value }, options = displayNames, label = paramName, type = type, ) } } @Preview @Composable private fun Preview() = KiraScope().oneOfMany( paramName = "param name", type = ClassType("String", ClassType.Variant.CLASS), values = AnnotationTarget.values().map { it withName it.name } ).build().Ui() @Preview @Composable private fun NullablePreview() = KiraScope().nullableOneOfMany( paramName = "param name", type = ClassType("String", ClassType.Variant.CLASS), values = AnnotationTarget.values().map { it withName it.name } ).build().Ui()
0
Kotlin
0
5
b65f7af94b94cd5334fd5070b1676b99a15fbffe
4,245
kira
Apache License 2.0
app/src/main/java/br/com/fiap/calculodejuros/MainActivity.kt
GusGaiotti
682,293,262
false
null
package br.com.fiap.calculodejuros import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import br.com.fiap.calculodejuros.juros.JurosScreen import br.com.fiap.calculodejuros.juros.JurosScreenViewModel class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { JurosScreen(JurosScreenViewModel()) } } } }
0
Kotlin
0
0
85c7c0d096595d9465551369035bcbe78bb34617
876
interest-calculator
MIT License
app/src/main/java/com/cuidedacidade/features/main/di/MainComponent.kt
daniloabranches
281,368,825
false
null
package com.cuidedacidade.features.main.di import com.cuidedacidade.features.main.MainActivity import dagger.Subcomponent @Subcomponent interface MainComponent { @Subcomponent.Factory interface Factory { fun create(): MainComponent } fun inject(activity: MainActivity) }
0
Kotlin
0
1
ee646396e98595aad72d048b80beaec9712e56a2
297
app-cuide-cidade-igti
MIT License
src/main/kotlin/com/example/v1oauthauthorizationservice/infrastructure/configuration/oauth2/authorizationserver/CustomAuthenticationEntrypoint.kt
team-xquare
494,272,840
false
{"Kotlin": 89316, "Shell": 417, "Dockerfile": 391}
package com.example.v1oauthauthorizationservice.infrastructure.configuration.oauth2.authorizationserver import com.example.v1oauthauthorizationservice.infrastructure.configuration.exception.basic.InternalServerError import com.example.v1oauthauthorizationservice.infrastructure.configuration.exception.utils.ExceptionResponseUtils.convertToBaseExceptionIfPossible import com.example.v1oauthauthorizationservice.infrastructure.configuration.exception.utils.ExceptionResponseUtils.sendErrorResponse import com.example.v1oauthauthorizationservice.infrastructure.configuration.oauth2.exceptions.FailedToAuthorizeException import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.security.authentication.InsufficientAuthenticationException import org.springframework.security.core.AuthenticationException import org.springframework.security.web.AuthenticationEntryPoint import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse class CustomAuthenticationEntrypoint( private val objectMapper: ObjectMapper ) : AuthenticationEntryPoint { override fun commence( request: HttpServletRequest, response: HttpServletResponse, authException: AuthenticationException ) { authException.printStackTrace() when (val exception = authException.convertToBaseExceptionIfPossible()) { is InsufficientAuthenticationException -> FailedToAuthorizeException(FailedToAuthorizeException.FULL_AUTHORIZATION_NEEDED) is AuthenticationException -> FailedToAuthorizeException(FailedToAuthorizeException.AUTHORIZATION_FAILED_EXCEPTION) else -> InternalServerError(exception.message) }.sendErrorResponse(response, objectMapper) } }
1
Kotlin
0
2
e051e84b40a983775023b9978b747c2428c1d00d
1,757
v1-service-oauth
MIT License
src/main/kotlin/com/cc/csdnexport/wordpress/TableTermTaxonomy.kt
cclover
146,782,036
false
null
package com.cc.csdnexport.wordpress import java.math.BigInteger /** * TableTerms只记录术语,而这个表记录各种类型的terms */ class TableTermTaxonomy { companion object { const val CATEGORY = "category" const val POST_TAG = "post_tag" const val NAV_MENU = "nav_menu" } constructor(termID: Long, taxonomy: String, count: Long) { term_id = termID.toBigInteger() this.taxonomy = taxonomy this.count = count.toBigInteger() } var term_taxonomy_id: BigInteger = BigInteger.ZERO /** * 关了TableTerms */ var term_id: BigInteger = BigInteger.ZERO /** * 术语表分类 * category 文章分类 * nav_menu 导航菜单 * post_tag 文章tag */ var taxonomy: String = "" /** * 描述,一般是空 */ var description: String = "" /** * 父term,一般为0 */ var parent: BigInteger = BigInteger.ZERO /** * 使用这个term的数量 */ var count: BigInteger = BigInteger.ZERO }
0
Kotlin
0
0
c1796f0b715f07295e51612f9cac4b68d4f4c110
963
csdnexport
Apache License 2.0
src/main/kotlin/com/cc/csdnexport/wordpress/TableTermTaxonomy.kt
cclover
146,782,036
false
null
package com.cc.csdnexport.wordpress import java.math.BigInteger /** * TableTerms只记录术语,而这个表记录各种类型的terms */ class TableTermTaxonomy { companion object { const val CATEGORY = "category" const val POST_TAG = "post_tag" const val NAV_MENU = "nav_menu" } constructor(termID: Long, taxonomy: String, count: Long) { term_id = termID.toBigInteger() this.taxonomy = taxonomy this.count = count.toBigInteger() } var term_taxonomy_id: BigInteger = BigInteger.ZERO /** * 关了TableTerms */ var term_id: BigInteger = BigInteger.ZERO /** * 术语表分类 * category 文章分类 * nav_menu 导航菜单 * post_tag 文章tag */ var taxonomy: String = "" /** * 描述,一般是空 */ var description: String = "" /** * 父term,一般为0 */ var parent: BigInteger = BigInteger.ZERO /** * 使用这个term的数量 */ var count: BigInteger = BigInteger.ZERO }
0
Kotlin
0
0
c1796f0b715f07295e51612f9cac4b68d4f4c110
963
csdnexport
Apache License 2.0
src/main/kotlin/org/kirinhorse/kbt/decorators/Repeat.kt
KirinHorse
674,049,029
false
{"Kotlin": 67726}
package org.kirinhorse.kbt.decorators import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.kirinhorse.kbt.Component import org.kirinhorse.kbt.Decorator import org.kirinhorse.kbt.KBTInput import org.kirinhorse.kbt.NodeConfig import org.kirinhorse.kbt.Types @KBTInput("times", Types.KBTType.Int) @KBTInput("stop", Types.KBTType.Bool) class Repeat(component: Component, config: NodeConfig) : Decorator(component, config) { override suspend fun onExecute(): Boolean { val times = getInputOrNull("times", Int::class) var exe = 0 return withContext(Dispatchers.Default) { while (getInputOrNull("stop", Boolean::class) != true) { if (times != null && times >= 0 && exe++ >= times) break if (isPaused) pauseDeferred?.await() if (!isRunning || child?.execute() == false) return@withContext false } true } } }
0
Kotlin
0
1
df984343faadf5920c8c215f5f78bafc670f163b
959
KotlinBehaviors
MIT License
src/main/kotlin/com/sononio/bookmaker/util/enhancement/LocalDateTimeEnhancement.kt
sononio
280,885,581
false
null
package com.sononio.bookmaker.util.enhancement import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.* fun String.toDate(formatter: DateTimeFormatter): Date? { return LocalDateTime.parse(this, formatter).toDate() } fun LocalDateTime.toDate(): Date { return Date.from(this.atZone(ZoneId.systemDefault()).toInstant()) }
9
Kotlin
0
1
4246dc9812b194cc0d6775e2e02ad7b785a35f05
388
bookmakerbot
Apache License 2.0
components/membership/membership-http-rpc-impl/src/test/kotlin/net/corda/membership/impl/httprpc/v1/CertificatesRestResourceImplTest.kt
corda
346,070,752
false
null
package net.corda.membership.impl.httprpc.v1 import net.corda.crypto.cipher.suite.KeyEncodingService import net.corda.crypto.client.CryptoOpsClient import net.corda.crypto.core.CryptoConsts import net.corda.crypto.core.CryptoTenants.P2P import net.corda.data.certificates.CertificateUsage import net.corda.data.crypto.wire.CryptoSigningKey import net.corda.httprpc.HttpFileUpload import net.corda.httprpc.exception.BadRequestException import net.corda.httprpc.exception.InternalServerException import net.corda.httprpc.exception.InvalidInputDataException import net.corda.httprpc.exception.ResourceNotFoundException import net.corda.httprpc.exception.ServiceUnavailableException import net.corda.lifecycle.LifecycleCoordinator import net.corda.lifecycle.LifecycleCoordinatorFactory import net.corda.lifecycle.LifecycleEventHandler import net.corda.lifecycle.LifecycleStatus import net.corda.lifecycle.RegistrationStatusChangeEvent import net.corda.membership.certificate.client.CertificatesClient import net.corda.membership.certificates.CertificateUsageUtils.publicName import net.corda.membership.httprpc.v1.CertificatesRestResource.Companion.SIGNATURE_SPEC import net.corda.messaging.api.exception.CordaRPCAPIPartitionException import net.corda.v5.base.exceptions.CordaRuntimeException import net.corda.v5.base.types.MemberX500Name import net.corda.v5.crypto.DigitalSignature import net.corda.v5.crypto.ECDSA_SECP256R1_CODE_NAME import net.corda.v5.crypto.SignatureSpec import net.corda.v5.crypto.SignatureSpec.Companion.ECDSA_SHA256 import net.corda.virtualnode.HoldingIdentity import net.corda.virtualnode.ShortHash import net.corda.virtualnode.VirtualNodeInfo import net.corda.virtualnode.read.VirtualNodeInfoReadService import org.assertj.core.api.Assertions.assertThat import org.bouncycastle.asn1.DEROctetString import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x509.Extension import org.bouncycastle.asn1.x509.GeneralName import org.bouncycastle.asn1.x509.GeneralNames import org.bouncycastle.openssl.PEMParser import org.bouncycastle.pkcs.PKCS10CertificationRequest import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.nio.ByteBuffer import java.security.KeyPairGenerator import java.security.SecureRandom import java.security.spec.ECGenParameterSpec class CertificatesRestResourceImplTest { private val cryptoOpsClient = mock<CryptoOpsClient>() private val keyEncodingService = mock<KeyEncodingService>() private val coordinator = mock<LifecycleCoordinator>() private val handler = argumentCaptor<LifecycleEventHandler>() private val lifecycleCoordinatorFactory = mock<LifecycleCoordinatorFactory> { on { createCoordinator(any(), handler.capture()) } doReturn coordinator } private val virtualNodeInfoReadService = mock<VirtualNodeInfoReadService>() private val certificatesClient = mock<CertificatesClient>() private val certificatesOps = CertificatesRestResourceImpl( cryptoOpsClient, keyEncodingService, lifecycleCoordinatorFactory, certificatesClient, virtualNodeInfoReadService, ) @Nested inner class LifeCycleTests { @Test fun `isRunning returns the coordinator status`() { whenever(coordinator.status).doReturn(LifecycleStatus.UP) assertThat(certificatesOps.isRunning).isTrue } @Test fun `start starts the coordinator`() { certificatesOps.start() verify(coordinator).start() } @Test fun `stop stops the coordinator`() { certificatesOps.stop() verify(coordinator).stop() } @Test fun `UP event will set the status to up`() { handler.firstValue.processEvent(RegistrationStatusChangeEvent(mock(), LifecycleStatus.UP), mock()) verify(coordinator).updateStatus(LifecycleStatus.UP, "Dependencies are UP") } @Test fun `DOWN event will set the status to down`() { handler.firstValue.processEvent(RegistrationStatusChangeEvent(mock(), LifecycleStatus.DOWN), mock()) verify(coordinator).updateStatus(LifecycleStatus.DOWN, "Dependencies are DOWN") } } @Nested inner class GenerateCsrTests { private val holdingIdentityShortHash = "id" private val keyId = "keyId" private val x500Name = "CN=Alice" private val publicKeyBytes = "123".toByteArray() private val key = mock<CryptoSigningKey> { on { publicKey } doReturn ByteBuffer.wrap(publicKeyBytes) on { schemeCodeName } doReturn ECDSA_SECP256R1_CODE_NAME on { tenantId } doReturn holdingIdentityShortHash } private val publicKey = KeyPairGenerator.getInstance("EC").let { keyPairGenerator -> val rnd = mock<SecureRandom> { on { nextBytes(any()) } doAnswer { val array = it.arguments[0] as ByteArray array.fill(106) } } keyPairGenerator.initialize(ECGenParameterSpec("secp256r1"), rnd) keyPairGenerator.generateKeyPair().public } @BeforeEach fun setUp() { whenever(cryptoOpsClient.lookup(holdingIdentityShortHash, listOf(keyId))).doReturn(listOf(key)) whenever( cryptoOpsClient.sign( eq(holdingIdentityShortHash), eq(publicKey), argThat<SignatureSpec> { this.signatureName == ECDSA_SHA256.signatureName }, any(), eq(emptyMap()) ) ).doReturn( DigitalSignature.WithKey( publicKey, byteArrayOf(1), emptyMap() ) ) whenever(keyEncodingService.decodePublicKey(publicKeyBytes)).doReturn(publicKey) } @Test fun `it throws exception if key is not available`() { whenever(cryptoOpsClient.lookup(any(), any())).doReturn(emptyList()) assertThrows<ResourceNotFoundException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, null, ) } } @Test fun `it throws ServiceUnavailableException when repartition event happens while trying to retrieve key`() { whenever(cryptoOpsClient.lookup(any(), any())).doThrow(CordaRPCAPIPartitionException("repartition event")) val details = assertThrows<ServiceUnavailableException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, null, ) } assertThat(details.message).isEqualTo("Could not find key with ID keyId for id: Repartition Event!") } @Test fun `it sign the request`() { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, null, ) verify(cryptoOpsClient).sign( eq(holdingIdentityShortHash), eq(publicKey), argThat<SignatureSpec> { this.signatureName == ECDSA_SHA256.signatureName }, any(), eq(emptyMap()) ) } @Test fun `it returns the correct signature`() { val pem = certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, null, ) assertThat(pem.fromPem().signature).isEqualTo(byteArrayOf(1)) } @Test fun `it adds alternative subject names when some are provided`() { val pem = certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, listOf("www.alice.net", "alice.net", "10.101.100.65"), null, ) assertThat( pem.fromPem() .requestedExtensions .getExtension(Extension.subjectAlternativeName) ).isEqualTo( Extension( Extension.subjectAlternativeName, true, DEROctetString( GeneralNames( arrayOf( GeneralName(GeneralName.dNSName, "www.alice.net"), GeneralName(GeneralName.dNSName, "alice.net"), GeneralName(GeneralName.iPAddress, "10.101.100.65") ) ) ) ) ) } @Test fun `it will not adds alternative subject names when none are provided`() { val pem = certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, null, ) assertThat( pem.fromPem() .requestedExtensions .getExtension(Extension.subjectAlternativeName) ).isNull() } @Test fun `it will use the correct x500 name`() { val pem = certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, emptyMap(), ) assertThat( pem.fromPem() .subject ).isEqualTo(X500Name(x500Name)) } @Test fun `it will throw an exception for invalid X500 name`() { assertThrows<InvalidInputDataException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, "nop", null, emptyMap(), ) } } @Test fun `it will throw an exception for invalid member name for TLS certificate`() { whenever(key.category).doReturn(CryptoConsts.Categories.TLS) assertThrows<InvalidInputDataException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, emptyMap(), ) } } @Test fun `it will generate a CSR for a valid member name for TLS certificate`() { whenever(key.category).doReturn(CryptoConsts.Categories.TLS) val csr = certificatesOps.generateCsr( holdingIdentityShortHash, keyId, "O=Alice, L=LDN, C=GB", null, emptyMap(), ) assertThat(csr).isNotNull } @Test fun `it will throw an exception for invalid name for session certificate`() { whenever(key.category).doReturn(CryptoConsts.Categories.SESSION_INIT) assertThrows<InvalidInputDataException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, emptyMap(), ) } } @Test fun `it will throw an exception for session certificate cluster key where the member can not be found`() { whenever(key.category).doReturn(CryptoConsts.Categories.SESSION_INIT) whenever(virtualNodeInfoReadService.getAll()).doReturn(emptyList()) whenever(cryptoOpsClient.lookup(P2P, listOf(keyId))).doReturn(listOf(key)) assertThrows<InvalidInputDataException> { certificatesOps.generateCsr( P2P, keyId, "O=Alice, L=LDN, C=GB", null, emptyMap(), ) } } @Test fun `it will generate CSR for session certificate cluster key where the member can be found`() { whenever(key.category).doReturn(CryptoConsts.Categories.SESSION_INIT) val nodeHoldingIdentity = mock<HoldingIdentity> { on { x500Name } doReturn MemberX500Name.parse("O=Alice, L=LDN, C=GB") } val nodeInfo = mock<VirtualNodeInfo> { on { holdingIdentity } doReturn nodeHoldingIdentity } whenever(virtualNodeInfoReadService.getAll()).doReturn(listOf(nodeInfo)) whenever( cryptoOpsClient.sign( eq(P2P), eq(publicKey), any<SignatureSpec>(), any(), eq(emptyMap()) ) ).doReturn( DigitalSignature.WithKey( publicKey, byteArrayOf(1), emptyMap() ) ) whenever(cryptoOpsClient.lookup(P2P, listOf(keyId))).doReturn(listOf(key)) val csr = certificatesOps.generateCsr( P2P, keyId, nodeHoldingIdentity.x500Name.toString(), null, emptyMap(), ) assertThat(csr).isNotNull } @Test fun `it will generate CSR for session certificate member key where the member name is correct`() { whenever(key.category).doReturn(CryptoConsts.Categories.SESSION_INIT) val tenantId = "123123123123" val nodeHoldingIdentity = mock<HoldingIdentity> { on { x500Name } doReturn MemberX500Name.parse("O=Alice, L=LDN, C=GB") } val nodeInfo = mock<VirtualNodeInfo> { on { holdingIdentity } doReturn nodeHoldingIdentity } whenever( virtualNodeInfoReadService.getByHoldingIdentityShortHash( ShortHash.of(tenantId) ) ).doReturn(nodeInfo) whenever( cryptoOpsClient.sign( eq(tenantId), eq(publicKey), any<SignatureSpec>(), any(), eq(emptyMap()) ) ).doReturn( DigitalSignature.WithKey( publicKey, byteArrayOf(1), emptyMap() ) ) whenever(cryptoOpsClient.lookup(tenantId, listOf(keyId))).doReturn(listOf(key)) val csr = certificatesOps.generateCsr( tenantId, keyId, nodeHoldingIdentity.x500Name.toString(), null, emptyMap(), ) assertThat(csr).isNotNull } @Test fun `it will throw an exception for session certificate member key where the member name is not correct`() { whenever(key.category).doReturn(CryptoConsts.Categories.SESSION_INIT) val tenantId = "123123123123" val nodeHoldingIdentity = mock<HoldingIdentity> { on { x500Name } doReturn MemberX500Name.parse("O=Alice, L=LDN, C=GB") } val nodeInfo = mock<VirtualNodeInfo> { on { holdingIdentity } doReturn nodeHoldingIdentity } whenever( virtualNodeInfoReadService.getByHoldingIdentityShortHash( ShortHash.of(tenantId) ) ).doReturn(nodeInfo) whenever( cryptoOpsClient.sign( eq(tenantId), eq(publicKey), any<SignatureSpec>(), any(), eq(emptyMap()) ) ).doReturn( DigitalSignature.WithKey( publicKey, byteArrayOf(1), emptyMap() ) ) whenever(cryptoOpsClient.lookup(tenantId, listOf(keyId))).doReturn(listOf(key)) assertThrows<InvalidInputDataException> { certificatesOps.generateCsr( tenantId, keyId, "O=Bob, L=LDN, C=GB", null, emptyMap(), ) } } @Test fun `it throws exception if Signature OID can not be inferred`() { assertThrows<ResourceNotFoundException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, mapOf(SIGNATURE_SPEC to "Nop") ) } } @Test fun `it throws exception if key code name is invalid`() { whenever(key.schemeCodeName).doReturn("Nop") assertThrows<ResourceNotFoundException> { certificatesOps.generateCsr( holdingIdentityShortHash, keyId, x500Name, null, null, ) } } private fun String.fromPem(): PKCS10CertificationRequest { return PEMParser(this.reader()).use { parser -> parser.readObject() as PKCS10CertificationRequest } } } @Nested inner class ImportCertificateChainTests { @Test fun `invalid certificate will throw an exception`() { val certificateText = "hello" val certificate = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } assertThrows<InvalidInputDataException> { certificatesOps.importCertificateChain("rpc-api-tls", null, "alias", listOf(certificate)) } } @Test fun `valid certificate will send it to the client`() { val certificateText = ClassLoader.getSystemResource("r3.pem").readText() val certificate = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } certificatesOps.importCertificateChain("p2p-tls", null, "alias", listOf(certificate)) verify(certificatesClient).importCertificates(CertificateUsage.P2P_TLS, null, "alias", certificateText) } @Test fun `holding id will be translate to short hash`() { val certificateText = ClassLoader.getSystemResource("r3.pem").readText() val certificate = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } certificatesOps.importCertificateChain("p2p-tls", "123123123123", "alias", listOf(certificate)) verify(certificatesClient).importCertificates( CertificateUsage.P2P_TLS, ShortHash.of("123123123123"), "alias", certificateText ) } @Test fun `invalid usage will throw an exception`() { val certificateText = ClassLoader.getSystemResource("r3.pem").readText() val certificate = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } assertThrows<InvalidInputDataException> { certificatesOps.importCertificateChain("nop", "123123123123", "alias", listOf(certificate)) } } @Test fun `no certificates throws an exception`() { assertThrows<InvalidInputDataException> { certificatesOps.importCertificateChain("rpc-api-tls", null, "alias", emptyList()) } } @Test fun `empty alias throws an exception`() { val certificateText = ClassLoader.getSystemResource("r3.pem").readText() val certificate = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } val details = assertThrows<InvalidInputDataException> { certificatesOps.importCertificateChain("rpc-api-tls", null, "", listOf(certificate)) }.details assertThat(details).containsKey("alias") } @Test fun `valid multiple certificate will send all to the client`() { val certificateText = ClassLoader.getSystemResource("r3.pem").readText() val certificate1 = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } val certificate2 = mock<HttpFileUpload> { on { content } doReturn ("$certificateText\n$certificateText").byteInputStream() } certificatesOps.importCertificateChain("rpc-api-tls", null, "alias", listOf(certificate1, certificate2)) verify(certificatesClient).importCertificates( CertificateUsage.RPC_API_TLS, null, "alias", "$certificateText\n$certificateText\n$certificateText" ) } @Test fun `repartition event during operation throws ServiceUnavailableException`() { val certificateText = ClassLoader.getSystemResource("r3.pem").readText() val certificate = mock<HttpFileUpload> { on { content } doReturn certificateText.byteInputStream() } whenever(certificatesClient.importCertificates(CertificateUsage.P2P_TLS, null, "alias", certificateText)) .doThrow(CordaRPCAPIPartitionException("repartition event")) val details = assertThrows<ServiceUnavailableException> { certificatesOps.importCertificateChain("p2p-tls", null, "alias", listOf(certificate)) } assertThat(details.message).isEqualTo("Could not import certificate: Repartition Event!") } } @Nested inner class GetCertificateAliasesTests { @Test fun `it throws exception for invalid short hash`() { assertThrows<BadRequestException> { certificatesOps.getCertificateAliases( CertificateUsage.RPC_API_TLS.publicName, "nop" ) } } @Test fun `it throws exception for bad usage`() { assertThrows<InvalidInputDataException> { certificatesOps.getCertificateAliases( "nop", "012301230123" ) } } @Test fun `it calls the client with the correct arguments`() { whenever(certificatesClient.getCertificateAliases(any(), any())).doReturn(emptyList()) certificatesOps.getCertificateAliases( CertificateUsage.RPC_API_TLS.publicName, "012301230123", ) verify(certificatesClient).getCertificateAliases( CertificateUsage.RPC_API_TLS, ShortHash.of("012301230123") ) } @Test fun `it return the correct data`() { whenever(certificatesClient.getCertificateAliases(any(), anyOrNull())).doReturn(listOf("one", "two")) val aliases = certificatesOps.getCertificateAliases( CertificateUsage.RPC_API_TLS.publicName, null, ) assertThat(aliases).containsExactlyInAnyOrder("one", "two") } @Test fun `it throws an exception if the request fails`() { whenever(certificatesClient.getCertificateAliases(any(), any())).doThrow(CordaRuntimeException("Ooops")) assertThrows<InternalServerException> { certificatesOps.getCertificateAliases( CertificateUsage.RPC_API_TLS.publicName, "012301230123", ) } } @Test fun `it throws an exception if repartition event occurs while waiting for response`() { whenever(certificatesClient.getCertificateAliases(any(), any())).doThrow(CordaRPCAPIPartitionException("repartition")) val details = assertThrows<ServiceUnavailableException> { certificatesOps.getCertificateAliases( CertificateUsage.RPC_API_TLS.publicName, "012301230123", ) } assertThat(details.message).isEqualTo("Could not get certificate aliases: Repartition Event!") } } @Nested inner class GetCertificateChainTests { @Test fun `it throws an exception for empty alias`() { assertThrows<InvalidInputDataException> { certificatesOps.getCertificateChain( CertificateUsage.RPC_API_TLS.publicName, null, " " ) } } @Test fun `it throws an exception for invalid holding ID`() { assertThrows<BadRequestException> { certificatesOps.getCertificateChain( CertificateUsage.RPC_API_TLS.publicName, " ", "alias" ) } } @Test fun `it throws an exception for invalid usage`() { assertThrows<InvalidInputDataException> { certificatesOps.getCertificateChain( "nop", null, "alias" ) } } @Test fun `it throws an exception if alias can not be found`() { whenever(certificatesClient.retrieveCertificates(null, CertificateUsage.RPC_API_TLS, "alias")).doReturn(null) assertThrows<ResourceNotFoundException> { certificatesOps.getCertificateChain( CertificateUsage.RPC_API_TLS.publicName, null, "alias" ) } } @Test fun `it return the correct data if the alias was found`() { val hash = "321432143214" val usage = CertificateUsage.P2P_SESSION val pemCertificate = "yep" val alias = "alias" whenever(certificatesClient.retrieveCertificates(ShortHash.of(hash), usage, alias)).doReturn(pemCertificate) val certificate = certificatesOps.getCertificateChain( usage.publicName, hash, alias, ) assertThat(certificate).isEqualTo(pemCertificate) } @Test fun `it throws an exception if the client had an error`() { whenever( certificatesClient.retrieveCertificates(null, CertificateUsage.P2P_SESSION, "alias") ).doThrow(CordaRuntimeException("Ooops")) assertThrows<InternalServerException> { certificatesOps.getCertificateChain( CertificateUsage.P2P_SESSION.publicName, null, "alias", ) } } @Test fun `it throws an exception if repartition event occurs while waiting for response`() { whenever(certificatesClient.retrieveCertificates(null, CertificateUsage.P2P_SESSION, "alias")) .doThrow(CordaRPCAPIPartitionException("repartition")) val details = assertThrows<ServiceUnavailableException> { certificatesOps.getCertificateChain( CertificateUsage.P2P_SESSION.publicName, null, "alias", ) } assertThat(details.message).isEqualTo("Could not get certificate chain: Repartition Event!") } } }
82
Kotlin
7
24
17f5d2e5585a8ac56e559d1c099eaee414e6ec5a
29,078
corda-runtime-os
Apache License 2.0
app/src/main/java/com/lucianbc/receiptscan/domain/extract/Scannable.kt
lucianbc
183,749,890
false
null
package com.lucianbc.receiptscan.domain.extract import android.graphics.Bitmap import io.reactivex.Observable interface Scannable { fun ocrElements(): Observable<OcrElements> fun image(): Observable<Bitmap> }
13
null
1
2
05950c87f2eda6f53f886e340459aa13cdbdd621
218
ReceiptScan
Apache License 2.0
html/src/main/java/rikka.html/text/HtmlCompat.kt
An0nYm0u5101
261,490,724
true
{"Java Properties": 2, "Gradle": 15, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 11, "Git Config": 1, "INI": 6, "Java": 196, "Proguard": 10, "XML": 389, "Kotlin": 29, "AIDL": 1, "Soong": 1}
@file:Suppress("unused") package rikka.html.text import android.text.Spanned fun CharSequence.toHtml(flags: Int = 0): Spanned { return HtmlCompat.fromHtml(this.toString(), flags) }
0
null
0
0
0d61dc24364df25d5c4665427fa24831e0e251b6
187
libraries
MIT License
ktaf/src/test/kotlin/com/github/benpollarduk/ktaf/command/conversation/NextTest.kt
benpollarduk
696,256,399
false
{"Kotlin": 526799, "JavaScript": 486, "HTML": 346, "CSS": 343}
package com.github.benpollarduk.ktaf.command.conversation import com.github.benpollarduk.ktaf.assets.characters.NonPlayableCharacter import com.github.benpollarduk.ktaf.assets.interaction.ReactionResult import com.github.benpollarduk.ktaf.commands.conversation.Next import com.github.benpollarduk.ktaf.logic.GameTestHelper import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class NextTest { @Test fun `given no converser when invoke then return error`() { // Given val command = Next() // When val result = command.invoke(GameTestHelper.getBlankGame()) // Then Assertions.assertEquals(ReactionResult.ERROR, result.result) } @Test fun `given converser when invoke then return internal`() { // Given val command = Next() val game = GameTestHelper.getBlankGame() game.startConversation(NonPlayableCharacter("", "")) // When val result = command.invoke(game) // Then Assertions.assertEquals(ReactionResult.INTERNAL, result.result) } }
0
Kotlin
0
9
b892bacb2a877b58a2192b7d01a7ee22aff9c5de
1,097
ktaf
MIT License
sentry/src/test/java/io/sentry/BaggageTest.kt
getsentry
3,368,190
false
null
package io.sentry import com.github.javafaker.Faker import io.sentry.Baggage.MAX_BAGGAGE_LIST_MEMBER_COUNT import io.sentry.Baggage.MAX_BAGGAGE_STRING_LENGTH import io.sentry.protocol.SentryId import java.util.UUID import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class BaggageTest { lateinit var logger: ILogger @BeforeTest fun setup() { logger = NoOpLogger.getInstance() } @Test fun `can parse single baggage string with white spaces in it`() { val baggage = Baggage.fromHeader("sentry-userId = alice , sentry-serverNode = DF%2028,sentry-isProduction=false", false, logger) assertEquals("alice", baggage.get("sentry-userId")) assertEquals("DF 28", baggage.get("sentry-serverNode")) assertEquals("false", baggage.get("sentry-isProduction")) assertEquals("sentry-isProduction=false,sentry-serverNode=DF%2028,sentry-userId=alice", baggage.toHeaderString(null)) } @Test fun `retain single third party baggage string`() { val baggage = Baggage.fromHeader("userId=alice,serverNode=DF%2028,isProduction=false", true, logger) assertEquals("userId=alice,serverNode=DF%2028,isProduction=false", baggage.toHeaderString(baggage.getThirdPartyHeader())) } @Test fun `sentry values in third party baggage string are removed`() { val baggage = Baggage.fromHeader("userId=alice,sentry-thirdParty=thirdPartyValue,serverNode=DF%2028,isProduction=false", true, logger) assertEquals("userId=alice,serverNode=DF%2028,isProduction=false", baggage.getThirdPartyHeader()) } @Test fun `third party headers are dropped if not specified to keep`() { val baggage = Baggage.fromHeader("userId=alice,sentry-serverNode=DF%2028,isProduction=false", logger) assertEquals("sentry-serverNode=DF%2028", baggage.toHeaderString(null)) } @Test fun `multiple baggage headers are merged into one, third party headers are dropped`() { val headerValues = listOf( "userId=alice,sentry-serverNode=DF%2028,isProduction=false", "sentry-environment=production, os=android", "trace=123456, isSampled=true" ) val baggage = Baggage.fromHeader(headerValues, logger) assertEquals("sentry-environment=production,sentry-serverNode=DF%2028", baggage.toHeaderString(null)) } @Test fun `sentry entries are stripped from third party headers and saved in original order`() { val headerValues = listOf( "userId=alice,sentry-serverNode=DF%2028,isProduction=false", "sentry-environment=production, os=android", "trace=123456, isSampled=true" ) val baggage = Baggage.fromHeader(headerValues, true, logger) assertEquals("userId=alice,isProduction=false,os=android,trace=123456,isSampled=true", baggage.thirdPartyHeader) } @Test fun `when merging incoming and thirdparty baggages, sentry values are appended at the end`() { val headerValues = listOf( "userId=alice,sentry-serverNode=DF%2028,isProduction=false", "sentry-environment=production, os=android", "trace=123456, isSampled=true" ) val baggage = Baggage.fromHeader(headerValues, false, logger) val thirdPartyBaggage = Baggage.fromHeader(headerValues, true, logger) assertEquals("userId=alice,isProduction=false,os=android,trace=123456,isSampled=true,sentry-environment=production,sentry-serverNode=DF%2028", baggage.toHeaderString(thirdPartyBaggage.thirdPartyHeader)) } @Test fun `when merging and thirdparty headers already use up the available space, sentry values are not added`() { val largeThirdPartyHeaderValue = Faker.instance().random().hex(MAX_BAGGAGE_STRING_LENGTH - 16 - 12 - 1) // 8192 - "large-value=" - "otherValue=value" - "," val incomingHeaderValues = listOf( "userId=alice,sentry-serverNode=DF%2028,isProduction=false", "sentry-environment=production, os=android", "trace=123456, isSampled=true" ) val thirdPartyHeaderValues = "large-value=$largeThirdPartyHeaderValue, otherValue=value" val baggage = Baggage.fromHeader(incomingHeaderValues, false, logger) val thirdPartyBaggage = Baggage.fromHeader(thirdPartyHeaderValues, true, logger) val headerString = baggage.toHeaderString(thirdPartyBaggage.thirdPartyHeader) assertEquals(MAX_BAGGAGE_STRING_LENGTH, headerString.length) assertEquals("large-value=$largeThirdPartyHeaderValue,otherValue=value", headerString) } @Test fun `when merging third party baggage is kept even if it exceeds the allowed max length`() { val largeThirdPartyHeaderValue = Faker.instance().random().hex(MAX_BAGGAGE_STRING_LENGTH) val headerValues = listOf( "userId=alice,sentry-serverNode=DF%2028,isProduction=false", "sentry-environment=production, os=android", "trace=123456, isSampled=true" ) val baggage = Baggage.fromHeader(headerValues, false, logger) val thirdPartyBaggage = Baggage.fromHeader("largeHeader=$largeThirdPartyHeaderValue", true, logger) val headerString = baggage.toHeaderString(thirdPartyBaggage.thirdPartyHeader) assertEquals(MAX_BAGGAGE_STRING_LENGTH + 12, headerString.length) assertEquals("largeHeader=$largeThirdPartyHeaderValue", headerString) } @Test fun `exceeding entry limit causes values to be dropped`() { val baggage = Baggage(logger) val expectedItems = mutableListOf<String>() for (i in 1..100) { val key = 100 + i baggage.set("a$key", "$i") if (i <= MAX_BAGGAGE_LIST_MEMBER_COUNT) { expectedItems.add("a$key=$i") } } val expectedHeaderString = expectedItems.joinToString(",") assertEquals(expectedHeaderString, baggage.toHeaderString(null)) } @Test fun `if third party header exceeds entry limit, sentry headers are not added`() { val baggage = Baggage(logger) baggage.set("sentry-one", "value1") baggage.set("sentry-two", "value2") val thirdPartyItems = mutableListOf<String>() for (i in 1..70) { val key = 70 + i thirdPartyItems.add("a$key=$i") } val thirdPartyHeaderString = thirdPartyItems.joinToString(",") assertEquals(thirdPartyHeaderString, baggage.toHeaderString(thirdPartyHeaderString)) } @Test fun `if third party header is close to entry limit only some sentry headers are added`() { val baggage = Baggage(logger) baggage.set("sentry-one", "value1") baggage.set("sentry-two", "value2") val thirdPartyItems = mutableListOf<String>() for (i in 1..63) { val key = 63 + i thirdPartyItems.add("a$key=$i") } val thirdPartyHeaderString = thirdPartyItems.joinToString(",") val expectedHeaderString = "$thirdPartyHeaderString,sentry-one=value1" assertEquals(expectedHeaderString, baggage.toHeaderString(thirdPartyHeaderString)) } @Test fun `keys are encoded and decoded as well`() { val baggage = Baggage.fromHeader("sentry-user%2Bid=alice,sentry-server%2Bnode=DF%2028,sentry-is%2Bproduction=false", logger) assertEquals("alice", baggage.get("sentry-user+id")) assertEquals("DF 28", baggage.get("sentry-server+node")) assertEquals("false", baggage.get("sentry-is+production")) assertEquals("sentry-is%2Bproduction=false,sentry-server%2Bnode=DF%2028,sentry-user%2Bid=alice", baggage.toHeaderString(null)) } @Test fun `can parse multiple baggage strings`() { val baggage = Baggage.fromHeader( listOf( "sentry-userId=alice", "sentry-serverNode=DF%2028,sentry-isProduction=false" ), logger ) assertEquals("alice", baggage.get("sentry-userId")) assertEquals("DF 28", baggage.get("sentry-serverNode")) assertEquals("false", baggage.get("sentry-isProduction")) assertEquals("sentry-isProduction=false,sentry-serverNode=DF%2028,sentry-userId=alice", baggage.toHeaderString(null)) } @Test fun `can parse multiple baggage strings with white spaces`() { val baggage = Baggage.fromHeader( listOf( "sentry-userId = alice", "sentry-serverNode = DF%2028, sentry-isProduction = false" ), logger ) assertEquals("alice", baggage.get("sentry-userId")) assertEquals("DF 28", baggage.get("sentry-serverNode")) assertEquals("false", baggage.get("sentry-isProduction")) assertEquals("sentry-isProduction=false,sentry-serverNode=DF%2028,sentry-userId=alice", baggage.toHeaderString(null)) } @Test fun `can parse null baggage string`() { val nothing: String? = null val baggage = Baggage.fromHeader(nothing, logger) assertEquals("", baggage.toHeaderString(null)) } @Test fun `can parse blank baggage string`() { val baggage = Baggage.fromHeader("", logger) assertEquals("", baggage.toHeaderString(null)) } @Test fun `can parse whitespace only baggage string`() { val baggage = Baggage.fromHeader(" ", logger) assertEquals("", baggage.toHeaderString(null)) } @Test fun `can parse whitespace only baggage strings`() { val baggage = Baggage.fromHeader(listOf(" ", " "), logger) assertEquals("", baggage.toHeaderString(null)) } @Test fun `single large value is dropped and small values are kept`() { val largeValue = Faker.instance().random().hex(8193) val baggage = Baggage.fromHeader("sentry-smallValue=remains,sentry-largeValue=$largeValue,sentry-otherValue=kept", logger) assertEquals("remains", baggage.get("sentry-smallValue")) assertNotNull(baggage.get("sentry-largeValue")) assertEquals("kept", baggage.get("sentry-otherValue")) assertEquals("sentry-otherValue=kept,sentry-smallValue=remains", baggage.toHeaderString(null)) } @Test fun `medium size value can cause small values to be dropped`() { val mediumValue = Faker.instance().random().hex(MAX_BAGGAGE_STRING_LENGTH - 19 - 22 - 1) // 8192 - "sentry-mediumValue=" - "sentry-otherValue=kept" - "," val baggage = Baggage.fromHeader("sentry-mediumValue=$mediumValue,sentry-smallValue=removed,sentry-otherValue=kept", logger) assertEquals("removed", baggage.get("sentry-smallValue")) assertEquals(mediumValue, baggage.get("sentry-mediumValue")) assertEquals("kept", baggage.get("sentry-otherValue")) val headerString = baggage.toHeaderString(null) assertEquals(MAX_BAGGAGE_STRING_LENGTH, headerString.length) assertEquals("sentry-mediumValue=$mediumValue,sentry-otherValue=kept", headerString) } @Test fun `medium size value can cause all values to be dropped`() { // nothing else will fit after mediumValue as the separator + any key/value would exceed the limit val mediumValue = Faker.instance().random().hex(MAX_BAGGAGE_STRING_LENGTH - 19 - 22) // 8192 - "sentry-mediumValue=" - "sentry-otherValue=lost" val baggage = Baggage.fromHeader("sentry-mediumValue=$mediumValue,sentry-smallValue=stripped,sentry-otherValue=lost", logger) assertEquals("stripped", baggage.get("sentry-smallValue")) assertEquals(mediumValue, baggage.get("sentry-mediumValue")) assertEquals("lost", baggage.get("sentry-otherValue")) val headerString = baggage.toHeaderString(null) assertEquals(8170, headerString.length) assertEquals("sentry-mediumValue=$mediumValue", headerString) } @Test fun `null value is omitted from header string`() { val baggage = Baggage(logger) baggage.traceId = null baggage.publicKey = null baggage.release = null baggage.environment = null baggage.transaction = null baggage.userId = null baggage.userSegment = null assertEquals("", baggage.toHeaderString(null)) } @Test fun `can set values from trace context`() { val baggage = Baggage(logger) val publicKey = Dsn(dsnString).publicKey val traceId = SentryId().toString() val userId = UUID.randomUUID().toString() baggage.setTraceId(traceId) baggage.setPublicKey(publicKey) baggage.setRelease("1.0-rc.1") baggage.setEnvironment("production") baggage.setTransaction("TX") baggage.setUserId(userId) baggage.setUserSegment("segmentA") baggage.setSampleRate((1.0 / 3.0).toString()) assertEquals("sentry-environment=production,sentry-public_key=$publicKey,sentry-release=1.0-rc.1,sentry-sample_rate=0.3333333333333333,sentry-trace_id=$traceId,sentry-transaction=TX,sentry-user_id=$userId,sentry-user_segment=segmentA", baggage.toHeaderString(null)) } @Test fun `duplicate entries are lost`() { val baggage = Baggage.fromHeader("sentry-duplicate=a,sentry-duplicate=b", logger) assertEquals("sentry-duplicate=b", baggage.toHeaderString(null)) } @Test fun `setting a value multiple times only keeps the last`() { val baggage = Baggage.fromHeader("", logger) baggage.traceId = "a" baggage.traceId = "b" baggage.traceId = "c" assertEquals("sentry-trace_id=c", baggage.toHeaderString(null)) } @Test fun `setting values if header contains sentry values has no effect`() { val baggage = Baggage.fromHeader("sentry-trace_id=a,sentry-transaction=sentryTransaction", logger) baggage.traceId = "b" baggage.traceId = "c" baggage.transaction = "newTransaction" baggage.environment = "production" assertEquals("sentry-trace_id=a,sentry-transaction=sentryTransaction", baggage.toHeaderString(null)) } @Test fun `value may contain = sign`() { val baggage = Baggage(logger) baggage.setTransaction("a=b") assertEquals("sentry-transaction=a%3Db", baggage.toHeaderString(null)) } @Test fun `corrupted string does not throw out`() { val baggage = Baggage.fromHeader("a", logger) assertEquals("", baggage.toHeaderString(null)) } @Test fun `corrupted string does not throw out 2`() { val baggage = Baggage.fromHeader("a=b=", logger) assertEquals("", baggage.toHeaderString(null)) } @Test fun `corrupted string can be parsed partially`() { val baggage = Baggage.fromHeader("sentry-a=value,sentry-b", logger) assertEquals("sentry-a=value", baggage.toHeaderString(null)) } @Test fun `baggage value encoding`() { // keep baggage-octet: %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E val values = percentEncodedValues().also { /* some characters have been commented out * as per baggage specification we are allowed to encode these * and java.net.URLEncoder encodes them by default */ // it["!"] = "!" // instead of %21 // it["#"] = "#" // instead of %23 // it["$"] = "$" // instead of %24 // it["%"] = "%" // instead of %25 // it["&"] = "&" // instead of %26 // it["'"] = "'" // instead of %27 // it["("] = "(" // instead of %28 // it[")"] = ")" // instead of %29 it["*"] = "*" // instead of %2A // it["+"] = "+" // instead of %2B it["-"] = "-" // instead of %2D it["."] = "." // instead of %2E // it["/"] = "/" // instead of %2F it["0"] = "0" // instead of %30 it["1"] = "1" // instead of %31 it["2"] = "2" // instead of %32 it["3"] = "3" // instead of %33 it["4"] = "4" // instead of %34 it["5"] = "5" // instead of %35 it["6"] = "6" // instead of %36 it["7"] = "7" // instead of %37 it["8"] = "8" // instead of %38 it["9"] = "9" // instead of %39 // it[":"] = ":" // instead of %3A // it["<"] = "<" // instead of %3C // it["="] = "=" // instead of %3D // it[">"] = ">" // instead of %3E // it["?"] = "?" // instead of %3F // it["@"] = "@" // instead of %40 it["A"] = "A" // instead of %41 it["B"] = "B" // instead of %42 it["C"] = "C" // instead of %43 it["D"] = "D" // instead of %44 it["E"] = "E" // instead of %45 it["F"] = "F" // instead of %46 it["G"] = "G" // instead of %47 it["H"] = "H" // instead of %48 it["I"] = "I" // instead of %49 it["J"] = "J" // instead of %4A it["K"] = "K" // instead of %4B it["L"] = "L" // instead of %4C it["M"] = "M" // instead of %4D it["N"] = "N" // instead of %4E it["O"] = "O" // instead of %4F it["P"] = "P" // instead of %50 it["Q"] = "Q" // instead of %51 it["R"] = "R" // instead of %52 it["S"] = "S" // instead of %53 it["T"] = "T" // instead of %54 it["U"] = "U" // instead of %55 it["V"] = "V" // instead of %56 it["W"] = "W" // instead of %57 it["X"] = "X" // instead of %58 it["Y"] = "Y" // instead of %59 it["Z"] = "Z" // instead of %5A // it["["] = "[" // instead of %5B // it["]"] = "]" // instead of %5D // it["^"] = "^" // instead of %5E it["_"] = "_" // instead of %5F // it["`"] = "`" // instead of %60 it["a"] = "a" // instead of %61 it["b"] = "b" // instead of %62 it["c"] = "c" // instead of %63 it["d"] = "d" // instead of %64 it["e"] = "e" // instead of %65 it["f"] = "f" // instead of %66 it["g"] = "g" // instead of %67 it["h"] = "h" // instead of %68 it["i"] = "i" // instead of %69 it["j"] = "j" // instead of %6A it["k"] = "k" // instead of %6B it["l"] = "l" // instead of %6C it["m"] = "m" // instead of %6D it["n"] = "n" // instead of %6E it["o"] = "o" // instead of %6F it["p"] = "p" // instead of %70 it["q"] = "q" // instead of %71 it["r"] = "r" // instead of %72 it["s"] = "s" // instead of %73 it["t"] = "t" // instead of %74 it["u"] = "u" // instead of %75 it["v"] = "v" // instead of %76 it["w"] = "w" // instead of %77 it["x"] = "x" // instead of %78 it["y"] = "y" // instead of %79 it["z"] = "z" // instead of %7A } val failures = mutableListOf<String>() values.forEach { key, value -> val baggage = Baggage(logger) baggage.setTransaction(key) val headerString = baggage.toHeaderString(null) if ("sentry-transaction=$value" != headerString) { failures.add("$key should be $value but was >$headerString<") } val decodedBaggage = Baggage.fromHeader(headerString, logger) decodedBaggage.get("sentry-transaction") } assertTrue(failures.joinToString("\n")) { failures.isEmpty() } } @Test fun `all characters defined as valid for keys can be used`() { val baggage = Baggage(logger) val key = "sentry-" + validTokenCharacters().joinToString("") baggage.set(key, "value") val reparsedBaggage = Baggage.fromHeader(baggage.toHeaderString(null), logger) assertEquals("value", reparsedBaggage.get(key)) } @Test fun `baggage key replaces invalid characters`() { val baggage = Baggage(logger) baggage.set(invalidTokenCharacters().joinToString(""), "value") assertEquals("%22%28%29%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%7B%7D=value", baggage.toHeaderString(null)) } @Test fun `can skip logger for header from single string`() { val baggage = Baggage.fromHeader("sentry-trace_id=a,sentry-transaction=sentryTransaction") assertEquals("sentry-trace_id=a,sentry-transaction=sentryTransaction", baggage.toHeaderString(null)) } @Test fun `can skip logger for header from list of strings`() { val baggage = Baggage.fromHeader(listOf("sentry-trace_id=a", "sentry-transaction=sentryTransaction")) assertEquals("sentry-trace_id=a,sentry-transaction=sentryTransaction", baggage.toHeaderString(null)) } /** * token = 1*tchar * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" * / DIGIT / ALPHA * ; any VCHAR, except delimiters */ private fun validTokenCharacters() = mutableListOf( "!", "#", "$", "%", "&", "'", "*", "+", "-", ".", "^", "_", "`", "|", "~", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ) private fun invalidTokenCharacters() = mutableListOf( "\"", "(", ")", ",", "/", ":", ";", "<", "=", ">", "?", "@", "[", "\\", "]", "{", "}" ) private fun percentEncodedValues() = mutableMapOf( " " to "%20", "!" to "%21", "\"" to "%22", "#" to "%23", "$" to "%24", "%" to "%25", "&" to "%26", "'" to "%27", "(" to "%28", ")" to "%29", "*" to "%2A", "+" to "%2B", "," to "%2C", "-" to "%2D", "." to "%2E", "/" to "%2F", "0" to "%30", "1" to "%31", "2" to "%32", "3" to "%33", "4" to "%34", "5" to "%35", "6" to "%36", "7" to "%37", "8" to "%38", "9" to "%39", ":" to "%3A", ";" to "%3B", "<" to "%3C", "=" to "%3D", ">" to "%3E", "?" to "%3F", "@" to "%40", "A" to "%41", "B" to "%42", "C" to "%43", "D" to "%44", "E" to "%45", "F" to "%46", "G" to "%47", "H" to "%48", "I" to "%49", "J" to "%4A", "K" to "%4B", "L" to "%4C", "M" to "%4D", "N" to "%4E", "O" to "%4F", "P" to "%50", "Q" to "%51", "R" to "%52", "S" to "%53", "T" to "%54", "U" to "%55", "V" to "%56", "W" to "%57", "X" to "%58", "Y" to "%59", "Z" to "%5A", "[" to "%5B", "\\" to "%5C", "]" to "%5D", "^" to "%5E", "_" to "%5F", "`" to "%60", "a" to "%61", "b" to "%62", "c" to "%63", "d" to "%64", "e" to "%65", "f" to "%66", "g" to "%67", "h" to "%68", "i" to "%69", "j" to "%6A", "k" to "%6B", "l" to "%6C", "m" to "%6D", "n" to "%6E", "o" to "%6F", "p" to "%70", "q" to "%71", "r" to "%72", "s" to "%73", "t" to "%74", "u" to "%75", "v" to "%76", "w" to "%77", "x" to "%78", "y" to "%79", "z" to "%7A", "{" to "%7B", "|" to "%7C", "}" to "%7D", "~" to "%7E", "\u007F" to "%7F", "€" to "%E2%82%AC", "" to "%C2%81", "‚" to "%E2%80%9A", "ƒ" to "%C6%92", "„" to "%E2%80%9E", "…" to "%E2%80%A6", "†" to "%E2%80%A0", "‡" to "%E2%80%A1", "ˆ" to "%CB%86", "‰" to "%E2%80%B0", "Š" to "%C5%A0", "‹" to "%E2%80%B9", "Œ" to "%C5%92", "" to "%C2%8D", "Ž" to "%C5%BD", "" to "%C2%8F", "" to "%C2%90", "‘" to "%E2%80%98", "’" to "%E2%80%99", "“" to "%E2%80%9C", "”" to "%E2%80%9D", "•" to "%E2%80%A2", "–" to "%E2%80%93", "—" to "%E2%80%94", "˜" to "%CB%9C", "™" to "%E2%84%A2", "š" to "%C5%A1", "›" to "%E2%80%BA", "œ" to "%C5%93", "" to "%C2%9D", "ž" to "%C5%BE", "Ÿ" to "%C5%B8", "\u00A0" to "%C2%A0", // nbsp "¡" to "%C2%A1", "¢" to "%C2%A2", "£" to "%C2%A3", "¤" to "%C2%A4", "¥" to "%C2%A5", "¦" to "%C2%A6", "§" to "%C2%A7", "¨" to "%C2%A8", "©" to "%C2%A9", "ª" to "%C2%AA", "«" to "%C2%AB", "¬" to "%C2%AC", "­" to "%C2%AD", "®" to "%C2%AE", "¯" to "%C2%AF", "°" to "%C2%B0", "±" to "%C2%B1", "²" to "%C2%B2", "³" to "%C2%B3", "´" to "%C2%B4", "µ" to "%C2%B5", "¶" to "%C2%B6", "·" to "%C2%B7", "¸" to "%C2%B8", "¹" to "%C2%B9", "º" to "%C2%BA", "»" to "%C2%BB", "¼" to "%C2%BC", "½" to "%C2%BD", "¾" to "%C2%BE", "¿" to "%C2%BF", "À" to "%C3%80", "Á" to "%C3%81", "Â" to "%C3%82", "Ã" to "%C3%83", "Ä" to "%C3%84", "Å" to "%C3%85", "Æ" to "%C3%86", "Ç" to "%C3%87", "È" to "%C3%88", "É" to "%C3%89", "Ê" to "%C3%8A", "Ë" to "%C3%8B", "Ì" to "%C3%8C", "Í" to "%C3%8D", "Î" to "%C3%8E", "Ï" to "%C3%8F", "Ð" to "%C3%90", "Ñ" to "%C3%91", "Ò" to "%C3%92", "Ó" to "%C3%93", "Ô" to "%C3%94", "Õ" to "%C3%95", "Ö" to "%C3%96", "×" to "%C3%97", "Ø" to "%C3%98", "Ù" to "%C3%99", "Ú" to "%C3%9A", "Û" to "%C3%9B", "Ü" to "%C3%9C", "Ý" to "%C3%9D", "Þ" to "%C3%9E", "ß" to "%C3%9F", "à" to "%C3%A0", "á" to "%C3%A1", "â" to "%C3%A2", "ã" to "%C3%A3", "ä" to "%C3%A4", "å" to "%C3%A5", "æ" to "%C3%A6", "ç" to "%C3%A7", "è" to "%C3%A8", "é" to "%C3%A9", "ê" to "%C3%AA", "ë" to "%C3%AB", "ì" to "%C3%AC", "í" to "%C3%AD", "î" to "%C3%AE", "ï" to "%C3%AF", "ð" to "%C3%B0", "ñ" to "%C3%B1", "ò" to "%C3%B2", "ó" to "%C3%B3", "ô" to "%C3%B4", "õ" to "%C3%B5", "ö" to "%C3%B6", "÷" to "%C3%B7", "ø" to "%C3%B8", "ù" to "%C3%B9", "ú" to "%C3%BA", "û" to "%C3%BB", "ü" to "%C3%BC", "ý" to "%C3%BD", "þ" to "%C3%BE", "ÿ" to "%C3%BF" ) }
300
Kotlin
435
995
549cbb4657b9dea1048c4882e79504e87d6acc4f
27,745
sentry-java
MIT License
src/main/kotlin/com/example/home/configuration/security/SecurityConfiguration.kt
Winnie-the-Pooh2019
730,062,537
false
{"Kotlin": 29973, "HTML": 17610, "Dockerfile": 194, "PLpgSQL": 177}
package com.example.home.configuration.security import com.example.home.service.HomeUserDetailsService import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.AuthenticationProvider import org.springframework.security.authentication.dao.DaoAuthenticationProvider import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter @Configuration @EnableWebSecurity @EnableMethodSecurity(prePostEnabled = true) class SecurityConfiguration( @Autowired private val userDetailsService: HomeUserDetailsService, @Autowired private val passwordEncoder: PasswordEncoder, @Autowired private val jwtAuthenticationFilter: JwtAuthenticationFilter ) { @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http.csrf { it.disable() } .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } .authorizeHttpRequests { it .requestMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() } .authenticationProvider(authenticationProvider()) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java) return http.build() } @Bean fun authenticationProvider(): AuthenticationProvider { val authProvider = DaoAuthenticationProvider() authProvider.setUserDetailsService(userDetailsService) authProvider.setPasswordEncoder(passwordEncoder) return authProvider } @Bean fun authenticationManager(config: AuthenticationConfiguration): AuthenticationManager { return config.authenticationManager } }
0
Kotlin
0
0
2d9b87827cd3935b39ef6a09c41fa8b097b6cbfa
2,535
home
MIT License
app/src/main/java/com/ateca/domain/core/SortType.kt
atecaorg
483,473,306
false
null
package com.ateca.domain.core /** * Created by dronpascal on 29.05.2022. */ sealed class SortType { object Created : SortType() object Modified : SortType() object Name : SortType() object Idle : SortType() }
1
Kotlin
0
3
aca913f87263d6eac4a8925c74e6e801729ba6bf
232
Ateca
Apache License 2.0
plugins/base/src/main/kotlin/renderers/html/htmlPreprocessors.kt
kamilok1965
171,309,084
false
null
package org.jetbrains.dokka.base.renderers.html import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.DokkaBaseConfiguration import org.jetbrains.dokka.base.renderers.sourceSets import org.jetbrains.dokka.model.DEnum import org.jetbrains.dokka.model.DEnumEntry import org.jetbrains.dokka.model.DFunction import org.jetbrains.dokka.model.withDescendants import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.configuration import org.jetbrains.dokka.transformers.pages.PageTransformer object NavigationPageInstaller : PageTransformer { private val mapper = jacksonObjectMapper() fun SearchRecord.Companion.from(node: NavigationNode, location: String): SearchRecord = SearchRecord(name = node.name, location = location) override fun invoke(input: RootPageNode): RootPageNode { val nodes = input.children.filterIsInstance<ContentPage>().single() .let(NavigationPageInstaller::visit) val page = RendererSpecificResourcePage( name = "scripts/navigation-pane.json", children = emptyList(), strategy = RenderingStrategy.LocationResolvableWrite { resolver -> mapper.writeValueAsString( nodes.withDescendants().map { SearchRecord.from(it, resolver(it.dri, it.sourceSets)) }) }) return input.modified( children = input.children + page + NavigationPage(nodes) ) } private fun visit(page: ContentPage): NavigationNode = NavigationNode( name = page.displayableName, dri = page.dri.first(), sourceSets = page.sourceSets(), children = page.navigableChildren() ) private fun ContentPage.navigableChildren(): List<NavigationNode> = when { this !is ClasslikePageNode -> children.filterIsInstance<ContentPage>().map { visit(it) } documentable is DEnum -> children.filter { it is ContentPage && it.documentable is DEnumEntry }.map { visit(it as ContentPage) } else -> emptyList() }.sortedBy { it.name.toLowerCase() } private val ContentPage.displayableName: String get() = if (documentable is DFunction) { "$name()" } else { name } } class CustomResourceInstaller(val dokkaContext: DokkaContext) : PageTransformer { private val configuration = configuration<DokkaBase, DokkaBaseConfiguration>(dokkaContext) private val customAssets = configuration?.customAssets?.map { RendererSpecificResourcePage("images/${it.name}", emptyList(), RenderingStrategy.Copy(it.absolutePath)) }.orEmpty() private val customStylesheets = configuration?.customStyleSheets?.map { RendererSpecificResourcePage("styles/${it.name}", emptyList(), RenderingStrategy.Copy(it.absolutePath)) }.orEmpty() override fun invoke(input: RootPageNode): RootPageNode { val customResourcesPaths = (customAssets + customStylesheets).map { it.name }.toSet() val withEmbeddedResources = input.transformContentPagesTree { it.modified(embeddedResources = it.embeddedResources + customResourcesPaths) } val (currentResources, otherPages) = withEmbeddedResources.children.partition { it is RendererSpecificResourcePage } return input.modified(children = otherPages + currentResources.filterNot { it.name in customResourcesPaths } + customAssets + customStylesheets) } } object ScriptsInstaller : PageTransformer { private val scriptsPages = listOf( "scripts/clipboard.js", "scripts/navigation-loader.js", "scripts/platform-content-handler.js", "scripts/main.js" ) override fun invoke(input: RootPageNode): RootPageNode { return input.modified( children = input.children + scriptsPages.toRenderSpecificResourcePage() ).transformContentPagesTree { it.modified( embeddedResources = it.embeddedResources + scriptsPages ) } } } object StylesInstaller : PageTransformer { private val stylesPages = listOf( "styles/style.css", "styles/logo-styles.css", "styles/jetbrains-mono.css", "styles/main.css" ) override fun invoke(input: RootPageNode): RootPageNode = input.modified( children = input.children + stylesPages.toRenderSpecificResourcePage() ).transformContentPagesTree { it.modified( embeddedResources = it.embeddedResources + stylesPages ) } } object AssetsInstaller : PageTransformer { private val imagesPages = listOf( "images/arrow_down.svg", "images/docs_logo.svg", "images/logo-icon.svg" ) override fun invoke(input: RootPageNode) = input.modified( children = input.children + imagesPages.toRenderSpecificResourcePage() ) } private fun List<String>.toRenderSpecificResourcePage(): List<RendererSpecificResourcePage> = map { RendererSpecificResourcePage(it, emptyList(), RenderingStrategy.Copy("/dokka/$it")) } class SourcesetDependencyAppender(val context: DokkaContext) : PageTransformer { private val name = "scripts/sourceset_dependencies.js" override fun invoke(input: RootPageNode): RootPageNode { val dependenciesMap = context.configuration.sourceSets.map { it.sourceSetID to it.dependentSourceSets }.toMap() fun createDependenciesJson(): String = "sourceset_dependencies = '{${ dependenciesMap.entries.joinToString(", ") { "\"${it.key}\": [${ it.value.joinToString(",") { "\"$it\"" } }]" } }}'" val deps = RendererSpecificResourcePage( name = name, children = emptyList(), strategy = RenderingStrategy.Write(createDependenciesJson()) ) return input.modified( children = input.children + deps ).transformContentPagesTree { it.modified(embeddedResources = it.embeddedResources + name) } } }
1
null
1
1
7c036dff0d40b1ea8bca8ee5aea5a211d4f090af
6,313
dokka
Apache License 2.0
geary-papermc-plugin/src/main/kotlin/com/mineinabyss/geary/papermc/plugin/commands/GearyStatsCommand.kt
MineInAbyss
592,086,123
false
{"Kotlin": 245944}
package com.mineinabyss.geary.papermc.plugin.commands import com.mineinabyss.geary.helpers.entity import com.mineinabyss.geary.modules.archetypes import com.mineinabyss.idofront.commands.Command import com.mineinabyss.idofront.messaging.info fun Command.stats() { "stats" { action { val tempEntity = entity() sender.info( """ |Archetype count: ${archetypes.queryManager.archetypeCount} |Next entity ID: ${tempEntity.id} |""".trimMargin() ) tempEntity.removeEntity() } } }
1
Kotlin
0
4
f765a15878512d314808f8622cd54dc85ed12beb
612
geary-papermc
MIT License
libraries/tools/kotlin-gradle-plugin-idea-proto/src/generated/kotlin/org/jetbrains/kotlin/gradle/idea/proto/generated/tcs/IdeaKotlinBinaryCoordinatesProtoKt.kt
JetBrains
3,432,266
false
null
//Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto_tcs.proto package org.jetbrains.kotlin.gradle.idea.proto.generated.tcs; @kotlin.jvm.JvmName("-initializeideaKotlinBinaryCoordinatesProto") inline fun ideaKotlinBinaryCoordinatesProto(block: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProtoKt.Dsl.() -> kotlin.Unit): org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto = org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProtoKt.Dsl._create(org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto.newBuilder()).apply { block() }._build() object IdeaKotlinBinaryCoordinatesProtoKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker class Dsl private constructor( private val _builder: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto.Builder ) { companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto = _builder.build() /** * <code>optional string group = 1;</code> */ var group: kotlin.String @JvmName("getGroup") get() = _builder.getGroup() @JvmName("setGroup") set(value) { _builder.setGroup(value) } /** * <code>optional string group = 1;</code> */ fun clearGroup() { _builder.clearGroup() } /** * <code>optional string group = 1;</code> * @return Whether the group field is set. */ fun hasGroup(): kotlin.Boolean { return _builder.hasGroup() } /** * <code>optional string module = 2;</code> */ var module: kotlin.String @JvmName("getModule") get() = _builder.getModule() @JvmName("setModule") set(value) { _builder.setModule(value) } /** * <code>optional string module = 2;</code> */ fun clearModule() { _builder.clearModule() } /** * <code>optional string module = 2;</code> * @return Whether the module field is set. */ fun hasModule(): kotlin.Boolean { return _builder.hasModule() } /** * <code>optional string version = 3;</code> */ var version: kotlin.String @JvmName("getVersion") get() = _builder.getVersion() @JvmName("setVersion") set(value) { _builder.setVersion(value) } /** * <code>optional string version = 3;</code> */ fun clearVersion() { _builder.clearVersion() } /** * <code>optional string version = 3;</code> * @return Whether the version field is set. */ fun hasVersion(): kotlin.Boolean { return _builder.hasVersion() } /** * <code>optional string source_set_name = 4;</code> */ var sourceSetName: kotlin.String @JvmName("getSourceSetName") get() = _builder.getSourceSetName() @JvmName("setSourceSetName") set(value) { _builder.setSourceSetName(value) } /** * <code>optional string source_set_name = 4;</code> */ fun clearSourceSetName() { _builder.clearSourceSetName() } /** * <code>optional string source_set_name = 4;</code> * @return Whether the sourceSetName field is set. */ fun hasSourceSetName(): kotlin.Boolean { return _builder.hasSourceSetName() } /** * An uninstantiable, behaviorless type to represent the field in * generics. */ @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) class CapabilitiesProxy private constructor() : com.google.protobuf.kotlin.DslProxy() /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> */ val capabilities: com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy> @kotlin.jvm.JvmSynthetic get() = com.google.protobuf.kotlin.DslList( _builder.getCapabilitiesList() ) /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> * @param value The capabilities to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("addCapabilities") fun com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy>.add(value: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto) { _builder.addCapabilities(value) } /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> * @param value The capabilities to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("plusAssignCapabilities") @Suppress("NOTHING_TO_INLINE") inline operator fun com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy>.plusAssign(value: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto) { add(value) } /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> * @param values The capabilities to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("addAllCapabilities") fun com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy>.addAll(values: kotlin.collections.Iterable<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto>) { _builder.addAllCapabilities(values) } /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> * @param values The capabilities to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("plusAssignAllCapabilities") @Suppress("NOTHING_TO_INLINE") inline operator fun com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy>.plusAssign(values: kotlin.collections.Iterable<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto>) { addAll(values) } /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> * @param index The index to set the value at. * @param value The capabilities to set. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("setCapabilities") operator fun com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy>.set(index: kotlin.Int, value: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto) { _builder.setCapabilities(index, value) } /** * <code>repeated .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto capabilities = 5;</code> */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("clearCapabilities") fun com.google.protobuf.kotlin.DslList<org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCapabilityProto, CapabilitiesProxy>.clear() { _builder.clearCapabilities() } /** * <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto attributes = 6;</code> */ var attributes: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto @JvmName("getAttributes") get() = _builder.getAttributes() @JvmName("setAttributes") set(value) { _builder.setAttributes(value) } /** * <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto attributes = 6;</code> */ fun clearAttributes() { _builder.clearAttributes() } /** * <code>optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto attributes = 6;</code> * @return Whether the attributes field is set. */ fun hasAttributes(): kotlin.Boolean { return _builder.hasAttributes() } val IdeaKotlinBinaryCoordinatesProtoKt.Dsl.attributesOrNull: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto? get() = _builder.attributesOrNull } } @kotlin.jvm.JvmSynthetic inline fun org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto.copy(block: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProtoKt.Dsl.() -> kotlin.Unit): org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProto = org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProtoKt.Dsl._create(this.toBuilder()).apply { block() }._build() val org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryCoordinatesProtoOrBuilder.attributesOrNull: org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinBinaryAttributesProto? get() = if (hasAttributes()) getAttributes() else null
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
9,827
kotlin
Apache License 2.0
wasi-emscripten-host/src/commonMain/kotlin/wasi/preview1/type/Rights.kt
illarionov
769,429,996
false
{"Kotlin": 1838071}
/* * Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ @file:Suppress("MagicNumber") package at.released.weh.wasi.preview1.type import at.released.weh.wasi.preview1.WasiTypename import at.released.weh.wasm.core.WasmValueType public data class Rights( public val mask: Long, ) { public constructor( vararg flags: Flags, ) : this( flags.fold(0L) { acc, flag -> acc.or(flag.mask) }, ) public enum class Flags( public val mask: Long, ) { /** * The right to invoke `fd_datasync`. * * If `path_open` is set, includes the right to invoke * `path_open` with `fdflags::dsync`. */ FD_DATASYNC(0), /** * The right to invoke `fd_read` and `sock_recv`. * * If `rights::fd_seek` is set, includes the right to invoke `fd_pread`. */ FD_READ(1), /** * The right to invoke `fd_seek`. This flag implies `rights::fd_tell`. */ FD_SEEK(2), /** * The right to invoke `fd_fdstat_set_flags` */ FD_FDSTAT_SET_FLAGS(3), /** * The right to invoke `fd_sync`. * * If `path_open` is set, includes the right to invoke * `path_open` with `fdflags::rsync` and `fdflags::dsync`. */ FD_SYNC(4), /** * The right to invoke `fd_seek` in such a way that the file offset * remains unaltered (i.e., `whence::cur` with offset zero), or to * invoke `fd_tell`. */ FD_TELL(5), /** * The right to invoke `fd_write` and `sock_send`. * * If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`. */ FD_WRITE(6), /** * The right to invoke `fd_advise`. */ FD_ADVISE(7), /** * The right to invoke `fd_allocate`. */ FD_ALLOCATE(8), /** * The right to invoke `path_create_directory`. */ PATH_CREATE_DIRECTORY(9), /** * If `path_open` is set, the right to invoke `path_open` with `oflags::creat`. */ PATH_CREATE_FILE(10), /** * The right to invoke `path_link` with the file descriptor as the * source directory. */ PATH_LINK_SOURCE(11), /** * The right to invoke `path_link` with the file descriptor as the * target directory. */ PATH_LINK_TARGET(12), /** * The right to invoke `path_open`. */ PATH_OPEN(13), /** * The right to invoke `fd_readdir`. */ FD_READDIR(14), /** * The right to invoke `path_readlink`. */ PATH_READLINK(15), /** * The right to invoke `path_rename` with the file descriptor as the source directory. */ PATH_RENAME_SOURCE(16), /** * The right to invoke `path_rename` with the file descriptor as the target directory. */ PATH_RENAME_TARGET(17), /** * The right to invoke `path_filestat_get`. */ PATH_FILESTAT_GET(18), /** * The right to change a file's size. * If `path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`. * Note: there is no function named `path_filestat_set_size`. This follows POSIX design, * which only has `ftruncate` and does not provide `ftruncateat`. * While such function would be desirable from the API design perspective, there are virtually * no use cases for it since no code written for POSIX systems would use it. * Moreover, implementing it would require multiple syscalls, leading to inferior performance. */ PATH_FILESTAT_SET_SIZE(19), /** * The right to invoke `path_filestat_set_times`. */ PATH_FILESTAT_SET_TIMES(20), /** * The right to invoke `fd_filestat_get`. */ FD_FILESTAT_GET(21), /** * The right to invoke `fd_filestat_set_size`. */ FD_FILESTAT_SET_SIZE(22), /** * The right to invoke `fd_filestat_set_times`. */ FD_FILESTAT_SET_TIMES(23), /** * The right to invoke `path_symlink`. */ PATH_SYMLINK(24), /** * The right to invoke `path_remove_directory`. */ PATH_REMOVE_DIRECTORY(25), /** * The right to invoke `path_unlink_file`. */ PATH_UNLINK_FILE(26), /** * If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe * to `eventtype::fd_read`. * If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe * to `eventtype::fd_write`. */ POLL_FD_READWRITE(27), /** * The right to invoke `sock_shutdown`. */ SOCK_SHUTDOWN(28), /** * The right to invoke `sock_accept`. */ SOCK_ACCEPT(29), ; constructor(bit: Int) : this(1L.shl(bit)) } public companion object : WasiTypename { @WasmValueType override val wasmValueType: Int = WasiValueTypes.U16 } }
0
Kotlin
1
3
5f513e2413987ce681f12ea8e14a2aff2c56a7fd
5,621
wasm-sqlite-open-helper
Apache License 2.0
features/src/main/kotlin/ru/mobileup/features/root/DI.kt
MobileUpLLC
495,342,634
false
{"Kotlin": 206427}
package ru.mobileup.features.root import com.arkivanov.decompose.ComponentContext import ru.mobileup.core.ComponentFactory import ru.mobileup.features.root.ui.RealRootComponent import ru.mobileup.features.root.ui.RootComponent import org.koin.core.component.get fun ComponentFactory.createRootComponent(componentContext: ComponentContext): RootComponent { return RealRootComponent(componentContext, get()) }
0
Kotlin
1
1
717fec2a43e5e9314b7ffe0d3aaa94047b6ca229
413
Education-Space-Android
MIT License
src/main/kotlin/com/lapismc/minecraft/yggdrasil/ProfileList.kt
lapis-mc
97,967,682
false
null
package com.lapismc.minecraft.yggdrasil import java.util.UUID /** * Collection of profiles the player can choose from to play with. * @param available List of all profiles the player has. * @param selectedId ID of the profile the player is currently using. */ class ProfileList(val available: List<Profile>, val selectedId: UUID) { /** * Retrieves the player's currently selected profile. */ val selected = available.find { it.id == selectedId } }
0
Kotlin
0
1
ff17e7084d4ed45d135a187a68d5abf6eaf8965f
471
yggdrasil
MIT License
solar/src/main/java/com/chiksmedina/solar/bold/messagesconversation/ChatRoundDots.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.bold.messagesconversation import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.bold.MessagesConversationGroup val MessagesConversationGroup.ChatRoundDots: ImageVector get() { if (_chatRoundDots != null) { return _chatRoundDots!! } _chatRoundDots = Builder( name = "ChatRoundDots", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(12.0f, 22.0f) curveTo(17.5228f, 22.0f, 22.0f, 17.5228f, 22.0f, 12.0f) curveTo(22.0f, 6.4771f, 17.5228f, 2.0f, 12.0f, 2.0f) curveTo(6.4771f, 2.0f, 2.0f, 6.4771f, 2.0f, 12.0f) curveTo(2.0f, 13.5997f, 2.3756f, 15.1116f, 3.0435f, 16.4525f) curveTo(3.2209f, 16.8088f, 3.28f, 17.2161f, 3.1771f, 17.6006f) lineTo(2.5815f, 19.8267f) curveTo(2.3229f, 20.793f, 3.207f, 21.677f, 4.1733f, 21.4185f) lineTo(6.3994f, 20.8229f) curveTo(6.7839f, 20.72f, 7.1912f, 20.7791f, 7.5475f, 20.9565f) curveTo(8.8884f, 21.6244f, 10.4003f, 22.0f, 12.0f, 22.0f) close() } path( fill = SolidColor(Color(0xFFffffff)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(15.0f, 12.0f) curveTo(15.0f, 12.5523f, 15.4477f, 13.0f, 16.0f, 13.0f) curveTo(16.5523f, 13.0f, 17.0f, 12.5523f, 17.0f, 12.0f) curveTo(17.0f, 11.4477f, 16.5523f, 11.0f, 16.0f, 11.0f) curveTo(15.4477f, 11.0f, 15.0f, 11.4477f, 15.0f, 12.0f) close() } path( fill = SolidColor(Color(0xFFffffff)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(11.0f, 12.0f) curveTo(11.0f, 12.5523f, 11.4477f, 13.0f, 12.0f, 13.0f) curveTo(12.5523f, 13.0f, 13.0f, 12.5523f, 13.0f, 12.0f) curveTo(13.0f, 11.4477f, 12.5523f, 11.0f, 12.0f, 11.0f) curveTo(11.4477f, 11.0f, 11.0f, 11.4477f, 11.0f, 12.0f) close() } path( fill = SolidColor(Color(0xFFffffff)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(7.0f, 12.0f) curveTo(7.0f, 12.5523f, 7.4477f, 13.0f, 8.0f, 13.0f) curveTo(8.5523f, 13.0f, 9.0f, 12.5523f, 9.0f, 12.0f) curveTo(9.0f, 11.4477f, 8.5523f, 11.0f, 8.0f, 11.0f) curveTo(7.4477f, 11.0f, 7.0f, 11.4477f, 7.0f, 12.0f) close() } } .build() return _chatRoundDots!! } private var _chatRoundDots: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
3,904
SolarIconSetAndroid
MIT License
app/src/main/java/com/example/tmobileappkotlin/model/Attributes.kt
suki-sahota
280,921,015
false
null
package com.example.tmobileappkotlin.model import com.squareup.moshi.Json data class Attributes( // text attributes @Json(name = "font") val font: Font, @Json(name = "text_color") val text_color: String )
0
Kotlin
0
1
b3939049163d20e60351134f08345a2e32678afc
214
tMobileAppKotlin
MIT License
app/src/main/java/uk/co/sentinelweb/cuer/app/ui/play_control/mvi/CastPlayerMviFragment.kt
sentinelweb
220,796,368
false
null
package uk.co.sentinelweb.cuer.app.ui.play_control.mvi import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SeekBar import androidx.annotation.ColorRes import androidx.core.view.isVisible import androidx.fragment.app.Fragment import com.arkivanov.mvikotlin.core.utils.diff import com.arkivanov.mvikotlin.core.view.BaseMviView import com.arkivanov.mvikotlin.core.view.ViewRenderer import com.bumptech.glide.Glide import com.google.android.material.snackbar.Snackbar import org.koin.android.ext.android.inject import org.koin.android.scope.AndroidScopeComponent import org.koin.core.context.GlobalContext.get import org.koin.core.qualifier.named import org.koin.core.scope.Scope import org.koin.dsl.module import uk.co.sentinelweb.cuer.app.R import uk.co.sentinelweb.cuer.app.databinding.CastPlayerViewBinding import uk.co.sentinelweb.cuer.app.ui.common.navigation.NavigationModel import uk.co.sentinelweb.cuer.app.ui.common.navigation.NavigationProvider import uk.co.sentinelweb.cuer.app.ui.player.PlayerContract import uk.co.sentinelweb.cuer.app.ui.player.PlayerContract.View.Event import uk.co.sentinelweb.cuer.app.ui.player.PlayerContract.View.Model import uk.co.sentinelweb.cuer.app.util.cast.ChromeCastWrapper import uk.co.sentinelweb.cuer.app.util.extension.fragmentScopeWithSource import uk.co.sentinelweb.cuer.app.util.extension.linkScopeToActivity import uk.co.sentinelweb.cuer.app.util.firebase.FirebaseImageProvider import uk.co.sentinelweb.cuer.app.util.wrapper.ResourceWrapper import uk.co.sentinelweb.cuer.domain.PlayerStateDomain class CastPlayerMviFragment() : Fragment(), AndroidScopeComponent { override val scope: Scope by fragmentScopeWithSource<CastPlayerMviFragment>() private val chromeCastWrapper: ChromeCastWrapper by inject() private val imageProvider: FirebaseImageProvider by inject() private val res: ResourceWrapper by inject() private var _binding: CastPlayerViewBinding? = null private val binding get() = _binding!! private lateinit var _mviView: CastPlayerViewImpl val mviView: CastPlayerViewImpl get() = _mviView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = CastPlayerViewBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) _mviView = CastPlayerViewImpl() binding.castPlayerFab.setOnClickListener { _mviView.dispatch(Event.PlayPauseClicked()) }// todo get playstate binding.castPlayerSeekBack.setOnClickListener { _mviView.dispatch(Event.SkipBackClicked) } binding.castPlayerSeekForward.setOnClickListener { _mviView.dispatch(Event.SkipFwdClicked) } binding.castPlayerSeekBack.setOnLongClickListener { _mviView.dispatch(Event.SkipBackSelectClicked); true } binding.castPlayerSeekForward.setOnLongClickListener { _mviView.dispatch(Event.SkipFwdSelectClicked); true } binding.castPlayerTrackLast.setOnClickListener { _mviView.dispatch(Event.TrackBackClicked) } binding.castPlayerTrackNext.setOnClickListener { _mviView.dispatch(Event.TrackFwdClicked) } binding.castPlayerPlaylistText.setOnClickListener { _mviView.dispatch(Event.PlaylistClicked) } binding.castPlayerImage.setOnClickListener { _mviView.dispatch(Event.ItemClicked) } binding.castPlayerSupport.setOnClickListener { _mviView.dispatch(Event.Support) } binding.castPlayerSeek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { // if (fromUser) { // // todo update time ui // } } override fun onStartTrackingTouch(view: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) { _mviView.dispatch(Event.SeekBarChanged(seekBar.progress / seekBar.max.toFloat())) } }) } override fun onAttach(context: Context) { super.onAttach(context) linkScopeToActivity() } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onResume() { super.onResume() } fun initMediaRouteButton() { chromeCastWrapper.initMediaRouteButton(binding.mediaRouteButton) } fun setPosition(second: String) { binding.castPlayerPosition.text = second } fun setLiveTime(second: String?) { binding.castPlayerLiveTime.isVisible = second != null second?.apply { binding.castPlayerLiveTime.text = second } } fun setDurationColors(@ColorRes text: Int, @ColorRes upcomingBackground: Int) { binding.castPlayerDuration.setTextColor(res.getColor(text)) binding.castPlayerDuration.setBackgroundColor(res.getColor(upcomingBackground)) } fun setDuration(duration: String) { binding.castPlayerDuration.text = duration } fun setPlaying() { binding.castPlayerFab.setImageState(intArrayOf(android.R.attr.state_enabled, android.R.attr.state_checked), false) binding.castPlayerFab.showProgress(false) } fun setPaused() { binding.castPlayerFab.setImageState(intArrayOf(android.R.attr.state_enabled), false) binding.castPlayerFab.showProgress(false) } fun showBuffering() { binding.castPlayerFab.showProgress(true) } fun hideBuffering() { binding.castPlayerFab.showProgress(false) } fun showMessage(msg: String) { Snackbar.make(requireView(), msg, Snackbar.LENGTH_LONG).show() } fun setTitle(title: String) { binding.castPlayerTitle.text = title } fun setImage(url: String) { Glide.with(requireContext()) .load(url) .into(binding.castPlayerImage) } fun clearImage() { binding.castPlayerImage.setImageResource(0) } fun setPlaylistName(name: String) { binding.castPlayerPlaylistText.text = name } fun setPlaylistImage(url: String?) { // url?.apply { // Glide.with(requireContext()) // .loadFirebaseOrOtherUrl(this, imageProvider) // .into(binding.castPlayerPlaylistImage) // } ?: binding.castPlayerPlaylistImage.setImageResource(R.drawable.ic_nav_playlist_black) } fun setSkipFwdText(text: String) { binding.castPlayerSkipfwdText.text = text } fun setSkipBackText(text: String) { binding.castPlayerSkipbackText.text = text } fun setSeekEnabled(enabled: Boolean) { binding.castPlayerSeek.isEnabled = enabled } fun setState(state: PlayerStateDomain?) { binding.castPlayerCurrentState.text = state?.toString() } fun updateSeekPosition(ratio: Float) { binding.castPlayerSeek.progress = (ratio * binding.castPlayerSeek.max).toInt() } fun navigate(navModel: NavigationModel) { (activity as NavigationProvider).navigate(navModel) } // region MVI view inner class CastPlayerViewImpl constructor( ) : BaseMviView<Model, Event>(), PlayerContract.View { override val renderer: ViewRenderer<Model> = diff { diff(get = Model::playState, set = { when (it) { PlayerStateDomain.BUFFERING -> showBuffering() PlayerStateDomain.PLAYING -> setPlaying() PlayerStateDomain.PAUSED -> setPaused() else -> Unit } }) diff(get = Model::itemImage, set = { url -> url?.let { setImage(it) } }) diff(get = Model::texts, set = { texts -> texts.title?.let { setTitle(it) } texts.playlistTitle?.let { setPlaylistName(it) } texts.playlistTitle?.let { setPlaylistName(it) } texts.skipFwdText?.let { setSkipFwdText(it) } texts.skipBackText?.let { setSkipBackText(it) } }) diff(get = Model::times, set = { times -> updateSeekPosition(times.seekBarFraction) setPosition(times.positionText) setLiveTime(times.liveTime) if (times.isLive) { setDurationColors(R.color.white, R.color.live_background) setDuration(res.getString(R.string.live)) updateSeekPosition(0f) } else { setDurationColors(R.color.text_primary, R.color.transparent) setDuration(times.durationText) updateSeekPosition(times.seekBarFraction) } setSeekEnabled(!times.isLive) }) } override suspend fun processLabel(label: PlayerContract.MviStore.Label) = Unit } // endreigon companion object { val TRANS_IMAGE by lazy { get().get<ResourceWrapper>().getString(R.string.cast_player_trans_image) } val TRANS_TITLE by lazy { get().get<ResourceWrapper>().getString(R.string.cast_player_trans_title) } @JvmStatic val fragmentModule = module { scope(named<CastPlayerMviFragment>()) { } } } }
95
null
0
2
cd5b28c720c08c9b718f904421b0580e6b716ec0
9,532
cuer
Apache License 2.0
src/main/kotlin/no/nav/syfo/tilgang/AnsattTilgangApiV2.kt
navikt
233,810,005
false
{"Kotlin": 36477, "Dockerfile": 217}
package no.nav.syfo.tilgang import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.response.* import io.ktor.server.routing.* import no.nav.syfo.util.* import org.slf4j.Logger import org.slf4j.LoggerFactory private val LOG: Logger = LoggerFactory.getLogger("no.nav.syfo") private const val PID_CLAIM_NAME = "pid" const val BASE_PATH_V2: String = "/api/v2/tilgang/ansatt" fun Route.registerAnsattTilgangApiV2(ansattTilgangService: AnsattTilgangService) { route(BASE_PATH_V2) { get("/{fnr}") { try { val ansattFnr: String = call.parameters["fnr"]?.takeIf { validateFnr(it) } ?: throw IllegalArgumentException("Fnr mangler") val credentials = call.principal<JWTPrincipal>() val callId = getCallId() credentials?.let { creds -> val pidClaim = creds.payload.getClaim(PID_CLAIM_NAME) if (pidClaim.isNull) { LOG.warn( "Mangler credentials for å authorisere bruker for tilgang til ansatt, {}, {}", callIdArgument(callId), consumerIdArgument(getConsumerId()) ) call.respond( HttpStatusCode.Unauthorized, "Kan ikke hente tilgang til ansatt: 'pid'-claim mangler i token fra id-porten" ) } else { val loggedInFnr = pidClaim.asString() if (ansattTilgangService.hasAccessToAnsatt(loggedInFnr, ansattFnr)) { call.respond(true) } else { LOG.warn( "Innlogget bruker har ikke tilgang til oppslått ansatt, {}, {}", callIdArgument(callId), consumerIdArgument(getConsumerId()) ) call.respond(false) } } } ?: run { LOG.warn( "Mangler credentials for å authorisere bruker for tilgang til ansatt, {}, {}", callIdArgument(callId), consumerIdArgument(getConsumerId()) ) call.respond(HttpStatusCode.Unauthorized, "Kan ikke hente tilgang til ansatt: Mangler credentials") } } catch (e: IllegalArgumentException) { LOG.error( "Kan ikke hente tilgang til ansatt med fnr: {}, {}, {}", e.message, callIdArgument(getCallId()), consumerIdArgument(getConsumerId()) ) call.respond(HttpStatusCode.BadRequest, e.message ?: "Kan ikke hente tilgang til ansatt") } } } }
2
Kotlin
0
0
c429aed643b8b72460551d6612184b19f3c7fba8
3,077
syfobrukertilgang
MIT License
solidblocks-hetzner-nuke/nuker/src/main/kotlin/de/solidblocks/hetzner/nuke/Cli.kt
pellepelster
427,474,970
false
null
package de.solidblocks.hetzner.nuke import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.parameters.options.multiple import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import com.github.ajalt.clikt.parameters.options.validate import java.util.regex.Pattern class CliCommand : CliktCommand() { override fun run() { } } public fun validLabelParameter(label: String): Boolean { val labelParts = label.split("=") if (labelParts.size != 2) { return false } val regex = "^[a-z0-9A-Z][a-z0-9A-Z\\.\\-_]*[a-z0-9A-Z]$" val pattern = Pattern.compile(regex, Pattern.MULTILINE) val matcher = pattern.matcher(labelParts[0]) if (!matcher.find()) { return false } return true } class NukeCommand : CliktCommand(help = "delete all Hetzner cloud resources") { private val hcloudToken by option("--hcloud-token", envvar = "HCLOUD_TOKEN").required() /* private val labels: List<String> by option("--label").multiple().validate { } */ override fun run() { Nuker(hcloudToken).deleteAll(true) } } class SimulateCommand : CliktCommand(help = "simulate deletion of all Hetzner cloud resources") { private val hcloudToken by option("--hcloud-token", envvar = "HCLOUD_TOKEN").required() override fun run() { Nuker(hcloudToken).deleteAll(false) } } fun main(args: Array<String>) = CliCommand().subcommands(SimulateCommand(), NukeCommand()).main(args)
6
null
5
8
7e8c67129ba674a3c604e70c70a69ed3eb2723f8
1,589
solidblocks
MIT License
samples/KaraDemo/src/karademo/models/Post.kt
erokhins
11,252,917
false
null
package karademo.models import java.util.Date /** */ public class Post(var date : Date, var title : String) { public var body : String = "" }
0
null
0
1
77aabd409ebc4d940256c8a42444a484e5116b1d
151
kara
Apache License 2.0
privacy-config/privacy-config-impl/src/main/java/com/duckduckgo/privacy/config/impl/plugins/PrivacyFeaturePlugin.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2021 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.privacy.config.impl.plugins import com.duckduckgo.app.global.plugins.PluginPoint import com.duckduckgo.privacy.config.api.PrivacyFeatureName interface PrivacyFeaturePlugin { fun store(name: String, jsonString: String): Boolean val featureName: PrivacyFeatureName } class PrivacyFeaturePluginPoint( private val privacyFeatures: Set<@JvmSuppressWildcards PrivacyFeaturePlugin> ) : PluginPoint<PrivacyFeaturePlugin> { override fun getPlugins(): Collection<PrivacyFeaturePlugin> { return privacyFeatures } }
41
null
671
2,413
7e23d4cc5aa890bd727d977f8ac438239915509d
1,157
Android
Apache License 2.0
src/test/kotlin/com/marcinziolo/kotlin/wiremock/ResponseTest.kt
wiremock
267,131,008
false
{"Kotlin": 78596}
package com.marcinziolo.kotlin.wiremock import io.restassured.module.kotlin.extensions.Then import io.restassured.module.kotlin.extensions.When import org.hamcrest.Matchers.equalTo import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class ResponseTest : AbstractTest() { @Test fun `response with two headers`() { wiremock.get { url equalTo "/hello" } returns { statusCode = 200 header = "TraceId" to "abcd123" header = "ExecutionTime" to "10" } When { get("$url/hello") } Then { statusCode(200) header("TraceId", "abcd123") header("ExecutionTime", "10") } } @Test fun `response with multi-value headers`() { wiremock.get { url equalTo "/hello" } returns { statusCode = 200 header = "TraceId" to "abcd123" header = "TraceId" to "efgh456" } When { get("$url/hello") } Then { statusCode(200) extract().headers().getValues("TraceId").also { values -> assertEquals(listOf("abcd123", "efgh456"), values) } } } @Test fun `returns json`() { wiremock.get { url equalTo "/hello" } returnsJson { body = """ {"pet": "dog"} """ } When { get("$url/hello") } Then { statusCode(200) body("pet", equalTo("dog")) } } }
2
Kotlin
6
43
0df736c8337f0d2c43b80dd46368c94a1b8e0d65
1,619
kotlin-wiremock
Apache License 2.0
src/main/kotlin/aoc2023/Day01.kt
lukellmann
574,273,843
false
{"Kotlin": 140858}
package aoc2023 import AoCDay import util.illegalInput // https://adventofcode.com/2023/day/1 object Day01 : AoCDay<Int>( title = "Trebuchet?!", part1ExampleAnswer = 142 + (11 + 11 + 22 + 33 + 42 + 24 + 77), part1Answer = 54597, part2ExampleAnswer = 142 + 281, part2Answer = 54504, ) { private val DIGIT_REGEX = Regex("[0-9]|one|two|three|four|five|six|seven|eight|nine") private fun digitToInt(digit: String) = when (digit) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 "seven" -> 7 "eight" -> 8 "nine" -> 9 else -> if (digit.length == 1 && digit[0] in '0'..'9') digit[0] - '0' else illegalInput(digit) } override fun part1(input: String) = input .lineSequence() .sumOf { line -> val firstDigit = line.first { it in '0'..'9' } val lastDigit = line.last { it in '0'..'9' } (firstDigit - '0') * 10 + (lastDigit - '0') } override fun part2(input: String) = input .lineSequence() .sumOf { line -> val firstDigit = DIGIT_REGEX.find(line)?.value ?: illegalInput(line) val lastDigit = line.indices .reversed() .firstNotNullOf { index -> DIGIT_REGEX.find(line, startIndex = index)?.value } digitToInt(firstDigit) * 10 + digitToInt(lastDigit) } }
0
Kotlin
0
1
23af2465bbc958bbbeba381f34e0d62f0d0f70da
1,442
advent-of-code-kotlin
MIT License
sources/storage/src/main/java/com/mikyegresl/valostat/storage/ValorantStorageImpl.kt
sergey-lvovich-kim
629,918,357
false
null
package com.mikyegresl.valostat.storage import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.JsonSyntaxException import com.mikyegresl.valostat.base.error.CacheFileNotFoundException import com.mikyegresl.valostat.base.error.CacheMalformedException import com.mikyegresl.valostat.base.manager.FileManager import com.mikyegresl.valostat.base.manager.FileType import com.mikyegresl.valostat.base.storage.ValorantStorage import java.io.ByteArrayInputStream class ValorantStorageImpl( private val cacheDir: String, private val fileManager: FileManager, private val gson: Gson ) : ValorantStorage { private fun getAgentsCache() = "$cacheDir/$AGENTS_CACHE_FILE_NAME/" private fun getWeaponsCache() = "$cacheDir/$WEAPONS_CACHE_FILE_NAME/" companion object { private const val AGENTS_CACHE_FILE_NAME = "agents_cache" private const val WEAPONS_CACHE_FILE_NAME = "weapons_cache" } override suspend fun getAgents(): JsonElement? { val path = getAgentsCache() val file = fileManager.getFileIfExists(path, FileType.JSON_OBJECT) ?: throw CacheFileNotFoundException("No cache file at $path") return try { gson.fromJson(file.readText(), JsonElement::class.java) } catch (jsonEx: JsonSyntaxException) { throw CacheMalformedException(jsonEx) } } override suspend fun saveAgents(agentsJson: JsonElement) { val path = getAgentsCache() val file = fileManager.getFile(path, FileType.JSON_OBJECT) val gsonString = gson.toJson(agentsJson) val stream = ByteArrayInputStream(gsonString.toByteArray()) // following method should clear existing file and write in a clean one fileManager.writeFile( stream, file ) } override suspend fun removeAgents() { val path = getAgentsCache() fileManager.getFileIfExists(path, FileType.JSON_OBJECT)?.delete() } override suspend fun getWeapons(): JsonElement? { val path = getWeaponsCache() val file = fileManager.getFileIfExists(path, FileType.JSON_OBJECT) ?: throw CacheFileNotFoundException("No cache file at $path") return try { gson.fromJson(file.readText(), JsonElement::class.java) } catch (jsonEx: JsonSyntaxException) { throw CacheMalformedException(jsonEx) } } override suspend fun saveWeapons(weaponsJson: JsonElement) { val path = getWeaponsCache() val file = fileManager.getFile(path, FileType.JSON_OBJECT) val gsonString = gson.toJson(weaponsJson) val stream = ByteArrayInputStream(gsonString.toByteArray()) // following method should clear existing file and write in a clean one fileManager.writeFile( stream, file ) } override suspend fun removeWeapons() { val path = getWeaponsCache() fileManager.getFileIfExists(path, FileType.JSON_OBJECT)?.delete() } }
0
Kotlin
0
0
ca5b07227d9fbfe3806571cb21e19e02430ae819
3,064
ValoStat
Apache License 2.0
serialization/src/main/kotlin/net/corda/serialization/internal/GeneratedAttachment.kt
noordheenm
160,531,644
true
{"Gradle": 71, "INI": 27, "Markdown": 85, "Shell": 24, "Text": 13, "Ignore List": 10, "Java Properties": 3, "Batchfile": 5, "XML": 99, "Java": 129, "Kotlin": 1625, "YAML": 5, "Makefile": 2, "Python": 7, "Gherkin": 3, "Groovy": 2, "Dockerfile": 1, "RPM Spec": 1, "CSS": 10, "SVG": 4, "PowerShell": 1, "JSON": 2, "AppleScript": 1, "HTML": 7, "JavaScript": 17, "reStructuredText": 137, "TeX": 6, "BibTeX": 1}
package net.corda.serialization.internal import net.corda.core.KeepForDJVM import net.corda.core.crypto.sha256 import net.corda.core.internal.AbstractAttachment @KeepForDJVM class GeneratedAttachment(val bytes: ByteArray) : AbstractAttachment({ bytes }) { override val id = bytes.sha256() }
0
Kotlin
0
1
c533e0ab0ca38d39d055aa9112052213cb69fe7b
297
corda
Apache License 2.0
serialization/src/main/kotlin/net/corda/serialization/internal/GeneratedAttachment.kt
noordheenm
160,531,644
true
{"Gradle": 71, "INI": 27, "Markdown": 85, "Shell": 24, "Text": 13, "Ignore List": 10, "Java Properties": 3, "Batchfile": 5, "XML": 99, "Java": 129, "Kotlin": 1625, "YAML": 5, "Makefile": 2, "Python": 7, "Gherkin": 3, "Groovy": 2, "Dockerfile": 1, "RPM Spec": 1, "CSS": 10, "SVG": 4, "PowerShell": 1, "JSON": 2, "AppleScript": 1, "HTML": 7, "JavaScript": 17, "reStructuredText": 137, "TeX": 6, "BibTeX": 1}
package net.corda.serialization.internal import net.corda.core.KeepForDJVM import net.corda.core.crypto.sha256 import net.corda.core.internal.AbstractAttachment @KeepForDJVM class GeneratedAttachment(val bytes: ByteArray) : AbstractAttachment({ bytes }) { override val id = bytes.sha256() }
0
Kotlin
0
1
c533e0ab0ca38d39d055aa9112052213cb69fe7b
297
corda
Apache License 2.0
pluto-plugins/plugins/layout-inspector/lib/src/main/java/com/pluto/plugins/layoutinspector/internal/attributes/data/mutability/AttributeDimenSP.kt
androidPluto
390,471,457
false
{"Kotlin": 744352, "Shell": 646}
package com.pluto.plugins.layoutinspector.internal.attributes.data.mutability import android.view.View import android.widget.TextView import com.pluto.plugins.layoutinspector.internal.attributes.data.Attribute import com.pluto.plugins.layoutinspector.internal.attributes.data.MutableAttribute import com.pluto.utilities.extensions.px2sp import com.pluto.utilities.views.keyvalue.KeyValuePairEditRequest internal abstract class AttributeDimenSP(title: String, value: Float) : Attribute<Float>(title, value), MutableAttribute { override fun displayText(): CharSequence? = "${value.px2sp.toInt()} sp" override fun requestEdit(): KeyValuePairEditRequest = KeyValuePairEditRequest( key = "$title (sp)", value = value.px2sp.toInt().toString(), hint = "enter value (in sp)", metaData = this ) class TextSize(title: String, value: Float) : AttributeDimenSP(title, value) { override fun handleEdit(view: View, updatedValue: String) { if (view is TextView) { view.textSize = updatedValue.toFloat() } } } }
23
Kotlin
64
657
5562cb7065bcbcf18493820e287d87c7726f630b
1,084
pluto
Apache License 2.0
app/src/main/java/com/example/calculatorapp/model/ButtonData.kt
thisishisham1
689,881,117
false
{"Kotlin": 35118}
package com.example.calculatorapp.model import androidx.compose.foundation.layout.requiredSize import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp data class ButtonData( val number: String, val isDark: Boolean, val onClick: () -> Unit, val sizeButton: Modifier = Modifier.requiredSize(90.dp), val containerColor: Color, val contentColor: Color )
0
Kotlin
0
0
e59aaf88d41c8578faa1bb002153e1b2b3fc90d8
432
Calculator-App
MIT License
src/commonMain/kotlin/de/voize/pytorch_lite_multiplatform/IValue.kt
voize-gmbh
474,316,962
false
{"Kotlin": 29619, "Objective-C++": 13304, "Ruby": 3748, "Objective-C": 3559, "Python": 1823, "Swift": 999, "Shell": 474}
package de.voize.pytorch_lite_multiplatform expect class IValue { fun isNull(): Boolean fun isTensor(): Boolean fun isBool(): Boolean fun isLong(): Boolean fun isDouble(): Boolean fun isString(): Boolean fun isTuple(): Boolean fun isBoolList(): Boolean fun isLongList(): Boolean fun isDoubleList(): Boolean fun isTensorList(): Boolean fun isList(): Boolean fun isDictStringKey(): Boolean fun isDictLongKey(): Boolean fun toTensor(): Tensor fun toTensorList(): List<Tensor> fun toBool(): Boolean fun toLong(): Long fun toDouble(): Double fun toStr(): String fun toBoolList(): List<Boolean> fun toLongList(): List<Long> fun toDoubleList(): List<Double> fun toList(): List<IValue> fun toTuple(): List<IValue> fun toDictStringKey(): Map<String, IValue> fun toDictLongKey(): Map<Long, IValue> companion object { fun optionalNull(): IValue fun from(tensor: Tensor): IValue fun from(value: Boolean): IValue fun from(value: Long): IValue fun from(value: Double): IValue fun from(value: String): IValue fun listFrom(vararg values: IValue): IValue fun listFrom(vararg tensors: Tensor): IValue fun listFrom(vararg list: Boolean, scope: PLMScope): IValue fun listFrom(vararg list: Long, scope: PLMScope): IValue fun listFrom(vararg list: Double, scope: PLMScope): IValue fun tupleFrom(vararg values: IValue): IValue fun dictStringKeyFrom(map: Map<String, IValue>): IValue fun dictLongKeyFrom(map: Map<Long, IValue>): IValue } }
3
Kotlin
4
33
661372dd5b084f00d9f0326e889dbabafc044cdc
1,647
pytorch-lite-multiplatform
Apache License 2.0
app/src/main/java/com/p4indiafsm/features/addAttendence/model/LeaveTypeResponseModel.kt
DebashisINT
600,987,989
false
null
package com.p4indiafsm.features.addAttendence.model import com.p4indiafsm.base.BaseResponse /** * Created by Saikat on 22-11-2018. */ class LeaveTypeResponseModel : BaseResponse() { var leave_type_list: ArrayList<LeaveTypeDataModel>? = null }
0
Kotlin
0
0
5ffdb2743eaf7f3e6fe1988cb97c67ebdae0d870
250
P4India
Apache License 2.0
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/EnumEntryNameCaseRule.kt
pinterest
64,293,719
false
null
package com.pinterest.ktlint.ruleset.standard import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.ruleset.standard.internal.regExIgnoringDiacriticsAndStrokesOnLetters import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.CompositeElement import org.jetbrains.kotlin.psi.KtEnumEntry /** * https://kotlinlang.org/docs/coding-conventions.html#property-names */ public class EnumEntryNameCaseRule : Rule("enum-entry-name-case") { internal companion object { val ENUM_ENTRY_IDENTIFIER_REGEX = "[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)".regExIgnoringDiacriticsAndStrokesOnLetters() } override fun beforeVisitChildNodes( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { if (node !is CompositeElement) { return } val enumEntry = node.psi as? KtEnumEntry ?: return val name = enumEntry.name ?: return if (!name.matches(ENUM_ENTRY_IDENTIFIER_REGEX)) { emit( node.startOffset, "Enum entry name should be uppercase underscore-separated names like \"ENUM_ENTRY\" or upper camel-case like \"EnumEntry\"", false, ) } } }
83
Kotlin
461
5,381
d51de4cb14473ed5cbb732039585d5247c7af2de
1,334
ktlint
MIT License
ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvmAndNix/src/io/ktor/server/plugins/contentnegotiation/ContentNegotiation.kt
Kotlin
40,136,600
false
null
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.contentnegotiation import io.ktor.http.* import io.ktor.http.content.* import io.ktor.serialization.* import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.plugins.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.util.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* /** * Functional type for accepted content types contributor * @see ContentNegotiation.Configuration.accept */ public typealias AcceptHeaderContributor = ( call: ApplicationCall, acceptedContentTypes: List<ContentTypeWithQuality> ) -> List<ContentTypeWithQuality> /** * Pair of [ContentType] and [quality] usually parsed from [HttpHeaders.Accept] headers. * @param contentType * @param quality */ public data class ContentTypeWithQuality(val contentType: ContentType, val quality: Double = 1.0) { init { require(quality in 0.0..1.0) { "Quality should be in range [0, 1]: $quality" } } } /** * This plugin provides automatic content conversion according to Content-Type and Accept headers * * See normative documents: * * * https://tools.ietf.org/html/rfc7231#section-5.3 * * https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation */ public val ContentNegotiation: RouteScopedPlugin<ContentNegotiationConfig> = createRouteScopedPlugin( "ContentNegotiation", { ContentNegotiationConfig() } ) { convertRequestBody() convertResponseBody() } /** * Detect suitable charset for an application call by `Accept` header or fallback to [defaultCharset] */ public fun ApplicationCall.suitableCharset(defaultCharset: Charset = Charsets.UTF_8): Charset { for ((charset, _) in request.acceptCharsetItems()) when { charset == "*" -> return defaultCharset Charset.isSupported(charset) -> return Charset.forName(charset) } return defaultCharset }
264
Kotlin
784
9,455
b5b59ca3ae61601e6175f334e6a1252609638e61
2,047
ktor
Apache License 2.0
domain/src/main/java/com/team_sunshijo/domain/entity/auth/LoginEntity.kt
Team-Sunshijo
640,839,334
false
null
package com.team_sunshijo.domain.entity.auth data class LoginEntity( val account_id: String, val password: String )
0
Kotlin
0
1
bd983ab706f202c6560118426544501c5ae002f2
125
Sunshijo-Android
MIT License
src/test/kotlin/g3001_3100/s3098_find_the_sum_of_subsequence_powers/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g3001_3100.s3098_find_the_sum_of_subsequence_powers import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun sumOfPowers() { assertThat(Solution().sumOfPowers(intArrayOf(1, 2, 3, 4), 3), equalTo(4)) } @Test fun sumOfPowers2() { assertThat(Solution().sumOfPowers(intArrayOf(2, 2), 2), equalTo(0)) } @Test fun sumOfPowers3() { assertThat(Solution().sumOfPowers(intArrayOf(4, 3, -1), 2), equalTo(10)) } }
0
Kotlin
20
43
471d45c60f669ea1a2e103e6b4d8d54da55711df
577
LeetCode-in-Kotlin
MIT License