repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
PolymerLabs/arcs | javatests/arcs/core/host/SimpleSchedulerProviderTest.kt | 1 | 3694 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.host
import arcs.core.testutil.runTest
import arcs.core.util.Scheduler
import arcs.core.util.testutil.LogRule
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.util.concurrent.Executors
import kotlin.test.assertFailsWith
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.withContext
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class SimpleSchedulerProviderTest {
@get:Rule
val log = LogRule()
@Test
fun one_thread_multipleSchedulers() = runTest {
val coroutineContext = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val schedulerProvider = SimpleSchedulerProvider(coroutineContext)
val schedulerA = schedulerProvider("a")
val schedulerB = schedulerProvider("b")
val schedulerC = schedulerProvider("c")
// All should be separate instances.
assertThat(schedulerA).isNotEqualTo(schedulerB)
assertThat(schedulerA).isNotEqualTo(schedulerC)
assertThat(schedulerB).isNotEqualTo(schedulerC)
val schedulerAThread = CompletableDeferred<Thread>()
val schedulerBThread = CompletableDeferred<Thread>()
val schedulerCThread = CompletableDeferred<Thread>()
// All three run on the same thread.
schedulerA.schedule(
SimpleProc("a") { schedulerAThread.complete(Thread.currentThread()) }
)
schedulerB.schedule(
SimpleProc("b") { schedulerBThread.complete(Thread.currentThread()) }
)
schedulerC.schedule(
SimpleProc("c") { schedulerCThread.complete(Thread.currentThread()) }
)
assertThat(schedulerAThread.await()).isEqualTo(schedulerBThread.await())
assertThat(schedulerBThread.await()).isEqualTo(schedulerCThread.await())
schedulerProvider.cancelAll()
}
@Test
fun throwing_from_a_task_failsTheParentContext() = runTest {
val e = assertFailsWith<IllegalStateException> {
withContext(coroutineContext) {
val schedulerProvider = SimpleSchedulerProvider(coroutineContext)
val scheduler = schedulerProvider("a")
scheduler.schedule(
SimpleProc("test") {
throw IllegalStateException("Washington DC is not a state.")
}
)
scheduler.waitForIdle()
}
}
assertThat(e).hasMessageThat().contains("Washington DC is not a state.")
}
@Test
fun canceling_thenReInvoking_givesNewScheduler() = runTest {
val coroutineContext = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val schedulerProvider = SimpleSchedulerProvider(coroutineContext)
val scheduler = schedulerProvider("a")
// Cancel the scheduler, and wait until its job has completed before trying to create
// another scheduler with the same arcId.
scheduler.cancel()
scheduler.awaitCompletion()
val newScheduler = schedulerProvider("a")
assertWithMessage(
"After canceling the original scheduler, we should get a new one, even with the " +
"same arcId."
).that(newScheduler).isNotEqualTo(scheduler)
schedulerProvider.cancelAll()
}
private class SimpleProc(
val name: String,
block: () -> Unit
) : Scheduler.Task.Processor(block) {
override fun toString() = "SimpleProc($name)"
}
}
| bsd-3-clause |
JStege1206/AdventOfCode | aoc-archetype/src/main/resources/archetype-resources/src/main/kotlin/days/Day07.kt | 1 | 285 | package ${package}.days
import nl.jstege.adventofcode.aoccommon.days.Day
class Day07 : Day(title = "") {
override fun first(input: Sequence<String>): Any {
TODO("Implement")
}
override fun second(input: Sequence<String>): Any {
TODO("Implement")
}
}
| mit |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/vimscript/model/functions/handlers/HasFunctionHandler.kt | 1 | 1416 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.functions.handlers
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.statistic.VimscriptState
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
import com.maddyhome.idea.vim.vimscript.model.expressions.Expression
import com.maddyhome.idea.vim.vimscript.model.functions.FunctionHandler
object HasFunctionHandler : FunctionHandler() {
override val name = "has"
override val minimumNumberOfArguments = 1
override val maximumNumberOfArguments = 2
private val supportedFeatures = setOf("ide")
override fun doFunction(
argumentValues: List<Expression>,
editor: VimEditor,
context: ExecutionContext,
vimContext: VimLContext,
): VimDataType {
val feature = argumentValues[0].evaluate(editor, context, vimContext).asString()
if (feature == "ide") {
VimscriptState.isIDESpecificConfigurationUsed = true
}
return if (supportedFeatures.contains(feature))
VimInt.ONE
else
VimInt.ZERO
}
}
| mit |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/util/impl/NoOpCache.kt | 1 | 283 | package org.hexworks.zircon.internal.util.impl
import org.hexworks.zircon.api.util.Cache
/**
* This is a no-op cache implementation.
*/
class NoOpCache<T> : Cache<T> {
override fun retrieveIfPresentOrNull(key: String): T? = null
override fun store(obj: T): T = obj
}
| apache-2.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PostListActionTracker.kt | 1 | 2805 | package org.wordpress.android.ui.posts
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.util.analytics.AnalyticsUtils
import org.wordpress.android.widgets.PostListButtonType
import org.wordpress.android.widgets.PostListButtonType.BUTTON_CANCEL_PENDING_AUTO_UPLOAD
import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY
import org.wordpress.android.widgets.PostListButtonType.BUTTON_COPY_URL
import org.wordpress.android.widgets.PostListButtonType.BUTTON_DELETE
import org.wordpress.android.widgets.PostListButtonType.BUTTON_DELETE_PERMANENTLY
import org.wordpress.android.widgets.PostListButtonType.BUTTON_EDIT
import org.wordpress.android.widgets.PostListButtonType.BUTTON_MORE
import org.wordpress.android.widgets.PostListButtonType.BUTTON_MOVE_TO_DRAFT
import org.wordpress.android.widgets.PostListButtonType.BUTTON_PREVIEW
import org.wordpress.android.widgets.PostListButtonType.BUTTON_PUBLISH
import org.wordpress.android.widgets.PostListButtonType.BUTTON_RETRY
import org.wordpress.android.widgets.PostListButtonType.BUTTON_SHOW_MOVE_TRASHED_POST_TO_DRAFT_DIALOG
import org.wordpress.android.widgets.PostListButtonType.BUTTON_STATS
import org.wordpress.android.widgets.PostListButtonType.BUTTON_SUBMIT
import org.wordpress.android.widgets.PostListButtonType.BUTTON_SYNC
import org.wordpress.android.widgets.PostListButtonType.BUTTON_TRASH
import org.wordpress.android.widgets.PostListButtonType.BUTTON_VIEW
fun trackPostListAction(site: SiteModel, buttonType: PostListButtonType, postData: PostModel, statsEvent: Stat) {
val properties = HashMap<String, Any?>()
if (!postData.isLocalDraft) {
properties["post_id"] = postData.remotePostId
}
properties["action"] = when (buttonType) {
BUTTON_EDIT -> {
properties[AnalyticsUtils.HAS_GUTENBERG_BLOCKS_KEY] = PostUtils
.contentContainsGutenbergBlocks(postData.content)
"edit"
}
BUTTON_RETRY -> "retry"
BUTTON_SUBMIT -> "submit"
BUTTON_VIEW -> "view"
BUTTON_PREVIEW -> "preview"
BUTTON_STATS -> "stats"
BUTTON_TRASH -> "trash"
BUTTON_COPY -> "copy"
BUTTON_DELETE,
BUTTON_DELETE_PERMANENTLY -> "delete"
BUTTON_PUBLISH -> "publish"
BUTTON_SYNC -> "sync"
BUTTON_MORE -> "more"
BUTTON_MOVE_TO_DRAFT -> "move_to_draft"
BUTTON_CANCEL_PENDING_AUTO_UPLOAD -> "cancel_pending_auto_upload"
BUTTON_SHOW_MOVE_TRASHED_POST_TO_DRAFT_DIALOG -> "show_move_trashed_post_to_draft_post_dialog"
BUTTON_COPY_URL -> "copy_url"
}
AnalyticsUtils.trackWithSiteDetails(statsEvent, site, properties)
}
| gpl-2.0 |
JoeSteven/HuaBan | app/src/main/java/com/joe/zatuji/event/PictureLoadMoreEvent.kt | 1 | 157 | package com.joe.zatuji.event
/**
* Description:
* author:Joey
* date:2018/11/23
*/
data class PictureLoadMoreEvent(val host:Any? ,val isRequest:Boolean) | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IdeVirtualFileFinder.kt | 4 | 2214 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.vfilefinder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ID
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import java.io.FileNotFoundException
import java.io.InputStream
class IdeVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFinder() {
override fun findMetadata(classId: ClassId): InputStream? {
val file = findVirtualFileWithHeader(classId.asSingleFqName(), KotlinMetadataFileIndex.KEY)?.takeIf { it.exists() } ?: return null
return try {
file.inputStream
} catch (e: FileNotFoundException) {
null
}
}
override fun hasMetadataPackage(fqName: FqName): Boolean = KotlinMetadataFilePackageIndex.hasSomethingInPackage(fqName, scope)
override fun findBuiltInsData(packageFqName: FqName): InputStream? =
findVirtualFileWithHeader(packageFqName, KotlinBuiltInsMetadataIndex.KEY)?.inputStream
override fun findSourceOrBinaryVirtualFile(classId: ClassId) = findVirtualFileWithHeader(classId)
init {
if (scope != GlobalSearchScope.EMPTY_SCOPE && scope.project == null) {
LOG.warn("Scope with null project $scope")
}
}
override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? =
findVirtualFileWithHeader(classId.asSingleFqName(), KotlinClassFileIndex.KEY)
private fun findVirtualFileWithHeader(fqName: FqName, key: ID<FqName, Void>): VirtualFile? {
val iterator = FileBasedIndex.getInstance().getContainingFilesIterator(key, fqName, scope)
return if (iterator.hasNext()) {
iterator.next()
} else {
null
}
}
companion object {
private val LOG = Logger.getInstance(IdeVirtualFileFinder::class.java)
}
}
| apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideTreeStructure.kt | 1 | 1924 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.hierarchy.overrides
import com.intellij.icons.AllIcons
import com.intellij.ide.hierarchy.HierarchyNodeDescriptor
import com.intellij.ide.hierarchy.HierarchyTreeStructure
import com.intellij.openapi.project.Project
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
class KotlinOverrideTreeStructure(project: Project, declaration: KtCallableDeclaration) : HierarchyTreeStructure(project, null) {
init {
setBaseElement(KotlinOverrideHierarchyNodeDescriptor(null, declaration.containingClassOrObject!!, declaration))
}
private val baseElement = declaration.createSmartPointer()
override fun buildChildren(nodeDescriptor: HierarchyNodeDescriptor): Array<Any> {
val baseElement = baseElement.element ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val psiElement = nodeDescriptor.psiElement ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val subclasses = HierarchySearchRequest(psiElement, psiElement.useScope(), false).searchInheritors().findAll()
return subclasses.mapNotNull {
val subclass = it.unwrapped ?: return@mapNotNull null
KotlinOverrideHierarchyNodeDescriptor(nodeDescriptor, subclass, baseElement)
}
.filter { it.calculateState() != AllIcons.Hierarchy.MethodNotDefined }
.toTypedArray()
}
}
| apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/intentions/iterationOverMap/KeyValueWithDestructuring.kt | 9 | 222 | // WITH_STDLIB
// AFTER-WARNING: Variable 'key' is never used
// AFTER-WARNING: Variable 'value' is never used
fun foo(map: Map<Int, Int>) {
for (entry<caret> in map.entries) {
val (key, value) = entry
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/resolutionDebugging/ReportContext.kt | 4 | 1853 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.actions.internal.resolutionDebugging
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.base.utils.fqname.fqName
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.Printer
internal class ReportContext {
private val modules: MutableSet<ModuleDescriptor> = mutableSetOf()
private val types: MutableSet<KotlinType> = mutableSetOf()
fun ModuleDescriptor.referenceToInstance(): ModuleReference {
val ref = ModuleReference(instanceString(), name.toString())
if (modules.add(this)) {
allDependencyModules.forEach { it.referenceToInstance() }
allExpectedByModules.forEach { it.referenceToInstance() }
}
return ref
}
fun KotlinType.referenceToInstance(): KotlinTypeReference {
val ref = KotlinTypeReference(instanceString(), fqName.toString())
if (types.add(this)) {
supertypes().forEach { it.referenceToInstance() }
this.constructor.declarationDescriptor!!.module.referenceToInstance()
}
return ref
}
fun Printer.renderContextReport() {
println("Mentioned modules:")
pushIndent()
modules.forEach { descriptor ->
ModuleDebugReport(descriptor).render(this)
println()
}
popIndent()
println()
println("Mentioned types:")
pushIndent()
types.forEach { type ->
KotlinTypeDebugReport(type).render(this)
println()
}
popIndent()
println()
}
}
| apache-2.0 |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/radio/RadioActivity.kt | 1 | 4207 | package com.kelsos.mbrc.ui.navigation.radio;
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import butterknife.BindView
import butterknife.ButterKnife
import com.google.android.material.snackbar.Snackbar
import com.kelsos.mbrc.R
import com.kelsos.mbrc.data.RadioStation
import com.kelsos.mbrc.ui.activities.BaseActivity
import com.kelsos.mbrc.ui.navigation.radio.RadioAdapter.OnRadioPressedListener
import com.kelsos.mbrc.ui.widgets.EmptyRecyclerView
import com.kelsos.mbrc.ui.widgets.MultiSwipeRefreshLayout
import com.raizlabs.android.dbflow.list.FlowCursorList
import toothpick.Scope
import toothpick.Toothpick
import toothpick.smoothie.module.SmoothieActivityModule
import javax.inject.Inject
class RadioActivity : BaseActivity(),
RadioView,
SwipeRefreshLayout.OnRefreshListener,
OnRadioPressedListener {
private val PRESENTER_SCOPE: Class<*> = Presenter::class.java
@BindView(R.id.swipe_layout) lateinit var swipeLayout: MultiSwipeRefreshLayout
@BindView(R.id.radio_list) lateinit var radioView: EmptyRecyclerView
@BindView(R.id.empty_view) lateinit var emptyView: View
@BindView(R.id.list_empty_title) lateinit var emptyViewTitle: TextView
@BindView(R.id.list_empty_icon) lateinit var emptyViewIcon: ImageView
@BindView(R.id.list_empty_subtitle) lateinit var emptyViewSubTitle: TextView
@BindView(R.id.empty_view_progress_bar) lateinit var emptyViewProgress: ProgressBar
@Inject lateinit var presenter: RadioPresenter
@Inject lateinit var adapter: RadioAdapter
override fun active(): Int {
return R.id.nav_radio
}
private lateinit var scope: Scope
override fun onCreate(savedInstanceState: Bundle?) {
Toothpick.openScope(PRESENTER_SCOPE).installModules(RadioModule())
scope = Toothpick.openScopes(application, PRESENTER_SCOPE, this)
scope.installModules(SmoothieActivityModule(this))
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_radio)
Toothpick.inject(this, scope)
ButterKnife.bind(this)
super.setup()
swipeLayout.setOnRefreshListener(this)
swipeLayout.setSwipeableChildren(R.id.radio_list, R.id.empty_view)
emptyViewTitle.setText(R.string.radio__no_radio_stations)
emptyViewIcon.setImageResource(R.drawable.ic_radio_black_80dp)
radioView.adapter = adapter
radioView.emptyView = emptyView
radioView.layoutManager = LinearLayoutManager(this)
}
override fun onStart() {
super.onStart()
presenter.attach(this)
presenter.load()
adapter.setOnRadioPressedListener(this)
}
override fun onStop() {
super.onStop()
presenter.detach()
adapter.setOnRadioPressedListener(null)
}
override fun onDestroy() {
super.onDestroy()
if (isFinishing) {
Toothpick.closeScope(PRESENTER_SCOPE)
}
Toothpick.closeScope(this)
}
override fun update(data: FlowCursorList<RadioStation>) {
adapter.update(data)
}
override fun error(error: Throwable) {
Snackbar.make(radioView, R.string.radio__loading_failed, Snackbar.LENGTH_SHORT).show()
}
override fun onRadioPressed(path: String) {
presenter.play(path)
}
override fun onRefresh() {
presenter.refresh()
}
override fun radioPlayFailed() {
Snackbar.make(radioView, R.string.radio__play_failed, Snackbar.LENGTH_SHORT).show()
}
override fun radioPlaySuccessful() {
Snackbar.make(radioView, R.string.radio__play_successful, Snackbar.LENGTH_SHORT).show()
}
override fun showLoading() {
emptyViewProgress.visibility = View.VISIBLE
emptyViewIcon.visibility = View.GONE
emptyViewTitle.visibility = View.GONE
emptyViewSubTitle.visibility = View.GONE
}
override fun hideLoading() {
emptyViewProgress.visibility = View.GONE
emptyViewIcon.visibility = View.VISIBLE
emptyViewTitle.visibility = View.VISIBLE
emptyViewSubTitle.visibility = View.VISIBLE
swipeLayout.isRefreshing = false
}
@javax.inject.Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class Presenter
}
| gpl-3.0 |
Yubico/yubioath-android | app/src/main/kotlin/com/yubico/yubioath/exc/PasswordRequiredException.kt | 1 | 1712 | /*
* Copyright (c) 2013, Yubico AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package com.yubico.yubioath.exc
/**
* Created with IntelliJ IDEA.
* User: dain
* Date: 8/23/13
* Time: 4:26 PM
* To change this template use File | Settings | File Templates.
*/
class PasswordRequiredException(message: String, val deviceId: String, val salt: ByteArray, val isMissing: Boolean) : AppletSelectException(message)
| bsd-2-clause |
mdaniel/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/TextFieldComponent.kt | 5 | 2147 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.textField
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JComponent
class TextFieldComponent(
context: Context,
labelText: String? = null,
description: String? = null,
initialValue: String? = null,
validator: SettingValidator<String>? = null,
onValueUpdate: (String, isByUser: Boolean) -> Unit = { _, _ -> }
) : UIComponent<String>(
context,
labelText,
validator,
onValueUpdate
) {
private var isDisabled: Boolean = false
private var cachedValueWhenDisabled: String? = null
@Suppress("HardCodedStringLiteral")
private val textField = textField(initialValue.orEmpty(), ::fireValueUpdated)
override val alignTarget: JComponent get() = textField
override val uiComponent = componentWithCommentAtBottom(textField, description)
override fun updateUiValue(newValue: String) = safeUpdateUi {
textField.text = newValue
}
fun onUserType(action: () -> Unit) {
textField.addKeyListener(object : KeyAdapter() {
override fun keyReleased(e: KeyEvent?) = action()
})
}
fun disable(@Nls message: String) {
cachedValueWhenDisabled = getUiValue()
textField.isEditable = false
textField.foreground = UIUtil.getLabelDisabledForeground()
isDisabled = true
updateUiValue(message)
}
override fun validate(value: String) {
if (isDisabled) return
super.validate(value)
}
override fun getUiValue(): String = cachedValueWhenDisabled ?: textField.text
} | apache-2.0 |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/zolotayakorona/RussiaTaxCodes.kt | 1 | 4254 | package au.id.micolous.metrodroid.transit.zolotayakorona
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.util.NumberUtils
// Tax codes assigned by Russian Tax agency for places both inside Russia (e.g. Moscow) and outside (e.g. Baikonur)
// They are used by Zolotaya Korona and Umarsh
// This dataset may also include additional codes used by those systems
object RussiaTaxCodes {
@Suppress("FunctionName")
fun BCDToTimeZone(bcd: Int): MetroTimeZone = TAX_CODES[bcd]?.second ?: MetroTimeZone.MOSCOW
fun codeToName(regionNum: Int): String = TAX_CODES[NumberUtils.intToBCD(regionNum)]?.first?.let { Localizer.localizeString(it) } ?: Localizer.localizeString(R.string.unknown_format, regionNum)
@Suppress("FunctionName")
fun BCDToName(regionNum: Int): String = TAX_CODES[regionNum]?.first?.let { Localizer.localizeString(it) } ?: Localizer.localizeString(R.string.unknown_format, regionNum.toString(16))
private val TAX_CODES = mapOf(
// List of cities is taken from Zolotaya Korona website. Regions match
// license plate regions
//
// Gorno-Altaysk
0x04 to Pair(R.string.russia_region_04_altai_republic, MetroTimeZone.KRASNOYARSK),
// Syktyvkar and Ukhta
0x11 to Pair(R.string.russia_region_11_komi, MetroTimeZone.KIROV),
0x12 to Pair(R.string.russia_region_12_mari_el, MetroTimeZone.MOSCOW),
0x18 to Pair(R.string.russia_region_18_udmurt, MetroTimeZone.SAMARA),
// Biysk
0x22 to Pair(R.string.russia_region_22_altai, MetroTimeZone.KRASNOYARSK),
// Krasnodar and Sochi
0x23 to Pair(R.string.russia_region_23_krasnodar, MetroTimeZone.MOSCOW),
// Vladivostok
0x25 to Pair(R.string.russia_region_25_primorsky, MetroTimeZone.VLADIVOSTOK),
// Khabarovsk
0x27 to Pair(R.string.russia_region_27_khabarovsk, MetroTimeZone.VLADIVOSTOK),
// Blagoveshchensk
0x28 to Pair(R.string.russia_region_28_amur, MetroTimeZone.YAKUTSK),
// Arkhangelsk
0x29 to Pair(R.string.russia_region_29_arkhangelsk, MetroTimeZone.MOSCOW),
// Petropavlovsk-Kamchatsky
0x41 to Pair(R.string.russia_region_41_kamchatka, MetroTimeZone.KAMCHATKA),
// Kemerovo and Novokuznetsk
0x42 to Pair(R.string.russia_region_42_kemerovo, MetroTimeZone.NOVOKUZNETSK),
0x43 to Pair(R.string.russia_region_43_kirov, MetroTimeZone.KIROV),
// Kurgan
0x45 to Pair(R.string.russia_region_45_kurgan, MetroTimeZone.YEKATERINBURG),
0x52 to Pair(R.string.russia_region_52_nizhnij_novgorod, MetroTimeZone.MOSCOW),
// Veliky Novgorod
0x53 to Pair(R.string.russia_region_53_novgorod, MetroTimeZone.MOSCOW),
// Novosibirsk
0x54 to Pair(R.string.russia_region_54_novosibirsk, MetroTimeZone.NOVOSIBIRSK),
// Omsk
0x55 to Pair(R.string.russia_region_55_omsk, MetroTimeZone.OMSK),
// Orenburg
0x56 to Pair(R.string.russia_region_56_orenburg, MetroTimeZone.YEKATERINBURG),
0x58 to Pair(R.string.russia_region_58_penza, MetroTimeZone.MOSCOW),
// Pskov
0x60 to Pair(R.string.russia_region_60_pskov, MetroTimeZone.MOSCOW),
// Samara
0x63 to Pair(R.string.russia_region_63_samara, MetroTimeZone.SAMARA),
// Kholmsk
0x65 to Pair(R.string.russia_region_65_sakhalin, MetroTimeZone.SAKHALIN),
0x66 to Pair(R.string.russia_region_66_sverdlovsk, MetroTimeZone.YEKATERINBURG),
0x74 to Pair(R.string.russia_region_74_chelyabinsk, MetroTimeZone.YEKATERINBURG),
// Yaroslavl
0x76 to Pair(R.string.russia_region_76_yaroslavl, MetroTimeZone.MOSCOW),
// Birobidzhan
0x79 to Pair(R.string.russia_region_79_jewish_autonomous, MetroTimeZone.VLADIVOSTOK),
// 91 = Code used by Umarsh for Crimea
0x91 to Pair(R.string.umarsh_91_crimea, MetroTimeZone.SIMFEROPOL)
)
} | gpl-3.0 |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/hid/HIDButton.kt | 1 | 466 | package org.snakeskin.hid
import org.snakeskin.ability.IInvertable
import org.snakeskin.hid.provider.IButtonValueProvider
class HIDButton(private val provider: IButtonValueProvider,
override var inverted: Boolean = false): IInvertable {
internal var registered = false
@Synchronized fun read(): Boolean {
if (!registered) return inverted
if (inverted)
return !provider.read()
return provider.read()
}
} | gpl-3.0 |
VTUZ-12IE1bzud/TruckMonitor-Android | app/src/main/kotlin/ru/annin/truckmonitor/presentation/ui/activity/SplashActivity.kt | 1 | 1137 | package ru.annin.truckmonitor.presentation.ui.activity
import android.os.Bundle
import com.arellomobile.mvp.MvpAppCompatActivity
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.PresenterType
import com.arellomobile.mvp.presenter.ProvidePresenter
import ru.annin.truckmonitor.data.repository.SettingsRepository
import ru.annin.truckmonitor.presentation.presenter.SplashPresenter
import ru.annin.truckmonitor.presentation.ui.view.SplashView
/**
* Экран "Заставка".
*
* @author Pavel Annin.
*/
class SplashActivity : MvpAppCompatActivity(), SplashView {
// Component's
@InjectPresenter(type = PresenterType.LOCAL)
lateinit var presenter: SplashPresenter
@ProvidePresenter(type = PresenterType.LOCAL)
fun providePresenter() = SplashPresenter(SettingsRepository)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun navigate2Login() {
LoginActivity.start(this)
finish()
}
override fun navigate2Main() {
MainActivity.start(this)
finish()
}
} | apache-2.0 |
spinnaker/orca | orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/DeployCanaryServerGroupsStageTest.kt | 4 | 5273 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.kayenta.pipeline
import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.FindImageFromClusterStage
import com.netflix.spinnaker.orca.kato.pipeline.ParallelDeployStage
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilderImpl
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
internal object DeployCanaryServerGroupsStageTest : Spek({
describe("constructing synthetic stages") {
val subject = DeployCanaryServerGroupsStage()
given("a canary deployment pipeline") {
val baseline = mapOf(
"application" to "spindemo",
"account" to "prod",
"cluster" to "spindemo-prestaging-prestaging"
)
val controlServerGroupA = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "baseline-a"
)
}
val controlServerGroupB = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "baseline-b"
)
}
val experimentServerGroupA = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "canary-a"
)
}
val experimentServerGroupB = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "canary-b"
)
}
val pipeline = pipeline {
stage {
refId = "1"
type = KayentaCanaryStage.STAGE_TYPE
context["deployments"] = mapOf(
"baseline" to baseline,
"serverGroupPairs" to listOf(
mapOf(
"control" to controlServerGroupA,
"experiment" to experimentServerGroupA
),
mapOf(
"control" to controlServerGroupB,
"experiment" to experimentServerGroupB
)
)
)
stage {
refId = "1<1"
type = DeployCanaryServerGroupsStage.STAGE_TYPE
}
}
}
val canaryDeployStage = pipeline.stageByRef("1<1")
val beforeStages = subject.beforeStages(canaryDeployStage)
it("creates a find image and deploy stages for the control serverGroup") {
beforeStages.named("Find baseline image") {
assertThat(type).isEqualTo(FindImageFromClusterStage.PIPELINE_CONFIG_TYPE)
assertThat(requisiteStageRefIds).isEmpty()
assertThat(context["application"]).isEqualTo(baseline["application"])
assertThat(context["account"]).isEqualTo(baseline["account"])
assertThat(context["serverGroup"]).isEqualTo(baseline["serverGroup"])
assertThat(context["cloudProvider"]).isEqualTo("aws")
assertThat(context["regions"]).isEqualTo(setOf("us-west-1"))
}
beforeStages.named("Deploy control server groups") {
assertThat(type).isEqualTo(ParallelDeployStage.PIPELINE_CONFIG_TYPE)
assertThat(requisiteStageRefIds).hasSize(1)
assertThat(pipeline.stageByRef(requisiteStageRefIds.first()).name)
.isEqualTo("Find baseline image")
assertThat(context["clusters"]).isEqualTo(listOf(controlServerGroupA, controlServerGroupB))
}
}
it("creates a deploy stage for the experiment serverGroup") {
beforeStages.named("Deploy experiment server groups") {
assertThat(type).isEqualTo(ParallelDeployStage.PIPELINE_CONFIG_TYPE)
assertThat(requisiteStageRefIds).isEmpty()
assertThat(context["clusters"]).isEqualTo(listOf(experimentServerGroupA, experimentServerGroupB))
}
}
}
}
})
fun List<StageExecution>.named(name: String, block: StageExecution.() -> Unit) {
find { it.name == name }
?.apply(block)
?: fail("Expected a stage named '$name' but found ${map(StageExecution::getName)}")
}
fun StageDefinitionBuilder.beforeStages(stage: StageExecution) =
StageGraphBuilderImpl.beforeStages(stage).let { graph ->
beforeStages(stage, graph)
graph.build().toList().also {
stage.execution.stages.addAll(it)
}
}
| apache-2.0 |
andgate/Ikou | core/src/com/andgate/ikou/graphics/player/PlayerModel.kt | 1 | 2122 | /*
This file is part of Ikou.
Ikou is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License.
Ikou is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ikou. If not, see <http://www.gnu.org/licenses/>.
*/
package com.andgate.ikou.graphics.player;
import com.andgate.ikou.constants.*
import com.andgate.ikou.graphics.util.CubeMesher
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Mesh
import com.badlogic.gdx.graphics.g3d.Material
import com.badlogic.gdx.graphics.g3d.Renderable
import com.badlogic.gdx.graphics.g3d.RenderableProvider
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.Pool
class PlayerModel : RenderableProvider, Disposable
{
val material = Material(TILE_MATERIAL)
val mesh: Mesh
val transform = Matrix4()
init {
val mesher = CubeMesher()
mesher.calculateVerts(0f, TILE_HEIGHT, 0f, TILE_SPAN, TILE_HEIGHT, TILE_SPAN)
mesher.addAll(PLAYER_TILE_COLOR)
mesh = mesher.build()
}
override fun getRenderables(renderables: Array<Renderable>, pool: Pool<Renderable>)
{
val renderable: Renderable = pool.obtain()
renderable.material = material
renderable.meshPart.offset = 0
renderable.meshPart.size = mesh.getNumIndices()
renderable.meshPart.primitiveType = GL20.GL_TRIANGLES
renderable.meshPart.mesh = mesh
renderables.add(renderable)
renderable.worldTransform.set(transform)
}
override fun dispose()
{
mesh.dispose();
}
}
| gpl-2.0 |
kiwiandroiddev/starcraft-2-build-player | app/src/main/java/com/kiwiandroiddev/sc2buildassistant/feature/player/domain/BuildPlayerEventListener.kt | 1 | 536 | package com.kiwiandroiddev.sc2buildassistant.feature.player.domain
import com.kiwiandroiddev.sc2buildassistant.domain.entity.BuildItem
/** Interface used by BuildPlayer to notify high-level code of playback events */
interface BuildPlayerEventListener {
fun onBuildThisNow(item: BuildItem, position: Int)
fun onBuildPlay()
fun onBuildPaused()
fun onBuildStopped()
fun onBuildResumed()
fun onBuildFinished()
fun onBuildItemsChanged(newBuildItems: List<BuildItem>)
fun onIterate(newGameTimeMs: Long)
}
| mit |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/resource/FileResource.kt | 2 | 3104 | package com.eden.orchid.api.resources.resource
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.utilities.asInputStream
import org.apache.commons.io.IOUtils
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
/**
* A Resource type that provides a content to a template from a resource file on disk. When used with
* renderTemplate() or renderString(), this resource will supply the `page.content` variable to the template renderer as
* the file contents after having the embedded data removed, and any embedded data will be available in the renderer
* through the `page` variable. When used with renderRaw(), the raw contents (after having the embedded data removed)
* will be written directly instead.
*/
class FileResource(
reference: OrchidReference,
val file: File
) : OrchidResource(reference) {
override fun getContentStream(): InputStream {
return try {
FileInputStream(file)
} catch (e: Exception) {
e.printStackTrace()
"".asInputStream()
}
}
override fun canUpdate(): Boolean {
return true
}
override fun canDelete(): Boolean {
return true
}
@Throws(IOException::class)
override fun update(newContent: InputStream) {
Files.write(file.toPath(), IOUtils.toByteArray(newContent))
}
@Throws(IOException::class)
override fun delete() {
file.delete()
}
companion object {
fun pathFromFile(file: File, basePath: Path): String {
return pathFromFile(
file,
basePath.toFile()
)
}
fun pathFromFile(file: File, baseFile: File): String {
return pathFromFile(
file,
baseFile.absolutePath
)
}
fun pathFromFile(
file: File,
basePath: String
): String {
var baseFilePath = basePath
var filePath = file.path
// normalise Windows-style backslashes to common forward slashes
baseFilePath = baseFilePath.replace("\\\\".toRegex(), "/")
filePath = filePath.replace("\\\\".toRegex(), "/")
// Remove the common base path from the actual file path
if (filePath.startsWith(baseFilePath)) {
filePath = filePath.replace(baseFilePath.toRegex(), "")
}
if (filePath.startsWith("/")) {
filePath = filePath.removePrefix("/")
}
// if the path is not a child of the base path (i.e. still has relative path segments), strip those away. The
// resolved "path" of this resource will be the portion after those relative segments.
filePath = filePath.split("/".toRegex()).toTypedArray()
.filter { it: String -> !(it == ".." || it == ".") }
.joinToString("/", "", "", -1, "", null)
return filePath
}
}
}
| mit |
jk1/intellij-community | community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/createProject/CreateJavaProjectAndConfigureKotlinGuiTest.kt | 3 | 2673 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectWizard.kotlin.createProject
import com.intellij.ide.projectWizard.kotlin.model.*
import com.intellij.testGuiFramework.util.scenarios.projectStructureDialogScenarios
import org.junit.Ignore
import org.junit.Test
class CreateJavaProjectAndConfigureKotlinGuiTest : KotlinGuiTestCase() {
@Test
@JvmName("kotlin_cfg_jvm_with_lib")
fun configureKotlinJvmWithLibInJavaProject() {
createJavaProject(projectFolder)
configureKotlinJvm(libInPlugin = false)
checkKotlinLibInProject(
projectPath = projectFolder,
kotlinKind = KotlinKind.JVM,
kotlinVersion = KotlinTestProperties.kotlin_artifact_version)
projectStructureDialogScenarios.checkKotlinLibsInStructureFromProject(
projectPath = projectFolder,
kotlinKind = KotlinKind.JVM)
}
@Test
@JvmName("kotlin_cfg_jvm_no_lib")
fun configureKotlinJvmInJavaProject() {
createJavaProject(projectFolder)
configureKotlinJvm(libInPlugin = true)
projectStructureDialogScenarios.checkKotlinLibsInStructureFromPlugin(
kotlinKind = KotlinKind.JVM,
kotlinVersion = KotlinTestProperties.kotlin_artifact_version)
}
@Test
@JvmName("kotlin_cfg_js_with_lib")
fun configureKotlinJSWithLibInJavaProject() {
createJavaProject(projectFolder)
configureKotlinJs(libInPlugin = false)
checkKotlinLibInProject(
projectPath = projectFolder,
kotlinKind = KotlinKind.JS,
kotlinVersion = KotlinTestProperties.kotlin_artifact_version)
projectStructureDialogScenarios.checkKotlinLibsInStructureFromProject(
projectPath = projectFolder,
kotlinKind = KotlinKind.JS)
}
@Test
@JvmName("kotlin_cfg_js_no_lib")
fun configureKotlinJSInJavaProject() {
createJavaProject(projectFolder)
configureKotlinJs(libInPlugin = true)
projectStructureDialogScenarios.checkKotlinLibsInStructureFromPlugin(
kotlinKind = KotlinKind.JS,
kotlinVersion = KotlinTestProperties.kotlin_artifact_version)
}
@Test
@Ignore
@JvmName("kotlin_cfg_js_no_lib_from_file")
fun configureKotlinJSInJavaProjectFromKotlinFile() {
createJavaProject(projectFolder)
// createKotlinFile(
// projectName = projectFolder.name,
// fileName = "K1")
// ideFrame { popupClick("org.jetbrains.kotlin.idea.configuration.KotlinGradleModuleConfigurator@4aae5ef8")
// }
// configureKotlinJs(libInPlugin = true)
// checkKotlinLibsInStructureFromPlugin(
// projectType = KotlinKind.JS,
// errors = collector)
}
} | apache-2.0 |
NiciDieNase/chaosflix | touch/src/androidTest/java/de/nicidienase/chaosflix/PersistenceTest.kt | 1 | 972 | package de.nicidienase.chaosflix
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import de.nicidienase.chaosflix.common.ChaosflixDatabase
import de.nicidienase.chaosflix.common.userdata.entities.progress.PlaybackProgress
import java.util.Date
import org.junit.Test
import org.junit.runner.RunWith
/**
* Created by felix on 31.10.17.
*/
@RunWith(AndroidJUnit4::class)
class PersistenceTest {
@Test
fun test1() {
val context = InstrumentationRegistry.getInstrumentation().context
val dummyGuid = "asasdlfkjsd"
val playbackProgressDao = ChaosflixDatabase.getInstance(context).playbackProgressDao()
val watchDate = Date().time
playbackProgressDao.saveProgress(PlaybackProgress(23, dummyGuid, 1337, watchDate))
playbackProgressDao.getProgressForEvent(dummyGuid)
.observeForever { assert(it?.id == 23L && it.progress == 1337L) }
}
}
| mit |
pdvrieze/kotlinsql | sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/dml/Select1.kt | 1 | 1839 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.kotlinsql.dml
import io.github.pdvrieze.kotlinsql.ddl.Column
import io.github.pdvrieze.kotlinsql.ddl.IColumnType
import io.github.pdvrieze.kotlinsql.dml.impl._Select1
interface Select1<T1 : Any, S1 : IColumnType<T1, S1, C1>, C1 : Column<T1, S1, C1>> : SelectStatement {
override val select: _Select1<T1, S1, C1>
val col1: C1 get() = select.col1
/*
@NonMonadicApi
fun getSingle(connection: MonadicDBConnection<*>): T1
@NonMonadicApi
fun getSingleOrNull(connection: MonadicDBConnection<*>): T1?
@NonMonadicApi
fun getList(connection: MonadicDBConnection<*>): List<T1?>
@Deprecated("This can be done outside the function", ReplaceWith("getList(connection).filterNotNull()"),
DeprecationLevel.ERROR)
@NonMonadicApi
fun getSafeList(connection: MonadicDBConnection<*>): List<T1> = getList(connection).filterNotNull()
@NonMonadicApi
fun execute(connection: MonadicDBConnection<*>, block: (T1?) -> Unit): Boolean
@NonMonadicApi
fun hasRows(connection: MonadicDBConnection<*>): Boolean
*/
} | apache-2.0 |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/types/Extensions.kt | 1 | 2997 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types
import com.intellij.openapi.util.Computable
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import org.rust.ide.utils.recursionGuard
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.infer.*
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyReference
import org.rust.lang.core.types.ty.TyUnknown
val RsTypeReference.type: Ty
get() = recursionGuard(this, Computable { inferTypeReferenceType(this) })
?: TyUnknown
val RsTypeElement.lifetimeElidable: Boolean get() {
val typeOwner = owner.parent
return typeOwner !is RsFieldDecl && typeOwner !is RsTupleFieldDecl && typeOwner !is RsTypeAlias
}
val RsTypeBearingItemElement.type: Ty
get() = CachedValuesManager.getCachedValue(this, CachedValueProvider {
val type = recursionGuard(this, Computable { inferDeclarationType(this) })
?: TyUnknown
CachedValueProvider.Result.create(type, PsiModificationTracker.MODIFICATION_COUNT)
})
val RsFunction.inferenceContext: RsInferenceContext
get() = CachedValuesManager.getCachedValue(this, CachedValueProvider {
CachedValueProvider.Result.create(inferTypesIn(this), PsiModificationTracker.MODIFICATION_COUNT)
})
val RsPatBinding.type: Ty
get() = this.parentOfType<RsFunction>()?.inferenceContext?.getBindingType(this) ?: TyUnknown
val RsExpr.type: Ty
get() = this.parentOfType<RsFunction>()?.inferenceContext?.getExprType(this) ?: inferOutOfFnExpressionType(this)
val RsExpr.declaration: RsCompositeElement?
get() = when (this) {
is RsPathExpr -> path.reference.resolve()
else -> null
}
private val DEFAULT_MUTABILITY = true
val RsExpr.isMutable: Boolean get() {
return when (this) {
is RsPathExpr -> {
val declaration = path.reference.resolve() ?: return DEFAULT_MUTABILITY
if (declaration is RsSelfParameter) return declaration.isMut
if (declaration is RsPatBinding && declaration.isMut) return true
if (declaration is RsConstant) return declaration.isMut
val type = this.type
if (type is TyReference) return type.mutable
val letExpr = declaration.parentOfType<RsLetDecl>()
if (letExpr != null && letExpr.eq == null) return true
if (type is TyUnknown) return DEFAULT_MUTABILITY
if (declaration is RsEnumVariant) return true
false
}
// is RsFieldExpr -> (expr.type as? TyReference)?.mutable ?: DEFAULT_MUTABILITY // <- this one brings false positives without additional analysis
is RsUnaryExpr -> mul != null || (expr != null && expr?.isMutable ?: DEFAULT_MUTABILITY)
else -> DEFAULT_MUTABILITY
}
}
| mit |
marklemay/IntelliJATS | src/main/kotlin/com/atslangplugin/psi/impl/ATSStaticFileImpl.kt | 1 | 467 | package com.atslangplugin.psi.impl
import com.atslangplugin.ATSFileTypeStatic
import com.atslangplugin.ATSLanguage
import com.atslangplugin.psi.ATSStaticFile
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.FileViewProvider
class ATSStaticFileImpl(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, ATSLanguage), ATSStaticFile {
override fun getFileType(): FileType = ATSFileTypeStatic
} | gpl-3.0 |
ktorio/ktor | ktor-network/ktor-network-tls/nix/src/io/ktor/network/tls/CipherSuitesNative.kt | 1 | 220 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.tls
internal actual fun CipherSuite.isSupported(): Boolean = false
| apache-2.0 |
daviddenton/k2 | src/main/kotlin/io/github/daviddenton/k2/contract/Binding.kt | 1 | 2180 | package io.github.daviddenton.k2.contract
import io.github.daviddenton.k2.http.Method
import io.github.daviddenton.k2.http.Request
import io.github.daviddenton.k2.util.then
import io.netty.handler.codec.http.QueryStringEncoder
sealed class Binding(val parameter: NamedParameter<*, *>) : (RequestBuilder) -> RequestBuilder
class QueryBinding(parameter: NamedParameter<*, *>, private val value: String) : Binding(parameter) {
override fun invoke(requestBuild: RequestBuilder): RequestBuilder =
requestBuild.copy(queries = requestBuild.queries.plus(
parameter.name to listOf(value).plus(requestBuild.queries[parameter.name] ?: emptyList())))
}
class PathBinding(parameter: NamedParameter<*, *>, private val value: String) : Binding(parameter) {
override fun invoke(requestBuild: RequestBuilder) = requestBuild.copy(uriParts = requestBuild.uriParts.plus(value))
}
open class RequestBinding(parameter: NamedParameter<*, *>, private val into: (Request) -> Request) : Binding(parameter) {
override fun invoke(requestBuild: RequestBuilder) = requestBuild.copy(fn = requestBuild.fn.then(into))
}
class FormFieldBinding(parameter: NamedParameter<*, *>, private val value: String) : RequestBinding(parameter, { it }) {
operator fun invoke(form: Form): Form = form + (parameter.name to value)
}
class HeaderBinding(parameter: NamedParameter<*, *>, private val value: String) : RequestBinding(parameter,
{ it.header(parameter.name to value) })
data class RequestBuilder(val method: Method,
val uriParts: Iterable<String> = listOf(),
val queries: Map<String, List<String>> = emptyMap(),
val headers: Map<String, Set<String>> = emptyMap(),
val fn: (Request) -> Request) {
fun build(): Request {
val baseUri = uriParts.joinToString { "/" }
val uri = queries.toList().fold(QueryStringEncoder(if (baseUri.isEmpty()) "/" else baseUri), {
memo, q ->
q.second.forEach { v -> memo.addParam(q.first, v) }
memo
}).toString()
return fn(Request(method, uri, "", headers))
}
}
| apache-2.0 |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/test/io/ktor/server/application/ApplicationCallReceiveTest.kt | 1 | 1193 | /*
* 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.application
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.content.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlin.test.*
class ApplicationCallReceiveTest {
@Test
fun testReceiveNonNullable() = testApplication {
val nullPlugin = createApplicationPlugin("NullPlugin") {
onCallReceive { _ ->
transformBody {
NullBody
}
}
}
install(nullPlugin)
routing {
post("/") {
val result: String = try {
call.receive()
} catch (cause: Throwable) {
cause.message ?: cause.toString()
}
call.respond(result)
}
}
val response = client.post("/")
assertEquals("Cannot transform this request's content to kotlin.String", response.bodyAsText())
}
}
| apache-2.0 |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-websockets/jvm/test/io/ktor/tests/websocket/WebSocketWithContentNegotiationTest.kt | 1 | 1690 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.websocket
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.server.websocket.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.websocket.*
import kotlin.test.*
@Suppress("DEPRECATION")
class WebSocketWithContentNegotiationTest {
@Test
fun test(): Unit = withTestApplication {
application.install(WebSockets)
application.install(ContentNegotiation) {
val converter = object : ContentConverter {
override suspend fun serializeNullable(
contentType: ContentType,
charset: Charset,
typeInfo: TypeInfo,
value: Any?
): OutgoingContent = fail("convertForSend shouldn't be invoked")
override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any? {
fail("convertForReceive shouldn't be invoked")
}
}
register(ContentType.Any, converter)
}
application.routing {
webSocket("/") {
outgoing.send(Frame.Text("OK"))
}
}
handleWebSocketConversation("/", {}) { incoming, _ ->
incoming.receive()
}
}
}
| apache-2.0 |
HaliteChallenge/Halite-II | airesources/Kotlin/src/kotlin/halite/Move.kt | 1 | 394 | package halite
enum class MoveType { Noop, Thrust, Dock, Undock }
open class Move(val type: MoveType, val ship: Ship)
class ThrustMove(ship: Ship, val angle: Int, val thrust: Int) : Move(MoveType.Thrust, ship)
class UndockMove(ship: Ship) : Move(MoveType.Undock, ship)
class DockMove(ship: Ship, planet: Planet) : Move(MoveType.Dock, ship) {
val destinationId: Long = planet.id.toLong()
} | mit |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/EXT_timer_query.kt | 4 | 2273 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val EXT_timer_query = "EXTTimerQuery".nativeClassGL("EXT_timer_query", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
Applications can benefit from accurate timing information in a number of different ways. During application development, timing information can help
identify application or driver bottlenecks. At run time, applications can use timing information to dynamically adjust the amount of detail in a scene
to achieve constant frame rates. OpenGL implementations have historically provided little to no useful timing information. Applications can get some
idea of timing by reading timers on the CPU, but these timers are not synchronized with the graphics rendering pipeline. Reading a CPU timer does not
guarantee the completion of a potentially large amount of graphics work accumulated before the timer is read, and will thus produce wildly inaccurate
results. glFinish() can be used to determine when previous rendering commands have been completed, but will idle the graphics pipeline and adversely
affect application performance.
This extension provides a query mechanism that can be used to determine the amount of time it takes to fully complete a set of GL commands, and without
stalling the rendering pipeline. It uses the query object mechanisms first introduced in the occlusion query extension, which allow time intervals to
be polled asynchronously by the application.
Requires ${GL15.core}.
"""
IntConstant(
"Accepted by the {@code target} parameter of BeginQuery, EndQuery, and GetQueryiv.",
"TIME_ELAPSED_EXT"..0x88BF
)
void(
"GetQueryObjecti64vEXT",
"",
GLuint("id", ""),
GLenum("pname", ""),
RawPointer..ReturnParam..Check(1)..GLint64.p("params", "")
)
void(
"GetQueryObjectui64vEXT",
"",
GLuint("id", ""),
GLenum("pname", ""),
RawPointer..ReturnParam..Check(1)..GLuint64.p("params", "")
)
} | bsd-3-clause |
ayatk/biblio | app/src/main/kotlin/com/ayatk/biblio/ui/search/SearchActivity.kt | 1 | 5643 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.ui.search
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.SearchView
import androidx.core.view.GravityCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.ayatk.biblio.R
import com.ayatk.biblio.databinding.ActivitySearchBinding
import com.ayatk.biblio.di.ViewModelFactory
import com.ayatk.biblio.model.Novel
import com.ayatk.biblio.ui.search.item.SearchResultItem
import com.ayatk.biblio.ui.util.helper.navigateToDetail
import com.ayatk.biblio.ui.util.init
import com.ayatk.biblio.ui.util.initBackToolbar
import com.ayatk.biblio.util.Result
import com.ayatk.biblio.util.ext.observe
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import dagger.android.support.DaggerAppCompatActivity
import timber.log.Timber
import javax.inject.Inject
class SearchActivity : DaggerAppCompatActivity() {
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val viewModel: SearchViewModel by lazy {
ViewModelProvider(this, viewModelFactory).get(SearchViewModel::class.java)
}
private val binding: ActivitySearchBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_search)
}
private lateinit var searchView: SearchView
private val groupAdapter = GroupAdapter<ViewHolder>()
private val onItemClickListener = { novel: Novel ->
navigateToDetail(novel)
}
private val onDownloadClickListener: (Novel) -> Unit = { novel: Novel ->
viewModel.saveNovel(novel)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
overridePendingTransition(R.anim.activity_fade_enter, R.anim.activity_fade_exit)
binding.lifecycleOwner = this
binding.viewModel = viewModel
initBackToolbar(binding.toolbar)
val scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
searchView.clearFocus()
}
}
}
binding.searchResult.init(groupAdapter, scrollListener)
binding.drawerLayout.addDrawerListener(
object : ActionBarDrawerToggle(
this, binding.drawerLayout, R.string.drawer_open,
R.string.drawer_close
) {
override fun onDrawerStateChanged(newState: Int) {
super.onDrawerStateChanged(newState)
Timber.d(newState.toString())
if (newState != DrawerLayout.STATE_IDLE) {
searchView.clearFocus()
}
}
}
)
viewModel.result.observe(this) { result ->
when (result) {
is Result.Success -> {
val novels = result.data
groupAdapter.update(novels.map {
SearchResultItem(it, onItemClickListener, onDownloadClickListener)
})
if (binding.searchResult.isGone) {
binding.searchResult.isVisible = novels.isNotEmpty()
}
}
is Result.Failure -> Timber.e(result.e)
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_search, menu)
val menuItem = menu.findItem(R.id.action_search)
menuItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean = true
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
onBackPressed()
return false
}
}
)
menuItem.expandActionView()
searchView = menuItem.actionView as SearchView
searchView.setOnQueryTextListener(
object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean = onQueryTextChange(query)
override fun onQueryTextChange(newText: String): Boolean {
viewModel.setQuery(newText)
return false
}
}
)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_filter) {
searchView.clearFocus()
binding.drawerLayout.openDrawer(GravityCompat.END)
return true
}
return super.onOptionsItemSelected(item)
}
override fun finish() {
super.finish()
overridePendingTransition(0, R.anim.activity_fade_exit)
}
override fun onBackPressed() {
if (binding.drawerLayout.isDrawerOpen(GravityCompat.END)) {
binding.drawerLayout.closeDrawer(GravityCompat.END)
} else {
finish()
}
}
companion object {
fun createIntent(context: Context): Intent = Intent(context, SearchActivity::class.java)
}
}
| apache-2.0 |
octarine-noise/BetterFoliage | src/main/kotlin/mods/betterfoliage/client/render/RenderLog.kt | 1 | 3118 | package mods.betterfoliage.client.render
import mods.betterfoliage.BetterFoliageMod
import mods.betterfoliage.client.chunk.ChunkOverlayManager
import mods.betterfoliage.client.config.Config
import mods.betterfoliage.client.render.column.AbstractRenderColumn
import mods.betterfoliage.client.render.column.ColumnRenderLayer
import mods.betterfoliage.client.render.column.ColumnTextureInfo
import mods.betterfoliage.client.render.column.SimpleColumnInfo
import mods.octarinecore.client.render.BlockContext
import mods.octarinecore.client.resource.*
import mods.octarinecore.common.config.ConfigurableBlockMatcher
import mods.octarinecore.common.config.ModelTextureList
import mods.octarinecore.tryDefault
import net.minecraft.block.BlockLog
import net.minecraft.block.state.IBlockState
import net.minecraft.util.EnumFacing.Axis
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
class RenderLog : AbstractRenderColumn(BetterFoliageMod.MOD_ID) {
override val addToCutout: Boolean get() = false
override fun isEligible(ctx: BlockContext) =
Config.enabled && Config.roundLogs.enabled &&
Config.blocks.logClasses.matchesClass(ctx.block)
override val overlayLayer = RoundLogOverlayLayer()
override val connectPerpendicular: Boolean get() = Config.roundLogs.connectPerpendicular
override val radiusSmall: Double get() = Config.roundLogs.radiusSmall
override val radiusLarge: Double get() = Config.roundLogs.radiusLarge
init {
ChunkOverlayManager.layers.add(overlayLayer)
}
}
class RoundLogOverlayLayer : ColumnRenderLayer() {
override val registry: ModelRenderRegistry<ColumnTextureInfo> get() = LogRegistry
override val blockPredicate = { state: IBlockState -> Config.blocks.logClasses.matchesClass(state.block) }
override val surroundPredicate = { state: IBlockState -> state.isOpaqueCube && !Config.blocks.logClasses.matchesClass(state.block) }
override val connectSolids: Boolean get() = Config.roundLogs.connectSolids
override val lenientConnect: Boolean get() = Config.roundLogs.lenientConnect
override val defaultToY: Boolean get() = Config.roundLogs.defaultY
}
@SideOnly(Side.CLIENT)
object LogRegistry : ModelRenderRegistryRoot<ColumnTextureInfo>()
object StandardLogRegistry : ModelRenderRegistryConfigurable<ColumnTextureInfo>() {
override val logger = BetterFoliageMod.logDetail
override val matchClasses: ConfigurableBlockMatcher get() = Config.blocks.logClasses
override val modelTextures: List<ModelTextureList> get() = Config.blocks.logModels.list
override fun processModel(state: IBlockState, textures: List<String>) = SimpleColumnInfo.Key(logger, getAxis(state), textures)
fun getAxis(state: IBlockState): Axis? {
val axis = tryDefault(null) { state.getValue(BlockLog.LOG_AXIS).toString() } ?:
state.properties.entries.find { it.key.getName().toLowerCase() == "axis" }?.value?.toString()
return when (axis) {
"x" -> Axis.X
"y" -> Axis.Y
"z" -> Axis.Z
else -> null
}
}
} | mit |
Frederikam/FredBoat | FredBoat/src/test/java/fredboat/testutil/extensions/SharedSpringContext.kt | 1 | 3257 | package fredboat.testutil.extensions
import fredboat.commandmeta.CommandInitializer
import fredboat.main.Launcher
import fredboat.sentinel.SentinelTracker
import fredboat.testutil.IntegrationTest
import fredboat.testutil.config.RabbitConfig
import fredboat.testutil.sentinel.CommandTester
import fredboat.testutil.sentinel.SentinelState
import fredboat.testutil.sentinel.delayUntil
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.junit.Assert.assertTrue
import org.junit.jupiter.api.extension.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.support.AbstractApplicationContext
import java.lang.System.currentTimeMillis
import java.lang.Thread.sleep
import kotlin.system.exitProcess
class SharedSpringContext : ParameterResolver, BeforeAllCallback, AfterEachCallback {
companion object {
private val log: Logger = LoggerFactory.getLogger(SharedSpringContext::class.java)
private var application: AbstractApplicationContext? = null
}
override fun beforeAll(context: ExtensionContext) {
if (application != null) return // Don't start the application again
log.info("Initializing test context")
val job = GlobalScope.launch {
try {
Launcher.main(emptyArray())
} catch (t: Throwable) {
log.error("Failed initializing context", t)
exitProcess(-1)
}
}
val start = currentTimeMillis()
var i = 0
while (Launcher.instance == null) {
sleep(1000)
i++
if (currentTimeMillis() - start > 3 * 60000) {
log.error("Context initialization timed out")
exitProcess(-1)
}
}
log.info("Acquired Spring context after ${(currentTimeMillis() - start)/1000} seconds")
application = Launcher.springContext
try {
// Context may or may not be refreshed yet. Refreshing too many times will throw an exception
application!!.refresh()
} catch (ignored: IllegalStateException) {}
val helloSender = application!!.getBean(RabbitConfig.HelloSender::class.java)
val tracker = application!!.getBean(SentinelTracker::class.java)
delayUntil(timeout = 10000) {
helloSender.send()
tracker.getHello(0) != null
}
IntegrationTest.commandTester = application!!.getBean(CommandTester::class.java)
delayUntil(timeout = 10000) { CommandInitializer.initialized }
assertTrue("Command initialization timed out", CommandInitializer.initialized)
log.info("Successfully initialized test context ${application!!.javaClass.simpleName}")
}
override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean {
return application!!.getBean(parameterContext.parameter.type) != null
}
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any {
return application!!.getBean(parameterContext.parameter.type)
}
override fun afterEach(context: ExtensionContext?) {
SentinelState.reset()
}
} | mit |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/event/internal/EventEndpointCallShould.kt | 1 | 6088 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.event.internal
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.mock
import java.util.concurrent.Callable
import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutorImpl
import org.hisp.dhis.android.core.arch.api.testutils.RetrofitFactory
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter
import org.hisp.dhis.android.core.event.Event
import org.hisp.dhis.android.core.mockwebserver.Dhis2MockServer
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitMode
import org.hisp.dhis.android.core.trackedentity.internal.TrackerQueryCommonParams
import org.hisp.dhis.android.core.trackedentity.internal.TrackerQueryCommonParamsSamples.get
import org.hisp.dhis.android.core.tracker.exporter.TrackerAPIQuery
import org.hisp.dhis.android.core.user.internal.UserAccountDisabledErrorCatcher
import org.junit.AfterClass
import org.junit.BeforeClass
import org.junit.Test
import retrofit2.Retrofit
class EventEndpointCallShould {
private val orgunit = "orgunitUid"
private val program = "proramUid"
private val startDateStr = "2021-01-01"
private val databaseAdapter: DatabaseAdapter = mock()
private val userAccountDisabledErrorCatcher: UserAccountDisabledErrorCatcher = mock()
@Test
fun realize_request_with_page_filters_when_included_in_query() {
val eventEndpointCall = givenAEventCallByPagination(2, 32)
mockWebServer.enqueueMockResponse()
eventEndpointCall.call()
val request = mockWebServer.takeRequest()
assertThat(request.path).contains("paging=true&page=2&pageSize=32")
}
@Test
fun realize_request_with_orgUnit_program_filters_when_included_in_query() {
val eventEndpointCall = givenAEventCallByOrgUnitAndProgram(orgunit, program)
mockWebServer.enqueueMockResponse()
eventEndpointCall.call()
val request = mockWebServer.takeRequest()
assertThat(request.path).contains("orgUnit=$orgunit")
assertThat(request.path).contains("program=$program")
}
@Test
fun include_start_date_if_program_is_defined() {
val eventEndpointCall = givenAEventCallByOrgUnitAndProgram(orgunit, program, startDateStr)
mockWebServer.enqueueMockResponse()
eventEndpointCall.call()
val request = mockWebServer.takeRequest()
assertThat(request.path).contains(startDateStr)
}
@Test
fun does_not_include_start_date_if_program_is_not_defined() {
val eventEndpointCall = givenAEventCallByOrgUnitAndProgram(program, null, startDateStr)
mockWebServer.enqueueMockResponse()
eventEndpointCall.call()
val request = mockWebServer.takeRequest()
assertThat(request.path).doesNotContain(startDateStr)
}
private fun givenAEventCallByPagination(page: Int, pageCount: Int): Callable<List<Event>> {
val eventQuery = TrackerAPIQuery(
commonParams = get(),
page = page,
pageSize = pageCount,
paging = true
)
return givenACallForQuery(eventQuery)
}
private fun givenACallForQuery(eventQuery: TrackerAPIQuery): Callable<List<Event>> {
return EventEndpointCallFactory(
retrofit.create(EventService::class.java),
APICallExecutorImpl.create(databaseAdapter, userAccountDisabledErrorCatcher)
).getCall(eventQuery)
}
private fun givenAEventCallByOrgUnitAndProgram(
orgUnit: String,
program: String?,
startDate: String? = null
): Callable<List<Event>> {
val eventQuery = TrackerAPIQuery(
commonParams = TrackerQueryCommonParams(
listOf(),
listOfNotNull(program),
program,
startDate,
false,
OrganisationUnitMode.SELECTED, listOf(orgUnit),
10
),
orgUnit = orgUnit
)
return givenACallForQuery(eventQuery)
}
companion object {
private lateinit var retrofit: Retrofit
private lateinit var mockWebServer: Dhis2MockServer
@BeforeClass
@JvmStatic
fun setUpClass() {
mockWebServer = Dhis2MockServer(0)
retrofit = RetrofitFactory.fromDHIS2MockServer(mockWebServer)
}
@AfterClass
@JvmStatic
fun tearDownClass() {
mockWebServer.shutdown()
}
}
}
| bsd-3-clause |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutor.kt | 2 | 11039 | // Copyright 2000-2018 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 org.jetbrains.plugins.github.api
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.EventDispatcher
import com.intellij.util.ThrowableConvertor
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.HttpSecurityUtil
import com.intellij.util.io.RequestBuilder
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInBackground
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.data.GithubErrorMessage
import org.jetbrains.plugins.github.exceptions.*
import org.jetbrains.plugins.github.util.GithubSettings
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Reader
import java.net.HttpURLConnection
import java.util.*
import java.util.function.Supplier
import java.util.zip.GZIPInputStream
/**
* Executes API requests taking care of authentication, headers, proxies, timeouts, etc.
*/
sealed class GithubApiRequestExecutor {
protected val authDataChangedEventDispatcher = EventDispatcher.create(AuthDataChangeListener::class.java)
@CalledInBackground
@Throws(IOException::class, ProcessCanceledException::class)
abstract fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T
@TestOnly
@CalledInBackground
@Throws(IOException::class, ProcessCanceledException::class)
fun <T> execute(request: GithubApiRequest<T>): T = execute(EmptyProgressIndicator(), request)
fun addListener(listener: AuthDataChangeListener, disposable: Disposable) =
authDataChangedEventDispatcher.addListener(listener, disposable)
fun addListener(disposable: Disposable, listener: () -> Unit) =
authDataChangedEventDispatcher.addListener(object : AuthDataChangeListener {
override fun authDataChanged() {
listener()
}
}, disposable)
class WithTokenAuth internal constructor(githubSettings: GithubSettings,
token: String,
private val useProxy: Boolean) : Base(githubSettings) {
@Volatile
internal var token: String = token
set(value) {
field = value
authDataChangedEventDispatcher.multicaster.authDataChanged()
}
@Throws(IOException::class, ProcessCanceledException::class)
override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T {
indicator.checkCanceled()
return createRequestBuilder(request)
.tuner { connection ->
request.additionalHeaders.forEach(connection::addRequestProperty)
connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Token $token")
}
.useProxy(useProxy)
.execute(request, indicator)
}
}
class WithBasicAuth internal constructor(githubSettings: GithubSettings,
private val login: String,
private val password: CharArray,
private val twoFactorCodeSupplier: Supplier<String?>) : Base(githubSettings) {
private var twoFactorCode: String? = null
@Throws(IOException::class, ProcessCanceledException::class)
override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T {
indicator.checkCanceled()
val basicHeaderValue = HttpSecurityUtil.createBasicAuthHeaderValue(login, password)
return executeWithBasicHeader(indicator, request, basicHeaderValue)
}
private fun <T> executeWithBasicHeader(indicator: ProgressIndicator, request: GithubApiRequest<T>, header: String): T {
indicator.checkCanceled()
return try {
createRequestBuilder(request)
.tuner { connection ->
request.additionalHeaders.forEach(connection::addRequestProperty)
connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Basic $header")
twoFactorCode?.let { connection.addRequestProperty(OTP_HEADER_NAME, it) }
}
.execute(request, indicator)
}
catch (e: GithubTwoFactorAuthenticationException) {
twoFactorCode = twoFactorCodeSupplier.get() ?: throw e
executeWithBasicHeader(indicator, request, header)
}
}
}
abstract class Base(private val githubSettings: GithubSettings) : GithubApiRequestExecutor() {
protected fun <T> RequestBuilder.execute(request: GithubApiRequest<T>, indicator: ProgressIndicator): T {
indicator.checkCanceled()
try {
LOG.debug("Request: ${request.url} ${request.operationName} : Connecting")
return connect {
val connection = it.connection as HttpURLConnection
if (request is GithubApiRequest.WithBody) {
LOG.debug("Request: ${connection.requestMethod} ${connection.url} with body:\n${request.body} : Connected")
request.body?.let { body -> it.write(body) }
}
else {
LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Connected")
}
checkResponseCode(connection)
indicator.checkCanceled()
val result = request.extractResult(createResponse(it, indicator))
LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Result extracted")
result
}
}
catch (e: GithubStatusCodeException) {
@Suppress("UNCHECKED_CAST")
if (request is GithubApiRequest.Get.Optional<*> && e.statusCode == HttpURLConnection.HTTP_NOT_FOUND) return null as T else throw e
}
catch (e: GithubConfusingException) {
if (request.operationName != null) {
val errorText = "Can't ${request.operationName}"
e.setDetails(errorText)
LOG.debug(errorText, e)
}
throw e
}
}
protected fun createRequestBuilder(request: GithubApiRequest<*>): RequestBuilder {
return when (request) {
is GithubApiRequest.Get -> HttpRequests.request(request.url)
is GithubApiRequest.Post -> HttpRequests.post(request.url, request.bodyMimeType)
is GithubApiRequest.Put -> HttpRequests.put(request.url, request.bodyMimeType)
is GithubApiRequest.Patch -> HttpRequests.patch(request.url, request.bodyMimeType)
is GithubApiRequest.Head -> HttpRequests.head(request.url)
is GithubApiRequest.Delete -> HttpRequests.delete(request.url)
else -> throw UnsupportedOperationException("${request.javaClass} is not supported")
}
.connectTimeout(githubSettings.connectionTimeout)
.userAgent("Intellij IDEA Github Plugin")
.throwStatusCodeException(false)
.forceHttps(true)
.accept(request.acceptMimeType)
}
@Throws(IOException::class)
private fun checkResponseCode(connection: HttpURLConnection) {
if (connection.responseCode < 400) return
val statusLine = "${connection.responseCode} ${connection.responseMessage}"
val errorText = getErrorText(connection)
LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Error ${statusLine} body:\n${errorText}")
val jsonError = getJsonError(connection, errorText)
jsonError ?: LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Unable to parse JSON error")
throw when (connection.responseCode) {
HttpURLConnection.HTTP_UNAUTHORIZED,
HttpURLConnection.HTTP_PAYMENT_REQUIRED,
HttpURLConnection.HTTP_FORBIDDEN -> {
val otpHeader = connection.getHeaderField(OTP_HEADER_NAME)
if (otpHeader != null && otpHeader.contains("required", true)) {
GithubTwoFactorAuthenticationException(jsonError?.presentableError ?: errorText)
}
else if (jsonError?.containsReasonMessage("API rate limit exceeded") == true) {
GithubRateLimitExceededException(jsonError.presentableError)
}
else GithubAuthenticationException("Request response: " + (jsonError?.presentableError ?: errorText))
}
else -> {
if (jsonError != null) {
GithubStatusCodeException("$statusLine - ${jsonError.presentableError}", jsonError, connection.responseCode)
}
else {
GithubStatusCodeException("$statusLine - ${errorText}", connection.responseCode)
}
}
}
}
private fun getErrorText(connection: HttpURLConnection): String {
val errorStream = connection.errorStream ?: return ""
val stream = if (connection.contentEncoding == "gzip") GZIPInputStream(errorStream) else errorStream
return InputStreamReader(stream, Charsets.UTF_8).use { it.readText() }
}
private fun getJsonError(connection: HttpURLConnection, errorText: String): GithubErrorMessage? {
if (!connection.contentType.startsWith(GithubApiContentHelper.JSON_MIME_TYPE)) return null
return try {
return GithubApiContentHelper.fromJson(errorText)
}
catch (jse: GithubJsonException) {
null
}
}
private fun createResponse(request: HttpRequests.Request, indicator: ProgressIndicator): GithubApiResponse {
return object : GithubApiResponse {
override fun findHeader(headerName: String): String? = request.connection.getHeaderField(headerName)
override fun <T> readBody(converter: ThrowableConvertor<Reader, T, IOException>): T = request.getReader(indicator).use {
converter.convert(it)
}
override fun <T> handleBody(converter: ThrowableConvertor<InputStream, T, IOException>): T = request.inputStream.use {
converter.convert(it)
}
}
}
}
class Factory internal constructor(private val githubSettings: GithubSettings) {
@CalledInAny
fun create(token: String): WithTokenAuth {
return create(token, true)
}
@CalledInAny
fun create(token: String, useProxy: Boolean = true): WithTokenAuth {
return GithubApiRequestExecutor.WithTokenAuth(githubSettings, token, useProxy)
}
@CalledInAny
internal fun create(login: String, password: CharArray, twoFactorCodeSupplier: Supplier<String?>): WithBasicAuth {
return GithubApiRequestExecutor.WithBasicAuth(githubSettings, login, password, twoFactorCodeSupplier)
}
companion object {
@JvmStatic
fun getInstance(): Factory = service()
}
}
companion object {
private val LOG = logger<GithubApiRequestExecutor>()
private const val OTP_HEADER_NAME = "X-GitHub-OTP"
}
interface AuthDataChangeListener : EventListener {
fun authDataChanged()
}
} | apache-2.0 |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/events/PageDownloadEvent.kt | 2 | 140 | package org.wikipedia.events
import org.wikipedia.readinglist.database.ReadingListPage
class PageDownloadEvent(val page: ReadingListPage)
| apache-2.0 |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/TrackedEntityInstanceFilterHandler.kt | 1 | 3604 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity.internal
import dagger.Reusable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore
import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction
import org.hisp.dhis.android.core.arch.handlers.internal.HandlerWithTransformer
import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableHandlerImpl
import org.hisp.dhis.android.core.trackedentity.AttributeValueFilter
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceEventFilter
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceFilter
@Reusable
internal class TrackedEntityInstanceFilterHandler @Inject constructor(
trackedEntityInstanceFilterStore: IdentifiableObjectStore<TrackedEntityInstanceFilter>,
private val trackedEntityInstanceEventFilterHandler: HandlerWithTransformer<TrackedEntityInstanceEventFilter>,
private val attributeValueFilterHandler: HandlerWithTransformer<AttributeValueFilter>
) : IdentifiableHandlerImpl<TrackedEntityInstanceFilter>(trackedEntityInstanceFilterStore) {
override fun beforeCollectionHandled(
oCollection: Collection<TrackedEntityInstanceFilter>
): Collection<TrackedEntityInstanceFilter> {
store.delete()
return super.beforeCollectionHandled(oCollection)
}
override fun afterObjectHandled(o: TrackedEntityInstanceFilter, action: HandleAction) {
if (action !== HandleAction.Delete) {
trackedEntityInstanceEventFilterHandler
.handleMany(o.eventFilters()) { ef: TrackedEntityInstanceEventFilter ->
ef.toBuilder().trackedEntityInstanceFilter(o.uid()).build()
}
o.entityQueryCriteria().attributeValueFilters()?.let {
attributeValueFilterHandler.handleMany(it) { avf: AttributeValueFilter ->
avf.toBuilder().trackedEntityInstanceFilter(o.uid()).build()
}
}
}
}
}
| bsd-3-clause |
mdanielwork/intellij-community | community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/CommunityDTTestSuite.kt | 3 | 872 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.tests.community
import com.intellij.testGuiFramework.framework.FirstStartWith
import com.intellij.testGuiFramework.framework.RunWithIde
import com.intellij.testGuiFramework.framework.dtrace.GuiDTTestSuiteRunner
import com.intellij.testGuiFramework.launcher.ide.CommunityIde
import com.intellij.testGuiFramework.launcher.ide.CommunityIdeFirstStart
import com.intellij.testGuiFramework.tests.community.completionPopup.PopupWindowLeakTest
import org.junit.runner.RunWith
import org.junit.runners.Suite
@RunWith(GuiDTTestSuiteRunner::class)
@RunWithIde(CommunityIde::class)
@FirstStartWith(CommunityIdeFirstStart::class)
@Suite.SuiteClasses(PopupWindowLeakTest::class)
class CommunityDTTestSuite | apache-2.0 |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/parser/internal/service/utils/ExpressionHelper.kt | 1 | 3350 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.parser.internal.service.utils
import java.lang.NumberFormatException
import java.util.*
import org.apache.commons.lang3.math.NumberUtils
import org.hisp.dhis.android.core.datavalue.DataValue
import org.hisp.dhis.android.core.parser.internal.service.dataobject.DataElementObject
import org.hisp.dhis.android.core.parser.internal.service.dataobject.DataElementOperandObject
import org.hisp.dhis.android.core.parser.internal.service.dataobject.DimensionalItemObject
internal object ExpressionHelper {
@JvmStatic
fun getValueMap(dataValues: List<DataValue>): Map<DimensionalItemObject, Double> {
val valueMap: MutableMap<DimensionalItemObject, Double> = HashMap()
for (dataValue in dataValues) {
val deId = dataValue.dataElement()
val cocId = dataValue.categoryOptionCombo()
val dataElementItem: DimensionalItemObject = DataElementObject.create(deId)
addDimensionalItemValueToMap(dataElementItem, dataValue.value(), valueMap)
val dataElementOperandItem: DimensionalItemObject = DataElementOperandObject.create(deId, cocId)
addDimensionalItemValueToMap(dataElementOperandItem, dataValue.value(), valueMap)
}
return valueMap
}
private fun addDimensionalItemValueToMap(
item: DimensionalItemObject,
value: String?,
valueMap: MutableMap<DimensionalItemObject, Double>
) {
try {
val newValue = NumberUtils.createDouble(value)
val existingValue = valueMap[item]
val result = (existingValue ?: 0.0) + newValue
valueMap[item] = result
} catch (e: NumberFormatException) {
// Ignore non-numeric values
}
}
}
| bsd-3-clause |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/addAnnotationTarget/basic4.kt | 13 | 120 | // "Add annotation target" "true"
annotation class Foo
@Foo
class Test {
@Foo
fun foo(): <caret>@Foo Int = 1
} | apache-2.0 |
dahlstrom-g/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/auth/AccountDetails.kt | 8 | 366 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.collaboration.auth
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.annotations.NonNls
interface AccountDetails {
@get:NlsSafe
val name: String
@get:NonNls
val avatarUrl: String?
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantExplicitType/string.kt | 13 | 48 | fun foo() {
val s: <caret>String = "Hello"
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractKotlinExceptionFilterTest.kt | 3 | 5607 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.test
import com.intellij.execution.filters.FileHyperlinkInfo
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.idea.codegen.forTestCompile.ForTestCompileRuntime
import org.jetbrains.kotlin.idea.core.util.toVirtualFile
import org.jetbrains.kotlin.idea.debugger.InlineFunctionHyperLinkInfo
import org.jetbrains.kotlin.idea.debugger.KotlinExceptionFilterFactory
import org.jetbrains.kotlin.idea.test.*
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.net.URLClassLoader
abstract class AbstractKotlinExceptionFilterTest : KotlinLightCodeInsightFixtureTestCase() {
private companion object {
val MOCK_LIBRARY_SOURCES = IDEA_TEST_DATA_DIR.resolve("debugger/mockLibraryForExceptionFilter")
}
private lateinit var mockLibraryFacility: MockLibraryFacility
override fun fileName(): String {
val testName = getTestName(true)
return "$testName/$testName.kt"
}
override fun setUp() {
super.setUp()
val mainFile = dataFile()
val testDir = mainFile.parentFile ?: error("Invalid test directory")
val fileText = FileUtil.loadFile(mainFile, true)
val extraOptions = InTextDirectivesUtils.findListWithPrefixes(fileText, "// !LANGUAGE: ").map { "-XXLanguage:$it" }
mockLibraryFacility = MockLibraryFacility(
sources = listOf(MOCK_LIBRARY_SOURCES, testDir),
options = extraOptions
)
mockLibraryFacility.setUp(module)
}
override fun tearDown() {
runAll(
ThrowableRunnable { mockLibraryFacility.tearDown(module) },
ThrowableRunnable { super.tearDown() }
)
}
protected fun doTest(unused: String) {
val mainFile = dataFile()
val testDir = mainFile.parentFile ?: error("Invalid test directory")
val fileText = FileUtil.loadFile(mainFile, true)
val mainClass = InTextDirectivesUtils.stringWithDirective(fileText, "MAIN_CLASS")
val prefix = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// PREFIX: ") ?: "at"
val stackTraceElement = getStackTraceElement(mainClass)
val stackTraceString = stackTraceElement.toString()
val text = "$prefix $stackTraceString"
val filter = KotlinExceptionFilterFactory().create(GlobalSearchScope.allScope(project))
var result = filter.applyFilter(text, text.length) ?: throw AssertionError("Couldn't apply filter to $stackTraceElement")
if (InTextDirectivesUtils.isDirectiveDefined(fileText, "SMAP_APPLIED")) {
val info = result.firstHyperlinkInfo as FileHyperlinkInfo
val descriptor = info.descriptor!!
val file = descriptor.file
val line = descriptor.line + 1
val newStackString = stackTraceString
.replace(mainFile.name, file.name)
.replace(Regex(":\\d+\\)"), ":$line)")
val newText = "$prefix $newStackString"
result = filter.applyFilter(newText, newText.length) ?: throw AssertionError("Couldn't apply filter to $stackTraceElement")
}
val info = result.firstHyperlinkInfo as FileHyperlinkInfo
val descriptor = if (InTextDirectivesUtils.isDirectiveDefined(fileText, "NAVIGATE_TO_CALL_SITE")) {
(info as? InlineFunctionHyperLinkInfo)?.callSiteDescriptor
} else {
info.descriptor
}
if (descriptor == null) {
throw AssertionError("`$stackTraceString` did not resolve to an inline function call")
}
val expectedFileName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// FILE: ")!!
val expectedVirtualFile = File(testDir, expectedFileName).toVirtualFile()
?: File(MOCK_LIBRARY_SOURCES, expectedFileName).toVirtualFile()
?: throw AssertionError("Couldn't find file: name = $expectedFileName")
val expectedLineNumber = InTextDirectivesUtils.getPrefixedInt(fileText, "// LINE: ") ?: error("Line directive not found")
val document = FileDocumentManager.getInstance().getDocument(expectedVirtualFile)!!
val expectedOffset = document.getLineStartOffset(expectedLineNumber - 1)
val expectedLocation = "$expectedFileName:$expectedOffset"
val actualLocation = descriptor.file.name + ":" + descriptor.offset
assertEquals("Wrong result for line $stackTraceElement", expectedLocation, actualLocation)
}
private fun getStackTraceElement(mainClass: String): StackTraceElement {
val libraryRoots = ModuleRootManager.getInstance(module).orderEntries().runtimeOnly().withoutSdk()
.classesRoots.map { VfsUtilCore.virtualToIoFile(it).toURI().toURL() }
val classLoader = URLClassLoader(libraryRoots.toTypedArray(), ForTestCompileRuntime.runtimeJarClassLoader())
return try {
val clazz = classLoader.loadClass(mainClass)
clazz.getMethod("box").invoke(null)
throw AssertionError("class $mainClass should have box() method and throw exception")
} catch (e: InvocationTargetException) {
e.targetException.stackTrace[0]
}
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertToScope/convertToAlso/untilItParameter.kt | 9 | 293 | // WITH_STDLIB
// AFTER-WARNING: Parameter 'a' is never used
class MyClass {
fun foo1() = Unit
fun foo2(a: MyClass) = Unit
fun foo3() = Unit
fun foo4(it: MyClass) {
val a = MyClass()
a.foo1()
a.foo3()<caret>
a.foo2(it)
a.foo3()
}
} | apache-2.0 |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/notification/PollingState.kt | 1 | 538 | package jp.juggler.subwaytooter.notification
enum class PollingState(val desc: String) {
Complete("complete"),
Cancelled("cancelled"),
Error("error"),
Timeout("timeout"),
PrepareInstallId("preparing install id"),
CheckNetworkConnection("check network connection"),
CheckServerInformation("check server information"),
CheckPushSubscription("check push subscription"),
CheckNotifications("check notifications"),
;
companion object {
val valuesCache = values()
}
}
| apache-2.0 |
elpassion/el-space-android | el-debate/src/test/java/pl/elpassion/elspace/debate/login/DebateLoginControllerTest.kt | 1 | 6999 | package pl.elpassion.elspace.debate.login
import com.nhaarman.mockito_kotlin.*
import io.reactivex.schedulers.Schedulers
import io.reactivex.schedulers.TestScheduler
import io.reactivex.subjects.SingleSubject
import org.junit.Before
import org.junit.Test
import pl.elpassion.elspace.common.SchedulersSupplier
import pl.elpassion.elspace.dabate.details.createHttpException
import pl.elpassion.elspace.debate.DebatesRepository
import pl.elpassion.elspace.debate.LoginCredentials
class DebateLoginControllerTest {
private val view = mock<DebateLogin.View>()
private val debateRepo = mock<DebatesRepository>()
private val loginApi = mock<DebateLogin.Api>()
private val controller = DebateLoginController(view, debateRepo, loginApi, SchedulersSupplier(Schedulers.trampoline(), Schedulers.trampoline()))
private val apiSubject = SingleSubject.create<LoginCredentials>()
@Before
fun setUp() {
whenever(debateRepo.hasLoginCredentials(any())).thenReturn(false)
whenever(loginApi.login(any())).thenReturn(apiSubject)
}
@Test
fun shouldSaveReturnedTokenAndDebateCodeOnLogToDebate() {
logToDebate(debateCode = "12348")
returnTokenFromApi("authToken", 222)
verify(debateRepo).saveLoginCredentials(debateCode = "12348", loginCredentials = LoginCredentials("authToken", 222))
}
@Test
fun shouldReallySaveReturnedTokenAndDebateCodeOnLogToDebate() {
logToDebate(debateCode = "12345")
returnTokenFromApi("realAuthToken", 333)
verify(debateRepo).saveLoginCredentials(debateCode = "12345", loginCredentials = LoginCredentials("realAuthToken", 333))
}
@Test
fun shouldShowDebateClosedErrorOnLogin403CodeErrorFromApi() {
logToDebate()
apiSubject.onError(createHttpException(403))
verify(view).showDebateClosedError()
}
@Test
fun shouldShowErrorOnLoginError() {
controller.onLogToDebate("error")
val error = RuntimeException()
apiSubject.onError(error)
verify(view).showLoginError(error)
}
@Test
fun shouldNotShowErrorIfLoginSucceed() {
logToDebate()
returnTokenFromApi("authToken", 111)
verify(view, never()).showLoginError(any())
}
@Test
fun shouldShowLoaderOnLoginStart() {
logToDebate()
verify(view).showLoader()
}
@Test
fun shouldHideLoaderOnLoginEnd() {
logToDebate()
returnTokenFromApi("authToken", 111)
verify(view).hideLoader()
}
@Test
fun shouldNotHideLoaderWhenLoginIsStillInProgress() {
logToDebate()
verify(view, never()).hideLoader()
}
@Test
fun shouldHideLoaderOnDestroyIfCallIsStillInProgress() {
logToDebate()
controller.onDestroy()
verify(view).hideLoader()
}
@Test
fun shouldNotHideLoaderOnDestroyIfCallIsNotInProgress() {
controller.onDestroy()
verify(view, never()).hideLoader()
}
@Test
fun shouldOpenDebateScreenOnLoginSuccess() {
logToDebate()
returnTokenFromApi("authToken", 111)
verify(view).openDebateScreen(LoginCredentials("authToken", 111))
}
@Test
fun shouldNotOpenDebateScreenOnLoginFailure() {
logToDebate(debateCode = "123")
apiSubject.onError(RuntimeException())
verify(view, never()).openDebateScreen(any())
}
@Test
fun shouldOpenDebateScreenWithAuthTokenFromRepositoryIfAlreadyLoggedInOnLogin() {
val token = LoginCredentials("token", 111)
forCodeReturnTokenFromRepo(debateCode = "12345", token = token)
logToDebate("12345")
verify(view).openDebateScreen(token)
}
@Test
fun shouldOpenDebateScreenWithRealAuthTokenFromRepositoryIfAlreadyLoggedInOnLogin() {
val token = LoginCredentials("authToken", 777)
forCodeReturnTokenFromRepo(debateCode = "23456", token = token)
logToDebate("23456")
verify(view).openDebateScreen(token)
}
@Test
fun shouldShowLoaderOnLoggingWithTokenFromRepository() {
forCodeReturnTokenFromRepo(debateCode = "23456", token = LoginCredentials("authToken", 111))
logToDebate("23456")
verify(view).showLoader()
}
@Test
fun shouldShowWrongPinErrorWhenPinHasLessDigitsThan5() {
logToDebate("")
verify(view).showWrongPinError()
}
@Test
fun shouldShowWrongPinErrorWhenPinReallyHasLessDigitsThan5() {
logToDebate("1234")
verify(view).showWrongPinError()
}
@Test
fun shouldNotShowWrongPinErrorWhenPinHas5Digits() {
forCodeReturnTokenFromRepo(debateCode = "23456", token = LoginCredentials("authToken", 111))
logToDebate("23456")
verify(view, never()).showWrongPinError()
}
@Test
fun shouldUseGivenSchedulerForSubscribeOnInApiCall() {
val subscribeOn = TestScheduler()
val controller = DebateLoginController(view, debateRepo, loginApi, SchedulersSupplier(subscribeOn, Schedulers.trampoline()))
controller.onLogToDebate("12345")
returnTokenFromApi("authToken", 111)
verify(view, never()).hideLoader()
subscribeOn.triggerActions()
verify(view).hideLoader()
}
@Test
fun shouldUseGivenSchedulerForObserveOnInApiCall() {
val observeOn = TestScheduler()
val controller = DebateLoginController(view, debateRepo, loginApi, SchedulersSupplier(Schedulers.trampoline(), observeOn))
controller.onLogToDebate("12345")
returnTokenFromApi("authToken", 111)
verify(view, never()).hideLoader()
observeOn.triggerActions()
verify(view).hideLoader()
}
@Test
fun shouldSaveDebateCode() {
logToDebate(debateCode = "12345")
verify(debateRepo).saveLatestDebateCode("12345")
}
@Test
fun shouldNotFillLatestDebateCodeWhenNotSaved() {
whenever(debateRepo.getLatestDebateCode()).thenReturn(null)
controller.onCreate()
verify(view, never()).fillDebateCode(any())
}
@Test
fun shouldFillLatestDebateCodeWhenSaved() {
whenever(debateRepo.getLatestDebateCode()).thenReturn("12345")
controller.onCreate()
verify(view).fillDebateCode("12345")
}
@Test
fun shouldUseCorrectDebateCodeWhenCallingApi() {
controller.onCreate()
controller.onLogToDebate("12345")
verify(loginApi).login("12345")
}
private fun forCodeReturnTokenFromRepo(debateCode: String, token: LoginCredentials) {
whenever(debateRepo.hasLoginCredentials(debateCode = debateCode)).thenReturn(true)
whenever(debateRepo.getLoginCredentialsForDebate(debateCode = debateCode)).thenReturn(token)
}
private fun returnTokenFromApi(token: String, userId: Long) {
apiSubject.onSuccess(LoginCredentials(token, userId))
}
private fun logToDebate(debateCode: String = "12345") {
controller.onLogToDebate(debateCode)
}
}
| gpl-3.0 |
Alkaizyr/Trees | src/redblacktree/RedBlackTree.kt | 1 | 8880 | package redblacktree
import Tree
class RedBlackTree<K: Comparable<K>, V>: Tree<K, V>, Iterable<Pair<K, V>> {
var root: RBNode<K, V>? = null
override fun insert(key: K, value: V) {
var father: RBNode<K, V>? = null
var current: RBNode<K, V>? = root
while (current != null) {
father = current
when {
key < current.key -> current = current.left
key > current.key -> current = current.right
key == current.key -> {
current.value = value
return
}
}
}
if (father == null) {
root = RBNode(key, value, father, true)
return
}
if (key < father.key) {
father.left = RBNode(key, value, father, false)
insertFixup(father.left)
}
else {
father.right = RBNode(key, value, father, false)
insertFixup(father.right)
}
}
private fun insertFixup(node: RBNode<K, V>?) {
var uncle: RBNode<K, V>?
var current: RBNode<K, V>? = node
while (current?.parent?.colorBlack == false) {
if (current.parent == current.parent?.parent?.left) {
uncle = current.parent?.parent?.right
when {
uncle?.colorBlack == false -> {
current.parent?.colorBlack = true
uncle.colorBlack = true
current.parent?.parent?.colorBlack = false
current = current.parent?.parent
}
current == current.parent?.right -> {
current = current.parent
if (current!!.parent?.parent == null) root = current.parent
current.rotateLeft()
}
current == current.parent?.left -> {
if (current.parent?.parent?.parent == null) root = current.parent
current.parent?.parent?.rotateRight()
}
}
}
else {
uncle = current.parent?.parent?.left
when {
uncle?.colorBlack == false -> {
current.parent?.colorBlack = true
uncle.colorBlack = true
current.parent?.parent?.colorBlack = false
current = current.parent?.parent
}
current == current.parent?.left -> {
current = current.parent
if (current!!.parent?.parent == null) root = current.parent
current.rotateRight()
}
current == current.parent?.right -> {
if (current.parent?.parent?.parent == null) root = current.parent
current.parent?.parent?.rotateLeft()
}
}
}
}
root?.colorBlack = true
}
override fun find(key: K): Pair<K, V>? {
val result = findNode(key)
if (result == null)
return null
else
return Pair(result.key, result.value)
}
private fun findNode(key: K): RBNode<K, V>? {
var current = root
while (current != null ) {
if (key == current.key)
return current
if (key < current.key)
current = current.left
else
current = current.right
}
return null
}
override fun delete(key: K) {
val node = findNode(key) ?: return
deleteNode(node)
}
private fun deleteNode(node: RBNode<K, V>) {
val prev = max(node.left)
when {
(node.right != null && node.left != null) -> {
node.key = prev!!.key
node.value = prev.value
deleteNode(prev)
return
}
(node == root && node.isLeaf()) -> {
root = null
return
}
(!node.colorBlack && node.isLeaf()) -> {
if (node == node.parent!!.left)
node.parent!!.left = null
else
node.parent!!.right = null
return
}
(node.colorBlack && node.left != null && !node.left!!.colorBlack) -> {
node.key = node.left!!.key
node.value = node.left!!.value
node.left = null
return
}
(node.colorBlack && node.right != null && !node.right!!.colorBlack) -> {
node.key = node.right!!.key
node.value = node.right!!.value
node.right = null
return
}
else -> {
deleteCase1(node)
}
}
if (node == node.parent!!.left)
node.parent!!.left = null
else
node.parent!!.right = null
}
private fun deleteCase1(node: RBNode<K, V>) {
if (node.parent != null)
deleteCase2(node)
}
private fun deleteCase2(node: RBNode<K, V>) {
val brother = node.brother()
if (!brother!!.colorBlack) {
if (node == node.parent!!.left)
node.parent!!.rotateLeft()
else if (node == node.parent!!.right)
node.parent!!.rotateRight()
if (root == node.parent)
root = node.parent!!.parent
}
deleteCase3(node)
}
private fun deleteCase3(node: RBNode<K, V>) {
val brother = node.brother()
val a: Boolean = brother!!.left == null || brother.left!!.colorBlack
val b: Boolean = brother.right == null || brother.right!!.colorBlack
if (a && b && brother.colorBlack && node.parent!!.colorBlack) {
brother.colorBlack = false
deleteCase1(node.parent!!)
}
else
deleteCase4(node)
}
private fun deleteCase4(node: RBNode<K, V>) {
val brother = node.brother()
val a: Boolean = brother!!.left == null || brother.left!!.colorBlack
val b: Boolean = brother.right == null || brother.right!!.colorBlack
if (a && b && brother.colorBlack && !node.parent!!.colorBlack) {
brother.colorBlack = false
node.parent!!.colorBlack = true
}
else
deleteCase5(node)
}
private fun deleteCase5(node: RBNode<K, V>) {
val brother = node.brother()
val a: Boolean = brother!!.left == null || brother.left!!.colorBlack
val b: Boolean = brother.right == null || brother.right!!.colorBlack
if (brother.colorBlack) {
if (brother.left?.colorBlack == false && b && node == node.parent?.left)
brother.rotateRight()
else if (brother.right?.colorBlack == false && a && node == node.parent?.right)
brother.rotateLeft()
}
deleteCase6(node)
}
private fun deleteCase6(node: RBNode<K, V>) {
val brother = node.brother()
if (node == node.parent!!.left) {
brother?.right?.colorBlack = true
node.parent?.rotateLeft()
}
else {
brother?.left?.colorBlack = true
node.parent?.rotateRight()
}
if (root == node.parent)
root = node.parent!!.parent
}
override fun iterator(): Iterator<Pair<K, V>> {
return (object: Iterator<Pair<K, V>> {
var node = max(root)
var next = max(root)
val last = min(root)
override fun hasNext(): Boolean {
return node != null && node!!.key >= last!!.key
}
override fun next(): Pair<K, V> {
next = node
node = nextSmaller(node)
return Pair(next!!.key, next!!.value)
}
})
}
private fun nextSmaller(node: RBNode<K, V>?): RBNode<K, V>? {
var smaller = node ?: return null
if (smaller.left != null)
return max(smaller.left!!)
else if (smaller == smaller.parent?.left) {
while (smaller == smaller.parent?.left)
smaller = smaller.parent!!
}
return smaller.parent
}
private fun min(node: RBNode<K, V>?): RBNode<K, V>? {
if (node?.left == null)
return node
else
return min(node.left)
}
private fun max(node: RBNode<K, V>?): RBNode<K, V>? {
if (node?.right == null)
return node
else
return max(node.right)
}
} | mit |
paplorinc/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/components/impl/pathMacroManagerTest.kt | 5 | 982 | // Copyright 2000-2018 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.
// Copyright 2000-2018 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.
import com.intellij.application.options.PathMacrosImpl
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.SystemProperties
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.jps.model.serialization.PathMacroUtil
import org.junit.Test
class LightPathMacroManagerTest {
@Test
fun systemOverridesUser() {
val macros = PathMacrosImpl()
val userHome = FileUtil.toSystemIndependentName(SystemProperties.getUserHome())
macros.setMacro("foo", userHome)
val manager = PathMacroManager(macros)
assertThat(manager.collapsePath(userHome)).isEqualTo("$${PathMacroUtil.USER_HOME_NAME}$")
}
} | apache-2.0 |
paplorinc/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/GithubAsyncUtil.kt | 1 | 3097 | // Copyright 2000-2018 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 org.jetbrains.plugins.github.util
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import java.util.concurrent.*
import java.util.function.BiFunction
object GithubAsyncUtil {
@JvmStatic
fun <T> awaitFuture(progressIndicator: ProgressIndicator, future: Future<T>): T {
var result: T
while (true) {
try {
result = future.get(50, TimeUnit.MILLISECONDS)
break
}
catch (e: TimeoutException) {
progressIndicator.checkCanceled()
}
catch (e: Exception) {
if (isCancellation(e)) throw ProcessCanceledException()
if (e is ExecutionException) throw e.cause ?: e
throw e
}
}
return result
}
@JvmStatic
fun <T> futureOfMutable(futureSupplier: () -> CompletableFuture<T>): CompletableFuture<T> {
val result = CompletableFuture<T>()
handleToOtherIfCancelled(futureSupplier, result)
return result
}
private fun <T> handleToOtherIfCancelled(futureSupplier: () -> CompletableFuture<T>, other: CompletableFuture<T>) {
futureSupplier().handle { result, error ->
if (result != null) other.complete(result)
if (error != null) {
if (isCancellation(error)) handleToOtherIfCancelled(futureSupplier, other)
other.completeExceptionally(error.cause)
}
}
}
fun isCancellation(error: Throwable): Boolean {
return error is ProcessCanceledException
|| error is CancellationException
|| error is InterruptedException
|| error.cause?.let(::isCancellation) ?: false
}
}
fun <T> ProgressManager.submitBackgroundTask(project: Project,
title: String,
canBeCancelled: Boolean,
progressIndicator: ProgressIndicator,
process: (indicator: ProgressIndicator) -> T): CompletableFuture<T> {
val future = CompletableFuture<T>()
runProcessWithProgressAsynchronously(object : Task.Backgroundable(project, title, canBeCancelled) {
override fun run(indicator: ProgressIndicator) {
future.complete(process(indicator))
}
override fun onCancel() {
future.cancel(true)
}
override fun onThrowable(error: Throwable) {
future.completeExceptionally(error)
}
}, progressIndicator)
return future
}
fun <T> CompletableFuture<T>.handleOnEdt(handler: (T?, Throwable?) -> Unit): CompletableFuture<Unit> =
handleAsync(BiFunction<T?, Throwable?, Unit> { result: T?, error: Throwable? ->
handler(result, error)
}, EDT_EXECUTOR)
val EDT_EXECUTOR = Executor { runnable -> runInEdt { runnable.run() } } | apache-2.0 |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/JBProtocolCommand.kt | 3 | 3413 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.openapi.application
import com.intellij.diagnostic.PluginException
import com.intellij.ide.IdeBundle
import com.intellij.openapi.extensions.ExtensionPointName
import io.netty.handler.codec.http.QueryStringDecoder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.future.asDeferred
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
/**
* @author Konstantin Bulenkov
*/
abstract class JBProtocolCommand(private val command: String) {
companion object {
const val SCHEME = "jetbrains"
const val FRAGMENT_PARAM_NAME = "__fragment"
private val EP_NAME = ExtensionPointName<JBProtocolCommand>("com.intellij.jbProtocolCommand")
@ApiStatus.Internal
suspend fun execute(query: String): String? {
val decoder = QueryStringDecoder(query)
val parts = decoder.path().split('/').dropLastWhile { it.isEmpty() }
require(parts.size >= 2) {
// expected: at least a platform prefix and a command name
query
}
val commandName = parts[1]
for (command in EP_NAME.iterable) {
if (command.command != commandName) {
continue
}
val target = if (parts.size > 2) parts[2] else null
val parameters = LinkedHashMap<String, String>()
for ((key, list) in decoder.parameters()) {
parameters.put(key, if (list.isEmpty()) "" else list.get(list.size - 1))
}
val fragmentStart = query.lastIndexOf('#')
val fragment = if (fragmentStart > 0) query.substring(fragmentStart + 1) else null
return command.execute(target, parameters, fragment)
}
return IdeBundle.message("jb.protocol.unknown.command", commandName)
}
}
@Suppress("unused")
@Deprecated("please implement {@link #perform(String, Map, String)} instead",
ReplaceWith("perform(String, Map, String)"))
open fun perform(target: String?, parameters: Map<String, String?>) {
throw PluginException.createByClass(UnsupportedOperationException(), javaClass)
}
/**
* The method should return a future with the command execution result - `null` when successful,
* sentence-capitalized localized string in case of an error (see `"ide.protocol.*"` strings in `IdeBundle`).
*
* @see .parameter
*/
open fun perform(target: String?, parameters: Map<String, String>, fragment: String?): Future<String?> {
@Suppress("DEPRECATION")
perform(target, mapOf(FRAGMENT_PARAM_NAME to fragment))
return CompletableFuture.completedFuture(null)
}
protected open suspend fun execute(target: String?, parameters: Map<String, String>, fragment: String?): String? {
val result = withContext(Dispatchers.EDT) { perform(target, parameters, fragment) }
return if (result is CompletableFuture) result.asDeferred().await() else withContext(Dispatchers.IO) { result.get() }
}
protected fun parameter(parameters: Map<String, String>, name: String): String {
val value = parameters.get(name)
require(!value.isNullOrBlank()) { IdeBundle.message("jb.protocol.parameter.missing", name) }
return value
}
} | apache-2.0 |
google/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/KotlinGroupUsagesBySimilarityTest.kt | 2 | 2656 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.findUsages
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.assertEqualsToFile
import com.intellij.usages.UsageInfoToUsageConverter
import com.intellij.usages.similarity.clustering.ClusteringSearchSession
import org.jetbrains.kotlin.idea.findUsages.similarity.KotlinUsageSimilarityFeaturesProvider
import org.jetbrains.kotlin.idea.base.test.TestRoot
import org.jetbrains.kotlin.test.TestMetadata
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import java.io.File
@TestRoot("idea/tests")
@TestDataPath("\$CONTENT_ROOT")
@TestMetadata("testData/findUsages/similarity")
@RunWith(
JUnit38ClassRunner::class
)
class KotlinGroupUsagesBySimilarityTest : AbstractFindUsagesTest() {
fun testSimpleFeatures() {
myFixture.configureByFile(getTestName(true)+".kt")
val elementAtCaret = myFixture.getReferenceAtCaretPosition()!!.element
val features = KotlinUsageSimilarityFeaturesProvider().getFeatures(elementAtCaret)
assertEquals(1, features["VAR: "])
assertEquals(1, features["{CALL: inc}"])
}
@TestMetadata("general.kt")
@Throws(Exception::class)
fun testGeneral() {
doTest()
}
@TestMetadata("chainCalls")
fun testChainCalls() {
myFixture.configureByFile(getTestName(true)+".kt")
val findUsages = findUsages(myFixture.elementAtCaret, null, false, myFixture.project)
val session = ClusteringSearchSession();
findUsages.forEach { usage -> UsageInfoToUsageConverter.convertToSimilarUsage(arrayOf(myFixture.elementAtCaret), usage, session) }
val file = File(testDataDirectory, getTestName(true)+".results.txt")
assertEqualsToFile("", file, session.clusters.toString())
}
fun testListAdd() {
doTest()
}
fun testFilter() {
doTest()
}
private fun doTest() {
myFixture.configureByFile(getTestName(true)+".kt")
val findUsages = findUsages(myFixture.elementAtCaret, null, false, myFixture.project)
val session = ClusteringSearchSession();
findUsages.forEach { usage -> UsageInfoToUsageConverter.convertToSimilarUsage(arrayOf(myFixture.elementAtCaret), usage, session) }
val file = File(testDataDirectory, getTestName(true) + ".results.txt")
assertEqualsToFile("", file, session.clusters.toString())
}
} | apache-2.0 |
google/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/JvmLibraryInfo.kt | 5 | 574 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
class JvmLibraryInfo(project: Project, library: Library) : LibraryInfo(project, library) {
override val platform: TargetPlatform
get() = JvmPlatforms.defaultJvmPlatform
} | apache-2.0 |
google/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/SignTool.kt | 3 | 564 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build
import java.nio.file.Path
/**
* Implement this interfaces and pass the implementation to {@link ProprietaryBuildTools} constructor to sign the product's files.
*/
interface SignTool {
fun signFiles(files: List<Path>, context: BuildContext, options: Map<String, String>)
fun commandLineClient(context: BuildContext, os: OsFamily, arch: JvmArchitecture): Path?
} | apache-2.0 |
google/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/LibraryWrapper.kt | 3 | 1745 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.projectStructure
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.serviceContainer.AlreadyDisposedException
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
// Workaround for duplicated libraries, see KT-42607
@ApiStatus.Internal
class LibraryWrapper(val library: LibraryEx) {
private val allRootUrls: Set<String> by lazy {
mutableSetOf<String>().apply {
for (orderRootType in OrderRootType.getAllTypes()) {
ProgressManager.checkCanceled()
addAll(library.rootProvider.getUrls(orderRootType))
}
}
}
private val excludedRootUrls: Array<String> by lazy {
library.excludedRootUrls
}
private val hashCode by lazy {
31 + 37 * allRootUrls.hashCode() + excludedRootUrls.contentHashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is LibraryWrapper) return false
return allRootUrls == other.allRootUrls && excludedRootUrls.contentEquals(other.excludedRootUrls)
}
override fun hashCode(): Int = hashCode
fun checkValidity() {
library.checkValidity()
}
}
fun Library.checkValidity() {
safeAs<LibraryEx>()?.let {
if (it.isDisposed) {
throw AlreadyDisposedException("Library '${name}' is already disposed")
}
}
} | apache-2.0 |
JetBrains/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleJavaNewProjectWizardData.kt | 1 | 2329 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.util.Key
interface GradleJavaNewProjectWizardData : GradleNewProjectWizardData {
val addSampleCodeProperty: GraphProperty<Boolean>
var addSampleCode: Boolean
companion object {
@JvmStatic val KEY = Key.create<GradleJavaNewProjectWizardData>(GradleJavaNewProjectWizardData::class.java.name)
@JvmStatic val NewProjectWizardStep.gradleData get() = data.getUserData(KEY)!!
@JvmStatic val NewProjectWizardStep.sdkProperty get() = gradleData.sdkProperty
@JvmStatic val NewProjectWizardStep.gradleDslProperty get() = gradleData.gradleDslProperty
@JvmStatic val NewProjectWizardStep.parentProperty get() = gradleData.parentProperty
@JvmStatic val NewProjectWizardStep.groupIdProperty get() = gradleData.groupIdProperty
@JvmStatic val NewProjectWizardStep.artifactIdProperty get() = gradleData.artifactIdProperty
@JvmStatic val NewProjectWizardStep.versionProperty get() = gradleData.versionProperty
@JvmStatic val NewProjectWizardStep.addSampleCodeProperty get() = gradleData.addSampleCodeProperty
@JvmStatic var NewProjectWizardStep.sdk get() = gradleData.sdk; set(it) { gradleData.sdk = it }
@JvmStatic var NewProjectWizardStep.gradleDsl get() = gradleData.gradleDsl; set(it) { gradleData.gradleDsl = it }
@JvmStatic var NewProjectWizardStep.parent get() = gradleData.parent; set(it) { gradleData.parent = it }
@JvmStatic var NewProjectWizardStep.parentData get() = gradleData.parentData; set(it) { gradleData.parentData = it }
@JvmStatic var NewProjectWizardStep.groupId get() = gradleData.groupId; set(it) { gradleData.groupId = it }
@JvmStatic var NewProjectWizardStep.artifactId get() = gradleData.artifactId; set(it) { gradleData.artifactId = it }
@JvmStatic var NewProjectWizardStep.version get() = gradleData.version; set(it) { gradleData.version = it }
@JvmStatic var NewProjectWizardStep.addSampleCode get() = gradleData.addSampleCode; set(it) { gradleData.addSampleCode = it }
}
} | apache-2.0 |
JetBrains/intellij-community | plugins/full-line/local/src/org/jetbrains/completion/full/line/local/tokenizer/TokenizerTrie.kt | 1 | 3016 | package org.jetbrains.completion.full.line.local.tokenizer
import kotlin.math.max
import kotlin.math.min
internal class TokenizerTrie(val tokenizer: Tokenizer) {
private val sortedVocabEntries = tokenizer.vocab.toList().sortedBy { it.first }
private val root = TrieNode()
init {
sortedVocabEntries.mapIndexed { index, pair ->
root.addWord(pair.first, index)
}
}
fun getValuesWithCompletionAwarePrefix(prefix: String): IntArray {
val answer = getInternalValuesWithPrefix(prefix, strict = false)
val answerStrings = answer.map { sortedVocabEntries[it].first }
val completableAnswerStrings = answerStrings.filter {
val subPrefixLen = it.length
// TODO: filter by length
if (prefix.length > subPrefixLen) {
val toComplete = prefix.substring(subPrefixLen)
return@filter getInternalValuesWithPrefix(toComplete, strict = true).isNotEmpty()
}
else {
return@filter true
}
}
return completableAnswerStrings.map { tokenizer.vocab.getValue(it) }.toIntArray()
}
fun getValuesWithPrefix(prefix: String, strict: Boolean): IntArray {
return getInternalValuesWithPrefix(prefix, strict).map { sortedVocabEntries[it].second }.toIntArray()
}
private fun getInternalValuesWithPrefix(prefix: String, strict: Boolean): List<Int> {
val (foundTrie, path) = findTrie(prefix)
var answer = foundTrie?.subtrieValues ?: emptyList()
if (!strict) answer = answer + path.mapNotNull { it.value }
return answer
}
private fun findTrie(word: String): Pair<TrieNode?, List<TrieNode>> {
assert(word.isNotEmpty()) { "Word must not be empty" }
var curNode = this.root
var newNode: TrieNode? = null
val path = mutableListOf<TrieNode>()
for (char in word) {
path.add(curNode)
newNode = curNode.moveByChar(char)
newNode?.let { curNode = newNode } ?: break
}
return Pair(newNode, path)
}
internal class TrieNode {
private val moves: MutableMap<Char, TrieNode> = mutableMapOf()
var value: Int? = null
private var start: Int? = null
private var end: Int? = null
internal val subtrieValues: List<Int>
get() {
return ((start ?: return emptyList())..(end ?: return emptyList())).toList()
}
internal fun addWord(word: String, value: Int) {
var curNode = this
curNode.updateSubtrie(value)
for (char in word) {
curNode = curNode.moveByChar(char, createNew = true)!! // Can't be null when createNew is true
curNode.updateSubtrie(value)
}
curNode.value = value
}
internal fun moveByChar(char: Char, createNew: Boolean = false): TrieNode? {
if (!this.moves.containsKey(char)) {
if (createNew) this.moves[char] = TrieNode()
else return null
}
return this.moves.getValue(char)
}
private fun updateSubtrie(value: Int) {
start = start?.let { min(it, value) } ?: value
end = end?.let { max(it, value) } ?: value
}
}
}
| apache-2.0 |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/cache/video_player/model/VideoTimestamp.kt | 2 | 123 | package org.stepik.android.cache.video_player.model
class VideoTimestamp(
val videoId: Long,
val timestamp: Long
) | apache-2.0 |
liukeshao/Totoro | totoro-common/src/main/kotlin/xyz/gosick/totoro/common/annotation/NoArg.kt | 1 | 106 | package xyz.gosick.totoro.common.annotation
/**
* Created by ks on 2017/4/22.
*/
annotation class NoArg | apache-2.0 |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_purchase/analytic/BuyCourseVerificationSuccessAnalyticEvent.kt | 1 | 907 | package org.stepik.android.domain.course_purchase.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
import ru.nobird.app.core.model.mapOfNotNull
class BuyCourseVerificationSuccessAnalyticEvent(
courseId: Long,
coursePurchaseSource: String,
isWishlisted: Boolean,
promoName: String?
) : AnalyticEvent {
companion object {
private const val PARAM_COURSE = "course"
private const val PARAM_SOURCE = "source"
private const val PARAM_IS_WISHLISTED = "is_wishlisted"
private const val PARAM_PROMO = "promo"
}
override val name: String =
"Buy course verification success"
override val params: Map<String, Any> =
mapOfNotNull(
PARAM_COURSE to courseId,
PARAM_SOURCE to coursePurchaseSource,
PARAM_IS_WISHLISTED to isWishlisted,
PARAM_PROMO to promoName
)
} | apache-2.0 |
D-clock/KotlinSample | IntelliJIDEA_Project/src/lesson2/Coder.kt | 1 | 290 | package lesson2
/**
* Created by Clock on 2017/7/16.
*/
class Coder constructor(id: Int, name: String) {
var id = id
var name = name
/*init {
println("---------start init---------")
println("do sth...")
println("---------end init---------")
}*/
} | apache-2.0 |
scenerygraphics/scenery | src/test/kotlin/graphics/scenery/tests/examples/cluster/SlimClient.kt | 1 | 1215 | package graphics.scenery.tests.examples.cluster
import org.joml.Vector3f
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.net.NodeSubscriber
import kotlin.concurrent.thread
/**
* Empty scene to receive content via network
*
* Start with vm param:
* -ea -Dscenery.ServerAddress=tcp://127.0.0.1 [-Dscenery.RemoteCamera=false|true]
*
* Explanation:
* - RemoteCamera: (default false) Has to be set to true if the camera of the server provided scene should be used.
*/
class SlimClient : SceneryBase("Client", wantREPL = false) {
override fun init() {
renderer = hub.add(SceneryElement.Renderer,
Renderer.createRenderer(hub, applicationName, scene, 512, 512))
if(!Settings().get("RemoteCamera",false)) {
val cam: Camera = DetachedHeadCamera()
with(cam) {
spatial {
position = Vector3f(0.0f, 0.0f, 5.0f)
}
perspectiveCamera(50.0f, 512, 512)
scene.addChild(this)
}
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
SlimClient().main()
}
}
}
| lgpl-3.0 |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/selects/SelectJobTest.kt | 1 | 1500 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.selects
import kotlinx.coroutines.*
import kotlin.test.*
class SelectJobTest : TestBase() {
@Test
fun testSelectCompleted() = runTest {
expect(1)
launch { // makes sure we don't yield to it earlier
finish(4) // after main exits
}
val job = Job()
job.cancel()
select<Unit> {
job.onJoin {
expect(2)
}
}
expect(3)
// will wait for the first coroutine
}
@Test
fun testSelectIncomplete() = runTest {
expect(1)
val job = Job()
launch { // makes sure we don't yield to it earlier
expect(3)
val res = select<String> {
job.onJoin {
expect(6)
"OK"
}
}
expect(7)
assertEquals("OK", res)
}
expect(2)
yield()
expect(4)
job.cancel()
expect(5)
yield()
finish(8)
}
@Test
fun testSelectLazy() = runTest {
expect(1)
val job = launch(start = CoroutineStart.LAZY) {
expect(2)
}
val res = select<String> {
job.onJoin {
expect(3)
"OK"
}
}
finish(4)
assertEquals("OK", res)
}
} | apache-2.0 |
rightfromleft/weather-app | mobile-ui/src/main/java/com/rightfromleftsw/weather/ui/injection/module/ApplicationModule.kt | 1 | 3041 | package com.rightfromleftsw.weather.ui.injection.module
import android.app.Application
import android.content.Context
import com.rightfromleftsw.weather.data.WeatherDataRepository
import com.rightfromleftsw.weather.data.executor.JobExecutor
import com.rightfromleftsw.weather.data.mapper.WeatherMapper
import com.rightfromleftsw.weather.data.repository.IWeatherLocal
import com.rightfromleftsw.weather.data.repository.IWeatherRemote
import com.rightfromleftsw.weather.domain.executor.PostExecutionThread
import com.rightfromleftsw.weather.domain.executor.ThreadExecutor
import com.rightfromleftsw.weather.domain.repository.IWeatherRepository
import com.rightfromleftsw.weather.localdata.WeatherLocalDataImpl
import com.rightfromleftsw.weather.localdata.WeatherSharedPrefs
import com.rightfromleftsw.weather.remote.WeatherRemoteImpl
import com.rightfromleftsw.weather.remote.WeatherService
import com.rightfromleftsw.weather.remote.WeatherServiceFactory
import com.rightfromleftsw.weather.remote.mapper.WeatherRemoteEntityMapper
import com.rightfromleftsw.weather.ui.BuildConfig
import com.rightfromleftsw.weather.ui.UiThread
import com.rightfromleftsw.weather.ui.injection.scopes.PerApplication
import dagger.Module
import dagger.Provides
/**
* Module used to provide dependencies at an application-level.
*/
@Module
open class ApplicationModule {
@Provides
@PerApplication
fun provideContext(application: Application): Context {
return application
}
@Provides
@PerApplication
internal fun providePreferencesHelper(context: Context): WeatherSharedPrefs {
return WeatherSharedPrefs(context)
}
@Provides
@PerApplication
internal fun provideRepository(localDataStore: IWeatherLocal,
remoteDataStore: IWeatherRemote,
mapper: WeatherMapper): IWeatherRepository {
return WeatherDataRepository(localDataStore, remoteDataStore, mapper)
}
@Provides
@PerApplication
internal fun provideIWeatherLocal( //db: WeatherDatabase,
//dbMapper: WeatherDbMapper,
sharedPrefs: WeatherSharedPrefs): IWeatherLocal {
return WeatherLocalDataImpl(sharedPrefs)
}
@Provides
@PerApplication
internal fun provideIWeatherRemote(service: WeatherService,
remoteEntityMapper: WeatherRemoteEntityMapper): IWeatherRemote {
return WeatherRemoteImpl(service, remoteEntityMapper)
}
@Provides
@PerApplication
internal fun provideThreadExecutor(jobExecutor: JobExecutor): ThreadExecutor {
return jobExecutor
}
@Provides
@PerApplication
internal fun providePostExecutionThread(uiThread: UiThread): PostExecutionThread {
return uiThread
}
@Provides
@PerApplication
internal fun provideWeatherService(): WeatherService {
return WeatherServiceFactory.makeWeatherService(BuildConfig.DEBUG)
}
}
| mit |
LivingDoc/livingdoc | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/BooleanConverter.kt | 2 | 1419 | package org.livingdoc.converters
import java.lang.reflect.AnnotatedElement
import org.livingdoc.api.conversion.ConversionException
import org.livingdoc.api.conversion.TypeConverter
/**
* This converter is used to convert a String to a boolean, if the String is "true" or "false"
*/
open class BooleanConverter : TypeConverter<Boolean> {
/**
* This function converts the given parameter value with "true" or "false" to a boolean. If the content is not one
* of these two values, the function throws a Conversion exception.
*
* @param value the String that should have "true" or "false" as a content
* @return the boolean value of the given String
* @throws ConversionException if the content is not "true" or "false"
*/
@Throws(ConversionException::class)
override fun convert(value: String, element: AnnotatedElement?, documentClass: Class<*>?): Boolean {
val trimmedLowerCaseValue = value.trim().toLowerCase()
when (trimmedLowerCaseValue) {
"true" -> return true
"false" -> return false
}
throw ConversionException("Not a boolean value: '$value'")
}
override fun canConvertTo(targetType: Class<*>): Boolean {
val isJavaObjectType = Boolean::class.javaObjectType == targetType
val isKotlinType = Boolean::class.java == targetType
return isJavaObjectType || isKotlinType
}
}
| apache-2.0 |
Loong-T/Android-Showcase | app/src/main/kotlin/in/nerd_is/android_showcase/zhihu_daily/model/Date.kt | 1 | 755 | /*
* Copyright 2017 Xuqiang ZHENG
*
* 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 `in`.nerd_is.android_showcase.zhihu_daily.model
import org.threeten.bp.LocalDate
data class Date(val date: LocalDate) | apache-2.0 |
leafclick/intellij-community | plugins/devkit/devkit-core/src/inspections/missingApi/update/IdeExternalAnnotationsUpdater.kt | 1 | 9487 | // Copyright 2000-2018 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 org.jetbrains.idea.devkit.inspections.missingApi.update
import com.intellij.codeInspection.ex.modifyAndCommitProjectProfile
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.AnnotationOrderRootType
import com.intellij.openapi.util.BuildNumber
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.util.Consumer
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.inspections.missingApi.MissingRecentApiInspection
import org.jetbrains.idea.devkit.inspections.missingApi.resolve.IdeExternalAnnotations
import org.jetbrains.idea.devkit.inspections.missingApi.resolve.PublicIdeExternalAnnotationsRepository
import org.jetbrains.idea.devkit.inspections.missingApi.resolve.getAnnotationsBuildNumber
import org.jetbrains.idea.devkit.inspections.missingApi.resolve.isAnnotationsRoot
import java.time.Duration
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.concurrent.atomic.AtomicReference
/**
* Utility class that updates IntelliJ API external annotations.
*/
class IdeExternalAnnotationsUpdater {
companion object {
private val LOG = Logger.getInstance(IdeExternalAnnotationsUpdater::class.java)
private val NOTIFICATION_GROUP = NotificationGroup.balloonGroup("IntelliJ API Annotations")
private val UPDATE_RETRY_TIMEOUT = Duration.of(10, ChronoUnit.MINUTES)
fun getInstance(): IdeExternalAnnotationsUpdater = service()
}
private val buildNumberLastFailedUpdateInstant = hashMapOf<BuildNumber, Instant>()
private val buildNumberNotificationShown = hashSetOf<BuildNumber>()
private val buildNumberUpdateInProgress = hashSetOf<BuildNumber>()
private fun isInspectionEnabled(project: Project): Boolean {
return runReadAction {
ProjectInspectionProfileManager.getInstance(project).currentProfile
.getTools(MissingRecentApiInspection.INSPECTION_SHORT_NAME, project)
.isEnabled
}
}
fun updateIdeaJdkAnnotationsIfNecessary(project: Project, ideaJdk: Sdk, buildNumber: BuildNumber) {
if (!isInspectionEnabled(project)) {
return
}
if (synchronized(this) { buildNumber in buildNumberUpdateInProgress || buildNumber in buildNumberNotificationShown }) {
return
}
val attachedAnnotations = getAttachedAnnotationsBuildNumbers(ideaJdk)
if (attachedAnnotations.any { it >= buildNumber }) {
return
}
runInEdt {
val canShowNotification = synchronized(this) {
val lastFailedInstant = buildNumberLastFailedUpdateInstant[buildNumber]
val lastFailedWasLongAgo = lastFailedInstant == null || Instant.now().isAfter(lastFailedInstant.plus(UPDATE_RETRY_TIMEOUT))
if (lastFailedWasLongAgo && buildNumber !in buildNumberNotificationShown) {
buildNumberNotificationShown.add(buildNumber)
true
} else {
false
}
}
if (canShowNotification) {
showUpdateAnnotationsNotification(project, ideaJdk, buildNumber)
}
}
}
private fun reattachAnnotations(project: Project, ideaJdk: Sdk, annotationsRoot: IdeExternalAnnotations) {
val annotationsUrl = runReadAction { annotationsRoot.annotationsRoot.url }
ApplicationManager.getApplication().invokeAndWait {
if (project.isDisposed) {
return@invokeAndWait
}
runWriteAction {
val type = AnnotationOrderRootType.getInstance()
val sdkModificator = ideaJdk.sdkModificator
val attachedUrls = sdkModificator.getRoots(type)
.asSequence()
.filter { isAnnotationsRoot(it) }
.mapTo(mutableSetOf()) { it.url }
if (annotationsUrl !in attachedUrls) {
sdkModificator.addRoot(annotationsUrl, type)
}
for (redundantUrl in attachedUrls - annotationsUrl) {
sdkModificator.removeRoot(redundantUrl, type)
}
sdkModificator.commitChanges()
}
}
}
private fun getAttachedAnnotationsBuildNumbers(ideaJdk: Sdk): List<BuildNumber> =
ideaJdk.rootProvider
.getFiles(AnnotationOrderRootType.getInstance())
.mapNotNull { getAnnotationsBuildNumber(it) }
private fun showUpdateAnnotationsNotification(project: Project, ideaJdk: Sdk, buildNumber: BuildNumber) {
val notification = NOTIFICATION_GROUP.createNotification(
DevKitBundle.message("intellij.api.annotations.update.title", buildNumber),
DevKitBundle.message("intellij.api.annotations.update.confirmation.content", buildNumber),
NotificationType.INFORMATION,
null
).apply {
addAction(object : NotificationAction(DevKitBundle.message("intellij.api.annotations.update.confirmation.update.button")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
updateAnnotationsInBackground(ideaJdk, project, buildNumber)
notification.expire()
}
})
addAction(object : NotificationAction(
DevKitBundle.message("intellij.api.annotations.update.confirmation.disable.inspection.button")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
disableInspection(project)
notification.expire()
}
})
}
notification.whenExpired {
synchronized(this) {
buildNumberNotificationShown.remove(buildNumber)
}
}
notification.notify(project)
}
private fun disableInspection(project: Project) {
modifyAndCommitProjectProfile(project, Consumer {
it.disableToolByDefault(listOf(MissingRecentApiInspection.INSPECTION_SHORT_NAME), project)
})
}
private fun updateAnnotationsInBackground(ideaJdk: Sdk, project: Project, buildNumber: BuildNumber) {
if (synchronized(this) { !buildNumberUpdateInProgress.add(buildNumber) }) {
return
}
UpdateTask(project, ideaJdk, buildNumber).queue()
}
private fun showSuccessfullyUpdated(project: Project, buildNumber: BuildNumber, annotationsBuild: BuildNumber) {
synchronized(this) {
buildNumberLastFailedUpdateInstant.remove(buildNumber)
}
val updateMessage = if (annotationsBuild >= buildNumber) {
DevKitBundle.message("intellij.api.annotations.update.successfully.updated", buildNumber)
} else {
DevKitBundle.message("intellij.api.annotations.update.successfully.updated.but.not.latest.version", buildNumber, annotationsBuild)
}
NOTIFICATION_GROUP
.createNotification(
DevKitBundle.message("intellij.api.annotations.update.title", buildNumber),
updateMessage,
NotificationType.INFORMATION,
null
)
.notify(project)
}
private fun showUnableToUpdate(project: Project, throwable: Throwable, buildNumber: BuildNumber) {
synchronized(this) {
buildNumberLastFailedUpdateInstant[buildNumber] = Instant.now()
}
val message = DevKitBundle.message("intellij.api.annotations.update.failed", throwable.message)
LOG.warn(message, throwable)
NOTIFICATION_GROUP
.createNotification(
DevKitBundle.message("intellij.api.annotations.update.title", buildNumber),
message,
NotificationType.WARNING,
null
).notify(project)
}
private inner class UpdateTask(
project: Project,
private val ideaJdk: Sdk,
private val ideBuildNumber: BuildNumber
) : Task.Backgroundable(project, "Updating IntelliJ API Annotations $ideBuildNumber", true) {
private val ideAnnotations = AtomicReference<IdeExternalAnnotations>()
override fun run(indicator: ProgressIndicator) {
val annotations = tryDownloadAnnotations(ideBuildNumber)
?: throw Exception(DevKitBundle.message("intellij.api.annotations.update.failed.no.annotations.found", ideBuildNumber))
ideAnnotations.set(annotations)
reattachAnnotations(project, ideaJdk, annotations)
}
private fun tryDownloadAnnotations(ideBuildNumber: BuildNumber): IdeExternalAnnotations? {
return try {
PublicIdeExternalAnnotationsRepository(project).downloadExternalAnnotations(ideBuildNumber)
} catch (e: Exception) {
throw Exception("Failed to download annotations for $ideBuildNumber", e)
}
}
override fun onSuccess() {
showSuccessfullyUpdated(project, ideBuildNumber, ideAnnotations.get().annotationsBuild)
}
override fun onThrowable(error: Throwable) {
showUnableToUpdate(project, error, ideBuildNumber)
}
override fun onFinished() {
synchronized(this@IdeExternalAnnotationsUpdater) {
buildNumberUpdateInProgress.remove(ideBuildNumber)
}
}
}
} | apache-2.0 |
leafclick/intellij-community | python/src/com/jetbrains/python/sdk/pipenv/PyAddPipEnvPanel.kt | 1 | 6910 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk.pipenv
import com.intellij.application.options.ModuleListCellRenderer
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBTextField
import com.intellij.util.PlatformUtils
import com.intellij.util.text.nullize
import com.intellij.util.ui.FormBuilder
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PythonModuleTypeBase
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.add.PyAddNewEnvPanel
import com.jetbrains.python.sdk.add.PySdkPathChoosingComboBox
import com.jetbrains.python.sdk.add.addInterpretersAsync
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.ItemEvent
import java.io.File
import java.nio.file.Files
import javax.swing.Icon
import javax.swing.JComboBox
import javax.swing.event.DocumentEvent
/**
* The UI panel for adding the pipenv interpreter for the project.
*
* @author vlan
*/
class PyAddPipEnvPanel(private val project: Project?,
private val module: Module?,
private val existingSdks: List<Sdk>,
override var newProjectPath: String?,
context: UserDataHolder) : PyAddNewEnvPanel() {
override val envName = "Pipenv"
override val panelName = "Pipenv Environment"
override val icon: Icon = PIPENV_ICON
private val moduleField: JComboBox<Module>
private val baseSdkField = PySdkPathChoosingComboBox().apply {
val preferredSdkPath = PySdkSettings.instance.preferredVirtualEnvBaseSdk
val detectedPreferredSdk = items.find { it.homePath == preferredSdkPath }
selectedSdk = when {
detectedPreferredSdk != null -> detectedPreferredSdk
preferredSdkPath != null -> PyDetectedSdk(preferredSdkPath).apply {
childComponent.insertItemAt(this, 0)
}
else -> items.getOrNull(0)
}
}
init {
addInterpretersAsync(baseSdkField) {
findBaseSdks(existingSdks, module, context)
}
}
private val installPackagesCheckBox = JBCheckBox("Install packages from Pipfile").apply {
isVisible = newProjectPath == null
isSelected = isVisible
}
private val pipEnvPathField = TextFieldWithBrowseButton().apply {
addBrowseFolderListener(null, null, null, FileChooserDescriptorFactory.createSingleFileDescriptor())
val field = textField as? JBTextField ?: return@apply
detectPipEnvExecutable()?.let {
field.emptyText.text = PyBundle.message("configurable.pipenv.auto.detected", it.absolutePath)
}
PropertiesComponent.getInstance().pipEnvPath?.let {
field.text = it
}
}
init {
layout = BorderLayout()
val modules = project?.let {
ModuleUtil.getModulesOfType(it, PythonModuleTypeBase.getInstance())
} ?: emptyList()
moduleField = JComboBox(modules.toTypedArray()).apply {
renderer = ModuleListCellRenderer()
preferredSize = Dimension(Int.MAX_VALUE, preferredSize.height)
addItemListener {
if (it.stateChange == ItemEvent.SELECTED) {
update()
}
}
}
pipEnvPathField.textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
update()
}
})
val builder = FormBuilder.createFormBuilder().apply {
if (module == null && modules.size > 1) {
val associatedObject = if (PlatformUtils.isPyCharm()) "project" else "module"
addLabeledComponent("Associated $associatedObject:", moduleField)
}
addLabeledComponent(PyBundle.message("base.interpreter"), baseSdkField)
addComponent(installPackagesCheckBox)
addLabeledComponent(PyBundle.message("python.sdk.pipenv.executable"), pipEnvPathField)
}
add(builder.panel, BorderLayout.NORTH)
update()
}
override fun getOrCreateSdk(): Sdk? {
PropertiesComponent.getInstance().pipEnvPath = pipEnvPathField.text.nullize()
return setupPipEnvSdkUnderProgress(project, selectedModule, existingSdks, newProjectPath,
baseSdkField.selectedSdk?.homePath, installPackagesCheckBox.isSelected)?.apply {
PySdkSettings.instance.preferredVirtualEnvBaseSdk = baseSdkField.selectedSdk?.homePath
}
}
override fun validateAll(): List<ValidationInfo> =
listOfNotNull(validatePipEnvExecutable(), validatePipEnvIsNotAdded())
override fun addChangeListener(listener: Runnable) {
pipEnvPathField.textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
listener.run()
}
})
super.addChangeListener(listener)
}
/**
* Updates the view according to the current state of UI controls.
*/
private fun update() {
selectedModule?.let {
installPackagesCheckBox.isEnabled = it.pipFile != null
}
}
/**
* The effective module for which we add a new environment.
*/
private val selectedModule: Module?
get() = module ?: moduleField.selectedItem as? Module
/**
* Checks if `pipenv` is available on `$PATH`.
*/
private fun validatePipEnvExecutable(): ValidationInfo? {
val executable = pipEnvPathField.text.nullize()?.let { File(it) } ?:
detectPipEnvExecutable() ?:
return ValidationInfo(PyBundle.message("python.sdk.pipenv.executable.not.found"))
return when {
!executable.exists() -> ValidationInfo(PyBundle.message("python.sdk.file.not.found", executable.absolutePath))
!Files.isExecutable(executable.toPath()) || !executable.isFile -> ValidationInfo(PyBundle.message("python.sdk.cannot.execute", executable.absolutePath))
else -> null
}
}
/**
* Checks if the pipenv for the project hasn't been already added.
*/
private fun validatePipEnvIsNotAdded(): ValidationInfo? {
val path = projectPath ?: return null
val addedPipEnv = existingSdks.find {
it.associatedModulePath == path && it.isPipEnv
} ?: return null
return ValidationInfo(PyBundle.message("python.sdk.pipenv.has.been.selected", addedPipEnv.name))
}
/**
* The effective project path for the new project or for the existing project.
*/
private val projectPath: String?
get() = newProjectPath ?: selectedModule?.basePath ?: project?.basePath
}
| apache-2.0 |
leafclick/intellij-community | platform/configuration-store-impl/src/ProjectStateStorageManager.kt | 1 | 3138 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.serviceContainer.isWorkspaceComponent
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
// extended in upsource
open class ProjectStateStorageManager(macroSubstitutor: PathMacroSubstitutor,
private val project: Project,
useVirtualFileTracker: Boolean = true) : StateStorageManagerImpl(ROOT_TAG_NAME, macroSubstitutor, if (useVirtualFileTracker) project else null) {
companion object {
internal const val VERSION_OPTION = "version"
const val ROOT_TAG_NAME = "project"
}
private val fileBasedStorageConfiguration = object : FileBasedStorageConfiguration {
override val isUseVfsForWrite: Boolean
get() = true
override val isUseVfsForRead: Boolean
get() = project is VirtualFileResolver
override fun resolveVirtualFile(path: String): VirtualFile? {
return when (project) {
is VirtualFileResolver -> project.resolveVirtualFile(path)
else -> super.resolveVirtualFile(path)
}
}
}
override fun getFileBasedStorageConfiguration(fileSpec: String): FileBasedStorageConfiguration {
return when {
isSpecialStorage(fileSpec) -> appFileBasedStorageConfiguration
else -> fileBasedStorageConfiguration
}
}
override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), PROJECT_CONFIG_DIR)
override fun expandMacros(path: String): String {
if (path[0] == '$') {
return super.expandMacros(path)
}
else {
return "${expandMacro(PROJECT_CONFIG_DIR)}/$path"
}
}
override fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
rootAttributes.put(VERSION_OPTION, "4")
}
override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? {
val workspace = isWorkspaceComponent(project.picoContainer, component.javaClass)
if (workspace && (operation != StateStorageOperation.READ || getOrCreateStorage(StoragePathMacros.WORKSPACE_FILE, RoamingType.DISABLED).hasState(componentName, false))) {
return StoragePathMacros.WORKSPACE_FILE
}
return PROJECT_FILE
}
override val isExternalSystemStorageEnabled: Boolean
get() = project.isExternalStorageEnabled
}
// for upsource
@ApiStatus.Experimental
interface VirtualFileResolver {
@JvmDefault
fun resolveVirtualFile(path: String): VirtualFile? {
return defaultFileBasedStorageConfiguration.resolveVirtualFile(path)
}
} | apache-2.0 |
redism/rxtest | android/RxTest/app/src/test/java/me/snippex/rxtest/TestObserverTest.kt | 1 | 865 | package me.snippex.rxtest
import org.junit.Test
class TestObserverTest {
@Test
fun testObserver() {
generate("1,2,3", 200)
.test()
.await()
.assertResult(1, 2, 3) // check termination
.assertValues(1, 2, 3)
.assertValueSequence(listOf(1, 2, 3))
.assertValueSet(setOf(1, 2, 3, 4))
.assertValueCount(3)
.assertValueAt(1, { it == 2 })
.assertComplete()
.assertTerminated()
.assertNoErrors()
generate("1,2,3", 200)
.test()
.awaitCount(2)
// .assertResult(1, 2) // 이 테스트는 성공할 수 없다.
.assertValues(1, 2)
.awaitCount(3)
.assertResult(1, 2, 3)
}
}
| gpl-3.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/nonLocalReturns/tryFinally/exceptionTable/innerAndExternal.kt | 5 | 4252 | // FILE: 1.kt
package test
public class Exception1(message: String) : RuntimeException(message)
public class Exception2(message: String) : RuntimeException(message)
public inline fun doCall(block: ()-> String, exception: (e: Exception)-> Unit, exception2: (e: Exception)-> Unit, finallyBlock: ()-> String, res: String = "Fail") : String {
try {
block()
} catch (e: Exception1) {
exception(e)
} catch (e: Exception2) {
exception2(e)
} finally {
finallyBlock()
}
return res
}
public inline fun <R> doCall2(block: ()-> R, exception: (e: Exception)-> Unit, finallyBlock: ()-> R) : R {
try {
return block()
} catch (e: Exception) {
exception(e)
} finally {
finallyBlock()
}
throw RuntimeException("fail")
}
// FILE: 2.kt
import test.*
class Holder {
var value: String = ""
}
fun test0(h: Holder): String {
try {
val localResult = doCall (
{
h.value += "OK_NON_LOCAL"
return "OK_NON_LOCAL"
},
{
h.value += ", OK_EXCEPTION1"
return "OK_EXCEPTION1"
},
{
h.value += ", OK_EXCEPTION2"
return "OK_EXCEPTION2"
},
{
try {
h.value += ", OK_FINALLY"
throw RuntimeException("FINALLY")
"OK_FINALLY"
} finally {
h.value += ", OK_FINALLY_INNER"
}
})
return localResult;
}
catch (e: RuntimeException) {
if (e.message != "FINALLY") {
return "FAIL in exception: " + e.message
}
else {
return "CATCHED_EXCEPTION"
}
}
return "FAIL";
}
fun test01(h: Holder): String {
val localResult = doCall (
{
h.value += "OK_NON_LOCAL"
throw Exception1("1")
return "OK_NON_LOCAL"
},
{
h.value += ", OK_EXCEPTION1"
return "OK_EXCEPTION1"
},
{
h.value += ", OK_EXCEPTION2"
return "OK_EXCEPTION2"
},
{
try {
h.value += ", OK_FINALLY"
throw RuntimeException("FINALLY")
} catch(e: RuntimeException) {
h.value += ", OK_CATCHED"
} finally {
h.value += ", OK_FINALLY_INNER"
}
"OK_FINALLY"
})
return localResult;
}
fun test02(h: Holder): String {
val localResult = doCall (
{
h.value += "OK_NON_LOCAL"
throw Exception2("1")
return "OK_NON_LOCAL"
},
{
h.value += ", OK_EXCEPTION1"
return "OK_EXCEPTION1"
},
{
h.value += ", OK_EXCEPTION2"
return "OK_EXCEPTION2"
},
{
try {
h.value += ", OK_FINALLY"
throw RuntimeException("FINALLY")
} catch(e: RuntimeException) {
h.value += ", OK_CATCHED"
} finally {
h.value += ", OK_FINALLY_INNER"
}
"OK_FINALLY"
}, "OK")
return localResult;
}
fun box(): String {
var h = Holder()
val test0 = test0(h)
if (test0 != "CATCHED_EXCEPTION" || h.value != "OK_NON_LOCAL, OK_FINALLY, OK_FINALLY_INNER") return "test0: ${test0}, holder: ${h.value}"
h = Holder()
val test01 = test01(h)
if (test01 != "OK_EXCEPTION1" || h.value != "OK_NON_LOCAL, OK_EXCEPTION1, OK_FINALLY, OK_CATCHED, OK_FINALLY_INNER") return "test01: ${test01}, holder: ${h.value}"
h = Holder()
val test02 = test02(h)
if (test02 != "OK_EXCEPTION2" || h.value != "OK_NON_LOCAL, OK_EXCEPTION2, OK_FINALLY, OK_CATCHED, OK_FINALLY_INNER") return "test02: ${test02}, holder: ${h.value}"
return "OK"
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/destructuringDeclInLambdaParam/generic.kt | 5 | 247 | data class A<T, F>(val x: T, val y: F)
fun <X, Y> foo(a: A<X, Y>, block: (A<X, Y>) -> String) = block(a)
fun box(): String {
val x = foo(A("OK", 1)) { (x, y) -> x + (y.toString()) }
if (x != "OK1") return "fail1: $x"
return "OK"
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/ReversedViewsTest/testMutableRemoveByObj.kt | 2 | 335 | import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.*
fun box() {
val original = mutableListOf("a", "b", "c")
val reversed = original.asReversed()
reversed.remove("c")
assertEquals(listOf("a", "b"), original)
assertEquals(listOf("b", "a"), reversed)
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/when/emptyWhen.kt | 3 | 94 | enum class A { X1, X2 }
fun box(): String {
when {}
when (A.X1) {}
return "OK"
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/arrays/multiDecl/MultiDeclForComponentMemberExtensionsInExtensionFunction.kt | 5 | 367 | class C(val i: Int) {
}
class M {
operator fun C.component1() = i + 1
operator fun C.component2() = i + 2
}
fun M.doTest(l : Array<C>): String {
var s = ""
for ((a, b) in l) {
s += "$a:$b;"
}
return s
}
fun box(): String {
val l = Array<C>(3, {x -> C(x)})
val s = M().doTest(l)
return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s"
} | apache-2.0 |
AndroidX/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/visualaid/ColumnConfigurationDemo.kt | 3 | 7140 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.visualaid
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.InfiniteAnimationPolicy
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
@Preview
@Composable
fun ColumnConfigurationDemo() {
val height by produceState(250.dp) {
// Skip the animations in tests.
while (coroutineContext[InfiniteAnimationPolicy] == null) {
animate(
Dp.VectorConverter, 250.dp, 520.dp,
animationSpec = spring(Spring.DampingRatioMediumBouncy, Spring.StiffnessLow)
) { value, _ ->
this.value = value
}
delay(1000)
animate(
Dp.VectorConverter, 520.dp, 250.dp,
animationSpec = tween(520)
) { value, _ ->
this.value = value
}
delay(1000)
}
}
ResizableColumn(height)
}
@Composable
fun ResizableColumn(height: Dp) {
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier.background(Color.White, RoundedCornerShape(5.dp)).padding(10.dp)
) {
Text(
text = "Equal\nWeight",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 12.sp, textAlign = TextAlign.Center
)
Text(
text = "Space\nBetween",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 11.sp,
textAlign = TextAlign.Center
)
Text(
text = "Space\nAround",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 12.sp,
textAlign = TextAlign.Center
)
Text(
text = "Space\nEvenly",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 12.sp,
textAlign = TextAlign.Center
)
Text(
text = "Top",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 12.sp,
textAlign = TextAlign.Center
)
Text(
text = "Center",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 12.sp,
textAlign = TextAlign.Center
)
Text(
text = "Bottom",
modifier = Modifier.width(50.dp).padding(2.dp),
fontSize = 12.sp,
textAlign = TextAlign.Center
)
}
Row(Modifier.height(520.dp).requiredHeight(height)) {
Column(Modifier.default(androidBlue)) {
ColumnItem("A", fixedSize = false)
ColumnItem("B", fixedSize = false)
ColumnItem("C", fixedSize = false)
}
Column(Modifier.default(androidDark), verticalArrangement = Arrangement.SpaceBetween) {
ColumnItem(text = "A")
ColumnItem(text = "B")
ColumnItem(text = "C")
}
Column(Modifier.default(androidGreen), verticalArrangement = Arrangement.SpaceAround) {
ColumnItem(text = "A")
ColumnItem(text = "B")
ColumnItem(text = "C")
}
Column(Modifier.default(androidBlue), verticalArrangement = Arrangement.SpaceEvenly) {
ColumnItem(text = "A")
ColumnItem(text = "B")
ColumnItem(text = "C")
}
Column(Modifier.default(androidDark), verticalArrangement = Arrangement.Top) {
ColumnItem(text = "A")
ColumnItem(text = "B")
ColumnItem(text = "C")
}
Column(Modifier.default(androidGreen), verticalArrangement = Arrangement.Center) {
ColumnItem(text = "A")
ColumnItem(text = "B")
ColumnItem(text = "C")
}
Column(Modifier.default(androidBlue), verticalArrangement = Arrangement.Bottom) {
ColumnItem(text = "A")
ColumnItem(text = "B")
ColumnItem(text = "C")
}
}
}
}
private fun Modifier.default(backgroundColor: Color) =
this.width(50.dp).padding(2.dp)
.background(backgroundColor, RoundedCornerShape(5.dp)).padding(top = 3.dp, bottom = 3.dp)
.fillMaxHeight()
@Composable
fun ColumnScope.ColumnItem(text: String, fixedSize: Boolean = true) {
val modifier = if (fixedSize) Modifier.height(80.dp) else Modifier.weight(1f)
Box(
modifier.width(50.dp).padding(5.dp).shadow(10.dp)
.background(Color.White, shape = RoundedCornerShape(5.dp))
.padding(top = 5.dp, bottom = 5.dp)
) {
Text(text, Modifier.align(Alignment.Center), color = androidDark)
}
}
val androidBlue = Color(0xff4282f2) | apache-2.0 |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/socketing/items/combiner/MythicClickToCombineOptions.kt | 1 | 2210 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.settings.socketing.items.combiner
import com.squareup.moshi.JsonClass
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.socketing.items.combiner.ClickToCombineOptions
import com.tealcube.minecraft.bukkit.mythicdrops.getMaterial
import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString
import org.bukkit.Material
import org.bukkit.configuration.ConfigurationSection
@JsonClass(generateAdapter = true)
data class MythicClickToCombineOptions internal constructor(
override val name: String = "",
override val lore: List<String> = emptyList(),
override val material: Material = Material.AIR
) : ClickToCombineOptions {
companion object {
fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicClickToCombineOptions(
configurationSection.getNonNullString("name"),
configurationSection.getStringList("lore"),
configurationSection.getMaterial("material")
)
}
}
| mit |
Xenoage/Zong | utils-kotlin/src/com/xenoage/utils/math/Size2f.kt | 1 | 638 | package com.xenoage.utils.math
import kotlin.coroutines.experimental.EmptyCoroutineContext.get
import kotlin.math.roundToInt
/**
* 2D size in float precision.
*/
data class Size2f(
val width: Float,
val height: Float) {
constructor(size: Size2i) : this(size.width.toFloat(), size.height.toFloat())
val area: Float
get() = width * height
fun add(size: Size2i) = Size2f(this.width + size.width, this.height + size.height)
fun scale(f: Float) = Size2f(width * f, height * f)
override fun toString() = "${width}x${height}"
companion object {
/** Size with width and height of 0. */
val size0 = Size2f(0f, 0f)
}
}
| agpl-3.0 |
smmribeiro/intellij-community | images/src/org/intellij/images/actions/EditExternallyAction.kt | 4 | 3392 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.images.actions
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.util.EnvironmentUtil
import org.intellij.images.ImagesBundle
import org.intellij.images.fileTypes.ImageFileTypeManager
import org.intellij.images.options.impl.ImagesConfigurable
import java.awt.Desktop
import java.io.File
import java.io.IOException
/**
* Open image file externally.
*
* @author [Alexey Efimov](mailto:[email protected])
* @author Konstantin Bulenkov
*/
internal class EditExternallyAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val imageFile = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE)
var executablePath = PropertiesComponent.getInstance().getValue(EditExternalImageEditorAction.EXT_PATH_KEY, "")
if (!StringUtil.isEmpty(executablePath)) {
EnvironmentUtil.getEnvironmentMap().forEach { (varName, varValue) ->
executablePath = if (SystemInfo.isWindows) StringUtil.replace(executablePath, "%$varName%", varValue, true)
else StringUtil.replace(executablePath, "\${$varName}", varValue, false);
}
executablePath = FileUtil.toSystemDependentName(executablePath);
val executable = File(executablePath)
val commandLine = GeneralCommandLine()
val path = if(executable.exists()) executable.absolutePath else executablePath
if (SystemInfo.isMac) {
commandLine.exePath = ExecUtil.openCommandPath
commandLine.addParameter("-a")
commandLine.addParameter(path)
}
else {
commandLine.exePath = path
}
val typeManager = ImageFileTypeManager.getInstance()
if (imageFile.isInLocalFileSystem && typeManager.isImage(imageFile)) {
commandLine.addParameter(VfsUtilCore.virtualToIoFile(imageFile).absolutePath)
}
commandLine.workDirectory = File(executablePath).parentFile
try {
commandLine.createProcess()
}
catch (ex: ExecutionException) {
Messages.showErrorDialog(e.project, ex.localizedMessage, ImagesBundle.message("error.title.launching.external.editor"));
ImagesConfigurable.show(e.project)
}
}
else {
try {
Desktop.getDesktop().open(imageFile.toNioPath().toFile())
}
catch (ignore: IOException) {
}
}
}
override fun update(e: AnActionEvent) {
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
val enabled = file != null && ImageFileTypeManager.getInstance().isImage(file)
if (e.place == ActionPlaces.PROJECT_VIEW_POPUP) {
e.presentation.isVisible = enabled
}
e.presentation.isEnabled = enabled
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinPrimaryConstructorProperty/after/RenameKotlinPrimaryConstructorProperty.kt | 13 | 218 | package testing.rename
public open class Foo(public open val second: String)
public class Bar : Foo("abc") {
override val second = "xyzzy"
}
fun usages(f: Foo, b: Bar): String {
return f.second + b.second
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/moveLambdaOutsideParentheses/inapplicableOptionalParametersAfter.kt | 13 | 101 | // PROBLEM: none
fun foo() {
bar(<caret>{ it })
}
fun bar(b: (Int) -> Int, option: Int = 0) { }
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinCocoaPodsModelBuilder.kt | 1 | 1497 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling
import org.gradle.api.Project
import org.jetbrains.plugins.gradle.tooling.AbstractModelBuilderService
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext
private const val POD_IMPORT_TASK_NAME = "podImport"
interface EnablePodImportTask
class KotlinCocoaPodsModelBuilder : AbstractModelBuilderService() {
override fun canBuild(modelName: String?): Boolean {
return EnablePodImportTask::class.java.name == modelName
}
override fun buildAll(modelName: String, project: Project, context: ModelBuilderContext): Any? {
val startParameter = project.gradle.startParameter
val taskNames = mutableListOf<String>()
taskNames.addAll(startParameter.taskNames)
if (project.tasks.findByPath(POD_IMPORT_TASK_NAME) != null && POD_IMPORT_TASK_NAME !in taskNames) {
taskNames.add(POD_IMPORT_TASK_NAME)
startParameter.setTaskNames(taskNames)
}
return null
}
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(
project, e, "EnablePodImportTask error"
).withDescription("Unable to create $POD_IMPORT_TASK_NAME task.")
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/introduceParameter/functionMultipleUsages.kt | 26 | 135 | fun foo(a: Int, s: String): Int {
val t = (a + 1) * 2
return <selection>a + 1</selection> - t
}
fun test() {
foo(1, "2")
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/fir-low-level-api/testdata/lazyResolve/topLevelFunctionsWithImplicitType.kt | 4 | 120 | fun resolveMe() {
receive(functionWithLazyBody())
}
fun receive(value: String){}
fun functionWithLazyBody() = "42" | apache-2.0 |
WillowChat/Kale | src/test/kotlin/chat/willow/kale/irc/message/rfc1459/TopicMessageTests.kt | 2 | 2203 | package chat.willow.kale.irc.message.rfc1459
import chat.willow.kale.core.message.IrcMessage
import chat.willow.kale.irc.prefix.Prefix
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class TopicMessageTests {
private lateinit var messageParser: TopicMessage.Message.Parser
private lateinit var messageSerialiser: TopicMessage.Command.Serialiser
@Before fun setUp() {
messageParser = TopicMessage.Message.Parser
messageSerialiser = TopicMessage.Command.Serialiser
}
@Test fun test_parse_Channel() {
val message = messageParser.parse(IrcMessage(command = "TOPIC", prefix = "source", parameters = listOf("#channel")))
assertEquals(TopicMessage.Message(source = Prefix(nick = "source"), channel = "#channel"), message)
}
@Test fun test_parse_Source_Channel() {
val message = messageParser.parse(IrcMessage(command = "TOPIC", prefix = "source", parameters = listOf("#channel")))
assertEquals(TopicMessage.Message(source = Prefix(nick = "source"), channel = "#channel"), message)
}
@Test fun test_parse_Source_Channel_Topic() {
val message = messageParser.parse(IrcMessage(command = "TOPIC", prefix = "source", parameters = listOf("#channel", "channel topic!")))
assertEquals(TopicMessage.Message(source = Prefix(nick = "source"), channel = "#channel", topic = "channel topic!"), message)
}
@Test fun test_parse_TooFewParameters() {
val message = messageParser.parse(IrcMessage(command = "TOPIC", parameters = listOf()))
assertNull(message)
}
@Test fun test_serialise_Source_Channel() {
val message = messageSerialiser.serialise(TopicMessage.Command(channel = "#channel"))
assertEquals(IrcMessage(command = "TOPIC", parameters = listOf("#channel")), message)
}
@Test fun test_serialise_Source_Channel_Topic() {
val message = messageSerialiser.serialise(TopicMessage.Command(channel = "#channel", topic = "another channel topic!"))
assertEquals(IrcMessage(command = "TOPIC", parameters = listOf("#channel", "another channel topic!")), message)
}
} | isc |
smmribeiro/intellij-community | platform/ide-core-impl/src/com/intellij/ide/impl/OpenProjectTask.kt | 1 | 7243 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.impl
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.util.function.Consumer
import java.util.function.Predicate
data class OpenProjectTask(val forceOpenInNewFrame: Boolean = false,
val projectToClose: Project? = null,
val isNewProject: Boolean = false,
/**
* Ignored if isNewProject is set to false.
*/
val useDefaultProjectAsTemplate: Boolean = isNewProject,
/**
* Prepared project to open. If you just need to open newly created and prepared project (e.g. used by a new project action).
*/
val project: Project? = null,
val projectName: String? = null,
/**
* Whether to show welcome screen if failed to open project.
*/
val showWelcomeScreen: Boolean = true,
@set:Deprecated(message = "Pass to constructor", level = DeprecationLevel.ERROR)
@set:ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
var callback: ProjectOpenedCallback? = null,
val frameManager: Any? = null,
val line: Int = -1,
val column: Int = -1,
val isRefreshVfsNeeded: Boolean = true,
/**
* Whether to run DirectoryProjectConfigurator if a new project or no modules.
*/
val runConfigurators: Boolean = false,
val runConversionBeforeOpen: Boolean = true,
val projectWorkspaceId: String? = null,
val isProjectCreatedWithWizard: Boolean = false,
@TestOnly
val preloadServices: Boolean = true,
val beforeInit: ((Project) -> Unit)? = null,
/**
* Ignored if project is explicitly set.
*/
val beforeOpen: ((Project) -> Boolean)? = null,
val preparedToOpen: ((Module) -> Unit)? = null,
val openProcessorChooser: ((List<ProjectOpenProcessor>) -> ProjectOpenProcessor)? = null) {
constructor(forceOpenInNewFrame: Boolean = false,
projectToClose: Project? = null,
isNewProject: Boolean = false,
useDefaultProjectAsTemplate: Boolean = isNewProject,
project: Project? = null,
projectName: String? = null,
showWelcomeScreen: Boolean = true,
callback: ProjectOpenedCallback? = null,
frameManager: Any? = null,
line: Int = -1,
column: Int = -1,
isRefreshVfsNeeded: Boolean = true,
runConfigurators: Boolean = false,
runConversionBeforeOpen: Boolean = true,
projectWorkspaceId: String? = null,
isProjectCreatedWithWizard: Boolean = false,
preloadServices: Boolean = true,
beforeInit: ((Project) -> Unit)? = null,
beforeOpen: ((Project) -> Boolean)? = null,
preparedToOpen: ((Module) -> Unit)? = null) :
this(forceOpenInNewFrame,
projectToClose,
isNewProject,
useDefaultProjectAsTemplate,
project,
projectName,
showWelcomeScreen,
callback,
frameManager,
line,
column,
isRefreshVfsNeeded,
runConfigurators,
runConversionBeforeOpen,
projectWorkspaceId,
isProjectCreatedWithWizard,
preloadServices,
beforeInit,
beforeOpen,
preparedToOpen,
null)
@ApiStatus.Internal
fun withBeforeOpenCallback(callback: Predicate<Project>) = copy(beforeOpen = { callback.test(it) })
@ApiStatus.Internal
fun withPreparedToOpenCallback(callback: Consumer<Module>) = copy(preparedToOpen = { callback.accept(it) })
@ApiStatus.Internal
fun withProjectName(value: String?) = copy(projectName = value)
@ApiStatus.Internal
fun asNewProjectAndRunConfigurators() = copy(isNewProject = true, runConfigurators = true, useDefaultProjectAsTemplate = true)
@ApiStatus.Internal
fun withRunConfigurators() = copy(runConfigurators = true)
@ApiStatus.Internal
fun withForceOpenInNewFrame(value: Boolean) = copy(forceOpenInNewFrame = value)
@ApiStatus.Internal
fun withOpenProcessorChooser(value: (List<ProjectOpenProcessor>) -> ProjectOpenProcessor) = copy(openProcessorChooser = value)
private var _untrusted: Boolean = false
val untrusted: Boolean
get() = _untrusted
fun untrusted(): OpenProjectTask {
val copy = copy()
copy._untrusted = true
return copy
}
companion object {
@JvmStatic
@JvmOverloads
fun newProject(runConfigurators: Boolean = false): OpenProjectTask {
return OpenProjectTask(isNewProject = true, runConfigurators = runConfigurators)
}
@JvmStatic
fun newProjectFromWizardAndRunConfigurators(projectToClose: Project?, isRefreshVfsNeeded: Boolean): OpenProjectTask {
return OpenProjectTask(isNewProject = true,
projectToClose = projectToClose,
runConfigurators = true,
isProjectCreatedWithWizard = true,
isRefreshVfsNeeded = isRefreshVfsNeeded)
}
@JvmStatic
fun fromWizardAndRunConfigurators(): OpenProjectTask {
return OpenProjectTask(runConfigurators = true,
isProjectCreatedWithWizard = true,
isRefreshVfsNeeded = false)
}
@JvmStatic
@JvmOverloads
fun withProjectToClose(projectToClose: Project?, forceOpenInNewFrame: Boolean = false): OpenProjectTask {
return OpenProjectTask(projectToClose = projectToClose, forceOpenInNewFrame = forceOpenInNewFrame)
}
@JvmStatic
fun withProjectToClose(newProject: Project?, projectToClose: Project?, forceOpenInNewFrame: Boolean): OpenProjectTask {
return OpenProjectTask(
forceOpenInNewFrame = forceOpenInNewFrame,
projectToClose = projectToClose,
project = newProject)
}
@JvmStatic
fun withCreatedProject(project: Project?): OpenProjectTask {
return OpenProjectTask(project = project)
}
}
/** Used only by [ProjectUtil.openOrImport] */
@JvmField
var checkDirectoryForFileBasedProjects = true
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/operators/get/Implicit.kt | 10 | 29 | fun test() {
Main()[42]
} | apache-2.0 |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/macros/KotlinBundledPathMacroContributor.kt | 5 | 1684 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.macros
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.components.impl.ProjectWidePathMacroContributor
import org.jetbrains.kotlin.config.SettingConstants
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinArtifactsDownloader
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import java.nio.file.Paths
import kotlin.io.path.extension
const val KOTLIN_BUNDLED = "KOTLIN_BUNDLED"
class KotlinBundledPathMacroContributor : ProjectWidePathMacroContributor {
override fun getProjectPathMacros(projectFilePath: String): Map<String, String> {
// It's not possible to use KotlinJpsPluginSettings.getInstance(project) because the project isn't yet initialized
val path = Paths.get(projectFilePath)
.let { iprOrMisc ->
when (iprOrMisc.extension) {
ProjectFileType.DEFAULT_EXTENSION -> iprOrMisc
"xml" -> iprOrMisc.resolveSibling(SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE)
else -> error("projectFilePath should be either misc.xml or *.ipr file")
}
}
?.let { KotlinJpsPluginSettings.readFromKotlincXmlOrIpr(it) }
?.version
?.let { KotlinArtifactsDownloader.getUnpackedKotlinDistPath(it).canonicalPath }
?: KotlinPluginLayout.kotlinc.canonicalPath
return mapOf(KOTLIN_BUNDLED to path)
}
}
| apache-2.0 |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/CustomizationRecyclerViewAdapter.kt | 1 | 13087 | package com.habitrpg.android.habitica.ui.adapter
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import com.facebook.drawee.view.SimpleDraweeView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.CustomizationGridItemBinding
import com.habitrpg.android.habitica.databinding.CustomizationSectionHeaderBinding
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.inventory.Customization
import com.habitrpg.android.habitica.models.inventory.CustomizationSet
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.subjects.PublishSubject
import java.util.*
class CustomizationRecyclerViewAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
var userSize: String? = null
var hairColor: String? = null
var gemBalance: Int = 0
var unsortedCustomizations: List<Customization> = ArrayList()
var customizationList: MutableList<Any> = ArrayList()
set(value) {
field = value
notifyDataSetChanged()
}
var additionalSetItems: List<Customization> = ArrayList()
var activeCustomization: String? = null
set(value) {
field = value
this.notifyDataSetChanged()
}
var ownedCustomiztations: List<String> = listOf()
private val selectCustomizationEvents = PublishSubject.create<Customization>()
private val unlockCustomizationEvents = PublishSubject.create<Customization>()
private val unlockSetEvents = PublishSubject.create<CustomizationSet>()
fun updateOwnership(ownedCustomizations: List<String>) {
this.ownedCustomiztations = ownedCustomizations
setCustomizations(unsortedCustomizations)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
return if (viewType == 0) {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.customization_section_header, parent, false)
SectionViewHolder(view)
} else {
val viewID: Int = R.layout.customization_grid_item
val view = LayoutInflater.from(parent.context).inflate(viewID, parent, false)
CustomizationViewHolder(view)
}
}
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
val obj = customizationList[position]
if (obj.javaClass == CustomizationSet::class.java) {
(holder as SectionViewHolder).bind(obj as CustomizationSet)
} else {
(holder as CustomizationViewHolder).bind(customizationList[position] as Customization)
}
}
override fun getItemCount(): Int {
return customizationList.size
}
override fun getItemViewType(position: Int): Int {
return if (this.customizationList[position].javaClass == CustomizationSet::class.java) {
0
} else {
1
}
}
fun setCustomizations(newCustomizationList: List<Customization>) {
unsortedCustomizations = newCustomizationList
this.customizationList = ArrayList()
var lastSet = CustomizationSet()
val today = Date()
for (customization in newCustomizationList.reversed()) {
if (customization.availableFrom != null || customization.availableUntil != null) {
if ((customization.availableFrom?.compareTo(today) ?: 0 > 0 || customization.availableUntil?.compareTo(today) ?: 0 < 0) && !customization.isUsable(ownedCustomiztations.contains(customization.identifier))) {
continue
}
}
if (customization.customizationSet != null && customization.customizationSet != lastSet.identifier) {
val set = CustomizationSet()
set.identifier = customization.customizationSet
set.text = customization.customizationSetName
set.price = customization.setPrice
set.hasPurchasable = !customization.isUsable(ownedCustomiztations.contains(customization.identifier))
lastSet = set
customizationList.add(set)
}
customizationList.add(customization)
if (!customization.isUsable(ownedCustomiztations.contains(customization.identifier)) && !lastSet.hasPurchasable) {
lastSet.hasPurchasable = true
}
}
this.notifyDataSetChanged()
}
fun getSelectCustomizationEvents(): Flowable<Customization> {
return selectCustomizationEvents.toFlowable(BackpressureStrategy.DROP)
}
fun getUnlockCustomizationEvents(): Flowable<Customization> {
return unlockCustomizationEvents.toFlowable(BackpressureStrategy.DROP)
}
fun getUnlockSetEvents(): Flowable<CustomizationSet> {
return unlockSetEvents.toFlowable(BackpressureStrategy.DROP)
}
internal inner class CustomizationViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = CustomizationGridItemBinding.bind(itemView)
var customization: Customization? = null
init {
itemView.setOnClickListener(this)
}
fun bind(customization: Customization) {
this.customization = customization
DataBindingUtils.loadImage(binding.imageView, customization.getIconName(userSize, hairColor))
if (customization.type == "background") {
val params = (binding.imageView.layoutParams as? LinearLayout.LayoutParams)?.apply {
gravity = Gravity.CENTER
}
binding.imageView.layoutParams = params
}
if (customization.isUsable(ownedCustomiztations.contains(customization.identifier))) {
binding.buyButton.visibility = View.GONE
} else {
binding.buyButton.visibility = View.VISIBLE
if (customization.customizationSet?.contains("timeTravel") == true) {
binding.priceLabel.currency = "hourglasses"
} else {
binding.priceLabel.currency = "gems"
}
binding.priceLabel.value = customization.price?.toDouble() ?: 0.0
}
if (activeCustomization == customization.identifier) {
binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700_brand_border)
} else {
binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700)
}
}
override fun onClick(v: View) {
if (customization?.isUsable(ownedCustomiztations.contains(customization?.identifier)) == false) {
if (customization?.customizationSet?.contains("timeTravel") == true) {
val dialog = HabiticaAlertDialog(itemView.context)
dialog.setMessage(R.string.purchase_from_timetravel_shop)
dialog.addButton(R.string.go_shopping, true) { _, _ ->
MainNavigationController.navigate(R.id.shopsFragment, bundleOf(Pair("selectedTab", 3)))
}
dialog.addButton(R.string.reward_dialog_dismiss, false)
dialog.show()
} else {
val dialogContent = LayoutInflater.from(itemView.context).inflate(R.layout.dialog_purchase_customization, null) as LinearLayout
val imageView = dialogContent.findViewById<SimpleDraweeView>(R.id.imageView)
DataBindingUtils.loadImage(imageView, customization?.getImageName(userSize, hairColor))
val priceLabel = dialogContent.findViewById<TextView>(R.id.priceLabel)
priceLabel.text = customization?.price.toString()
(dialogContent.findViewById<View>(R.id.gem_icon) as? ImageView)?.setImageBitmap(HabiticaIconsHelper.imageOfGem())
val dialog = HabiticaAlertDialog(itemView.context)
dialog.addButton(R.string.purchase_button, true) { _, _ ->
if (customization?.price ?: 0 > gemBalance) {
MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", false)))
return@addButton
}
customization?.let {
unlockCustomizationEvents.onNext(it)
}
}
dialog.setTitle(R.string.purchase_customization)
dialog.setAdditionalContentView(dialogContent)
dialog.addButton(R.string.reward_dialog_dismiss, false)
dialog.show()
}
return
}
if (customization?.identifier == activeCustomization) {
return
}
customization?.let {
selectCustomizationEvents.onNext(it)
}
}
}
internal inner class SectionViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = CustomizationSectionHeaderBinding.bind(itemView)
private val label: TextView by bindView(itemView, R.id.label)
var context: Context = itemView.context
private var set: CustomizationSet? = null
init {
binding.purchaseSetButton.setOnClickListener(this)
}
fun bind(set: CustomizationSet) {
this.set = set
this.label.text = set.text
if (set.hasPurchasable && !set.identifier.contains("timeTravel")) {
binding.purchaseSetButton.visibility = View.VISIBLE
binding.setPriceLabel.value = set.price.toDouble()
binding.setPriceLabel.currency = "gems"
} else {
binding.purchaseSetButton.visibility = View.GONE
}
}
override fun onClick(v: View) {
val dialogContent = LayoutInflater.from(context).inflate(R.layout.dialog_purchase_customization, null) as LinearLayout
val priceLabel = dialogContent.findViewById<TextView>(R.id.priceLabel)
priceLabel.text = set?.price.toString()
val dialog = HabiticaAlertDialog(context)
dialog.addButton(R.string.purchase_button, true) { _, _ ->
if (set?.price ?: 0 > gemBalance) {
MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", false)))
return@addButton
}
set?.customizations = ArrayList()
customizationList
.filter { Customization::class.java.isAssignableFrom(it.javaClass) }
.map { it as Customization }
.filter { !it.isUsable(ownedCustomiztations.contains(it.identifier)) && it.customizationSet != null && it.customizationSet == set?.identifier }
.forEach { set?.customizations?.add(it) }
if (additionalSetItems.isNotEmpty()) {
additionalSetItems
.filter { !it.isUsable(ownedCustomiztations.contains(it.identifier)) && it.customizationSet != null && it.customizationSet == set?.identifier }
.forEach { set?.customizations?.add(it) }
}
set?.let {
unlockSetEvents.onNext(it)
}
}
dialog.setTitle(context.getString(R.string.purchase_set_title, set?.text))
dialog.setAdditionalContentView(dialogContent)
dialog.addButton(R.string.reward_dialog_dismiss, false)
dialog.show()
}
}
}
| gpl-3.0 |
viartemev/requestmapper | src/main/kotlin/com/viartemev/requestmapper/RequestMappingItem.kt | 1 | 1847 | package com.viartemev.requestmapper
import com.intellij.navigation.ItemPresentation
import com.intellij.navigation.NavigationItem
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
class RequestMappingItem(val psiElement: PsiElement, private val urlPath: String, private val requestMethod: String) : NavigationItem {
private val navigationElement = psiElement.navigationElement as? Navigatable
override fun getName(): String = this.requestMethod + " " + this.urlPath
override fun getPresentation(): ItemPresentation = RequestMappingItemPresentation()
override fun navigate(requestFocus: Boolean) = navigationElement?.navigate(requestFocus) ?: Unit
override fun canNavigate(): Boolean = navigationElement?.canNavigate() ?: false
override fun canNavigateToSource(): Boolean = true
override fun toString(): String {
return "RequestMappingItem(psiElement=$psiElement, urlPath='$urlPath', requestMethod='$requestMethod', navigationElement=$navigationElement)"
}
private inner class RequestMappingItemPresentation : ItemPresentation {
override fun getPresentableText() = [email protected] + " " + [email protected]
override fun getLocationString(): String {
val psiElement = [email protected]
val fileName = psiElement.containingFile?.name
return when (psiElement) {
is PsiMethod -> (psiElement.containingClass?.name ?: fileName ?: "unknownFile") + "." + psiElement.name
is PsiClass -> psiElement.name ?: fileName ?: "unknownFile"
else -> "unknownLocation"
}
}
override fun getIcon(b: Boolean) = RequestMapperIcons.SEARCH
}
}
| mit |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/OnScreenRenderPass.kt | 1 | 4115 | package de.fabmax.kool.platform.vk
import de.fabmax.kool.util.logD
import org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
import org.lwjgl.vulkan.VK10.*
class OnScreenRenderPass(swapChain: SwapChain) :
VkRenderPass(swapChain.sys, swapChain.extent.width(), swapChain.extent.height(), listOf(swapChain.imageFormat)) {
override val vkRenderPass: Long
init {
memStack {
val attachments = callocVkAttachmentDescriptionN(3) {
this[0]
.format(swapChain.imageFormat)
.samples(swapChain.sys.physicalDevice.msaaSamples)
.loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR)
.storeOp(VK_ATTACHMENT_STORE_OP_STORE)
.stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE)
.stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
.initialLayout(VK_IMAGE_LAYOUT_UNDEFINED)
.finalLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
this[1]
.format(swapChain.sys.physicalDevice.depthFormat)
.samples(swapChain.sys.physicalDevice.msaaSamples)
.loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR)
.storeOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
.stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE)
.stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
.initialLayout(VK_IMAGE_LAYOUT_UNDEFINED)
.finalLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
this[2]
.format(swapChain.imageFormat)
.samples(VK_SAMPLE_COUNT_1_BIT)
.loadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE)
.storeOp(VK_ATTACHMENT_STORE_OP_STORE)
.stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE)
.stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
.initialLayout(VK_IMAGE_LAYOUT_UNDEFINED)
.finalLayout(VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)
}
val colorAttachmentRef = callocVkAttachmentReferenceN(1) {
attachment(0)
layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
}
val depthAttachmentRef = callocVkAttachmentReferenceN(1) {
attachment(1)
layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
}
val colorAttachmentResolveRef = callocVkAttachmentReferenceN(1) {
attachment(2)
layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
}
val subpass = callocVkSubpassDescriptionN(1) {
pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS)
colorAttachmentCount(1)
pColorAttachments(colorAttachmentRef)
pDepthStencilAttachment(depthAttachmentRef[0])
pResolveAttachments(colorAttachmentResolveRef)
}
val dependency = callocVkSubpassDependencyN(1) {
srcSubpass(VK_SUBPASS_EXTERNAL)
dstSubpass(0)
srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)
srcAccessMask(0)
dstStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)
dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT or VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
}
val renderPassInfo = callocVkRenderPassCreateInfo {
sType(VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO)
pAttachments(attachments)
pSubpasses(subpass)
pDependencies(dependency)
}
vkRenderPass = checkCreatePointer { vkCreateRenderPass(swapChain.sys.device.vkDevice, renderPassInfo, null, it) }
}
swapChain.addDependingResource(this)
logD { "Created render pass" }
}
override fun freeResources() {
vkDestroyRenderPass(sys.device.vkDevice, vkRenderPass, null)
logD { "Destroyed render pass" }
}
} | apache-2.0 |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/procedural/Vase.kt | 1 | 5418 | package de.fabmax.kool.demo.procedural
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.math.toDeg
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.deferred.deferredPbrShader
import de.fabmax.kool.scene.Mesh
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.MeshBuilder
import de.fabmax.kool.scene.geometry.simpleShape
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.ColorGradient
import de.fabmax.kool.util.MdColor
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class Vase : Mesh(IndexedVertexList(Attribute.POSITIONS, Attribute.NORMALS, Attribute.COLORS)) {
init {
generate {
makeGeometry()
geometry.removeDegeneratedTriangles()
geometry.generateNormals()
}
shader = deferredPbrShader {
roughness = 0.3f
}
}
private fun MeshBuilder.makeGeometry() {
rotate(90f, Vec3f.NEG_X_AXIS)
translate(-7.5f, -2.5f, 0f)
scale(1.8f, 1.8f, 1.8f)
translate(0f, 0f, 0.15f)
val gridGrad = ColorGradient(MdColor.BROWN, MdColor.BLUE tone 300)
val tubeColors = Array(10) { i -> gridGrad.getColor(i / 9f).mix(Color.BLACK, 0.3f) }
val tubeGrad = ColorGradient(*tubeColors)
makeGrid(gridGrad)
makeTube(tubeGrad)
}
private fun MeshBuilder.makeGrid(gridGrad: ColorGradient) {
profile {
simpleShape(true) {
xy(0.8f, 1f); xy(-0.8f, 1f)
xy(-1f, 0.8f); xy(-1f, -0.8f)
xy(-0.8f, -1f); xy(0.8f, -1f)
xy(1f, -0.8f); xy(1f, 0.8f)
}
val n = 50
val cols = 24
for (c in 0 until cols) {
val rad = 2f * PI.toFloat() * c / cols
for (i in 0..n) {
withTransform {
val p = i.toFloat() / n
val rot = p * 180f * if (c % 2 == 0) 1 else -1
color = gridGrad.getColor(p).toLinear()
rotate(rot, Vec3f.Z_AXIS)
val r = 1f + (p - 0.5f) * (p - 0.5f) * 4
translate(cos(rad) * r, sin(rad) * r, 0f)
translate(0f, 0f, p * 10f)
rotate(rad.toDeg(), Vec3f.Z_AXIS)
scale(0.05f, 0.05f, 1f)
sample(i != 0)
}
}
}
}
}
private fun MeshBuilder.makeTube(tubeGrad: ColorGradient) {
profile {
circleShape(2.2f, 60)
withTransform {
for (i in 0..1) {
val invert = i == 1
withTransform {
color = tubeGrad.getColor(0f).toLinear()
scale(0.97f, 0.97f, 1f)
sample(connect = false, inverseOrientation = invert)
scale(1 / 0.97f, 1 / 0.97f, 1f)
scale(0.96f, 0.96f, 1f)
sample(inverseOrientation = invert)
scale(1 / 0.96f, 1 / 0.96f, 1f)
scale(0.95f, 0.95f, 1f)
//sample(inverseOrientation = invert)
for (j in 0..20) {
withTransform {
val p = j / 20f
val s = 1 - sin(p * PI.toFloat()) * 0.6f
val t = 5f - cos(p * PI.toFloat()) * 5
color = tubeGrad.getColor(p).toLinear()
translate(0f, 0f, t)
scale(s, s, 1f)
sample(inverseOrientation = invert)
}
if (j == 0) {
// actually fills bottom, but with inverted face orientation
fillTop()
}
}
translate(0f, 0f, 10f)
scale(1 / 0.95f, 1 / 0.95f, 1f)
scale(0.96f, 0.96f, 1f)
sample(inverseOrientation = invert)
scale(1 / 0.96f, 1 / 0.96f, 1f)
scale(0.97f, 0.97f, 1f)
sample(inverseOrientation = invert)
}
translate(0f, 0f, -0.15f)
scale(1f, 1f, 10.3f / 10f)
}
}
for (i in 0..1) {
color = tubeGrad.getColor(i.toFloat()).toLinear()
withTransform {
translate(0f, 0f, -0.15f + 10.15f * i)
scale(0.97f, 0.97f, 1f)
sample(connect = false)
scale(1f / 0.97f, 1f / 0.97f, 1f)
sample()
translate(0f, 0f, 0.03f)
scale(1.02f, 1.02f, 1f)
sample()
translate(0f, 0f, 0.09f)
sample()
translate(0f, 0f, 0.03f)
scale(1f / 1.02f, 1f / 1.02f, 1f)
sample()
scale(0.97f, 0.97f, 1f)
sample()
}
}
}
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/checker/recovery/namelessToplevelDeclarations.fir.kt | 10 | 566 | package<EOLError descr="Package name must be a '.'-separated identifier list placed on a single line"></EOLError>
<error descr="[FUNCTION_DECLARATION_WITH_NO_NAME] Function declaration must have a name">fun ()</error> {
}
val<error descr="Expecting property name or receiver type"> </error>: Int = 1
class<error descr="Name expected"> </error>{
}
interface<error descr="Name expected"> </error>{
}
object<error descr="Name expected"> </error>{
}
enum class<error descr="Name expected"> </error>{}
annotation class<error descr="Name expected"> </error>{}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/filterLastExplicit.kt | 4 | 97 | // WITH_RUNTIME
val x = listOf("1", "").filte<caret>r { element -> element.isNotEmpty() }.last() | apache-2.0 |
mseroczynski/CityBikes | app/src/main/kotlin/pl/ches/citybikes/util/extensions/Slimber.kt | 1 | 1913 | import android.util.Log
import timber.log.Timber
inline fun ifPlanted(action: () -> Any) {
if (Timber.forest().size > 0) {
action.invoke()
}
}
inline fun e(message: () -> String) = ifPlanted { Timber.e(message.invoke()) }
inline fun e(throwable: Throwable, message: () -> String) = ifPlanted { Timber.e(throwable, message.invoke()) }
inline fun w(message: () -> String) = ifPlanted { Timber.w(message.invoke()) }
inline fun w(throwable: Throwable, message: () -> String) = ifPlanted { Timber.w(throwable, message.invoke()) }
inline fun i(message: () -> String) = ifPlanted { Timber.i(message.invoke()) }
inline fun i(throwable: Throwable, message: () -> String) = ifPlanted { Timber.i(throwable, message.invoke()) }
inline fun d(message: () -> String) = ifPlanted { Timber.d(message.invoke()) }
inline fun d(throwable: Throwable, message: () -> String) = ifPlanted { Timber.d(throwable, message.invoke()) }
inline fun v(message: () -> String) = ifPlanted { Timber.v(message.invoke()) }
inline fun v(throwable: Throwable, message: () -> String) = ifPlanted { Timber.v(throwable, message.invoke()) }
inline fun wtf(message: () -> String) = ifPlanted { Timber.wtf(message.invoke()) }
inline fun wtf(throwable: Throwable, message: () -> String) = ifPlanted { Timber.wtf(throwable, message.invoke()) }
inline fun log(priority: Int, t: Throwable, message: () -> String) {
when (priority) {
Log.ERROR -> e(t, message)
Log.WARN -> w(t, message)
Log.INFO -> i(t, message)
Log.DEBUG -> d(t, message)
Log.VERBOSE -> v(t, message)
Log.ASSERT -> wtf(t, message)
}
}
inline fun log(priority: Int, message: () -> String) {
when (priority) {
Log.ERROR -> e(message)
Log.WARN -> w(message)
Log.INFO -> i(message)
Log.DEBUG -> d(message)
Log.VERBOSE -> v(message)
Log.ASSERT -> wtf(message)
}
} | gpl-3.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/typeAddition/protectedFunWithoutReturnType.kt | 5 | 102 | // "Specify return type explicitly" "true"
package a
class A() {
protected fun <caret>foo() = 1
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/suspiciousCallableReferenceInLambda/explicitThisReceiver.kt | 4 | 139 | // WITH_RUNTIME
class Test {
fun function(s: String): Boolean = true
fun test() {
"".let {<caret> this::function }
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveAtFromAnnotationArgument.kt | 1 | 1432 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
class RemoveAtFromAnnotationArgument(constructor: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(constructor) {
override fun getText() = KotlinBundle.message("remove.from.annotation.argument")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val elementToReplace = (element?.parent as? KtAnnotatedExpression) ?: return
val noAt = KtPsiFactory(elementToReplace.project).createExpression(elementToReplace.text.replaceFirst("@", ""))
elementToReplace.replace(noAt)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtAnnotationEntry>? =
(diagnostic.psiElement as? KtAnnotationEntry)?.let { RemoveAtFromAnnotationArgument(it) }
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/callChainWithLineBreak.kt | 4 | 179 | // PROBLEM: none
// WITH_RUNTIME
// HIGHLIGHT: INFORMATION
fun test(list: List<Int>) {
list.filter { it > 1 }
.filter { it > 2 }
.let<caret> { println(it) }
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/diagnosticBasedPostProcessing.kt | 2 | 4942 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.postProcessing
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.RangeMarker
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.quickfix.AddExclExclCallFix
import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionsFactory
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class DiagnosticBasedPostProcessingGroup(diagnosticBasedProcessings: List<DiagnosticBasedProcessing>) : FileBasedPostProcessing() {
constructor(vararg diagnosticBasedProcessings: DiagnosticBasedProcessing) : this(diagnosticBasedProcessings.toList())
private val diagnosticToFix =
diagnosticBasedProcessings.asSequence().flatMap { processing ->
processing.diagnosticFactories.asSequence().map { it to processing::fix }
}.groupBy { it.first }.mapValues { (_, list) ->
list.map { it.second }
}
override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) {
val diagnostics = runReadAction {
val resolutionFacade = KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(allFiles)
analyzeFileRange(file, rangeMarker, resolutionFacade).all()
}
for (diagnostic in diagnostics) {
val elementIsInRange = runReadAction {
val range = rangeMarker?.range ?: file.textRange
diagnostic.psiElement.isInRange(range)
}
if (!elementIsInRange) continue
diagnosticToFix[diagnostic.factory]?.forEach { fix ->
val elementIsValid = runReadAction { diagnostic.psiElement.isValid }
if (elementIsValid) {
fix(diagnostic)
}
}
}
}
private fun analyzeFileRange(file: KtFile, rangeMarker: RangeMarker?, resolutionFacade: ResolutionFacade): Diagnostics {
val elements = when {
rangeMarker == null -> listOf(file)
rangeMarker.isValid -> file.elementsInRange(rangeMarker.range!!).filterIsInstance<KtElement>()
else -> emptyList()
}
return if (elements.isNotEmpty())
resolutionFacade.analyzeWithAllCompilerChecks(elements).bindingContext.diagnostics
else Diagnostics.EMPTY
}
}
interface DiagnosticBasedProcessing {
val diagnosticFactories: List<DiagnosticFactory<*>>
fun fix(diagnostic: Diagnostic)
}
inline fun <reified T : PsiElement> diagnosticBasedProcessing(
vararg diagnosticFactory: DiagnosticFactory<*>,
crossinline fix: (T, Diagnostic) -> Unit
) =
object : DiagnosticBasedProcessing {
override val diagnosticFactories = diagnosticFactory.toList()
override fun fix(diagnostic: Diagnostic) {
val element = diagnostic.psiElement as? T
if (element != null) runUndoTransparentActionInEdt(inWriteAction = true) {
fix(element, diagnostic)
}
}
}
fun diagnosticBasedProcessing(fixFactory: KotlinIntentionActionsFactory, vararg diagnosticFactory: DiagnosticFactory<*>) =
object : DiagnosticBasedProcessing {
override val diagnosticFactories = diagnosticFactory.toList()
override fun fix(diagnostic: Diagnostic) {
val fix = runReadAction { fixFactory.createActions(diagnostic).singleOrNull() } ?: return
runUndoTransparentActionInEdt(inWriteAction = true) {
fix.invoke(diagnostic.psiElement.project, null, diagnostic.psiFile)
}
}
}
fun addExclExclFactoryNoImplicitReceiver(initialFactory: KotlinSingleIntentionActionFactory) =
object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? =
initialFactory.createActions(diagnostic).singleOrNull()
?.safeAs<AddExclExclCallFix>()
?.let {
AddExclExclCallFix(diagnostic.psiElement, checkImplicitReceivers = false)
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.