repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
leafclick/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemEventDispatcher.kt
1
5792
// 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.openapi.externalSystem.service.execution import com.intellij.build.BuildEventDispatcher import com.intellij.build.BuildProgressListener import com.intellij.build.events.BuildEvent import com.intellij.build.events.FinishBuildEvent import com.intellij.build.output.BuildOutputInstantReaderImpl import com.intellij.build.output.BuildOutputParser import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.ApiStatus import java.io.Closeable import java.util.concurrent.CompletableFuture import java.util.function.Consumer /** * @author Vladislav.Soroka */ @ApiStatus.Experimental class ExternalSystemEventDispatcher(taskId: ExternalSystemTaskId, progressListener: BuildProgressListener?, appendOutputToMainConsole: Boolean) : BuildEventDispatcher { constructor(taskId: ExternalSystemTaskId, progressListener: BuildProgressListener?) : this(taskId, progressListener, true) private lateinit var outputMessageDispatcher: ExternalSystemOutputMessageDispatcher private var isStdOut: Boolean = true override fun setStdOut(stdOut: Boolean) { this.isStdOut = stdOut outputMessageDispatcher.stdOut = stdOut } init { val buildOutputParsers = SmartList<BuildOutputParser>() if (progressListener != null) { ExternalSystemOutputParserProvider.EP_NAME.extensions.forEach { if (taskId.projectSystemId == it.externalSystemId) { buildOutputParsers.addAll(it.getBuildOutputParsers(taskId)) } } var foundFactory: ExternalSystemOutputDispatcherFactory? = null EP_NAME.extensions.forEach { if (taskId.projectSystemId == it.externalSystemId) { if (foundFactory != null) { throw RuntimeException("'" + EP_NAME.name + "' extension should be one per external system") } foundFactory = it } } outputMessageDispatcher = foundFactory?.create(taskId, progressListener, appendOutputToMainConsole, buildOutputParsers) ?: DefaultOutputMessageDispatcher(taskId, progressListener, buildOutputParsers) } } override fun onEvent(buildId: Any, event: BuildEvent) { outputMessageDispatcher.onEvent(buildId, event) } override fun invokeOnCompletion(consumer: Consumer<Throwable?>) { outputMessageDispatcher.invokeOnCompletion(consumer) } override fun append(csq: CharSequence): BuildEventDispatcher? { outputMessageDispatcher.append(csq) return this } override fun append(csq: CharSequence, start: Int, end: Int): BuildEventDispatcher? { outputMessageDispatcher.append(csq, start, end) return this } override fun append(c: Char): BuildEventDispatcher? { outputMessageDispatcher.append(c) return this } override fun close() { outputMessageDispatcher.close() } companion object { private val EP_NAME = ExtensionPointName.create<ExternalSystemOutputDispatcherFactory>("com.intellij.externalSystemOutputDispatcher") } } private class DefaultOutputMessageDispatcher(buildProgressListener: BuildProgressListener, val outputReader: BuildOutputInstantReaderImpl) : AbstractOutputMessageDispatcher(buildProgressListener), Appendable by outputReader { constructor(buildId: Any, buildProgressListener: BuildProgressListener, parsers: List<BuildOutputParser>) : this(buildProgressListener, BuildOutputInstantReaderImpl(buildId, buildId, buildProgressListener, parsers)) override var stdOut = true override fun closeAndGetFuture(): CompletableFuture<Unit> { return outputReader.closeAndGetFuture() } } interface ExternalSystemOutputDispatcherFactory { val externalSystemId: Any? fun create(buildId: Any, buildProgressListener: BuildProgressListener, appendOutputToMainConsole: Boolean, parsers: List<BuildOutputParser>): ExternalSystemOutputMessageDispatcher } interface ExternalSystemOutputMessageDispatcher : Closeable, Appendable, BuildProgressListener { var stdOut: Boolean fun invokeOnCompletion(handler: Consumer<Throwable?>) } @ApiStatus.Experimental abstract class AbstractOutputMessageDispatcher(private val buildProgressListener: BuildProgressListener) : ExternalSystemOutputMessageDispatcher { private val onCompletionHandlers = ContainerUtil.createConcurrentList<Consumer<Throwable?>>() @Volatile private var isClosed: Boolean = false override fun onEvent(buildId: Any, event: BuildEvent) = when (event) { is FinishBuildEvent -> invokeOnCompletion(Consumer { buildProgressListener.onEvent(buildId, event) }) else -> buildProgressListener.onEvent(buildId, event) } override fun invokeOnCompletion(handler: Consumer<Throwable?>) { if (isClosed) { LOG.warn("Attempt to add completion handler for closed output dispatcher, the handler will be ignored", if (LOG.isDebugEnabled) Throwable() else null) } else { onCompletionHandlers.add(handler) } } protected abstract fun closeAndGetFuture(): CompletableFuture<*> final override fun close() { val future = closeAndGetFuture() isClosed = true for (handler in onCompletionHandlers.asReversed()) { future.whenComplete { _, u -> handler.accept(u) } } onCompletionHandlers.clear() } companion object { private val LOG = logger<AbstractOutputMessageDispatcher>() } }
apache-2.0
9f8dae039a293bb69aa14551578c4088
36.856209
146
0.755007
5.313761
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/pick/PickPOIViewModel.kt
1
3748
package org.mtransit.android.ui.pick import androidx.lifecycle.LiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.liveData import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import org.mtransit.android.commons.MTLog import org.mtransit.android.commons.provider.POIProviderContract import org.mtransit.android.data.POIManager import org.mtransit.android.datasource.DataSourcesRepository import org.mtransit.android.datasource.POIRepository import org.mtransit.android.ui.MTViewModelWithLocation import org.mtransit.android.ui.favorites.FavoritesViewModel import org.mtransit.android.ui.view.common.Event import org.mtransit.android.ui.view.common.PairMediatorLiveData import org.mtransit.android.ui.view.common.getLiveDataDistinct import java.util.ArrayList import javax.inject.Inject import kotlin.math.min @HiltViewModel class PickPOIViewModel @Inject constructor( savedStateHandle: SavedStateHandle, dataSourcesRepository: DataSourcesRepository, private val poiRepository: POIRepository, ) : MTViewModelWithLocation() { companion object { private val LOG_TAG = PickPOIViewModel::class.java.simpleName internal const val EXTRA_POI_UUIDS = "extra_poi_uuids" internal const val EXTRA_POI_AUTHORITIES = "extra_poi_authorities" private val POI_ALPHA_COMPARATOR = FavoritesViewModel.POIAlphaComparator() } override fun getLogTag(): String = LOG_TAG private val _uuids = savedStateHandle.getLiveDataDistinct<ArrayList<String>?>(EXTRA_POI_UUIDS) private val _authorities = savedStateHandle.getLiveDataDistinct<ArrayList<String>?>(EXTRA_POI_AUTHORITIES) private val _allAgencyAuthorities = dataSourcesRepository.readingAllAgencyAuthorities() val dataSourceRemovedEvent: LiveData<Event<Boolean?>> = PairMediatorLiveData(_authorities, _allAgencyAuthorities).switchMap { (authorities, allAgencyAuthorities) -> liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { emit(Event(checkForDataSourceRemoved(authorities, allAgencyAuthorities))) } } private fun checkForDataSourceRemoved(authorities: List<String>?, allAgencyAuthorities: List<String>?): Boolean? { if (authorities == null || allAgencyAuthorities == null) { return null // SKIP } authorities.firstOrNull { !allAgencyAuthorities.contains(it) }?.let { MTLog.d(this, "Authority $it doesn't exist anymore, dismissing dialog.") return true } return false } val poiList: LiveData<List<POIManager>?> = PairMediatorLiveData(_uuids, _authorities).switchMap { (uuids, authorities) -> liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { emit(getPOIList(uuids, authorities)) } } private fun getPOIList(uuids: List<String>?, authorities: List<String>?): List<POIManager>? { if (uuids == null || authorities == null) { return null } val size = min(uuids.size, authorities.size) val authorityToUUIDs = mutableMapOf<String, MutableList<String>>() for (i in 0 until size) { authorityToUUIDs.getOrPut(authorities[i]) { mutableListOf() }.add(uuids[i]) } val poiList = mutableListOf<POIManager>() authorityToUUIDs.forEach { (authority, uuids) -> poiRepository.findPOIMs(authority, POIProviderContract.Filter.getNewUUIDsFilter(uuids))?.let { poiList.addAll(it) } } poiList.sortWith(POI_ALPHA_COMPARATOR) return poiList } }
apache-2.0
b8e2d3ed6ba4e1271c0f2bba6668bdc9
40.655556
125
0.72572
4.587515
false
false
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KMergeTwoSortedLinkedLists.kt
1
1923
package me.consuegra.algorithms import me.consuegra.datastructure.KListNode /** * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together * the nodes of the first two lists. */ class KMergeTwoSortedLinkedLists { fun merge(list1: KListNode<Int>?, list2: KListNode<Int>?) : KListNode<Int>? { var auxList1 = list1 var auxList2 = list2 var result: KListNode<Int>? = null while (auxList1 != null || auxList2 != null) { when { auxList1 != null && auxList2 != null -> { if (auxList1.data <= auxList2.data) { result = result?.append(auxList1.data) ?: KListNode(auxList1.data) auxList1 = auxList1.next } else { result = result?.append(auxList2.data) ?: KListNode(auxList2.data) auxList2 = auxList2.next } } auxList1 != null -> { result = result?.append(auxList1.data) ?: KListNode(auxList1.data) auxList1 = auxList1.next } auxList2 != null -> { result = result?.append(auxList2.data) ?: KListNode(auxList2.data) auxList2 = auxList2.next } } } return result } fun mergeRec(list1: KListNode<Int>?, list2: KListNode<Int>?) : KListNode<Int>? { if (list1 == null) { return list2 } if (list2 == null) { return list1 } val result: KListNode<Int>? if (list1.data < list2.data) { result = list1 result.next = merge(list1.next, list2) } else { result = list2 result.next = merge(list1, list2.next) } return result } }
mit
4949af597e8c372d9cc22ab981d73485
32.736842
110
0.50234
4.144397
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/ieee754/nullableFloatNotEquals10.kt
2
708
// LANGUAGE_VERSION: 1.0 fun myNotEquals(a: Float?, b: Float?) = a != b fun myNotEquals1(a: Float?, b: Float) = a != b fun myNotEquals2(a: Float, b: Float?) = a != b fun myNotEquals0(a: Float, b: Float) = a != b fun box(): String { if (myNotEquals(null, null)) return "fail 1" if (!myNotEquals(null, 0.0F)) return "fail 2" if (!myNotEquals(0.0F, null)) return "fail 3" if (myNotEquals(0.0F, 0.0F)) return "fail 4" if (!myNotEquals1(null, 0.0F)) return "fail 5" if (myNotEquals1(0.0F, 0.0F)) return "fail 6" if (!myNotEquals2(0.0F, null)) return "fail 7" if (myNotEquals2(0.0F, 0.0F)) return "fail 8" if (myNotEquals0(0.0F, 0.0F)) return "fail 9" return "OK" }
apache-2.0
c97cbc8bb704814bf69f2e7a2ff616a8
26.269231
50
0.611582
2.602941
false
false
false
false
AndroidX/androidx
camera/camera-core/src/test/java/androidx/camera/core/imagecapture/FakeImageCaptureControl.kt
3
2378
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.core.imagecapture import androidx.camera.core.impl.CaptureConfig import androidx.camera.core.impl.utils.futures.Futures import androidx.concurrent.futures.CallbackToFutureAdapter import com.google.common.util.concurrent.ListenableFuture /** * Fake [ImageCaptureControl] that records method calls. */ class FakeImageCaptureControl : ImageCaptureControl { companion object { // By default, this fake object returns an immediate successful result. private val IMMEDIATE_RESULT: ListenableFuture<Void> = Futures.immediateFuture(null) } val actions = arrayListOf<Action>() var latestCaptureConfigs: List<CaptureConfig?> = arrayListOf() // Flip this flag to return a custom result using pendingResultCompleter. var shouldUsePendingResult = false lateinit var pendingResultCompleter: CallbackToFutureAdapter.Completer<Void> var pendingResult = CallbackToFutureAdapter.getFuture { completer -> pendingResultCompleter = completer "FakeImageCaptureControl's pendingResult" } override fun lockFlashMode() { actions.add(Action.LOCK_FLASH) } override fun unlockFlashMode() { actions.add(Action.UNLOCK_FLASH) } override fun submitStillCaptureRequests( captureConfigs: MutableList<CaptureConfig> ): ListenableFuture<Void> { actions.add(Action.SUBMIT_REQUESTS) latestCaptureConfigs = captureConfigs if (shouldUsePendingResult) { return pendingResult } return IMMEDIATE_RESULT } fun clear() { // Cancel pending futures. pendingResult.cancel(true) } enum class Action { LOCK_FLASH, UNLOCK_FLASH, SUBMIT_REQUESTS } }
apache-2.0
257dfb369a6e1290bd71217fdb9b9cd7
31.148649
92
0.718251
4.708911
false
true
false
false
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/kernel/services/ExpoKernelServiceRegistry.kt
2
1186
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.kernel.services import android.content.Context import host.exp.exponent.kernel.services.linking.LinkingKernelService import host.exp.exponent.kernel.services.sensors.* import host.exp.exponent.storage.ExponentSharedPreferences class ExpoKernelServiceRegistry( context: Context, exponentSharedPreferences: ExponentSharedPreferences ) { val linkingKernelService = LinkingKernelService() val gyroscopeKernelService = GyroscopeKernelService(context) val magnetometerKernelService = MagnetometerKernelService(context) val accelerometerKernelService = AccelerometerKernelService(context) val barometerKernelService = BarometerKernelService(context) val gravitySensorKernelService = GravitySensorKernelService(context) val rotationVectorSensorKernelService = RotationVectorSensorKernelService(context) val linearAccelerationSensorKernelService = LinearAccelerationSensorKernelService(context) val magnetometerUncalibratedKernelService = MagnetometerUncalibratedKernelService(context) val permissionsKernelService = PermissionsKernelService(context, exponentSharedPreferences) }
bsd-3-clause
19155a2c6c0272532a00b820ae1a8183
50.565217
93
0.865093
5.490741
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/JoinDeclarationAndAssignmentIntention.kt
2
8526
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceService import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.canOmitDeclaredType import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.unblockDocument import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils @Suppress("DEPRECATION") class JoinDeclarationAndAssignmentInspection : IntentionBasedInspection<KtProperty>( JoinDeclarationAndAssignmentIntention::class, KotlinBundle.message("can.be.joined.with.assignment") ) class JoinDeclarationAndAssignmentIntention : SelfTargetingRangeIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("join.declaration.and.assignment") ) { private fun equalNullableTypes(type1: KotlinType?, type2: KotlinType?): Boolean { if (type1 == null) return type2 == null if (type2 == null) return false return TypeUtils.equalTypes(type1, type2) } override fun applicabilityRange(element: KtProperty): TextRange? { if (element.hasDelegate() || element.hasInitializer() || element.setter != null || element.getter != null || element.receiverTypeReference != null || element.name == null ) { return null } val assignment = findAssignment(element) ?: return null val assignmentRight = assignment.right ?: return null val context = assignment.analyze() val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, element] if (assignmentRight.anyDescendantOfType<KtNameReferenceExpression> { context[BindingContext.REFERENCE_TARGET, it] == propertyDescriptor }) return null if (!assignmentRight.let { hasNoLocalDependencies(it, element) && ((element.isVar && !element.isLocal) || equalNullableTypes(it.getType(context), context[BindingContext.TYPE, element.typeReference])) }) return null return TextRange((element.modifierList ?: element.valOrVarKeyword).startOffset, (element.typeReference ?: element).endOffset) } override fun applyTo(element: KtProperty, editor: Editor?) { if (element.typeReference == null) return val assignment = findAssignment(element) ?: return val initializer = assignment.right ?: return element.initializer = initializer if (element.hasModifier(KtTokens.LATEINIT_KEYWORD)) element.removeModifier(KtTokens.LATEINIT_KEYWORD) val grandParent = assignment.parent.parent val initializerBlock = grandParent as? KtAnonymousInitializer val secondaryConstructor = grandParent as? KtSecondaryConstructor val newProperty = if (!element.isLocal && (initializerBlock != null || secondaryConstructor != null)) { assignment.delete() if ((initializerBlock?.body as? KtBlockExpression)?.isEmpty() == true) initializerBlock.delete() val secondaryConstructorBlock = secondaryConstructor?.bodyBlockExpression if (secondaryConstructorBlock?.isEmpty() == true) secondaryConstructorBlock.delete() element } else { assignment.replaced(element).also { element.delete() } } val newInitializer = newProperty.initializer!! val typeReference = newProperty.typeReference!! editor?.apply { unblockDocument() if (newProperty.canOmitDeclaredType(newInitializer, canChangeTypeToSubtype = !newProperty.isVar)) { val colon = newProperty.colon!! selectionModel.setSelection(colon.startOffset, typeReference.endOffset) moveCaret(typeReference.endOffset, ScrollType.CENTER) } else { moveCaret(newInitializer.startOffset, ScrollType.CENTER) } } } private fun findAssignment(property: KtProperty): KtBinaryExpression? { val propertyContainer = property.parent as? KtElement ?: return null property.typeReference ?: return null val assignments = mutableListOf<KtBinaryExpression>() fun process(binaryExpr: KtBinaryExpression) { if (binaryExpr.operationToken != KtTokens.EQ) return val leftReference = when (val left = binaryExpr.left) { is KtNameReferenceExpression -> left is KtDotQualifiedExpression -> if (left.receiverExpression is KtThisExpression) left.selectorExpression as? KtNameReferenceExpression else null else -> null } ?: return if (leftReference.getReferencedName() != property.name) return assignments += binaryExpr } propertyContainer.forEachDescendantOfType(::process) fun PsiElement?.invalidParent(): Boolean { when { this == null -> return true this === propertyContainer -> return false else -> { val grandParent = parent if (grandParent.parent !== propertyContainer) return true return grandParent !is KtAnonymousInitializer && grandParent !is KtSecondaryConstructor } } } if (assignments.any { it.parent.invalidParent() }) return null val firstAssignment = assignments.firstOrNull() ?: return null if (assignments.any { it !== firstAssignment && it.parent.parent is KtSecondaryConstructor }) return null val context = firstAssignment.analyze() if (!property.isLocal && firstAssignment.parent != propertyContainer && firstAssignment.right?.anyDescendantOfType<KtNameReferenceExpression> { val descriptor = context[BindingContext.REFERENCE_TARGET, it] descriptor is ValueParameterDescriptor && descriptor.containingDeclaration is ClassConstructorDescriptor } == true ) return null val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] ?: return null val assignedDescriptor = firstAssignment.left.getResolvedCall(context)?.candidateDescriptor ?: return null if (propertyDescriptor != assignedDescriptor) return null if (propertyContainer !is KtClassBody) return firstAssignment val blockParent = firstAssignment.parent as? KtBlockExpression ?: return null return if (blockParent.statements.firstOrNull() == firstAssignment) firstAssignment else null } // a block that only contains comments is not empty private fun KtBlockExpression.isEmpty() = contentRange().isEmpty private fun hasNoLocalDependencies(element: KtElement, property: KtProperty): Boolean { val localContext = property.parent val nextSiblings = property.siblings(forward = true, withItself = false) return !element.anyDescendantOfType<PsiElement> { child -> child.resolveAllReferences().any { it != null && PsiTreeUtil.isAncestor(localContext, it, false) && it in nextSiblings } } } } private fun PsiElement.resolveAllReferences(): Sequence<PsiElement?> = PsiReferenceService.getService().getReferences(this, PsiReferenceService.Hints.NO_HINTS) .asSequence() .map { it.resolve() }
apache-2.0
25725c205c2fa6aa914a6bf103caf5ed
45.846154
158
0.691063
5.409898
false
false
false
false
smmribeiro/intellij-community
platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.kt
1
9189
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.browsers import com.intellij.CommonBundle import com.intellij.Patches import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.execution.util.ExecUtil import com.intellij.ide.BrowserUtil import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtil import com.intellij.util.PathUtil import com.intellij.util.io.URLUtil import java.awt.Desktop import java.awt.GraphicsEnvironment import java.io.File import java.io.IOException import java.net.URI import java.nio.file.Path private val LOG = logger<BrowserLauncherAppless>() open class BrowserLauncherAppless : BrowserLauncher() { companion object { @JvmStatic fun canUseSystemDefaultBrowserPolicy(): Boolean = isDesktopActionSupported(Desktop.Action.BROWSE) || SystemInfo.isMac || SystemInfo.isWindows || SystemInfo.isUnix && SystemInfo.hasXdgOpen() fun isOpenCommandUsed(command: GeneralCommandLine): Boolean = SystemInfo.isMac && ExecUtil.openCommandPath == command.exePath } override fun open(url: String): Unit = openOrBrowse(url, false) override fun browse(file: File) { var path = file.absolutePath if (SystemInfo.isWindows && path[0] != '/') { path = "/$path" } openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true) } override fun browse(file: Path) { var path = file.toAbsolutePath().toString() if (SystemInfo.isWindows && path[0] != '/') { path = "/$path" } openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true) } protected open fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) { browseUsingPath(url, browserPath, project = project) } protected open fun openOrBrowse(_url: String, browse: Boolean, project: Project? = null) { val url = signUrl(_url.trim { it <= ' ' }) LOG.debug { "opening [$url]" } if (url.startsWith("mailto:") && isDesktopActionSupported(Desktop.Action.MAIL)) { try { LOG.debug("Trying Desktop#mail") Desktop.getDesktop().mail(URI(url)) } catch (e: Exception) { LOG.warn("[$url]", e) } return } if (!BrowserUtil.isAbsoluteURL(url)) { val file = File(url) if (!browse && isDesktopActionSupported(Desktop.Action.OPEN)) { if (!file.exists()) { showError(IdeBundle.message("error.file.does.not.exist", file.path), project = project) return } try { LOG.debug("Trying Desktop#open") Desktop.getDesktop().open(file) return } catch (e: IOException) { LOG.warn("[$url]", e) } } browse(file) return } val settings = generalSettings if (settings.isUseDefaultBrowser) { openWithDefaultBrowser(url, project) } else { openWithExplicitBrowser(url, settings.browserPath, project = project) } } private fun openWithDefaultBrowser(url: String, project: Project?) { if (isDesktopActionSupported(Desktop.Action.BROWSE)) { val uri = VfsUtil.toUri(url) if (uri == null) { showError(IdeBundle.message("error.malformed.url", url), project = project) return } try { LOG.debug("Trying Desktop#browse") Desktop.getDesktop().browse(uri) return } catch (e: Exception) { LOG.warn("[$url]", e) if (SystemInfo.isMac && e.message!!.contains("Error code: -10814")) { return // if "No application knows how to open" the URL, there is no sense in retrying with 'open' command } } } val command = defaultBrowserCommand if (command == null) { showError(IdeBundle.message("browser.default.not.supported"), project = project) return } if (url.startsWith("jar:")) return doLaunch(GeneralCommandLine(command).withParameters(url), project) } protected open fun signUrl(url: String): String = url override fun browse(url: String, browser: WebBrowser?, project: Project?) { val effectiveBrowser = getEffectiveBrowser(browser) // if browser is not passed, UrlOpener should be not used for non-http(s) urls if (effectiveBrowser == null || (browser == null && !url.startsWith(URLUtil.HTTP_PROTOCOL))) { openOrBrowse(url, true, project) } else { UrlOpener.EP_NAME.extensions.any { it.openUrl(effectiveBrowser, signUrl(url), project) } } } override fun browseUsingPath(url: String?, browserPath: String?, browser: WebBrowser?, project: Project?, openInNewWindow: Boolean, additionalParameters: Array<String>): Boolean { if (url != null && url.startsWith("jar:")) return false val byName = browserPath == null && browser != null val effectivePath = if (byName) PathUtil.toSystemDependentName(browser!!.path) else browserPath val fix: (() -> Unit)? = if (byName) { -> browseUsingPath(url, null, browser!!, project, openInNewWindow, additionalParameters) } else null if (effectivePath.isNullOrBlank()) { val message = browser?.browserNotFoundMessage ?: IdeBundle.message("error.please.specify.path.to.web.browser", CommonBundle.settingsActionPath()) showError(message, browser, project, IdeBundle.message("title.browser.not.found"), fix) return false } val commandWithUrl = BrowserUtil.getOpenBrowserCommand(effectivePath, openInNewWindow).toMutableList() if (url != null) { if (browser != null) browser.addOpenUrlParameter(commandWithUrl, url) else commandWithUrl += url } val commandLine = GeneralCommandLine(commandWithUrl) val browserSpecificSettings = browser?.specificSettings if (browserSpecificSettings != null) { commandLine.environment.putAll(browserSpecificSettings.environmentVariables) } val specific = browserSpecificSettings?.additionalParameters ?: emptyList() if (specific.size + additionalParameters.size > 0) { if (isOpenCommandUsed(commandLine)) { commandLine.addParameter("--args") } commandLine.addParameters(specific) commandLine.addParameters(*additionalParameters) } doLaunch(commandLine, project, browser, fix) return true } private fun doLaunch(command: GeneralCommandLine, project: Project?, browser: WebBrowser? = null, fix: (() -> Unit)? = null) { LOG.debug { command.commandLineString } ProcessIOExecutorService.INSTANCE.execute { try { val output = CapturingProcessHandler.Silent(command).runProcess(10000, false) if (!output.checkSuccess(LOG) && output.exitCode == 1) { @NlsSafe val error = output.stderrLines.firstOrNull() showError(error, browser, project, null, fix) } } catch (e: ExecutionException) { showError(e.message, browser, project, null, fix) } } } protected open fun showError(@NlsContexts.DialogMessage error: String?, browser: WebBrowser? = null, project: Project? = null, @NlsContexts.DialogTitle title: String? = null, fix: (() -> Unit)? = null) { // Not started yet. Not able to show message up. (Could happen in License panel under Linux). LOG.warn(error) } protected open fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? = browser } // AWT-replacing Projector is not affected by that bug, detect it by GE class name to avoid direct dependency on Projector private fun isAffectedByDesktopBug(): Boolean = Patches.SUN_BUG_ID_6486393 && (GraphicsEnvironment.isHeadless() || "PGraphicsEnvironment" != GraphicsEnvironment.getLocalGraphicsEnvironment()?.javaClass?.simpleName) private fun isDesktopActionSupported(action: Desktop.Action): Boolean = !isAffectedByDesktopBug() && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(action) private val generalSettings: GeneralSettings get() = (if (ApplicationManager.getApplication() != null) GeneralSettings.getInstance() else null) ?: GeneralSettings() private val defaultBrowserCommand: List<String>? get() = when { SystemInfo.isWindows -> listOf(ExecUtil.windowsShellName, "/c", "start", GeneralCommandLine.inescapableQuote("")) SystemInfo.isMac -> listOf(ExecUtil.openCommandPath) SystemInfo.isUnix && SystemInfo.hasXdgOpen() -> listOf("xdg-open") else -> null }
apache-2.0
b7a02208f4b7e076831680b0a81fa4dc
37.13278
205
0.688976
4.564829
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/coroutines/directUseOfResultType/complexBlock.kt
5
1008
// FIX: Add '.getOrThrow()' to function result (breaks use-sites!) // WITH_STDLIB package kotlin @Suppress("RESULT_CLASS_IN_RETURN_TYPE") fun <caret>incorrectBlock(arg: Boolean, arg2: Boolean?): Result<Int> { if (arg) { class Local { fun foo(): Result<String> { return Result("NO") } } return Result(1) } else { when (arg2) { true -> { val x = fun(): Result<Boolean> { return Result(false) } if (x().getOrThrow()) { return Result(2) } else { return Result(0) } } else -> { if (arg2 == false) { listOf(1, 2, 3).forEach { if (it == 2) return@forEach } return Result(3) } return Result(4) } } } }
apache-2.0
f6616cdb2bebd691d46db7af1acc31ae
25.526316
70
0.37996
4.623853
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/tasks/ChecklistItem.kt
1
2002
package com.habitrpg.android.habitica.models.tasks import android.os.Parcel import android.os.Parcelable import java.util.UUID import io.realm.RealmObject import io.realm.annotations.PrimaryKey /** * Created by viirus on 06/07/15. */ open class ChecklistItem : RealmObject, Parcelable { @PrimaryKey var id: String? = null var text: String? = null var completed: Boolean = false var position: Int = 0 @JvmOverloads constructor(id: String? = null, text: String? = null, completed: Boolean = false) { this.text = text if (id?.isNotEmpty() == true) { this.id = id } else { this.id = UUID.randomUUID().toString() } this.completed = completed } constructor(item: ChecklistItem) { this.text = item.text this.id = item.id this.completed = item.completed } override fun equals(other: Any?): Boolean { return if (other?.javaClass == ChecklistItem::class.java && this.id != null) { this.id == (other as? ChecklistItem)?.id } else super.equals(other) } override fun hashCode(): Int { return id?.hashCode() ?: 0 } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(id) dest.writeString(text) dest.writeByte(if (completed) 1.toByte() else 0.toByte()) dest.writeInt(position) } companion object CREATOR : Parcelable.Creator<ChecklistItem> { override fun createFromParcel(source: Parcel): ChecklistItem = ChecklistItem(source) override fun newArray(size: Int): Array<ChecklistItem?> = arrayOfNulls(size) } constructor(source: Parcel) { id = source.readString() text = source.readString() completed = source.readByte() == 1.toByte() position = source.readInt() } }
gpl-3.0
deb64f1649bf0978955e0f759853fe96
26.197183
101
0.6004
4.333333
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBasic_k.kt
1
2231
package info.nightscout.androidaps.danaRKorean.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification class MsgInitConnStatusBasic_k( injector: HasAndroidInjector ) : MessageBase(injector) { init { SetCommand(0x0303) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { if (bytes.size - 10 > 6) { return } danaPump.pumpSuspended = intFromBuff(bytes, 0, 1) == 1 val isUtilityEnable = intFromBuff(bytes, 1, 1) danaPump.isEasyModeEnabled = intFromBuff(bytes, 2, 1) == 1 val easyUIMode = intFromBuff(bytes, 3, 1) danaPump.password = intFromBuff(bytes, 4, 2) xor 0x3463 aapsLogger.debug(LTag.PUMPCOMM, "isStatusSuspendOn: " + danaPump.pumpSuspended) aapsLogger.debug(LTag.PUMPCOMM, "isUtilityEnable: $isUtilityEnable") aapsLogger.debug(LTag.PUMPCOMM, "Is EasyUI Enabled: " + danaPump.isEasyModeEnabled) aapsLogger.debug(LTag.PUMPCOMM, "easyUIMode: $easyUIMode") aapsLogger.debug(LTag.PUMPCOMM, "Pump password: " + danaPump.password) if (danaPump.isEasyModeEnabled) { val notification = Notification(Notification.EASYMODE_ENABLED, resourceHelper.gs(R.string.danar_disableeasymode), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.EASYMODE_ENABLED)) } if (!danaPump.isPasswordOK) { val notification = Notification(Notification.WRONG_PUMP_PASSWORD, resourceHelper.gs(R.string.wrongpumppassword), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.WRONG_PUMP_PASSWORD)) } } }
agpl-3.0
b1b10ad2bc0ca7b43395c178dd0827ad
46.489362
146
0.721649
4.409091
false
false
false
false
MER-GROUP/intellij-community
plugins/settings-repository/src/RepositoryService.kt
2
2658
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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 org.jetbrains.settingsRepository import com.intellij.openapi.ui.Messages import com.intellij.util.io.URLUtil import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.createBareRepository import java.awt.Container import java.io.File import java.io.IOException public interface RepositoryService { public fun checkUrl(uriString: String, messageParent: Container? = null): Boolean { val uri = URIish(uriString) val isFile: Boolean if (uri.scheme == URLUtil.FILE_PROTOCOL) { isFile = true } else { isFile = uri.scheme == null && uri.host == null } if (messageParent != null && isFile && !checkFileRepo(uriString, messageParent)) { return false } return true } public fun checkFileRepo(url: String, messageParent: Container): Boolean { val suffix = "/${Constants.DOT_GIT}" val file = File(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) if (file.exists()) { if (!file.isDirectory) { //noinspection DialogTitleCapitalization Messages.showErrorDialog(messageParent, "Specified path is not a directory", "Specified Path is Invalid") return false } else if (isValidRepository(file)) { return true } } else if (!file.isAbsolute) { Messages.showErrorDialog(messageParent, icsMessage("specify.absolute.path.dialog.message"), "") return false } if (Messages.showYesNoDialog(messageParent, icsMessage("init.dialog.message"), icsMessage("init.dialog.title"), Messages.getQuestionIcon()) == Messages.YES) { try { createBareRepository(file) return true } catch (e: IOException) { Messages.showErrorDialog(messageParent, icsMessage("init.failed.message", e.message), icsMessage("init.failed.title")) return false } } else { return false } } // must be protected, kotlin bug public fun isValidRepository(file: File): Boolean }
apache-2.0
8267c54b196cc3fae2e7df1c36fc918b
32.658228
162
0.696388
4.2528
false
false
false
false
siosio/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/configuration/utils/TestingBackgroundExecutor.kt
1
1794
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.script.configuration.utils import com.intellij.openapi.application.impl.LaterInvocator import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.HashSetQueue import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager class TestingBackgroundExecutor internal constructor( private val manager: CompositeScriptConfigurationManager ) : BackgroundExecutor { val rootsManager get() = manager.updater val backgroundQueue = HashSetQueue<BackgroundTask>() class BackgroundTask(val file: VirtualFile, val actions: () -> Unit) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BackgroundTask if (file != other.file) return false return true } override fun hashCode(): Int { return file.hashCode() } } @Synchronized override fun ensureScheduled(key: VirtualFile, actions: () -> Unit) { backgroundQueue.add(BackgroundTask(key, actions)) } fun doAllBackgroundTaskWith(actions: () -> Unit): Boolean { val copy = backgroundQueue.toList() backgroundQueue.clear() actions() rootsManager.update { copy.forEach { it.actions() } } LaterInvocator.ensureFlushRequested() LaterInvocator.dispatchPendingFlushes() return copy.isNotEmpty() } fun noBackgroundTasks(): Boolean = backgroundQueue.isEmpty() }
apache-2.0
50ee1c6d72e10b73daeea9f7eaaded1b
30.473684
158
0.676143
4.969529
false
true
false
false
jwren/intellij-community
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/whole/HighlightWholeProjectPerformanceTest.kt
1
8138
// 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.perf.whole import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.perf.suite.DefaultProfile import org.jetbrains.kotlin.idea.perf.suite.EmptyProfile import org.jetbrains.kotlin.idea.perf.suite.suite import org.jetbrains.kotlin.idea.perf.util.* import org.jetbrains.kotlin.idea.performance.tests.utils.logMessage import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor import org.jetbrains.kotlin.idea.performance.tests.utils.relativePath import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners import org.junit.runner.RunWith import java.io.File import java.nio.file.Files @RunWith(JUnit3RunnerWithInners::class) class HighlightWholeProjectPerformanceTest : UsefulTestCase() { override fun setUp() { val allowedErrorDescription = setOf( "Unknown artifact type: war", "Unknown artifact type: exploded-war" ) ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(testRootDisposable) { errorDescription -> val description = errorDescription.description if (description !in allowedErrorDescription) { throw RuntimeException(description) } else { logMessage { "project loading error: '$description' at '${errorDescription.elementName}'" } } } } fun testHighlightAllKtFilesInProject() { val emptyProfile = System.getProperty("emptyProfile", "false")!!.toBoolean() val percentOfFiles = System.getProperty("files.percentOfFiles", "10")!!.toInt() val maxFilesPerPart = System.getProperty("files.maxFilesPerPart", "300")!!.toInt() val minFileSize = System.getProperty("files.minFileSize", "300")!!.toInt() val warmUpIterations = System.getProperty("iterations.warmup", "1")!!.toInt() val numberOfIterations = System.getProperty("iterations.number", "10")!!.toInt() val clearPsiCaches = System.getProperty("caches.clearPsi", "true")!!.toBoolean() val projectSpecs = projectSpecs() logMessage { "projectSpecs: $projectSpecs" } for (projectSpec in projectSpecs) { val projectName = projectSpec.name val projectPath = projectSpec.path val suiteName = listOfNotNull("allKtFilesIn", "emptyProfile".takeIf { emptyProfile }, projectName) .joinToString(separator = "-") suite(suiteName = suiteName) { app { ExpressionsOfTypeProcessor.prodMode() warmUpProject() with(config) { warmup = warmUpIterations iterations = numberOfIterations fastIterations = true } try { project(ExternalProject.autoOpenProject(projectPath), refresh = true) { profile(if (emptyProfile) EmptyProfile else DefaultProfile) val ktFiles = mutableSetOf<VirtualFile>() project.runReadActionInSmartMode { val projectFileIndex = ProjectFileIndex.getInstance(project) val modules = mutableSetOf<Module>() val ktFileProcessor = { ktFile: VirtualFile -> if (projectFileIndex.isInSourceContent(ktFile)) { ktFiles.add(ktFile) } true } FileTypeIndex.processFiles( KotlinFileType.INSTANCE, ktFileProcessor, GlobalSearchScope.projectScope(project) ) modules } logStatValue("number of kt files", ktFiles.size) val filesToProcess = limitedFiles( ktFiles, percentOfFiles = percentOfFiles, maxFilesPerPart = maxFilesPerPart, minFileSize = minFileSize ) logStatValue("limited number of kt files", filesToProcess.size) filesToProcess.forEach { logMessage { "${project.relativePath(it)} fileSize: ${Files.size(it.toNioPath())}" } } filesToProcess.forEachIndexed { idx, file -> logMessage { "${idx + 1} / ${filesToProcess.size} : ${project.relativePath(file)} fileSize: ${Files.size(file.toNioPath())}" } try { fixture(file).use { measure<List<HighlightInfo>>(it.fileName, clearCaches = clearPsiCaches) { test = { it.highlight() } } } } catch (e: Exception) { // nothing as it is already caught by perfTest } } } } catch (e: Exception) { e.printStackTrace() // nothing as it is already caught by perfTest } } } } } private fun limitedFiles( ktFiles: Collection<VirtualFile>, percentOfFiles: Int, maxFilesPerPart: Int, minFileSize: Int ): Collection<VirtualFile> { val sortedBySize = ktFiles .filter { Files.size(it.toNioPath()) > minFileSize } .map { it to Files.size(it.toNioPath()) }.sortedByDescending { it.second } val numberOfFiles = minOf((sortedBySize.size * percentOfFiles) / 100, maxFilesPerPart) val topFiles = sortedBySize.take(numberOfFiles).map { it.first } val midFiles = sortedBySize.take(sortedBySize.size / 2 + numberOfFiles / 2).takeLast(numberOfFiles).map { it.first } val lastFiles = sortedBySize.takeLast(numberOfFiles).map { it.first } return LinkedHashSet(topFiles + midFiles + lastFiles) } private fun projectSpecs(): List<ProjectSpec> { val projects = System.getProperty("performanceProjects") val specs = projects?.split(",")?.map { val idx = it.indexOf("=") if (idx <= 0) ProjectSpec(it, "../$it") else ProjectSpec(it.substring(0, idx), it.substring(idx + 1)) } ?: emptyList() specs.forEach { val path = File(it.path) check(path.exists() && path.isDirectory) { "Project `${it.name}` path ${path.absolutePath} does not exist or it is not a directory" } } return specs.takeIf { it.isNotEmpty() } ?: error("No projects specified, use `-DperformanceProjects=projectName`") } private data class ProjectSpec(val name: String, val path: String) }
apache-2.0
baa7803b3b5b07653b9db3a3fcafca9c
46.590643
158
0.552101
5.788051
false
true
false
false
androidx/androidx
core/core-ktx/src/androidTest/java/androidx/core/graphics/PathTest.kt
3
3869
/* * Copyright (C) 2018 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.core.graphics import android.graphics.Path import android.graphics.RectF import androidx.test.filters.SdkSuppress import androidx.test.filters.SmallTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertTrue import org.junit.Test @SmallTest class PathTest { @SdkSuppress(minSdkVersion = 26) @Test fun testFlatten() { val p = Path() // Start with several moves p.moveTo(5.0f, 5.0f) p.moveTo(10.0f, 10.0f) p.lineTo(20.0f, 20.0f) p.lineTo(30.0f, 10.0f) // Several moves in the middle p.moveTo(40.0f, 10.0f) p.moveTo(50.0f, 10.0f) p.lineTo(60.0f, 20.0f) // End with several moves p.moveTo(10.0f, 10.0f) p.moveTo(30.0f, 30.0f) var count = 0 p.flatten().forEach { count++ assertNotEquals(it.startFraction, it.endFraction) } assertEquals(3, count) } @SdkSuppress(minSdkVersion = 19) @Test fun testUnion() { val r1 = Path().apply { addRect(0.0f, 0.0f, 10.0f, 10.0f, Path.Direction.CW) } val r2 = Path().apply { addRect(5.0f, 0.0f, 15.0f, 15.0f, Path.Direction.CW) } val p = r1 + r2 val r = RectF() p.computeBounds(r, true) assertEquals(RectF(0.0f, 0.0f, 15.0f, 15.0f), r) } @SdkSuppress(minSdkVersion = 19) @Test fun testOr() { val r1 = Path().apply { addRect(0.0f, 0.0f, 10.0f, 10.0f, Path.Direction.CW) } val r2 = Path().apply { addRect(5.0f, 0.0f, 15.0f, 15.0f, Path.Direction.CW) } val p = r1 or r2 val r = RectF() p.computeBounds(r, true) assertEquals(RectF(0.0f, 0.0f, 15.0f, 15.0f), r) } @SdkSuppress(minSdkVersion = 19) @Test fun testDifference() { val r1 = Path().apply { addRect(0.0f, 0.0f, 10.0f, 10.0f, Path.Direction.CW) } val r2 = Path().apply { addRect(5.0f, 0.0f, 15.0f, 15.0f, Path.Direction.CW) } val p = r1 - r2 val r = RectF() p.computeBounds(r, true) assertEquals(RectF(0.0f, 0.0f, 5.0f, 10.0f), r) } @SdkSuppress(minSdkVersion = 19) @Test fun testIntersection() { val r1 = Path().apply { addRect(0.0f, 0.0f, 10.0f, 10.0f, Path.Direction.CW) } val r2 = Path().apply { addRect(5.0f, 0.0f, 15.0f, 15.0f, Path.Direction.CW) } val p = r1 and r2 val r = RectF() p.computeBounds(r, true) assertEquals(RectF(5.0f, 0.0f, 10.0f, 10.0f), r) } @SdkSuppress(minSdkVersion = 19) @Test fun testEmptyIntersection() { val r1 = Path().apply { addRect(0.0f, 0.0f, 2.0f, 2.0f, Path.Direction.CW) } val r2 = Path().apply { addRect(5.0f, 5.0f, 7.0f, 7.0f, Path.Direction.CW) } val p = r1 and r2 assertTrue(p.isEmpty) } @SdkSuppress(minSdkVersion = 19) @Test fun testXor() { val r1 = Path().apply { addRect(0.0f, 0.0f, 10.0f, 10.0f, Path.Direction.CW) } val r2 = Path().apply { addRect(5.0f, 5.0f, 15.0f, 15.0f, Path.Direction.CW) } val p = r1 xor r2 val r = RectF() p.computeBounds(r, true) assertEquals(RectF(0.0f, 0.0f, 15.0f, 15.0f), r) } }
apache-2.0
a52dc7e6a815df331c42a48e8a283ab4
30.455285
86
0.600414
2.976154
false
true
false
false
androidx/androidx
navigation/navigation-dynamic-features-runtime/src/main/java/androidx/navigation/dynamicfeatures/DynamicNavGraphBuilder.kt
3
7016
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.dynamicfeatures import androidx.annotation.IdRes import androidx.navigation.NavDestination import androidx.navigation.NavDestinationDsl import androidx.navigation.NavGraph import androidx.navigation.NavGraphBuilder import androidx.navigation.NavigatorProvider import androidx.navigation.dynamicfeatures.DynamicActivityNavigator.Destination import androidx.navigation.get /** * Construct a new [DynamicGraphNavigator.DynamicNavGraph] * * @param id NavGraph id. * @param startDestination Id start destination in the graph * @param builder Another builder for chaining. */ @Suppress("Deprecation") @Deprecated( "Use routes to create your DynamicNavGraph instead", ReplaceWith( "navigation(startDestination = startDestination.toString(), route = id.toString()) " + "{ builder.invoke() }" ) ) public inline fun NavigatorProvider.navigation( @IdRes id: Int = 0, @IdRes startDestination: Int, builder: DynamicNavGraphBuilder.() -> Unit ): NavGraph = DynamicNavGraphBuilder( this, id, startDestination ).apply(builder).build() /** * Construct a nested [DynamicGraphNavigator.DynamicNavGraph] * * @param id NavGraph id. * @param startDestination Id start destination in the graph * @param builder Another builder for chaining. */ @Suppress("Deprecation") @Deprecated( "Use routes to create your DynamicNavGraph instead", ReplaceWith( "navigation(startDestination = startDestination.toString(), route = id.toString()) " + "{ builder.invoke() }" ) ) public inline fun DynamicNavGraphBuilder.navigation( @IdRes id: Int, @IdRes startDestination: Int, builder: DynamicNavGraphBuilder.() -> Unit ): Unit = destination( DynamicNavGraphBuilder( provider, id, startDestination ).apply(builder) ) /** * Construct a new [DynamicGraphNavigator.DynamicNavGraph] * * @param route NavGraph route. * @param startDestination route start destination in the graph * @param builder Another builder for chaining. */ public inline fun NavigatorProvider.navigation( startDestination: String, route: String? = null, builder: DynamicNavGraphBuilder.() -> Unit ): NavGraph = DynamicNavGraphBuilder( this, startDestination, route ).apply(builder).build() /** * Construct a nested [DynamicGraphNavigator.DynamicNavGraph] * * @param route NavGraph route. * @param startDestination route start destination in the graph * @param builder Another builder for chaining. */ public inline fun DynamicNavGraphBuilder.navigation( startDestination: String, route: String, builder: DynamicNavGraphBuilder.() -> Unit ): Unit = destination( DynamicNavGraphBuilder( provider, startDestination, route ).apply(builder) ) /** * DSL for constructing a new [DynamicGraphNavigator.DynamicNavGraph] */ @NavDestinationDsl public class DynamicNavGraphBuilder : NavGraphBuilder { @IdRes private var startDestinationId: Int = 0 private var startDestinationRoute: String? = null @Suppress("Deprecation") @Deprecated( "Use routes to create your DynamicNavGraphBuilder instead", ReplaceWith( "DynamicNavGraphBuilder(provider, startDestination = startDestination.toString(), " + "route = id.toString())" ) ) public constructor( provider: NavigatorProvider, @IdRes id: Int, @IdRes startDestination: Int ) : super(provider, id, startDestination) { this.startDestinationId = startDestination } public constructor( provider: NavigatorProvider, startDestination: String, route: String? = null ) : super(provider, startDestination, route) { this.startDestinationRoute = startDestination } /** * The module name of this [Destination]'s dynamic feature module. This has to be the * same as defined in the dynamic feature module's AndroidManifest.xml file. */ public var moduleName: String? = null private var _progressDestination: Int = 0 /** * ID of the destination displayed during module installation. This generally does * not need to be set, but is instead filled in by the NavHost via * [DynamicGraphNavigator.installDefaultProgressDestination]. * * Setting this clears any previously set [progressDestinationRoute]. */ public var progressDestination: Int get() = _progressDestination set(p) { if (progressDestinationRoute != null) { progressDestinationRoute = null } _progressDestination = p } /** * Route of the destination displayed during module installation. This generally does * not need to be set, but is instead filled in by the NavHost via * [DynamicGraphNavigator.installDefaultProgressDestination]. * * Setting this overrides any previously set [progressDestination]. */ public var progressDestinationRoute: String? = null set(progDestRoute) { _progressDestination = if (progDestRoute == null) { 0 } else { require(progDestRoute.isNotBlank()) { "Cannot have an empty progress destination route" } NavDestination.createRoute(progressDestinationRoute).hashCode() } field = progDestRoute } /** * @return The [DynamicGraphNavigator.DynamicNavGraph]. */ override fun build(): NavGraph = super.build().also { navGraph -> if (navGraph is DynamicGraphNavigator.DynamicNavGraph) { navGraph.moduleName = moduleName if (navGraph.route != null) { navGraph.progressDestination = NavDestination.createRoute(progressDestinationRoute).hashCode() } else { navGraph.progressDestination = progressDestination } if (progressDestination == 0) { val navGraphNavigator: DynamicGraphNavigator = provider[DynamicGraphNavigator::class] navGraphNavigator.destinationsWithoutDefaultProgressDestination .add(navGraph) } } } }
apache-2.0
c1c8ab9793dc2838db838f60d0ba4697
32.09434
97
0.670895
5.084058
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/tinder/recommendation/RecommendationUserCommonFriendEntity.kt
1
459
package data.tinder.recommendation import android.arch.persistence.room.Entity import android.arch.persistence.room.Index import android.arch.persistence.room.PrimaryKey @Entity(indices = [Index("id")]) internal open class RecommendationUserCommonFriendEntity( @PrimaryKey var id: String, var name: String, var degree: String) { companion object { val NONE = RecommendationUserCommonFriendEntity(id = "", name = "", degree = "") } }
mit
cbb77655028ece76aac620d220c1ccc4
27.6875
84
0.740741
4.172727
false
false
false
false
androidx/androidx
compose/material/material/src/androidAndroidTest/kotlin/androidx/compose/material/SwipeToDismissTest.kt
3
9514
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipeLeft import androidx.compose.ui.test.swipeRight import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalMaterialApi::class) class SwipeToDismissTest { @get:Rule val rule = createComposeRule() private val backgroundTag = "background" private val dismissContentTag = "dismissContent" private val swipeToDismissTag = "swipeToDismiss" private fun advanceClock() { rule.mainClock.advanceTimeBy(100_000L) } @Test fun swipeToDismiss_testOffset_whenDefault() { rule.setContent { SwipeToDismiss( state = rememberDismissState(DismissValue.Default), background = { }, dismissContent = { Box(Modifier.fillMaxSize().testTag(dismissContentTag)) } ) } rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(0.dp) } @Test fun swipeToDismiss_testOffset_whenDismissedToEnd() { rule.setContent { SwipeToDismiss( state = rememberDismissState(DismissValue.DismissedToEnd), background = { }, dismissContent = { Box(Modifier.fillMaxSize().testTag(dismissContentTag)) } ) } val width = rule.rootWidth() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(width) } @Test fun swipeToDismiss_testOffset_whenDismissedToStart() { rule.setContent { SwipeToDismiss( state = rememberDismissState(DismissValue.DismissedToStart), background = { }, dismissContent = { Box(Modifier.fillMaxSize().testTag(dismissContentTag)) } ) } val width = rule.rootWidth() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(-width) } @Test fun swipeToDismiss_testBackgroundMatchesContentSize() { rule.setContent { SwipeToDismiss( state = rememberDismissState(DismissValue.Default), background = { Box(Modifier.fillMaxSize().testTag(backgroundTag)) }, dismissContent = { Box(Modifier.size(100.dp)) } ) } rule.onNodeWithTag(backgroundTag) .assertIsSquareWithSize(100.dp) } @Ignore("Fix test in a follow-up CL. b/179501119") @Test fun swipeToDismiss_dismissAndReset(): Unit = runBlocking { lateinit var dismissState: DismissState rule.setContent { dismissState = rememberDismissState(DismissValue.Default) SwipeToDismiss( state = dismissState, background = { }, dismissContent = { Box(Modifier.fillMaxSize().testTag(dismissContentTag)) } ) } val width = rule.rootWidth() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(0.dp) dismissState.dismiss(DismissDirection.StartToEnd) advanceClock() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(width) dismissState.reset() advanceClock() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(0.dp) dismissState.dismiss(DismissDirection.EndToStart) advanceClock() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(-width) dismissState.reset() advanceClock() rule.onNodeWithTag(dismissContentTag) .assertLeftPositionInRootIsEqualTo(0.dp) } @Test fun swipeToDismiss_dismissBySwipe_toEnd() { lateinit var dismissState: DismissState rule.setContent { dismissState = rememberDismissState(DismissValue.Default) SwipeToDismiss( modifier = Modifier.testTag(swipeToDismissTag), state = dismissState, directions = setOf(DismissDirection.StartToEnd), background = { }, dismissContent = { Box(Modifier.fillMaxSize()) } ) } rule.onNodeWithTag(swipeToDismissTag).performTouchInput { swipeRight() } advanceClock() rule.runOnIdle { assertThat(dismissState.currentValue).isEqualTo(DismissValue.DismissedToEnd) } } @Test fun swipeToDismiss_dismissBySwipe_toStart() { lateinit var dismissState: DismissState rule.setContent { dismissState = rememberDismissState(DismissValue.Default) SwipeToDismiss( modifier = Modifier.testTag(swipeToDismissTag), state = dismissState, directions = setOf(DismissDirection.EndToStart), background = { }, dismissContent = { Box(Modifier.fillMaxSize()) } ) } rule.onNodeWithTag(swipeToDismissTag).performTouchInput { swipeLeft() } advanceClock() rule.runOnIdle { assertThat(dismissState.currentValue).isEqualTo(DismissValue.DismissedToStart) } } @Test fun swipeToDismiss_dismissBySwipe_toEnd_rtl() { lateinit var dismissState: DismissState rule.setContent { dismissState = rememberDismissState(DismissValue.Default) CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { SwipeToDismiss( modifier = Modifier.testTag(swipeToDismissTag), state = dismissState, directions = setOf(DismissDirection.StartToEnd), background = { }, dismissContent = { Box(Modifier.fillMaxSize()) } ) } } rule.onNodeWithTag(swipeToDismissTag).performTouchInput { swipeLeft() } advanceClock() rule.runOnIdle { assertThat(dismissState.currentValue).isEqualTo(DismissValue.DismissedToEnd) } } @Test fun swipeToDismiss_dismissBySwipe_toStart_rtl() { lateinit var dismissState: DismissState rule.setContent { dismissState = rememberDismissState(DismissValue.Default) CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { SwipeToDismiss( modifier = Modifier.testTag(swipeToDismissTag), state = dismissState, directions = setOf(DismissDirection.EndToStart), background = { }, dismissContent = { Box(Modifier.fillMaxSize()) } ) } } rule.onNodeWithTag(swipeToDismissTag).performTouchInput { swipeRight() } advanceClock() rule.runOnIdle { assertThat(dismissState.currentValue).isEqualTo(DismissValue.DismissedToStart) } } @Test fun swipeToDismiss_dismissBySwipe_disabled() { lateinit var dismissState: DismissState rule.setContent { dismissState = rememberDismissState(DismissValue.Default) SwipeToDismiss( modifier = Modifier.testTag(swipeToDismissTag), state = dismissState, directions = setOf(), background = { }, dismissContent = { Box(Modifier.fillMaxSize()) } ) } rule.onNodeWithTag(swipeToDismissTag).performTouchInput { swipeRight() } advanceClock() rule.runOnIdle { assertThat(dismissState.currentValue).isEqualTo(DismissValue.Default) } rule.onNodeWithTag(swipeToDismissTag).performTouchInput { swipeLeft() } advanceClock() rule.runOnIdle { assertThat(dismissState.currentValue).isEqualTo(DismissValue.Default) } } }
apache-2.0
ab04d3b1f2f6fe85106aff74d2e48486
31.810345
91
0.644629
5.250552
false
true
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/codeInsight/daemon/impl/quickfix/CreateAnnotationTest.kt
4
7000
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.daemon.impl.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.jvm.actions.* import com.intellij.psi.PsiJvmModifiersOwner import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase class CreateAnnotationTest : LightJavaCodeInsightFixtureTestCase() { private fun createAnnotationAction(modifierListOwner: PsiJvmModifiersOwner, annotationRequest: AnnotationRequest): IntentionAction = createAddAnnotationActions(modifierListOwner, annotationRequest).single() @SuppressWarnings fun `test add annotation with value text literal`() { myFixture.configureByText("A.java", """ class A { void bar(){} } """.trimIndent()) val modifierListOwner = myFixture.findElementByText("bar", PsiJvmModifiersOwner::class.java) myFixture.launchAction(createAnnotationAction(modifierListOwner, annotationRequest("java.lang.SuppressWarnings", stringAttribute("value", "someText")))) myFixture.checkResult(""" class A { @SuppressWarnings("someText") void bar(){} } """.trimIndent()) } @SuppressWarnings fun `test add annotation with two parameters`() { myFixture.addClass(""" public @interface Anno{ String text(); int num(); } """.trimIndent()) myFixture.configureByText("A.java", """ class A {} """.trimIndent()) val modifierListOwner = myFixture.findElementByText("A", PsiJvmModifiersOwner::class.java) myFixture.launchAction(createAnnotationAction(modifierListOwner, annotationRequest( "java.lang.SuppressWarnings", intAttribute("num", 12), stringAttribute("text", "anotherText") ) ) ) myFixture.checkResult(""" @SuppressWarnings(num = 12, text = "anotherText") class A {} """.trimIndent()) } fun `test add annotation with class access literal`() { myFixture.addClass(""" public @interface Anno { Class<?> value(); } """.trimIndent()) myFixture.configureByText("A.java", """ class A {} """.trimIndent()) val modifierListOwner = myFixture.findElementByText("A", PsiJvmModifiersOwner::class.java) myFixture.launchAction(createAnnotationAction(modifierListOwner, annotationRequest( "Anno", classAttribute("value", "A"), ) ) ) myFixture.checkResult(""" @Anno(A.class) class A {} """.trimIndent()) } fun `test add annotation with field reference`() { myFixture.addClass(""" public @interface Anno { int field1(); int field2(); int field3(); } """.trimIndent()) myFixture.configureByText("A.java", """ class A { private static final int CONSTANT = 1; } """.trimIndent()) val modifierListOwner = myFixture.findElementByText("A", PsiJvmModifiersOwner::class.java) val annotation = annotationRequest("Anno", constantAttribute("field1", "A.CONSTANT"), constantAttribute("field2", "A.INVALID_CONSTANT"), constantAttribute("field3", "CONSTANT")) myFixture.launchAction(createAnnotationAction(modifierListOwner, annotation)) myFixture.checkResult(""" @Anno(field1 = A.CONSTANT, field2 = A.INVALID_CONSTANT, field3 = CONSTANT) class A { private static final int CONSTANT = 1; } """.trimIndent()) } fun `test add annotation with array value`() { myFixture.addClass(""" public @interface Anno { String[] value(); } """.trimIndent()) myFixture.configureByText("A.java", """ class A {} """.trimIndent()) val modifierListOwner = myFixture.findElementByText("A", PsiJvmModifiersOwner::class.java) val arrayMembers = listOf( AnnotationAttributeValueRequest.StringValue("member 1"), AnnotationAttributeValueRequest.StringValue("member 2"), AnnotationAttributeValueRequest.StringValue("member 3") ) val annotation = annotationRequest("Anno", arrayAttribute("value", arrayMembers)) myFixture.launchAction(createAnnotationAction(modifierListOwner, annotation)) myFixture.checkResult(""" @Anno({"member 1", "member 2", "member 3"}) class A {} """.trimIndent()) } fun `test add annotation with deep nesting`() { myFixture.addClass(""" public @interface Root { Nested1 value(); } """.trimIndent()) myFixture.addClass(""" public @interface Nested1 { Nested2[] value() default {}; } """.trimIndent()) myFixture.addClass(""" public @interface Nested2 { Nested1 single(); Nested3[] array() default {}; } """.trimIndent()) myFixture.addClass(""" public @interface Nested3 {} """.trimIndent()) myFixture.configureByText("A.java", """ class A {} """.trimIndent()) val modifierListOwner = myFixture.findElementByText("A", PsiJvmModifiersOwner::class.java) val nested2_1 = annotationRequest( "Nested2", nestedAttribute("single", annotationRequest("Nested1")), arrayAttribute("array", listOf( AnnotationAttributeValueRequest.NestedAnnotation(annotationRequest("Nested3")), AnnotationAttributeValueRequest.NestedAnnotation(annotationRequest("Nested3")) )) ) val nested2_2 = annotationRequest( "Nested2", nestedAttribute("single", annotationRequest("Nested1", arrayAttribute("value", listOf( AnnotationAttributeValueRequest.NestedAnnotation( annotationRequest("Nested2", nestedAttribute("single", annotationRequest("Nested1")))) )))) ) val nested1 = annotationRequest("Nested1", arrayAttribute("value", listOf( AnnotationAttributeValueRequest.NestedAnnotation(nested2_1), AnnotationAttributeValueRequest.NestedAnnotation(nested2_2) ))) val root = annotationRequest("Root", nestedAttribute("value", nested1)) myFixture.launchAction(createAnnotationAction(modifierListOwner, root)) myFixture.checkResult(""" @Root(@Nested1({@Nested2(single = @Nested1, array = {@Nested3, @Nested3}), @Nested2(single = @Nested1({@Nested2(single = @Nested1)}))})) class A {} """.trimIndent()) } }
apache-2.0
59cb2af081a558c5400fcbfcb70db452
34.175879
142
0.606143
5.347594
false
true
false
false
GunoH/intellij-community
build/tasks/src/org/jetbrains/intellij/build/io/ZipFileWriter.kt
2
9196
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ConstPropertyName") package org.jetbrains.intellij.build.io import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.nio.channels.FileChannel.MapMode import java.nio.channels.WritableByteChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import java.util.zip.CRC32 import java.util.zip.Deflater import java.util.zip.ZipEntry import kotlin.math.min // 1 MB private const val largeFileThreshold = 1_048_576 private const val compressThreshold = 8 * 1024 // 8 MB (as JDK) private const val mappedTransferSize = 8L * 1024L * 1024L inline fun writeNewZip(file: Path, compress: Boolean = false, withOptimizedMetadataEnabled: Boolean = !compress, task: (ZipFileWriter) -> Unit) { Files.createDirectories(file.parent) ZipFileWriter(channel = FileChannel.open(file, W_CREATE_NEW), deflater = if (compress) Deflater(Deflater.DEFAULT_COMPRESSION, true) else null, withOptimizedMetadataEnabled = !compress && withOptimizedMetadataEnabled).use { task(it) } } // you must pass SeekableByteChannel if files will be written (`file` method) class ZipFileWriter(channel: WritableByteChannel, private val deflater: Deflater? = null, withOptimizedMetadataEnabled: Boolean = deflater == null) : AutoCloseable { // size is written as part of optimized metadata - so, if compression is enabled, optimized metadata will be incorrect internal val resultStream = ZipArchiveOutputStream(channel, withOptimizedMetadataEnabled = withOptimizedMetadataEnabled) private val crc32 = CRC32() private val bufferAllocator = ByteBufferAllocator() private val deflateBufferAllocator = if (deflater == null) null else ByteBufferAllocator() @Suppress("DuplicatedCode") fun file(nameString: String, file: Path) { var isCompressed = deflater != null && !nameString.endsWith(".png") val name = nameString.toByteArray() val headerSize = 30 + name.size crc32.reset() val input: ByteBuffer val size: Int FileChannel.open(file, EnumSet.of(StandardOpenOption.READ)).use { channel -> size = channel.size().toInt() if (size == 0) { writeEmptyFile(name, headerSize) return } if (size < compressThreshold) { isCompressed = false } if (size > largeFileThreshold || isCompressed) { val headerPosition = resultStream.getChannelPositionAndAdd(headerSize) var compressedSize = writeLargeFile(size.toLong(), channel, if (isCompressed) deflater else null).toInt() val crc = crc32.value val method: Int if (compressedSize == -1) { method = ZipEntry.STORED compressedSize = size } else { method = ZipEntry.DEFLATED } val buffer = bufferAllocator.allocate(headerSize) writeLocalFileHeader(name = name, size = size, compressedSize = compressedSize, crc32 = crc, method = method, buffer = buffer) buffer.position(0) assert(buffer.remaining() == headerSize) resultStream.writeEntryHeaderAt(name = name, header = buffer, position = headerPosition, size = size, compressedSize = compressedSize, crc = crc, method = method) return } input = bufferAllocator.allocate(headerSize + size) input.position(headerSize) // set position to compute CRC input.mark() do { channel.read(input) } while (input.hasRemaining()) input.reset() crc32.update(input) } val crc = crc32.value input.position(0) writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, input) input.position(0) assert(input.remaining() == (size + headerSize)) resultStream.writeRawEntry(input, name, size, size, ZipEntry.STORED, crc, headerSize) } private fun writeLargeFile(fileSize: Long, channel: FileChannel, deflater: Deflater?): Long { // channel.transferTo will use a slow path for untrusted (custom) WritableByteChannel implementations, so, duplicate what JDK does // see FileChannelImpl.transferFromFileChannel var remaining = fileSize var position = 0L var compressedSize = 0L var effectiveDeflater = deflater while (remaining > 0L) { val size = min(remaining, mappedTransferSize) val buffer = channel.map(MapMode.READ_ONLY, position, size) remaining -= size position += size try { buffer.mark() crc32.update(buffer) buffer.reset() buffer.mark() if (effectiveDeflater == null) { resultStream.writeBuffer(buffer) compressedSize = -1 } else { val output = deflateBufferAllocator!!.allocate(size.toInt() + 4096) effectiveDeflater.setInput(buffer) if (remaining <= 0) { effectiveDeflater.finish() } do { val n = effectiveDeflater.deflate(output, Deflater.SYNC_FLUSH) assert(n != 0) } while (buffer.hasRemaining()) output.flip() compressedSize += output.remaining() if (position == 0L && compressedSize > size) { // incompressible effectiveDeflater = null buffer.reset() resultStream.writeBuffer(buffer) compressedSize = -1 } else { resultStream.writeBuffer(output) } } } finally { unmapBuffer(buffer) } } effectiveDeflater?.reset() return compressedSize } fun compressedData(nameString: String, data: ByteArray) { val name = nameString.toByteArray() val headerSize = 30 + name.size val input = ByteBuffer.wrap(data) val size = data.size crc32.reset() crc32.update(data) val crc = crc32.value input.position(0) val output = deflateBufferAllocator!!.allocate(headerSize + size + 4096) output.position(headerSize) deflater!!.setInput(input) deflater.finish() do { val n = deflater.deflate(output, Deflater.SYNC_FLUSH) assert(n != 0) } while (input.hasRemaining()) deflater.reset() output.limit(output.position()) output.position(0) val compressedSize = output.remaining() - headerSize writeLocalFileHeader(name, size, compressedSize, crc, ZipEntry.DEFLATED, output) output.position(0) assert(output.remaining() == (compressedSize + headerSize)) resultStream.writeRawEntry(output, name, size, compressedSize, ZipEntry.DEFLATED, crc, headerSize) } fun uncompressedData(nameString: String, data: String) { uncompressedData(nameString, ByteBuffer.wrap(data.toByteArray())) } fun uncompressedData(nameString: String, data: ByteBuffer) { val name = nameString.toByteArray() val headerSize = 30 + name.size if (!data.hasRemaining()) { writeEmptyFile(name, headerSize) return } data.mark() crc32.reset() crc32.update(data) val crc = crc32.value data.reset() val size = data.remaining() val header = bufferAllocator.allocate(headerSize) writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, header) header.position(0) resultStream.writeRawEntry(header, data, name, size, size, ZipEntry.STORED, crc) } fun uncompressedData(nameString: String, maxSize: Int, dataWriter: (ByteBuffer) -> Unit) { val name = nameString.toByteArray() val headerSize = 30 + name.size val output = bufferAllocator.allocate(headerSize + maxSize) output.position(headerSize) dataWriter(output) output.limit(output.position()) output.position(headerSize) val size = output.remaining() crc32.reset() crc32.update(output) val crc = crc32.value output.position(0) writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, output) output.position(0) assert(output.remaining() == (size + headerSize)) resultStream.writeRawEntry(output, name, size, size, ZipEntry.STORED, crc, headerSize) } private fun writeEmptyFile(name: ByteArray, headerSize: Int) { val input = bufferAllocator.allocate(headerSize) writeLocalFileHeader(name, size = 0, compressedSize = 0, crc32 = 0, method = ZipEntry.STORED, buffer = input) input.position(0) input.limit(headerSize) resultStream.writeRawEntry(input, name, 0, 0, ZipEntry.STORED, 0, headerSize) } fun dir(name: String) { resultStream.addDirEntry(name) } override fun close() { @Suppress("ConvertTryFinallyToUseCall") try { bufferAllocator.close() deflateBufferAllocator?.close() deflater?.end() } finally { resultStream.close() } } }
apache-2.0
d71626682d7337eff8f24de8e5c3f75c
31.270175
134
0.64702
4.431807
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/ch0201/Sim1ParametersProvider.kt
1
9702
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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 3 of the License, or * (at your option) any later version. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch0201 import alice.tuprolog.* import alice.tuprolog.Int import cc.altruix.econsimtr01.* import org.joda.time.DateTime import org.joda.time.DateTimeConstants import org.slf4j.LoggerFactory import java.util.* /** * Created by pisarenko on 08.04.2016. */ open class Sim1ParametersProvider(val theoryTxt: String) : ISimParametersProvider { val LOGGER = LoggerFactory.getLogger(Sim1ParametersProvider::class.java) var resources:List<PlResource> get private set override val flows:MutableList<PlFlow> = LinkedList() get override val agents:MutableList<IAgent> = LinkedList() get override val initialResourceLevels:MutableList<InitialResourceLevel> = LinkedList() get override val infiniteResourceSupplies:MutableList<InfiniteResourceSupply> = LinkedList() get override val transformations:MutableList<PlTransformation> = LinkedList() get init { val prolog = theoryTxt.toPrologTheory() this.resources = extractResources(prolog) readFlows(prolog) readAgents(prolog) readInitialResourceLevels(prolog) readInfiniteResourceSupplies(prolog) readTransformations(prolog) } private fun readInfiniteResourceSupplies(prolog: Prolog) { prolog.getResults("infiniteResourceSupply(Agent, Resource).", "Agent", "Resource").forEach { map -> infiniteResourceSupplies.add( InfiniteResourceSupply( map.get("Agent") ?: "", map.get("Resource")?.removeSingleQuotes() ?: "" ) ) } } private fun readInitialResourceLevels(prolog: Prolog) { prolog.getResults("initialResourceLevel(Agent, Resource, Amount).", "Agent", "Resource", "Amount") .forEach { map -> initialResourceLevels.add(InitialResourceLevel( map.get("Agent") ?: "", map.get("Resource")?.removeSingleQuotes() ?: "", map.get("Amount")?.toDouble() ?: 0.0 )) } } open protected fun readAgents(prolog: Prolog) { val agentsPl = prolog.getResults("isAgent(X).", "X") agentsPl .map { x -> x.removeSingleQuotes() } .forEach { apl -> this.agents.add(DefaultAgent(apl.removeSingleQuotes())) } } protected fun readFlows(prolog: Prolog) { try { val reses = composeReses( prolog, "hasFlow(Id, Source, Target, Resource, Amount, Time)." ) reses.forEach { this.flows.add(createFlow(it, prolog)) } } catch (exception: NoMoreSolutionException) { LOGGER.error("", exception) } catch (exception: MalformedGoalException) { LOGGER.error("", exception) } } protected fun readTransformations(prolog: Prolog) { try { val reses = composeReses( prolog, "hasTransformation(Id, Agent, InputAmount, InputResource, OutputAmount, OutputResource, Time)." ) reses.forEach { this.transformations.add(createTransformation(it)) } } catch (exception: NoMoreSolutionException) { LOGGER.error("", exception) } catch (exception: MalformedGoalException) { LOGGER.error("", exception) } } private fun composeReses(prolog: Prolog, query: String): LinkedList<SolveInfo> { val reses = LinkedList<SolveInfo>() var res = prolog.solve(query) if (res.isSuccess()) { reses.add(res) while (prolog.hasOpenAlternatives()) { res = prolog.solveNext() reses.add(res) } } return reses } open fun createFlow(res: SolveInfo, prolog: Prolog): PlFlow { val fdata = extractFlowData(res) val flow = createFlow(fdata) return flow } open protected fun createFlow(fdata: ExtractFlowDataResult): PlFlow { return PlFlow( fdata.id, fdata.src, fdata.target, fdata.resource, fdata.amt, fdata.timeFunction ) } open protected fun createTransformation(res: SolveInfo): PlTransformation { return PlTransformation( extractId(res), extractAgent(res, "Agent"), extractAmount(res, "InputAmount") ?: 0.0, extractResource(res, "InputResource"), extractAmount(res, "OutputAmount") ?: 0.0, extractResource(res, "OutputResource"), extractFiringFunction(res) ) } data class ExtractFlowDataResult(val id:String, val src:String, val target:String, val resource:String, val amt:Double?, val timeFunction:(DateTime) -> Boolean) open fun extractFlowData(res:SolveInfo):ExtractFlowDataResult = ExtractFlowDataResult(extractId(res), extractAgent(res, "Source"), extractAgent(res, "Target"), extractResource(res, "Resource"), extractAmount(res, "Amount"), extractFiringFunction(res)) protected fun extractResource(res: SolveInfo, paramName: String) = res.getTerm(paramName).toString().removeSingleQuotes() protected fun extractAgent(res: SolveInfo, paramName: String) = res.getTerm(paramName).toString() protected fun extractId(res: SolveInfo) = res.getTerm("Id").toString() open fun extractFiringFunction(res: SolveInfo): (DateTime) -> Boolean { val timeFunctionPl = res.getTerm("Time") var timeFunction = { x: DateTime -> false } if (timeFunctionPl is Struct) { when (timeFunctionPl.name) { "businessDays" -> timeFunction = businessDaysTriggerFunction() "oncePerMonth" -> { val day = (timeFunctionPl.getArg(0) as Int).intValue() timeFunction = oncePerMonthTriggerFunction(day) } "daily" -> { val hour = (timeFunctionPl.getArg(0) as Int).intValue() val minute = (timeFunctionPl.getArg(1) as Int).intValue() timeFunction = daily(hour, minute) } } } return timeFunction } fun oncePerMonthTriggerFunction(day: kotlin.Int): (DateTime) -> Boolean = { time:DateTime -> val curDay = time.dayOfMonth (day == curDay) && (time.hourOfDay == 0) && (time.minuteOfHour == 0) && (time.secondOfMinute == 0) } protected fun extractAmount(res: SolveInfo, paramName: String): Double? { val amtRaw = res.getTerm(paramName) val amt: Double? if (amtRaw is alice.tuprolog.Double) { amt = amtRaw.doubleValue() } else { amt = null } return amt } fun businessDaysTriggerFunction(): (DateTime) -> Boolean = { time: DateTime -> val dayOfWeek = time.dayOfWeek().get() if ((dayOfWeek == DateTimeConstants.SATURDAY) || (dayOfWeek == DateTimeConstants.SUNDAY) ) { false } else if ((time.hourOfDay == 18) && (time.minuteOfHour == 0) && (time.secondOfMinute == 0)) { true } else { false } } private fun extractResources(prolog: Prolog): ArrayList<PlResource> { val resData = prolog.getResults("resource(Id, Name, Unit).", "Id", "Name", "Unit") val resList = ArrayList<PlResource>(resData.size) resData.forEach { map -> val res = PlResource( map.get("Id").emptyIfNull().removeSingleQuotes(), map.get("Name").emptyIfNull().removeSingleQuotes(), map.get("Unit").emptyIfNull().removeSingleQuotes() ) resList.add(res) } return resList } }
gpl-3.0
77fff9bef5bc84b900cb24a2b617378a
35.604651
125
0.553597
4.772258
false
false
false
false
Drepic26/CouponCodes3
mods/canary/src/main/kotlin/tech/feldman/couponcodes/canary/database/CanaryDatabaseHandler.kt
2
6853
/** * The MIT License * Copyright (c) 2015 Nicholas Feldman (AngrySoundTech) * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * 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 tech.feldman.couponcodes.canary.database import net.canarymod.database.Database import net.canarymod.database.exceptions.DatabaseReadException import net.canarymod.database.exceptions.DatabaseWriteException import tech.feldman.couponcodes.api.coupon.* import tech.feldman.couponcodes.api.exceptions.UnknownMaterialException import tech.feldman.couponcodes.core.coupon.* import tech.feldman.couponcodes.core.database.SimpleDatabaseHandler import java.util.* class CanaryDatabaseHandler : SimpleDatabaseHandler() { override fun addCouponToDatabase(coupon: Coupon): Boolean { if (couponExists(coupon)) return false val da: CanaryDataAccess = CanaryDataAccess() da.couponName = coupon.name da.usetimes = coupon.useTimes da.usedplayers = playerHashToString(coupon.usedPlayers) da.ctype = coupon.type da.timeuse = coupon.time if (coupon is ItemCoupon) { da.ids = itemHashToString(coupon.items) } else if (coupon is EconomyCoupon) { da.money = coupon.money } else if (coupon is RankCoupon) { da.groupname = coupon.group } else if (coupon is XpCoupon) { da.xp = coupon.xp } else if (coupon is CommandCoupon) { da.command = coupon.cmd } val filter: HashMap<String, *> = hashMapOf( Pair("name", coupon.name) ) try { Database.get().update(da, filter) return true } catch (e: DatabaseWriteException) { return false } } override fun removeCouponFromDatabase(coupon: Coupon): Boolean { if (!couponExists(coupon)) return false val da: CanaryDataAccess = CanaryDataAccess() val filter: HashMap<String, *> = hashMapOf( Pair("name", coupon.name) ) try { Database.get().remove(da, filter) return true } catch (e: DatabaseWriteException) { return false } } override fun removeCouponFromDatabase(coupon: String): Boolean { if (!couponExists(coupon)) return false val da: CanaryDataAccess = CanaryDataAccess() val filter: HashMap<String, *> = hashMapOf( Pair("name", coupon) ) try { Database.get().remove(da, filter) return true } catch (e: DatabaseWriteException) { return false } } override fun getCoupons(): List<String> { val da: CanaryDataAccess = CanaryDataAccess() val ds: List<CanaryDataAccess> = arrayListOf() val filter: Map<String, Any> = hashMapOf() val coupons: MutableList<String> = mutableListOf() try { Database.get().loadAll(da, ds, filter) } catch (e: DatabaseReadException) { return coupons } for (cda in ds) { coupons.add(cda.name) } return coupons } override fun updateCoupon(coupon: Coupon) { val da: CanaryDataAccess = CanaryDataAccess() da.couponName = coupon.name da.usetimes = coupon.useTimes da.timeuse = coupon.time da.usedplayers = playerHashToString(coupon.usedPlayers) da.ctype = coupon.type if (coupon is ItemCoupon) { da.ids = itemHashToString(coupon.items) } else if (coupon is EconomyCoupon) { da.money = coupon.money } else if (coupon is RankCoupon) { da.groupname = coupon.group } else if (coupon is XpCoupon) { da.xp = coupon.xp } if (coupon is CommandCoupon) { da.command = coupon.cmd } val filter: HashMap<String, *> = hashMapOf( Pair("name", coupon.name) ) try { Database.get().update(da, filter) } catch (e: DatabaseWriteException) { e.printStackTrace() } } override fun updateCouponTime(coupon: Coupon) { updateCoupon(coupon) } override fun getCoupon(coupon: String): Coupon? { if (!couponExists(coupon)) return null val da: CanaryDataAccess = CanaryDataAccess() val filter: HashMap<String, *> = hashMapOf( Pair("name", coupon) ) try { Database.get().load(da, filter) } catch (e: DatabaseReadException) { e.printStackTrace() return null } val usetimes = da.usetimes val time = da.timeuse val usedplayers = playerStringToHash(da.usedplayers) if (da.ctype.equals("Item", ignoreCase = true)) try { return SimpleItemCoupon(coupon, usetimes, time, usedplayers, itemStringToHash(da.ids)) } catch (e: UnknownMaterialException) { // This should never happen, unless the database was modified by something not this plugin return null } else if (da.ctype.equals("Economy", ignoreCase = true)) return SimpleEconomyCoupon(coupon, usetimes, time, usedplayers, da.money) else if (da.ctype.equals("Rank", ignoreCase = true)) return SimpleRankCoupon(coupon, usetimes, time, usedplayers, da.groupname) else if (da.ctype.equals("Xp", ignoreCase = true)) return SimpleXpCoupon(coupon, usetimes, time, usedplayers, da.xp) else if (da.ctype.equals("Command", ignoreCase = true)) return SimpleCommandCoupon(coupon, usetimes, time, usedplayers, da.command) else return null } }
mit
9f6e78beb3466119273dbbfd983f6505
33.611111
106
0.619583
4.331858
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/TreeTableFixture.kt
4
1568
// Copyright 2000-2017 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.fixtures import com.intellij.testGuiFramework.driver.ExtendedJTreeDriver import com.intellij.testGuiFramework.driver.ExtendedJTreePathFinder import com.intellij.ui.treeStructure.treetable.TreeTable import org.fest.swing.core.MouseButton import org.fest.swing.core.Robot import org.fest.swing.driver.ComponentPreconditions import org.fest.swing.driver.JTreeLocation import java.awt.Dimension import java.awt.Point import java.awt.Rectangle class TreeTableFixture(val robot: Robot, val target: TreeTable) : ComponentFixture<TreeTableFixture, TreeTable>(TreeTableFixture::class.java, robot, target) { @Suppress("unused") fun clickColumn(column: Int, vararg pathStrings: String) { ComponentPreconditions.checkEnabledAndShowing(target) val tree = target.tree val pathWithoutRoot = ExtendedJTreePathFinder().findMatchingPath(tree, pathStrings.asList()) val path = ExtendedJTreeDriver.addRootIfInvisible(tree, pathWithoutRoot) var x = target.location.x + (0 until column).sumBy { target.columnModel.getColumn(it).width } x += target.columnModel.getColumn(column).width / 3 val y = JTreeLocation().pathBoundsAndCoordinates(tree, path).second.y val visibleHeight = target.visibleRect.height target.scrollRectToVisible(Rectangle(Point(0, y + visibleHeight / 2), Dimension(0, 0))) robot.click(target, Point(x, y), MouseButton.LEFT_BUTTON, 1) } }
apache-2.0
b90c0e215a0b5230038225b901bb02e9
43.828571
140
0.788265
4.062176
false
true
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/widget/WidgetSettingsViewModel.kt
1
2929
package ch.rmy.android.http_shortcuts.activities.widget import android.app.Application import android.graphics.Color import ch.rmy.android.framework.viewmodel.BaseViewModel import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId import ch.rmy.android.http_shortcuts.extensions.createDialogState import ch.rmy.android.http_shortcuts.icons.ShortcutIcon import ch.rmy.android.http_shortcuts.utils.ColorPickerFactory import javax.inject.Inject class WidgetSettingsViewModel(application: Application) : BaseViewModel<WidgetSettingsViewModel.InitData, WidgetSettingsViewState>(application), WithDialog { @Inject lateinit var colorPickerFactory: ColorPickerFactory init { getApplicationComponent().inject(this) } private val shortcutId: ShortcutId get() = initData.shortcutId private val shortcutName: String get() = initData.shortcutName private val shortcutIcon: ShortcutIcon get() = initData.shortcutIcon data class InitData( val shortcutId: ShortcutId, val shortcutName: String, val shortcutIcon: ShortcutIcon, ) override var dialogState: DialogState? get() = currentViewState?.dialogState set(value) { updateViewState { copy(dialogState = value) } } override fun initViewState() = WidgetSettingsViewState( showLabel = true, labelColor = Color.WHITE, shortcutIcon = shortcutIcon, shortcutName = shortcutName, ) fun onLabelColorInputClicked() { showColorPicker() } private fun showColorPicker() { doWithViewState { viewState -> dialogState = createDialogState("widget-color-picker") { colorPickerFactory.createColorPicker( onColorPicked = ::onLabelColorSelected, onDismissed = { dialogState?.let(::onDialogDismissed) }, initialColor = viewState.labelColor, ) } } } fun onShowLabelChanged(enabled: Boolean) { updateViewState { copy(showLabel = enabled) } } private fun onLabelColorSelected(color: Int) { updateViewState { copy(labelColor = color) } } fun onCreateButtonClicked() { doWithViewState { viewState -> finishWithOkResult( WidgetSettingsActivity.OpenWidgetSettings.createResult( shortcutId = shortcutId, labelColor = viewState.labelColorFormatted, showLabel = viewState.showLabel, ), ) } } }
mit
c375a3fa6dd9b76a73cc71f609bae23c
29.831579
90
0.644247
5.230357
false
false
false
false
kerubistan/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/vg/RemoveDiskFromVGExecutorTest.kt
2
2782
package com.github.kerubistan.kerub.planner.steps.storage.lvm.vg import com.github.kerubistan.kerub.data.HostDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.hardware.BlockDevice import com.github.kerubistan.kerub.sshtestutils.mockCommandExecution import com.github.kerubistan.kerub.sshtestutils.verifyCommandExecution import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import com.github.kerubistan.kerub.testLvmCapability import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import io.github.kerubistan.kroki.size.TB import org.apache.sshd.client.session.ClientSession import org.junit.Test import java.math.BigInteger import kotlin.test.assertTrue class RemoveDiskFromVGExecutorTest { @Test fun execute() { val hostDao = mock<HostDao>() val hostCommandExecutor = mock<HostCommandExecutor>() val session = mock<ClientSession>() val capability = testLvmCapability.copy( physicalVolumes = testLvmCapability.physicalVolumes + ("/dev/sdb" to 2.TB) + ("/dev/sdd" to 1.TB), size = 4.TB ) val host = testHost.copy( capabilities = testHostCapabilities.copy( blockDevices = listOf( BlockDevice("/dev/sda1", 1.TB), BlockDevice("/dev/sdb", 2.TB), BlockDevice("/dev/sdd", 1.TB) ), storageCapabilities = listOf(capability) ) ) session.mockCommandExecution("lvm pvmove.*".toRegex()) session.mockCommandExecution("lvm vgreduce.*".toRegex()) session.mockCommandExecution( "lvm vgs.*".toRegex(), """ RsDNYC-Un0h-QvhF-hMqe-dEny-Bjlg-qbeeZa:test-vg:433800085504B:4194304B:103426:1 """) doAnswer { val update = it.arguments[1] as (ClientSession) -> BigInteger update(session) }.whenever(hostCommandExecutor).execute(any(), any<(ClientSession) -> Unit>()) var updatedHost: Host? = null doAnswer { val change = it.arguments[2] as (Host) -> Host updatedHost = change(host) updatedHost }.whenever(hostDao).update(id = eq(host.id), retrieve = any(), change = any()) RemoveDiskFromVGExecutor(hostCommandExecutor = hostCommandExecutor, hostDao = hostDao).execute( RemoveDiskFromVG( capability = capability, device = "/dev/sdd", host = host ) ) session.verifyCommandExecution("lvm pvmove.*".toRegex()) session.verifyCommandExecution("lvm vgreduce.*".toRegex()) session.verifyCommandExecution("lvm vgs.*".toRegex()) assertTrue { updatedHost!!.capabilities!!.index.storageCapabilitiesById.getValue(capability.id).size < capability.size } } }
apache-2.0
3ebc12a39dbf21080f02a7c0f5fbe2a3
33.7875
108
0.747304
3.694555
false
true
false
false
deviant-studio/energy-meter-scanner
app/src/main/java/ds/meterscanner/mvvm/viewmodel/AuthViewModel.kt
1
1216
package ds.meterscanner.mvvm.viewmodel import android.util.Patterns import com.github.salomonbrys.kodein.Kodein import ds.bindingtools.binding import ds.meterscanner.R import ds.meterscanner.mvvm.BindableViewModel import ds.meterscanner.mvvm.invoke class AuthViewModel(kodein: Kodein) : BindableViewModel(kodein) { val login: String by binding("") val password: String by binding("") val loginError = Validator(::login) { when { !Patterns.EMAIL_ADDRESS.matcher(it).matches() -> getString(R.string.wrong_email) else -> "" } } val passwordError = Validator(::password) { when { it.isEmpty() -> getString(R.string.shouldnt_be_empty) else -> "" } } override val runAuthScreenCommand = null fun onSignIn() = async { loginError.validate() && passwordError.validate() || return@async authenticator.signIn(login, password) finishCommand() } fun onSignUp() = async { loginError.validate() && passwordError.validate() || return@async authenticator.signUp(login, password) showSnackbarCommand(getString(R.string.user_created)) onSignIn() } }
mit
11cdd4d9afa14d9ba91484b9a6a05e6d
28.682927
92
0.652961
4.251748
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/event/faq/EventFAQFragment.kt
2
2007
package org.fossasia.openevent.general.event.faq import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fragment_event_faq.view.faqEmptyView import kotlinx.android.synthetic.main.fragment_event_faq.view.faqRv import org.fossasia.openevent.general.R import org.fossasia.openevent.general.about.AboutEventFragmentArgs import org.fossasia.openevent.general.utils.Utils import org.koin.androidx.viewmodel.ext.android.viewModel class EventFAQFragment : Fragment() { private lateinit var rootView: View private val eventFAQViewModel by viewModel<EventFAQViewModel>() private val faqAdapter = FAQRecyclerAdapter() private val safeArgs: AboutEventFragmentArgs by navArgs() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = layoutInflater.inflate(R.layout.fragment_event_faq, container, false) rootView.faqRv.layoutManager = LinearLayoutManager(context) rootView.faqRv.adapter = faqAdapter Utils.setToolbar(activity, getString(R.string.frequently_asked_questions)) setHasOptionsMenu(true) eventFAQViewModel.eventFAQ.observe(viewLifecycleOwner, Observer { faqAdapter.addAll(it) rootView.faqEmptyView.visibility = if (it.isEmpty()) View.VISIBLE else View.GONE }) eventFAQViewModel.loadEventFaq(safeArgs.eventId) return rootView } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } }
apache-2.0
17a1717600ea271b45b9856d9ceacc41
37.596154
116
0.744893
4.635104
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/OpenUrlSingleAction.kt
1
4944
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action.item import android.app.AlertDialog import android.os.Parcel import android.os.Parcelable import android.view.View import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.core.utility.utils.ArrayUtils import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity import jp.hazuki.yuzubrowser.legacy.browser.BrowserManager import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo import java.io.IOException class OpenUrlSingleAction : SingleAction, Parcelable { var url = "" private set var targetTab = BrowserManager.LOAD_URL_TAB_CURRENT private set @Throws(IOException::class) constructor(id: Int, reader: JsonReader?) : super(id) { if (reader != null) { if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return reader.beginObject() while (reader.hasNext()) { if (reader.peek() != JsonReader.Token.NAME) return when (reader.nextName()) { FIELD_NAME_URL -> { if (reader.peek() != JsonReader.Token.STRING) return url = reader.nextString() } FIELD_NAME_TARGET_TAB -> { if (reader.peek() != JsonReader.Token.NUMBER) return targetTab = reader.nextInt() } else -> reader.skipValue() } } reader.endObject() } } @Throws(IOException::class) override fun writeIdAndData(writer: JsonWriter) { writer.value(id) writer.beginObject() writer.name(FIELD_NAME_URL) writer.value(url) writer.name(FIELD_NAME_TARGET_TAB) writer.value(targetTab) writer.endObject() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) dest.writeString(url) dest.writeInt(targetTab) } private constructor(source: Parcel) : super(source.readInt()) { url = source.readString()!! targetTab = source.readInt() } override fun showMainPreference(context: ActionActivity): StartActivityInfo? { return showSubPreference(context) } override fun showSubPreference(context: ActionActivity): StartActivityInfo? { val view = View.inflate(context, R.layout.action_open_url_setting, null) val urlEditText = view.findViewById<EditText>(R.id.urlEditText) val tabSpinner = view.findViewById<Spinner>(R.id.tabSpinner) urlEditText.setText(url) val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, context.resources.getStringArray(R.array.pref_newtab_list)) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) tabSpinner.adapter = adapter val targetValues = context.resources.getIntArray(R.array.pref_newtab_values) tabSpinner.setSelection(ArrayUtils.findIndexOfValue(targetTab, targetValues)) AlertDialog.Builder(context) .setTitle(R.string.action_settings) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> url = urlEditText.text.toString() targetTab = targetValues[tabSpinner.selectedItemPosition] } .setNegativeButton(android.R.string.cancel, null) .show() return null } companion object { private const val FIELD_NAME_URL = "0" private const val FIELD_NAME_TARGET_TAB = "1" @JvmField val CREATOR: Parcelable.Creator<OpenUrlSingleAction> = object : Parcelable.Creator<OpenUrlSingleAction> { override fun createFromParcel(source: Parcel): OpenUrlSingleAction { return OpenUrlSingleAction(source) } override fun newArray(size: Int): Array<OpenUrlSingleAction?> { return arrayOfNulls(size) } } } }
apache-2.0
9693656e96f61218c52bdfebdde3ccd3
35.352941
141
0.645631
4.515068
false
false
false
false
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/search/impact/genemutationupdate/StringGeneMutationUpdateTest.kt
1
6585
package org.evomaster.core.search.impact.genemutationupdate import com.google.inject.Injector import com.google.inject.Key import com.google.inject.Module import com.google.inject.TypeLiteral import com.netflix.governator.guice.LifecycleInjector import org.evomaster.core.BaseModule import org.evomaster.core.EMConfig import org.evomaster.core.TestUtils import org.evomaster.core.search.EvaluatedIndividual import org.evomaster.core.search.algorithms.MioAlgorithm import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.matchproblem.* import org.evomaster.core.search.service.Archive import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.EvaluatedMutation import org.evomaster.core.search.service.mutator.MutatedGeneSpecification import org.evomaster.core.search.service.mutator.StandardMutator import org.evomaster.core.search.service.mutator.genemutation.ArchiveGeneMutator import org.evomaster.core.search.tracer.ArchiveMutationTrackService import org.evomaster.core.search.tracer.TrackingHistory import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* /** * created by manzh on 2020-09-10 */ class StringGeneMutationUpdateTest { private lateinit var config: EMConfig private lateinit var mio: MioAlgorithm<PrimitiveTypeMatchIndividual> private lateinit var mutator : StandardMutator<PrimitiveTypeMatchIndividual> private lateinit var sampler : PrimitiveTypeMatchSampler private lateinit var ff: PrimitiveTypeMatchFitness private lateinit var archive : Archive<PrimitiveTypeMatchIndividual> private lateinit var agm : ArchiveGeneMutator private lateinit var tracker : ArchiveMutationTrackService private val budget = 300 @BeforeEach fun init(){ val injector: Injector = LifecycleInjector.builder() .withModules(* arrayOf<Module>(PrimitiveTypeMatchModule(), BaseModule())) .build().createInjector() mio = injector.getInstance(Key.get( object : TypeLiteral<MioAlgorithm<PrimitiveTypeMatchIndividual>>() {})) config = injector.getInstance(EMConfig::class.java) config.maxActionEvaluations = budget config.stoppingCriterion = EMConfig.StoppingCriterion.FITNESS_EVALUATIONS config.probOfRandomSampling = 0.0 sampler = injector.getInstance(PrimitiveTypeMatchSampler::class.java) sampler.template = PrimitiveTypeMatchIndividual.stringTemplate() ff = injector.getInstance(PrimitiveTypeMatchFitness::class.java) ff.type = ONE2M.ONE_EQUAL_WITH_ONE archive = injector.getInstance(Key.get(object : TypeLiteral<Archive<PrimitiveTypeMatchIndividual>>(){})) mutator = injector.getInstance( Key.get(object : TypeLiteral<StandardMutator<PrimitiveTypeMatchIndividual>>(){})) tracker = injector.getInstance(ArchiveMutationTrackService::class.java) agm = injector.getInstance(ArchiveGeneMutator::class.java) config.enableTrackEvaluatedIndividual = true config.probOfArchiveMutation = 1.0 config.weightBasedMutationRate = true config.maxLengthOfTraces = 10 config.maxlengthOfHistoryForAGM = 10 } @Test fun testHistoryExtraction(){ config.archiveGeneMutation = EMConfig.ArchiveGeneMutation.NONE val first = ff.calculateCoverage(sampler.sample())!!.also { archive.addIfNeeded(it) } val mutated = mutator.mutateAndSave(10, first, archive) assertNotNull(mutated.tracking) assertEquals(10, mutated.tracking!!.history.size) val copy = mutated.copy(tracker.getCopyFilterForEvalInd(mutated)) val ind = copy.individual.copy() as PrimitiveTypeMatchIndividual assertEquals(1, ind.seeGenes().size) val geneToMutate = ind.seeGenes().first() val mutationInfo = MutatedGeneSpecification() val additionalInfo = mutator.mutationConfiguration( gene = geneToMutate, individual = ind, eval = copy, enableAGS = true, enableAGM = true, targets = archive.notCoveredTargets(), mutatedGene = mutationInfo, includeSameValue = true) assertNotNull(additionalInfo) assertEquals(10, additionalInfo!!.history.size) } @Test fun testMutationUpdate(){ val template = PrimitiveTypeMatchIndividual.stringTemplate() val specified = listOf("","a","ax","bx","bg","be","bc","ba","bax","baq") val history = mutableListOf<EvaluatedIndividual<PrimitiveTypeMatchIndividual>>() specified.forEach { val ind = template.copy() as PrimitiveTypeMatchIndividual TestUtils.doInitializeIndividualForTesting(ind, Randomness().apply { updateSeed(42) }) (ind.gene as StringGene).value = it val eval = ff.calculateCoverage(ind, archive.notCoveredTargets()) assertNotNull(eval) val er = if(history.isNotEmpty()){ mutator.evaluateMutation( mutated = history.last(), current = eval!!, archive = archive, targets = archive.notCoveredTargets() ).apply { assertEquals(EvaluatedMutation.BETTER_THAN, this) } }else{ EvaluatedMutation.UNSURE } eval!!.wrapWithEvaluatedResults(er) history.add(eval) } val current = (history.last().copy(tracker.getCopyFilterForEvalInd(history.last()))) val th = TrackingHistory<EvaluatedIndividual<PrimitiveTypeMatchIndividual>>(config.maxLengthOfTraces) th.history.addAll(history) current.wrapWithEvaluatedResults(null) current.wrapWithTracking(history.last().evaluatedResult, th) val msp = MutatedGeneSpecification() val aminfo = mutator.mutationConfiguration( gene = current.individual.gene, individual = current.individual, eval = current, enableAGS = false, enableAGM = true, targets = setOf(0), mutatedGene = msp, includeSameValue =false) assertNotNull(aminfo) agm.historyBasedValueMutation(aminfo!!, current.individual.gene, listOf(current.individual.gene)) val mt = (current.individual.gene as StringGene).value assert( (mt.length == 3 && mt[2].toInt() <= 'x'.toInt()/2.0 + 'q'.toInt()/2.0) || mt.length == 4 || mt.length == 2 ) } }
lgpl-3.0
991d404d9f38f288a231674a95770eb7
41.490323
122
0.69795
4.747657
false
true
false
false
Esri/arcgis-runtime-samples-android
kotlin/change-viewpoint/src/main/java/com/esri/arcgisruntime/sample/changeviewpoint/MainActivity.kt
1
3894
/* * Copyright 2020 Esri * * 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.esri.arcgisruntime.sample.changeviewpoint import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.geometry.PointCollection import com.esri.arcgisruntime.geometry.Polyline import com.esri.arcgisruntime.geometry.SpatialReferences import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.Viewpoint import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.sample.changeviewpoint.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } private val scale = 5000.0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a map with an imagery basemap and set it to the map view mapView.map = ArcGISMap(BasemapStyle.ARCGIS_IMAGERY) // create point for starting location val startPoint = Point(-14093.0, 6711377.0, SpatialReferences.getWebMercator()) // set viewpoint of map view to starting point and scale mapView.setViewpointCenterAsync(startPoint, scale) } fun onAnimateClicked(view: View) { // create the London location point val londonPoint = Point(-14093.0, 6711377.0, SpatialReferences.getWebMercator()) // create the viewpoint with the London point and scale val viewpoint = Viewpoint(londonPoint, scale) // set the map view's viewpoint to London with a seven second animation duration mapView.setViewpointAsync(viewpoint, 7f) } fun onCenterClicked(view: View) { // create the Waterloo location point val waterlooPoint = Point(-12153.0, 6710527.0, SpatialReferences.getWebMercator()) // set the map view's viewpoint centered on Waterloo and scaled mapView.setViewpointCenterAsync(waterlooPoint, scale) } fun onGeometryClicked(view: View) { // create a collection of points around Westminster val westminsterPoints = PointCollection(SpatialReferences.getWebMercator()) westminsterPoints.add(Point(-13823.0, 6710390.0)) westminsterPoints.add(Point(-13823.0, 6710150.0)) westminsterPoints.add(Point(-14680.0, 6710390.0)) westminsterPoints.add(Point(-14680.0, 6710150.0)) val geometry = Polyline(westminsterPoints) // set the map view's viewpoint to Westminster mapView.setViewpointGeometryAsync(geometry) } override fun onPause() { mapView.pause() super.onPause() } override fun onResume() { super.onResume() mapView.resume() } override fun onDestroy() { mapView.dispose() super.onDestroy() } }
apache-2.0
253f31b47b868777e4a4d9076a3a50b1
35.392523
96
0.72265
4.350838
false
false
false
false
cretz/asmble
compiler/src/main/kotlin/asmble/compile/jvm/InsnReworker.kt
1
17788
package asmble.compile.jvm import asmble.ast.Node open class InsnReworker { fun rework(ctx: ClsContext, func: Node.Func): List<Insn> { return injectNeededStackVars(ctx, func.instructions).let { insns -> addEagerLocalInitializers(ctx, func, insns) } } fun addEagerLocalInitializers(ctx: ClsContext, func: Node.Func, insns: List<Insn>): List<Insn> { if (func.locals.isEmpty()) return insns // The JVM requires you set a local before you access it. WASM requires that // all locals are implicitly zero. After some thought, we're going to make this // an easy algorithm where, for any get_local, there must be a set/tee_local // in a preceding insn before a branch of any form (br, br_if, and br_table). // If there isn't, an eager set_local will be added at the beginning to init // to 0. // // This should prevent any false positives (i.e. a get_local before // a set/tee_local) while reducing false negatives (i.e. a get_local where it // just doesn't seem like there is a set/tee but there is). Sure there are more // accurate ways such as specifically injecting sets where needed, or turning // the first non-set get to a tee, or counting specific block depths, but this // keeps it simple for now. // // Note, while walking backwards up the insns to find set/tee, we do skip entire // blocks/loops/if+else combined with "end" var neededEagerLocalIndices = emptySet<Int>() fun addEagerSetIfNeeded(getInsnIndex: Int, localIndex: Int) { // Within the param range? nothing needed if (localIndex < func.type.params.size) return // Already loading? nothing needed if (neededEagerLocalIndices.contains(localIndex)) return var blockInitsToSkip = 0 // Get first set/tee or branching insn (or nothing of course) val insn = insns.take(getInsnIndex).asReversed().find { insn -> insn is Insn.Node && when (insn.insn) { // End means we need to skip to next block start is Node.Instr.End -> { blockInitsToSkip++ false } // Else with no inits to skip means we are in the else // and we should skip to the if (i.e. nothing between // if and else) is Node.Instr.Else -> { if (blockInitsToSkip == 0) blockInitsToSkip++ false } // Block init, decrement skip count is Node.Instr.Block, is Node.Instr.Loop, is Node.Instr.If -> { if (blockInitsToSkip > 0) blockInitsToSkip-- false } // Branch means we found it if we're not skipping is Node.Instr.Br, is Node.Instr.BrIf, is Node.Instr.BrTable -> blockInitsToSkip == 0 // Set/Tee means we found it if the index is right // and we're not skipping is Node.Instr.SetLocal, is Node.Instr.TeeLocal -> blockInitsToSkip == 0 && (insn.insn as Node.Instr.Args.Index).index == localIndex // Anything else doesn't matter else -> false } } // If the insn is not set or tee, we have to eager init val needsEagerInit = insn == null || (insn is Insn.Node && insn.insn !is Node.Instr.SetLocal && insn.insn !is Node.Instr.TeeLocal) if (needsEagerInit) neededEagerLocalIndices += localIndex } insns.forEachIndexed { index, insn -> if (insn is Insn.Node && insn.insn is Node.Instr.GetLocal) addEagerSetIfNeeded(index, insn.insn.index) } // Now, in local order, prepend needed local inits return neededEagerLocalIndices.sorted().flatMap { val const: Node.Instr = when (func.localByIndex(it)) { is Node.Type.Value.I32 -> Node.Instr.I32Const(0) is Node.Type.Value.I64 -> Node.Instr.I64Const(0) is Node.Type.Value.F32 -> Node.Instr.F32Const(0f) is Node.Type.Value.F64 -> Node.Instr.F64Const(0.0) } listOf(Insn.Node(const), Insn.Node(Node.Instr.SetLocal(it))) } + insns } fun injectNeededStackVars(ctx: ClsContext, insns: List<Node.Instr>): List<Insn> { ctx.trace { "Calculating places to inject needed stack variables" } // How we do this: // We run over each insn, and keep a running list of stack // manips. If there is an insn that needs something so far back, // we calc where it needs to be added and keep a running list of // insn inserts. Then at the end we settle up. // // Note, we don't do any injections for things like "this" if // they aren't needed up the stack (e.g. a simple getfield can // just aload 0 itself). Also we take special care not to inject // inside of an inner block. // Each pair is first the amount of stack that is changed (0 is // ignored, push is positive, pull is negative) then the index // of the insn that caused it. As a special case, if the stack // is dynamic (i.e. call_indirect var stackManips = emptyList<Pair<Int, Int>>() // Keyed by the index to inject. With how the algorithm works, we // guarantee the value will be in the right order if there are // multiple for the same index var insnsToInject = emptyMap<Int, List<Insn>>() fun injectBeforeLastStackCount(insn: Insn, count: Int) { ctx.trace { "Injecting $insn back $count stack values" } fun inject(index: Int) { insnsToInject += index to (insnsToInject[index]?.let { listOf(insn) + it } ?: listOf(insn)) } if (count == 0) return inject(stackManips.size) var countSoFar = 0 var foundUnconditionalJump = false var insideOfBlocks = 0 for ((amountChanged, insnIndex) in stackManips.asReversed()) { // We have to skip inner blocks because we don't want to inject inside of there if (insns[insnIndex] == Node.Instr.End) { insideOfBlocks++ ctx.trace { "Found end, not injecting until before $insideOfBlocks more block start(s)" } continue } // When we reach the top of a block, we need to decrement out inside count and // if we are at 0, add the result of said block if necessary to the count. if (insideOfBlocks > 0) { // If it's not a block, just ignore it (insns[insnIndex] as? Node.Instr.Args.Type)?.let { insideOfBlocks-- ctx.trace { "Found block begin, number of blocks we're still inside: $insideOfBlocks" } // We're back on our block, change the count if it had a result if (insideOfBlocks == 0 && it.type != null) countSoFar++ } if (insideOfBlocks > 0) continue } countSoFar += amountChanged if (!foundUnconditionalJump) foundUnconditionalJump = insns[insnIndex].let { insn -> insn is Node.Instr.Br || insn is Node.Instr.BrTable || insn is Node.Instr.Unreachable || insn is Node.Instr.Return } if (countSoFar == count) { ctx.trace { "Found injection point as before insn #$insnIndex" } return inject(insnIndex) } } // Only consider it a failure if we didn't hit any unconditional jumps if (!foundUnconditionalJump) throw CompileErr.StackInjectionMismatch(count, insn) } var traceStackSize = 0 // Used only for trace // Go over each insn, determining where to inject insns.forEachIndexed { index, insn -> // Handle special injection cases when (insn) { // Calls require "this" or fn ref before the params is Node.Instr.Call -> { val inject = if (insn.index < ctx.importFuncs.size) Insn.ImportFuncRefNeededOnStack(insn.index) else Insn.ThisNeededOnStack injectBeforeLastStackCount(inject, ctx.funcTypeAtIndex(insn.index).params.size) } // Indirect calls require "this" before the index is Node.Instr.CallIndirect -> injectBeforeLastStackCount(Insn.ThisNeededOnStack, 1) // Global set requires "this" before the single param is Node.Instr.SetGlobal -> { val inject = if (insn.index < ctx.importGlobals.size) Insn.ImportGlobalSetRefNeededOnStack(insn.index) else Insn.ThisNeededOnStack injectBeforeLastStackCount(inject, 1) } // Loads require "mem" before the single param is Node.Instr.I32Load, is Node.Instr.I64Load, is Node.Instr.F32Load, is Node.Instr.F64Load, is Node.Instr.I32Load8S, is Node.Instr.I32Load8U, is Node.Instr.I32Load16U, is Node.Instr.I32Load16S, is Node.Instr.I64Load8S, is Node.Instr.I64Load8U, is Node.Instr.I64Load16U, is Node.Instr.I64Load16S, is Node.Instr.I64Load32S, is Node.Instr.I64Load32U -> injectBeforeLastStackCount(Insn.MemNeededOnStack, 1) // Storage requires "mem" before the single param is Node.Instr.I32Store, is Node.Instr.I64Store, is Node.Instr.F32Store, is Node.Instr.F64Store, is Node.Instr.I32Store8, is Node.Instr.I32Store16, is Node.Instr.I64Store8, is Node.Instr.I64Store16, is Node.Instr.I64Store32 -> injectBeforeLastStackCount(Insn.MemNeededOnStack, 2) // Grow memory requires "mem" before the single param is Node.Instr.MemoryGrow -> injectBeforeLastStackCount(Insn.MemNeededOnStack, 1) else -> { } } // Log some trace output ctx.trace { insnStackDiff(ctx, insn).let { traceStackSize += it "Stack diff is $it for insn #$index $insn, stack size now: $traceStackSize" } } // Add the current diff stackManips += insnStackDiff(ctx, insn) to index } // Build resulting list return insns.foldIndexed(emptyList<Insn>()) { index, ret, insn -> val injections = insnsToInject[index] ?: emptyList() ret + injections + Insn.Node(insn) } } fun insnStackDiff(ctx: ClsContext, insn: Node.Instr) = when (insn) { is Node.Instr.Unreachable, is Node.Instr.Nop, is Node.Instr.Block, is Node.Instr.Loop, is Node.Instr.Else, is Node.Instr.End, is Node.Instr.Br, is Node.Instr.Return -> NOP is Node.Instr.If, is Node.Instr.BrIf, is Node.Instr.BrTable -> POP_PARAM is Node.Instr.Call -> ctx.funcTypeAtIndex(insn.index).let { // All calls pop params and any return is a push (POP_PARAM * it.params.size) + (if (it.ret == null) NOP else PUSH_RESULT) } is Node.Instr.CallIndirect -> ctx.typeAtIndex(insn.index).let { // We add one for the table index POP_PARAM + (POP_PARAM * it.params.size) + (if (it.ret == null) NOP else PUSH_RESULT) } is Node.Instr.Drop -> POP_PARAM is Node.Instr.Select -> (POP_PARAM * 3) + PUSH_RESULT is Node.Instr.GetLocal -> PUSH_RESULT is Node.Instr.SetLocal -> POP_PARAM is Node.Instr.TeeLocal -> POP_PARAM + PUSH_RESULT is Node.Instr.GetGlobal -> PUSH_RESULT is Node.Instr.SetGlobal -> POP_PARAM is Node.Instr.I32Load, is Node.Instr.I64Load, is Node.Instr.F32Load, is Node.Instr.F64Load, is Node.Instr.I32Load8S, is Node.Instr.I32Load8U, is Node.Instr.I32Load16U, is Node.Instr.I32Load16S, is Node.Instr.I64Load8S, is Node.Instr.I64Load8U, is Node.Instr.I64Load16U, is Node.Instr.I64Load16S, is Node.Instr.I64Load32S, is Node.Instr.I64Load32U -> POP_PARAM + PUSH_RESULT is Node.Instr.I32Store, is Node.Instr.I64Store, is Node.Instr.F32Store, is Node.Instr.F64Store, is Node.Instr.I32Store8, is Node.Instr.I32Store16, is Node.Instr.I64Store8, is Node.Instr.I64Store16, is Node.Instr.I64Store32 -> POP_PARAM + POP_PARAM is Node.Instr.MemorySize -> PUSH_RESULT is Node.Instr.MemoryGrow -> POP_PARAM + PUSH_RESULT is Node.Instr.I32Const, is Node.Instr.I64Const, is Node.Instr.F32Const, is Node.Instr.F64Const -> PUSH_RESULT is Node.Instr.I32Add, is Node.Instr.I32Sub, is Node.Instr.I32Mul, is Node.Instr.I32DivS, is Node.Instr.I32DivU, is Node.Instr.I32RemS, is Node.Instr.I32RemU, is Node.Instr.I32And, is Node.Instr.I32Or, is Node.Instr.I32Xor, is Node.Instr.I32Shl, is Node.Instr.I32ShrS, is Node.Instr.I32ShrU, is Node.Instr.I32Rotl, is Node.Instr.I32Rotr, is Node.Instr.I32Eq, is Node.Instr.I32Ne, is Node.Instr.I32LtS, is Node.Instr.I32LeS, is Node.Instr.I32LtU, is Node.Instr.I32LeU, is Node.Instr.I32GtS, is Node.Instr.I32GeS, is Node.Instr.I32GtU, is Node.Instr.I32GeU -> POP_PARAM + POP_PARAM + PUSH_RESULT is Node.Instr.I32Clz, is Node.Instr.I32Ctz, is Node.Instr.I32Popcnt, is Node.Instr.I32Eqz -> POP_PARAM + PUSH_RESULT is Node.Instr.I64Add, is Node.Instr.I64Sub, is Node.Instr.I64Mul, is Node.Instr.I64DivS, is Node.Instr.I64DivU, is Node.Instr.I64RemS, is Node.Instr.I64RemU, is Node.Instr.I64And, is Node.Instr.I64Or, is Node.Instr.I64Xor, is Node.Instr.I64Shl, is Node.Instr.I64ShrS, is Node.Instr.I64ShrU, is Node.Instr.I64Rotl, is Node.Instr.I64Rotr, is Node.Instr.I64Eq, is Node.Instr.I64Ne, is Node.Instr.I64LtS, is Node.Instr.I64LeS, is Node.Instr.I64LtU, is Node.Instr.I64LeU, is Node.Instr.I64GtS, is Node.Instr.I64GeS, is Node.Instr.I64GtU, is Node.Instr.I64GeU -> POP_PARAM + POP_PARAM + PUSH_RESULT is Node.Instr.I64Clz, is Node.Instr.I64Ctz, is Node.Instr.I64Popcnt, is Node.Instr.I64Eqz -> POP_PARAM + PUSH_RESULT is Node.Instr.F32Add, is Node.Instr.F32Sub, is Node.Instr.F32Mul, is Node.Instr.F32Div, is Node.Instr.F32Eq, is Node.Instr.F32Ne, is Node.Instr.F32Lt, is Node.Instr.F32Le, is Node.Instr.F32Gt, is Node.Instr.F32Ge, is Node.Instr.F32Min, is Node.Instr.F32Max, is Node.Instr.F32CopySign -> POP_PARAM + POP_PARAM + PUSH_RESULT is Node.Instr.F32Abs, is Node.Instr.F32Neg, is Node.Instr.F32Ceil, is Node.Instr.F32Floor, is Node.Instr.F32Trunc, is Node.Instr.F32Nearest, is Node.Instr.F32Sqrt -> POP_PARAM + PUSH_RESULT is Node.Instr.F64Add, is Node.Instr.F64Sub, is Node.Instr.F64Mul, is Node.Instr.F64Div, is Node.Instr.F64Eq, is Node.Instr.F64Ne, is Node.Instr.F64Lt, is Node.Instr.F64Le, is Node.Instr.F64Gt, is Node.Instr.F64Ge, is Node.Instr.F64Min, is Node.Instr.F64Max, is Node.Instr.F64CopySign -> POP_PARAM + POP_PARAM + PUSH_RESULT is Node.Instr.F64Abs, is Node.Instr.F64Neg, is Node.Instr.F64Ceil, is Node.Instr.F64Floor, is Node.Instr.F64Trunc, is Node.Instr.F64Nearest, is Node.Instr.F64Sqrt -> POP_PARAM + PUSH_RESULT is Node.Instr.I32WrapI64, is Node.Instr.I32TruncSF32, is Node.Instr.I32TruncUF32, is Node.Instr.I32TruncSF64, is Node.Instr.I32TruncUF64, is Node.Instr.I64ExtendSI32, is Node.Instr.I64ExtendUI32, is Node.Instr.I64TruncSF32, is Node.Instr.I64TruncUF32, is Node.Instr.I64TruncSF64, is Node.Instr.I64TruncUF64, is Node.Instr.F32ConvertSI32, is Node.Instr.F32ConvertUI32, is Node.Instr.F32ConvertSI64, is Node.Instr.F32ConvertUI64, is Node.Instr.F32DemoteF64, is Node.Instr.F64ConvertSI32, is Node.Instr.F64ConvertUI32, is Node.Instr.F64ConvertSI64, is Node.Instr.F64ConvertUI64, is Node.Instr.F64PromoteF32, is Node.Instr.I32ReinterpretF32, is Node.Instr.I64ReinterpretF64, is Node.Instr.F32ReinterpretI32, is Node.Instr.F64ReinterpretI64 -> POP_PARAM + PUSH_RESULT } fun nonAdjacentMemAccesses(insns: List<Insn>) = insns.fold(0 to false) { (count, lastCouldHaveMem), insn -> val inc = if (lastCouldHaveMem) 0 else if (insn == Insn.MemNeededOnStack) 1 else if (insn is Insn.Node && insn.insn is Node.Instr.MemorySize) 1 else 0 val couldSetMemNext = if (insn !is Insn.Node) false else when (insn.insn) { is Node.Instr.I32Store, is Node.Instr.I64Store, is Node.Instr.F32Store, is Node.Instr.F64Store, is Node.Instr.I32Store8, is Node.Instr.I32Store16, is Node.Instr.I64Store8, is Node.Instr.I64Store16, is Node.Instr.I64Store32, is Node.Instr.MemoryGrow -> true else -> false } (count + inc) to couldSetMemNext }.let { (count, _) -> count } companion object : InsnReworker() { const val POP_PARAM = -1 const val PUSH_RESULT = 1 const val NOP = 0 } }
mit
7cf3ee65e08ceff032ee5ec999b6357a
57.133987
117
0.605858
3.721339
false
false
false
false
arnobl/structural-typing-examples
src/staticTyping/nonStructural/kotlin/Main.kt
1
783
interface Duck { fun quack(): String fun dance(): String } class Wolf { public fun eat(d: Duck): String = " 😈 " public fun quack(): String = "QUACK QUACK WHOO" public fun dance(): String = " ¯\\_()_/¯ " } class Mallard : Duck { public override fun quack() = "quack quack" public override fun dance() = " _/¯ " } class DuckCosplay(val wolf: Wolf) : Duck { public override fun quack() = wolf.quack() public override fun dance() = wolf.dance() } fun main() { val wolf = Wolf() val theDuck: Duck = DuckCosplay(wolf) val aDuck: Duck = Mallard() twoDucksAlone(aDuck, theDuck) println(wolf.eat(aDuck)) } fun twoDucksAlone(d1: Duck, d2: Duck) { println(d1.quack()); println(d2.quack()); println(d1.dance()); println(d2.dance()); }
gpl-3.0
2e890f57a6a78de57ebaba2e2503e084
18.923077
48
0.622909
2.805054
false
false
false
false
Tomlezen/FragmentBuilder
lib/src/main/java/com/tlz/fragmentbuilder/FbActionEditor.kt
1
2364
package com.tlz.fragmentbuilder import android.os.Bundle import android.os.Parcelable import android.support.v4.app.Fragment import java.io.Serializable import kotlin.reflect.KClass /** * * Created by Tomlezen. * Date: 2017/7/13. * Time: 16:13. */ class FbActionEditor internal constructor( internal val kclass: KClass<out Fragment>?, internal val action: FbActionType, internal val requestCode: Int = 0) { val TAG: String = System.currentTimeMillis().toString() internal var resultCode = FbFragment.RESULT_OK internal var data = Bundle() fun putData(vararg params: Pair<String, Any>){ params.forEach { val value = it.second when (value) { is Int -> data.putInt(it.first, value) is Long -> data.putLong(it.first, value) is CharSequence -> data.putCharSequence(it.first, value) is String -> data.putString(it.first, value) is Float -> data.putFloat(it.first, value) is Double -> data.putDouble(it.first, value) is Char -> data.putChar(it.first, value) is Short -> data.putShort(it.first, value) is Boolean -> data.putBoolean(it.first, value) is Serializable -> data.putSerializable(it.first, value) is Parcelable -> data.putParcelable(it.first, value) is Array<*> -> when { value.isArrayOf<CharSequence>() -> data.putCharSequenceArray(it.first, value as Array<CharSequence>?) value.isArrayOf<String>() -> data.putStringArray(it.first, value as Array<out String>?) value.isArrayOf<Parcelable>() -> data.putParcelableArray(it.first, value as Array<out Parcelable>?) else -> throw IllegalArgumentException("data extra ${it.first} has wrong type ${value.javaClass.name}") } is IntArray -> data.putIntArray(it.first, value) is LongArray -> data.putLongArray(it.first, value) is FloatArray -> data.putFloatArray(it.first, value) is DoubleArray -> data.putDoubleArray(it.first, value) is CharArray -> data.putCharArray(it.first, value) is ShortArray -> data.putShortArray(it.first, value) is BooleanArray -> data.putBooleanArray(it.first, value) else -> throw IllegalArgumentException("data extra ${it.first} has wrong type ${value.javaClass.name}") } return@forEach } } var isClearPrev = false }
apache-2.0
668baf97103d502ffacf5d8fedd4a4ff
37.770492
113
0.670474
4.068847
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/scene3d/Model3D.kt
1
2477
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.scene3d import com.almasb.fxgl.core.Copyable import javafx.scene.Group import javafx.scene.paint.Color import javafx.scene.paint.Material import javafx.scene.paint.PhongMaterial import javafx.scene.shape.MeshView import javafx.scene.shape.TriangleMesh import java.util.stream.Collectors import java.util.stream.IntStream /** * TODO: clean up API and add doc * TODO: scale(Point3D), which modifies the mesh, not scaleXYZ * TODO: allow setting which way is up, e.g. Z-up * * A container for one or more [javafx.scene.shape.MeshView]. * * @author Almas Baimagambetov ([email protected]) */ open class Model3D : Group(), Copyable<Model3D> { var material: Material = PhongMaterial(Color.WHITE) set(value) { field = value models.forEach { it.material = value } meshViews.forEach { it.material = value } } val models = arrayListOf<Model3D>() val meshViews = arrayListOf<MeshView>() val vertices: List<CustomShape3D.MeshVertex> by lazy { val list = meshViews.map { it.mesh }.flatMap { toVertices(it as TriangleMesh) } list + models.flatMap { it.vertices } } private fun toVertices(mesh: TriangleMesh): List<CustomShape3D.MeshVertex> { val triMesh = mesh val numVertices = triMesh.points.size() / 3 return IntStream.range(0, numVertices) .mapToObj { CustomShape3D.MeshVertex(triMesh.points, it * 3) } .collect(Collectors.toList()) } fun addMeshView(view: MeshView) { meshViews += view children += view //view.material = material } fun removeMeshView(view: MeshView) { meshViews -= view children -= view } fun addModel(model: Model3D) { models += model children += model //model.material = material } fun removeModel(model: Model3D) { models -= model children -= model } override fun copy(): Model3D { val copy = Model3D() // TODO: handle materials? models.forEach { copy.addModel(it.copy()) } meshViews.forEach { original -> copy.addMeshView(MeshView(original.mesh).also { it.material = original.material }) } return copy } }
mit
2415dced0bdd3c2cbc928da3a52982f0
24.546392
94
0.627372
3.931746
false
false
false
false
nickdex/cosmos
code/sorting/src/bubble_sort/bubble_sort.kt
8
595
// Part of Cosmos by OpenGenus Foundation fun <T : Comparable<T>> bubbleSort(array: Array<T>) { var flag : Boolean for (i in array.indices) { flag = true for (j in 0 until (array.size - i - 1)) { if (array[j] > array[j + 1]) { array[j] = array[j + 1].also { array[j+1] = array[j] } flag = false } } if (flag) break } } fun main(args: Array<String>) { val sample: Array<Int> = arrayOf(0, 10, 2, 6, 1, 3, 5, 4, 9, 7, 8) bubbleSort(sample) println("Sorted: "+sample.joinToString()) }
gpl-3.0
33bf81f2380faea76fc6264df50c0724
27.333333
70
0.507563
3.164894
false
false
false
false
t-yoshi/peca-android
ui/src/main/java/org/peercast/core/ui/setting/UpnpSettingFragments.kt
1
4810
package org.peercast.core.ui.setting import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.leanback.preference.LeanbackPreferenceFragmentCompat import androidx.lifecycle.lifecycleScope import androidx.preference.* import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.peercast.core.common.upnp.UpnpManager import timber.log.Timber import java.io.IOException private class UpnpSettingFragmentDelegate(fragment: PreferenceFragmentCompat) : BaseLoadableDelegate(fragment) { private val upnpManager by fragment.inject<UpnpManager>() private lateinit var catInfo: PreferenceCategory override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { super.onCreatePreferences(savedInstanceState, rootKey) val screen = fragment.preferenceScreen screen.title = "UPnP" val c = fragment.requireContext() SwitchPreference(c).also { it.title = "UPnP" it.isChecked = appPrefs.isUPnPEnabled it.setOnPreferenceChangeListener { _, v -> appPrefs.isUPnPEnabled = v as Boolean if (v) { loadUpnpStatus() } true } screen.addPreference(it) } catInfo = PreferenceCategory(c) screen.addPreference(catInfo) if (appPrefs.isUPnPEnabled) { loadUpnpStatus() } } private fun loadUpnpStatus() { catInfo.removeAll() asyncExecute({ upnpManager.getStatuses() to upnpManager.getPortMaps() }, { (statuses, portMaps) -> portMaps.forEach { m -> CheckBoxPreference(catInfo.context).also { it.title = "${m.protocol} ${m.internalClient}:${m.internalPort}" it.summary = m.description it.isChecked = m.enabled catInfo.addPreference(it) it.setOnPreferenceChangeListener { _, newValue -> when (newValue as Boolean) { true -> { manipulatePort { upnpManager.addPort(m.internalPort) } } else -> { manipulatePort { upnpManager.removePort(m.internalPort) } } } true } } } statuses.forEach { (title, r) -> Preference(catInfo.context).also { it.title = "$title: $r" catInfo.addPreference(it) } } }, { e -> Timber.w(e) showErrorMessage(e.message.toString()) }) } private fun manipulatePort(f: suspend () -> Unit) { fragment.lifecycleScope.launch { try { f() } catch (e: IOException) { Timber.w(e) showErrorMessage(e.message.toString()) } } } private fun showErrorMessage(msg: CharSequence) { val p = catInfo.findPreference(KEY_ERROR) ?: Preference(catInfo.context).also { it.key = KEY_ERROR catInfo.addPreference(it) } p.title = msg } companion object { private const val KEY_ERROR = "_Key_Error" } } class UpnpSettingFragment : PreferenceFragmentCompat() { private val delegate = UpnpSettingFragmentDelegate(this) override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { delegate.onCreatePreferences(savedInstanceState, rootKey) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return delegate.wrapProgressView( super.onCreateView(inflater, container, savedInstanceState) ) } } class TvUpnpSettingFragment : LeanbackPreferenceFragmentCompat() { private val delegate = UpnpSettingFragmentDelegate(this) override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { delegate.onCreatePreferences(savedInstanceState, rootKey) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return delegate.wrapProgressView( super.onCreateView(inflater, container, savedInstanceState), ) } }
gpl-3.0
08b2af174e3f1277e4cf47e481ee3eae
30.644737
87
0.563617
5.309051
false
false
false
false
google/grpc-kapt
example/src/test/kotlin/com/google/api/example/ExampleTest.kt
1
1304
/* * * * Copyright 2019 Google LLC * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * https://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.google.api.example import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals private const val PORT = 8181 class ExampleTest { @Test fun `can say hello`() = withClient { client -> val response = client.ask(Question("Hello world!")) assertEquals(Answer("you said: 'Hello world!'"), response) } } private fun <T> withClient(block: suspend (SimpleServiceClient) -> T) = runBlocking { SimpleServer().asGrpcServer(PORT) { SimpleServiceClient.forAddress("localhost", PORT, channelOptions = { usePlaintext() }).use { block(it) } } }
apache-2.0
1bcb5f656b3903a4f43b289b508c23c0
28.636364
85
0.667945
3.915916
false
true
false
false
luxons/seven-wonders
sw-ui/src/main/kotlin/com/palantir/blueprintjs/BpCallout.kt
1
716
@file:JsModule("@blueprintjs/core") package com.palantir.blueprintjs import react.PureComponent import react.RState external interface ICalloutProps : IIntentProps, IProps { var icon: dynamic /* IconName | MaybeElement */ get() = definedExternally set(value) = definedExternally override var intent: Intent? get() = definedExternally set(value) = definedExternally var title: String? get() = definedExternally set(value) = definedExternally } open external class Callout : PureComponent<ICalloutProps, RState> { override fun render(): react.ReactElement open var getIconName: Any companion object { var displayName: String } }
mit
c9d1164e298c5aeddd01e19006e8a283
25.518519
68
0.694134
4.56051
false
false
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/ProfileDesigns.kt
1
981
package net.perfectdreams.loritta.cinnamon.pudding.tables import net.perfectdreams.loritta.common.utils.Rarity import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.array import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IdTable import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.TextColumnType object ProfileDesigns : IdTable<String>() { val internalName = text("internal_name") override val id: Column<EntityID<String>> = internalName.entityId() val enabled = bool("enabled").index() val rarity = enumeration("rarity", Rarity::class).index() val createdBy = array<String>("created_by", TextColumnType()) val availableToBuyViaDreams = bool("available_to_buy_via_dreams").index() val availableToBuyViaMoney = bool("available_to_buy_via_money").index() val set = optReference("set", Sets) val addedAt = long("added_at").default(-1L) override val primaryKey = PrimaryKey(id) }
agpl-3.0
b454d80729e7e5a9e5580bf0dcdd8e00
41.695652
77
0.756371
3.939759
false
false
false
false
shiraji/permissions-dispatcher-plugin
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/AddPMDependencies.kt
1
6995
package com.github.shiraji.permissionsdispatcherplugin.actions import com.github.shiraji.permissionsdispatcherplugin.data.AndroidGradleVersion import com.github.shiraji.permissionsdispatcherplugin.data.PdVersion import com.github.shiraji.permissionsdispatcherplugin.extentions.generateVersionNumberFrom import com.intellij.codeInsight.CodeInsightActionHandler import com.intellij.codeInsight.actions.CodeInsightAction import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCommandArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import javax.swing.JOptionPane class AddPMDependencies : CodeInsightAction() { override fun getHandler(): CodeInsightActionHandler { return AddPMDependenciesHandler() } override fun update(e: AnActionEvent?) { e ?: return super.update(e) val project = e.getData(CommonDataKeys.PROJECT) ?: return val dependenciesBlocks = FilenameIndex.getAllFilesByExt(project, "gradle", GlobalSearchScope.projectScope(project)).map { PsiManager.getInstance(project).findFile(it) as? GroovyFile }.filterNotNull().filter { it.findDescendantOfType<GrCommandArgumentList> { it.text.contains("com.android.application") } != null }.flatMap { it.collectDescendantsOfType<GrMethodCallExpression> { it.invokedExpression.text == "dependencies" } } if (dependenciesBlocks.firstOrNull { it.findDescendantOfType<GrCommandArgumentList> { it.text.contains("com.github.hotchemi:permissionsdispatcher:") } != null } != null) { e.presentation.isEnabledAndVisible = false } } class AddPMDependenciesHandler : CodeInsightActionHandler { override fun startInWriteAction() = true override fun invoke(project: Project, editor: Editor, file: PsiFile) { val result = JOptionPane.showOptionDialog(null, "Do you use native Fragment (android.app.Fragment)?", "Add PermissionsDispatcher dependencies", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) if (result == JOptionPane.CANCEL_OPTION) return val isUseNativeFragment = result == JOptionPane.OK_OPTION var hasAndroidApt = false var useKapt = false var androidGradleVersion: AndroidGradleVersion? = null var targetFile: GroovyFile? = null FilenameIndex.getAllFilesByExt(project, "gradle", GlobalSearchScope.projectScope(project)).forEach { val groovyFile = PsiManager.getInstance(project).findFile(it) as? GroovyFile ?: return@forEach if (groovyFile.findDescendantOfType<GrApplicationStatement> { it.text.contains("\'android-apt\'") } != null) hasAndroidApt = true if (groovyFile.findDescendantOfType<GrApplicationStatement> { it.text.contains("\'kotlin-android\'") } != null) useKapt = true if (groovyFile.findDescendantOfType<GrCommandArgumentList> { it.text.contains("com.android.application") } != null) targetFile = groovyFile val androidGradleBuildLine = groovyFile.findDescendantOfType<GrCommandArgumentList> { it.text.contains("com.android.tools.build:gradle:") } androidGradleBuildLine?.text?.let { text -> // for now, forget about variables... val versionText = text.generateVersionNumberFrom() androidGradleVersion = AndroidGradleVersion(versionText) } } val version = androidGradleVersion when { version == null -> Notifications.Bus.notify(Notification( "PermissionsManager Plugin", "[PermissionsManager Plugin] No Android Gradle Version found", "No android gradle version found. To avoid generating wrong dependency, stop 'Add PermissionsDispatcher dependencies'", NotificationType.INFORMATION)) !useKapt && version.isValid() && !version.isHigherThan2_2() && !hasAndroidApt -> Notifications.Bus.notify(Notification( "PermissionsManager Plugin", "[PermissionsManager Plugin] Missing settings", "No annotation processing settings found. Use 'android gradle plugin version >= 2.2' or 'android-apt'", NotificationType.WARNING)) else -> { val dependenciesBlock = targetFile?.findDescendantOfType<GrMethodCallExpression> { it.invokedExpression.text == "dependencies" } ?: return val factory = GroovyPsiElementFactory.getInstance(project) val aptRef = when { useKapt -> "kapt" hasAndroidApt -> "apt" else -> "annotationProcessor" } var compileDepTemplate = "compile ('com.github.hotchemi:permissionsdispatcher:${PdVersion.latestVersion}')" if (!isUseNativeFragment) compileDepTemplate += " { exclude module: 'support-v13' }" val compileExpression = factory.createExpressionFromText(compileDepTemplate) val annotationProcessorExpression = factory.createExpressionFromText("$aptRef 'com.github.hotchemi:permissionsdispatcher-processor:${PdVersion.latestVersion}'") dependenciesBlock.closureArguments[0]?.run { val applicationStatement = addBefore(compileExpression, rBrace) as? GrApplicationStatement addBefore(annotationProcessorExpression, rBrace) applicationStatement?.navigate(true) } } } } } }
apache-2.0
378839abebc9fadf73f166794e2a67e6
53.648438
180
0.658899
5.43512
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/services/db/DB.kt
2
4962
//package ir.iais.utilities.javautils.services.db // //import ir.iais.utilities.javautils.inject //import ir.iais.utilities.javautils.logger //import ir.iais.utilities.javautils.services.db.interfaces.ILoaderPersistence //import ir.iais.utilities.javautils.services.db.interfaces.IPersistence //import ir.iais.utilities.javautils.services.db.interfaces.ISaverPersistence //import ir.iais.utilities.javautils.services.db.interfaces.ISession //import java.lang.RuntimeException //import javax.persistence.EntityManagerFactory //import javax.persistence.FlushModeType //import javax.transaction.NotSupportedException // ///** @author yoones */ //class DB { // private var session: ISession? = null // private var stateless = false // private var readOnly = false // // internal suspend fun <R> load( // errorMessage: String = "", // emfs: () -> EntityManagerFactory, // serviceAction: suspend ILoaderPersistence.() -> R // ): R? { // return action(false, false, errorMessage, emfs, serviceAction) // } // // /** do a transaction without close session finally */ // internal suspend fun <R> load_trx( // errorMessage: String = "", // emfs: () -> EntityManagerFactory, // serviceAction: suspend IPersistence.() -> R // ): R? { // return action(true, false, errorMessage, emfs, serviceAction)!! // } // // /** do a transaction */ // internal suspend fun <R> trx( // errorMessage: String = "", // emfs: () -> EntityManagerFactory, // serviceAction: suspend ISaverPersistence.() -> R // ): R { // return action(true, true, errorMessage, emfs, serviceAction)!! // } // // private suspend fun <R> action( // openTransaction: Boolean, // closeSessionFinally: Boolean = openTransaction, // errorMessage: String = "", // emfs: () -> EntityManagerFactory, // serviceAction: suspend IPersistence.() -> R // ): R? { // var session: ISession? = null // var exceptionThrown = false // try { // session = this.session ?: getSession(emfs).openSession(openTransaction) // val gnI = if (readOnly) throw NotSupportedException() else getP(session) // val result = gnI.serviceAction() // if (openTransaction && this.session == null) session.commit() // return result // } catch (t: Throwable) { // exceptionThrown = true // if (session != null && openTransaction && this.session == null) session.rollback() // if (errorMessage.isNotEmpty()) DB::class.logger.error(errorMessage) // throw RuntimeException(t) // } finally { // val closeSession = this.session == null && (closeSessionFinally || exceptionThrown) // if (closeSession && session != null) session.close() // } // } // // suspend fun <R> action( // session: ISession, // errorMessage: String = "", // emfs: () -> EntityManagerFactory = IEntityManagerFactorySupplier::class.inject(), // serviceAction: suspend (IPersistence) -> R // ): R? { // this.session = session // return action(false, false, errorMessage, emfs, serviceAction) // } // // private fun getSession(emfs: () -> EntityManagerFactory): ISession { // return session ?: if (stateless) throw NotSupportedException() else HSession(emfs) // } // // fun stateless(): DB { // stateless = true // return this // } // // fun readOnly(): DB { // readOnly = true // return this // } // // companion object { // // /** // * Just write to database, no read // */ // @JvmOverloads // suspend fun <R> writeOnly( // errorMessage: String = "", // emfs: () -> EntityManagerFactory = IEntityManagerFactorySupplier::class.inject(), // action: suspend ISaverPersistence.() -> R // ) = DB().trx(errorMessage, emfs, action) // // @JvmOverloads // suspend fun <R> transaction( // errorMessage: String = "", // emfs: () -> EntityManagerFactory = IEntityManagerFactorySupplier::class.inject(), // action: suspend IPersistence.() -> R // ) = DB().load_trx(errorMessage, emfs, action) // // @JvmOverloads // suspend fun <R> readOnly( // errorMessage: String = "", // emfs: () -> EntityManagerFactory = IEntityManagerFactorySupplier::class.inject(), // action: suspend ILoaderPersistence.() -> R // ) = DB().load(errorMessage, emfs, action) // // /** get an [IPersistence] */ // private fun getP(s: ISession): IPersistence = StatefulPersistence.gnI(s) // .setQueryConfigurer { it.flushMode = FlushModeType.COMMIT } // } //}
gpl-3.0
5027183f8696a782dd6d754e0549a347
38.380952
99
0.58424
4.030869
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/items/Upgrades.kt
2
3064
package com.cout970.magneticraft.features.items import com.cout970.magneticraft.api.tool.IGear import com.cout970.magneticraft.misc.CreativeTabMg import com.cout970.magneticraft.misc.item.IItemCapability import com.cout970.magneticraft.misc.item.ItemCapabilityProvider import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.registry.ITEM_GEAR import com.cout970.magneticraft.systems.items.IItemMaker import com.cout970.magneticraft.systems.items.ItemBase import com.cout970.magneticraft.systems.items.ItemBuilder import net.minecraft.item.Item import net.minecraft.item.ItemStack import java.util.* /** * Created by cout970 on 2017/08/19. */ object Upgrades : IItemMaker { lateinit var brokenGear: ItemBase private set lateinit var ironGear: ItemBase private set lateinit var steelGear: ItemBase private set lateinit var tungstenGear: ItemBase private set lateinit var inserterUpgrade: ItemBase private set override fun initItems(): List<Item> { val builder = ItemBuilder().apply { creativeTab = CreativeTabMg isFull3d = true maxStackSize = 1 } brokenGear = builder.withName("broken_gear").copy { maxDamage = 0 customModels = listOf("normal" to resource("models/item/mcx/broken_gear.mcx")) }.build() ironGear = builder.withName("iron_gear").copy { capabilityProvider = { ItemCapabilityProvider(ITEM_GEAR to Gear(it.stack, 1f)) } maxDamage = 800 containerItem = brokenGear customModels = listOf("normal" to resource("models/item/mcx/iron_gear.mcx")) }.build() steelGear = builder.withName("steel_gear").copy { capabilityProvider = { ItemCapabilityProvider(ITEM_GEAR to Gear(it.stack, 1.25f)) } maxDamage = 1600 containerItem = brokenGear customModels = listOf("normal" to resource("models/item/mcx/steel_gear.mcx")) }.build() tungstenGear = builder.withName("tungsten_gear").copy { capabilityProvider = { ItemCapabilityProvider(ITEM_GEAR to Gear(it.stack, 1.5f)) } maxDamage = 3200 containerItem = brokenGear customModels = listOf("normal" to resource("models/item/mcx/tungsten_gear.mcx")) }.build() inserterUpgrade = builder.withName("inserter_upgrade").copy { variants = mapOf( 0 to "speed", 1 to "stack" ) }.build() return listOf(ironGear, brokenGear, steelGear, tungstenGear, inserterUpgrade) } class Gear(override val stack: ItemStack, val speed: Float) : IGear, IItemCapability { override fun getSpeedMultiplier(): Float = speed override fun getMaxDurability(): Int = stack.maxDamage override fun getDurability(): Int = stack.itemDamage override fun applyDamage(stack: ItemStack): ItemStack { stack.attemptDamageItem(1, Random(), null) return stack } } }
gpl-2.0
ec29cc0413fc43a88995292ebf45523b
35.488095
95
0.667102
4.297335
false
false
false
false
ReactiveCircus/FlowBinding
flowbinding-viewpager2/fixtures/src/main/java/reactivecircus/flowbinding/viewpager2/fixtures/ViewPager2Fragment.kt
1
1548
package reactivecircus.flowbinding.viewpager2.fixtures import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import reactivecircus.flowbinding.viewpager2.fixtures.databinding.FragmentViewpager2Binding import reactivecircus.flowbinding.viewpager2.fixtures.databinding.ItemViewpagerBinding class ViewPager2Fragment : Fragment(R.layout.fragment_viewpager2) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentViewpager2Binding.bind(view) binding.viewPager.adapter = ViewPagerAdapter() } } class ViewPagerAdapter : RecyclerView.Adapter<ViewPagerHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerHolder { val binding = ItemViewpagerBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewPagerHolder(binding) } override fun onBindViewHolder(holder: ViewPagerHolder, position: Int) { holder.bind(pages[position]) } override fun getItemCount(): Int { return pages.size } } private val pages = listOf("1", "2", "3") class ViewPagerHolder(private val binding: ItemViewpagerBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(pageTitle: String) { binding.pageTitleTextView.text = pageTitle } }
apache-2.0
b1fe9a0286d982601a07df9afc4af97c
31.93617
106
0.744832
4.748466
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/telemetry/ProfilerMarkerFactProcessor.kt
1
3963
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.telemetry import android.os.Handler import android.os.Looper import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.Companion.PRIVATE import mozilla.components.concept.base.profiler.Profiler import mozilla.components.support.base.facts.Action import mozilla.components.support.base.facts.Fact import mozilla.components.support.base.facts.FactProcessor /** * A fact processor that adds Gecko profiler markers for [Fact]s matching a specific format. * We look for the following format: * ``` * Fact( * action = Action.IMPLEMENTATION_DETAIL * item = <marker name> * ) * ``` * * This allows us to add profiler markers from android-components code. Using the Fact API for this * purpose, rather than calling [Profiler.addMarker] directly inside components, has trade-offs. Its * downsides are that it is less explicit and tooling does not work as well on it. However, we felt * it was worthwhile because: * * 1. we don't know what profiler markers are useful so we want to be able to iterate quickly. * Adding dependencies on the Profiler and landing these changes across two repos hinders that * 2. we want to instrument the code as close to specific method calls as possible (e.g. * GeckoSession.loadUrl) but it's not always easy to do so (e.g. in the previous example, passing a * Profiler reference to GeckoEngineSession is difficult because GES is not a global dependency) * 3. we can only add Profiler markers from the main thread so adding markers will become more * difficult if we have to understand the threading needs of each Profiler call site * * An additional benefit with having this infrastructure is that it's easy to add Profiler markers * for local debugging. * * That being said, if we find a location where it would be valuable to have a long term Profiler * marker, we should consider instrumenting it via the [Profiler] API. */ class ProfilerMarkerFactProcessor @VisibleForTesting(otherwise = PRIVATE) constructor( // We use a provider to defer accessing the profiler until we need it, because the property is a // child of the engine property and we don't want to initialize it earlier than we intend to. private val profilerProvider: () -> Profiler?, private val mainHandler: Handler = Handler(Looper.getMainLooper()), private val getMyLooper: () -> Looper? = { Looper.myLooper() }, ) : FactProcessor { override fun process(fact: Fact) { if (fact.action != Action.IMPLEMENTATION_DETAIL) { return } val markerName = fact.item // Java profiler markers can only be added from the main thread so, for now, we push all // markers to the the main thread (which also groups all the markers together, // making it easier to read). val profiler = profilerProvider() if (getMyLooper() == mainHandler.looper) { profiler?.addMarker(markerName) } else { // To reduce the performance burden, we could early return if the profiler isn't active. // However, this would change the performance characteristics from when the profiler is // active and when it's inactive so we always post instead. val now = profiler?.getProfilerTime() mainHandler.post { // We set now to both start and end time because we want a marker of without duration // and if end is omitted, the duration is created implicitly. profiler?.addMarker(markerName, now, now, null) } } } companion object { fun create(profilerProvider: () -> Profiler?) = ProfilerMarkerFactProcessor(profilerProvider) } }
mpl-2.0
26a6ac171e7f496309a135669f9165ad
45.623529
101
0.710068
4.498297
false
false
false
false
spark/photon-tinker-android
meshui/src/main/java/io/particle/mesh/ui/setup/NewMeshNetworkNameFragment.kt
1
2236
package io.particle.mesh.ui.setup import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentActivity import com.afollestad.materialdialogs.MaterialDialog import io.particle.mesh.setup.flow.FlowRunnerUiListener import io.particle.mesh.ui.BaseFlowFragment import io.particle.mesh.ui.R import kotlinx.android.synthetic.main.fragment_new_mesh_network_name.* class NewMeshNetworkNameFragment : BaseFlowFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_new_mesh_network_name, container, false) } override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) { super.onFragmentReady(activity, flowUiListener) action_next.setOnClickListener { onNetworkNameEntered() } } private fun onNetworkNameEntered() { val name = networkNameInputLayout.editText!!.text.toString() val isValid = validateNetworkName(name) if (!isValid) { MaterialDialog.Builder(requireActivity()) .content(R.string.p_newmeshnetworkname_invalid_name_dialog_text) .positiveText(android.R.string.ok) .show() return } flowUiListener?.mesh?.updateNewNetworkName(name) } private fun validateNetworkName(name: String): Boolean { val validations = listOf<(String) -> Boolean>( { it.length <= 16 }, { it.isNotBlank() }, { hasValidCharacters(it) } ) for (v in validations) { if (!v(name)) { return false } } return true } private fun hasValidCharacters(name: String): Boolean { for (chr in name.iterator()) { if (!ALLOWABLE_CHARS.contains(chr, ignoreCase = true)) { return false } } return true } } // FIXME: move all this validation to the backend private val ALLOWABLE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
apache-2.0
d528740855708ab13127464781a8ce44
31.897059
100
0.647138
4.767591
false
false
false
false
toastkidjp/Jitte
app/src/test/java/jp/toastkid/yobidashi/settings/initial/InitialIndexSettingUseCaseTest.kt
1
2347
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.settings.initial import android.os.Bundle import androidx.fragment.app.Fragment import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.yobidashi.editor.EditorFragment import jp.toastkid.yobidashi.search.SearchFragment import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class InitialIndexSettingUseCaseTest { private lateinit var initialIndexSettingUseCase: InitialIndexSettingUseCase @MockK private lateinit var argument: Bundle @Before fun setUp() { MockKAnnotations.init(this) initialIndexSettingUseCase = InitialIndexSettingUseCase() every { argument.putInt(any(), any()) }.answers { Unit } } @Test fun testNormalFragment() { initialIndexSettingUseCase.put(argument, Fragment::class.java) verify(exactly = 1) { argument.putInt(any(), 0) } } @Test fun testSearchFragment() { @Suppress("UNCHECKED_CAST") initialIndexSettingUseCase.put(argument, SearchFragment::class.java as Class<Fragment>) verify(exactly = 1) { argument.putInt(any(), 2) } } @Test fun testEditorFragment() { @Suppress("UNCHECKED_CAST") initialIndexSettingUseCase.put(argument, EditorFragment::class.java as Class<Fragment>) verify(exactly = 1) { argument.putInt(any(), 4) } } @Test fun testExtract() { every { argument.getInt("initialIndex") }.returns(2) assertEquals(2, initialIndexSettingUseCase.extract(argument)) verify(exactly = 1) { argument.getInt("initialIndex") } } @Test fun testExtractElseCase() { every { argument.getInt(any()) }.returns(0) assertEquals(0, initialIndexSettingUseCase.extract(argument)) verify(exactly = 1) { argument.getInt("initialIndex") } } @After fun tearDown() { unmockkAll() } }
epl-1.0
08eeeebc35e2d0f0e8fe32c1a7fbe265
25.988506
95
0.699617
4.370577
false
true
false
false
AdityaAnand1/Morphing-Material-Dialogs
library/src/main/java/com/adityaanand/morphdialog/Constants.kt
1
688
package com.adityaanand.morphdialog object Constants { const val MORPH_DIALOG_ID = "MORPH_DIALOG_ID281194" const val MORPH_DIALOG_ACTION_TYPE = "MORPH_DIALOG_ACTION_TYPE281194" const val MORPH_DIALOG_BUILDER_DATA = "MORPH_DIALOG_BUILDER_DATA281194" /*items*/ const val INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_POSITION = "INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_POSITION" const val INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_TEXT = "INTENT_KEY_SINGLE_CHOICE_LIST_ITEM_TEXT" const val INTENT_KEY_MULTI_CHOICE_LIST_ITEM_POSITIONS = "INTENT_KEY_MULTI_CHOICE_LIST_ITEM_POSITIONS" const val INTENT_KEY_MULTI_CHOICE_LIST_ITEM_TEXTS = "INTENT_KEY_MULTI_CHOICE_LIST_ITEM_TEXTS" }
mit
800abb0dad7aad3ae9f6c2dac2c8f3c2
48.142857
105
0.752907
3.085202
false
false
false
false
xfournet/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/editor/actions/GroovyTripleQuoteBackspaceHandlerDelegate.kt
5
1626
// Copyright 2000-2017 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.groovy.editor.actions import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.highlighter.HighlighterIterator import com.intellij.psi.PsiFile import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mGSTRING_LITERAL import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mSTRING_LITERAL class GroovyTripleQuoteBackspaceHandlerDelegate : BackspaceHandlerDelegate() { private var myWithinTripleQuoted: Boolean = false override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) { myWithinTripleQuoted = false if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) return if (c != '\'' && c != '"') return editor as? EditorEx ?: return val offset = editor.caretModel.offset val iterator: HighlighterIterator = editor.highlighter.createIterator(offset) val tokenType = iterator.tokenType if (tokenType == mSTRING_LITERAL || tokenType == mGSTRING_LITERAL) { myWithinTripleQuoted = iterator.start + 3 == offset && iterator.end - 3 == offset } } override fun charDeleted(c: Char, file: PsiFile, editor: Editor): Boolean { if (!myWithinTripleQuoted) return false val offset = editor.caretModel.offset editor.document.deleteString(offset, offset + 3) return true } }
apache-2.0
0eff69d338dc0dda4526aaa35ee0c1ea
44.194444
140
0.771833
4.336
false
false
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/changes/view/ChangesViewHolder.kt
1
2865
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.changes.view import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import butterknife.BindView import butterknife.ButterKnife import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.base.list.view.BaseViewHolder import com.github.vase4kin.teamcityapp.changes.data.ChangesDataModel /** * Changes single item view holder */ class ChangesViewHolder(parent: ViewGroup) : BaseViewHolder<ChangesDataModel>( LayoutInflater.from(parent.context).inflate( R.layout.item_changes_list, parent, false ) ) { @BindView(R.id.commitHash) lateinit var commitHash: TextView @BindView(R.id.commitName) lateinit var commitName: TextView @BindView(R.id.image) lateinit var image: ImageView @BindView(R.id.userName) lateinit var userName: TextView @BindView(R.id.commitDate) lateinit var commitDate: TextView init { ButterKnife.bind(this, itemView) } /** * {@inheritDoc} */ override fun bind(dataModel: ChangesDataModel, position: Int) { val filesCount = dataModel.getFilesCount(position) val iconRes = getCountIcon(filesCount) image.setImageResource(iconRes) commitName.text = dataModel.getComment(position) userName.text = dataModel.getUserName(position) commitDate.text = dataModel.getDate(position) commitHash.text = dataModel.getVersion(position) } private fun getCountIcon(count: Int): Int { return when (count) { 0 -> R.drawable.ic_filter_none_black_24dp 1 -> R.drawable.ic_filter_1_black_24dp 2 -> R.drawable.ic_filter_2_black_24dp 3 -> R.drawable.ic_filter_3_black_24dp 4 -> R.drawable.ic_filter_4_black_24dp 5 -> R.drawable.ic_filter_5_black_24dp 6 -> R.drawable.ic_filter_6_black_24dp 7 -> R.drawable.ic_filter_7_black_24dp 8 -> R.drawable.ic_filter_8_black_24dp 9 -> R.drawable.ic_filter_9_black_24dp 10 -> R.drawable.ic_filter_9_plus_black_24dp else -> R.drawable.ic_filter_9_plus_black_24dp } } }
apache-2.0
41e337513bf4c7e53b9ac4c2c57abcf5
33.518072
78
0.685864
3.882114
false
false
false
false
square/curtains
curtains/src/main/java/curtains/internal/WindowCallbackWrapper.kt
1
5409
package curtains.internal import android.view.KeyEvent import android.view.MotionEvent import android.view.Window import curtains.DispatchState import curtains.DispatchState.Consumed import java.lang.ref.WeakReference import java.util.WeakHashMap import kotlin.LazyThreadSafetyMode.NONE /** * Replaces the default Window callback to allows adding listeners / interceptors * for interesting events. */ internal class WindowCallbackWrapper constructor( private val delegate: Window.Callback ) : FixedWindowCallback(delegate) { private val listeners = WindowListeners() override fun dispatchKeyEvent(event: KeyEvent?): Boolean { return if (event != null) { val iterator = listeners.keyEventInterceptors.iterator() val dispatch: (KeyEvent) -> DispatchState = object : (KeyEvent) -> DispatchState { override fun invoke(interceptedEvent: KeyEvent): DispatchState { return if (iterator.hasNext()) { val nextInterceptor = iterator.next() nextInterceptor.intercept(interceptedEvent, this) } else { DispatchState.from(delegate.dispatchKeyEvent(interceptedEvent)) } } } if (iterator.hasNext()) { val firstInterceptor = iterator.next() firstInterceptor.intercept(event, dispatch) } else { DispatchState.from(delegate.dispatchKeyEvent(event)) } is Consumed } else { delegate.dispatchKeyEvent(event) } } override fun dispatchTouchEvent(event: MotionEvent?): Boolean { return if (event != null) { val iterator = listeners.touchEventInterceptors.iterator() val dispatch: (MotionEvent) -> DispatchState = object : (MotionEvent) -> DispatchState { override fun invoke(interceptedEvent: MotionEvent): DispatchState { return if (iterator.hasNext()) { val nextInterceptor = iterator.next() nextInterceptor.intercept(interceptedEvent, this) } else { DispatchState.from(delegate.dispatchTouchEvent(interceptedEvent)) } } } if (iterator.hasNext()) { val firstInterceptor = iterator.next() firstInterceptor.intercept(event, dispatch) } else { DispatchState.from(delegate.dispatchTouchEvent(event)) } is Consumed } else { delegate.dispatchTouchEvent(event) } } override fun onContentChanged() { listeners.onContentChangedListeners.forEach { it.onContentChanged() } delegate.onContentChanged() } override fun onWindowFocusChanged(hasFocus: Boolean) { listeners.onWindowFocusChangedListeners.forEach { it.onWindowFocusChanged(hasFocus) } delegate.onWindowFocusChanged(hasFocus) } companion object { private val jetpackWrapperClass by lazy(NONE) { try { Class.forName("androidx.appcompat.view.WindowCallbackWrapper") } catch (ignored: Throwable) { try { Class.forName("android.support.v7.view.WindowCallbackWrapper") } catch (ignored: Throwable) { null } } } private val jetpackWrappedField by lazy(NONE) { jetpackWrapperClass?.let { jetpackWrapperClass -> try { jetpackWrapperClass.getDeclaredField("mWrapped").apply { isAccessible = true } } catch (ignored: Throwable) { null } } } private val (Window.Callback?).isJetpackWrapper: Boolean get() = jetpackWrapperClass?.isInstance(this) ?: false private val (Window.Callback?).jetpackWrapped: Window.Callback? get() = jetpackWrappedField!![this] as Window.Callback? /** * Note: Ideally this would be a map of Window to WindowCallbackWrapper, however * the values of a WeakHashMap are strongly held and the callback chain typically holds a * strong ref back to the window (e.g. Activity is a Callback). To prevent leaks, we keep * a weak ref to the callback. The callback weak ref won't be cleared too early as the callback * is also held as part of the window callback chain. */ private val callbackCache = WeakHashMap<Window, WeakReference<WindowCallbackWrapper>>() // window callback wrapper has a weak ref to window. keys have a weak ref to window. window // has a strong ref to callbacks. private val listenersLock = Any() val Window.listeners: WindowListeners get() { synchronized(listenersLock) { val existingWrapper = callbackCache[this]?.get() if (existingWrapper != null) { return existingWrapper.listeners } val currentCallback = callback return if (currentCallback == null) { // We expect a window to always have a default callback // that we can delegate to, but who knows what apps can be up to. WindowListeners() } else { val windowCallbackWrapper = WindowCallbackWrapper(currentCallback) callback = windowCallbackWrapper callbackCache[this] = WeakReference(windowCallbackWrapper) windowCallbackWrapper.listeners } } } tailrec fun Window.Callback?.unwrap(): Window.Callback? { return when { this == null -> null this is WindowCallbackWrapper -> delegate.unwrap() isJetpackWrapper -> jetpackWrapped.unwrap() else -> this } } } }
apache-2.0
6efa218ed6633682ea44997a944d1a64
33.025157
99
0.665188
5.026952
false
false
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/entity/EntityFields.kt
1
10347
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.sdibt.korm.core.entity import com.sdibt.korm.core.annotatoin.* import com.sdibt.korm.core.db.ColumnInfo import com.sdibt.korm.core.idworker.IdWorkerType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.Table import kotlin.reflect.jvm.javaType import kotlin.reflect.jvm.kotlinProperty /** * 存储实体类的全局字段信息,以一种更为方便的方式访问实体类属性和对应的表字段 */ class EntityFields { /** * 获取实体类对应的表字段名称数组 */ var fields: Array<String> = arrayOf() private set /** * 获取实体属性名称数组 */ var fieldNames: Array<String> = arrayOf() private set var fieldValues: Array<Any?> = arrayOf() private set var autoIdFields: Map<String, IdWorkerType> = mapOf() private set /** * 获取实体属性的类型 */ var fieldTypes: Array<Class<*>> = arrayOf() private set var tableName: String? = null var schema: String? = null //数据源如无特别说明,就取默认default var dataSource: String = "default" var createdBy: String? = null var createdAt: String? = null var updatedBy: String? = null var updatedAt: String? = null var deletedAt: String? = null var version: String? = null /** * SQL DDL columns info Map */ var columns: Map<String, ColumnInfo> = mapOf() /** * 初始化实体类信息,必须确保单线程调用本方法 * @param entity * * * * * @return */ constructor(entity: EntityBase) { val entityType = entity::class.java if (entityType.isAnnotationPresent(Table::class.java)) { val an = entityType.getAnnotation(Table::class.java) this.tableName = an.name this.schema = an.schema } if (entityType.isAnnotationPresent(DataSource::class.java)) { val an = entityType.getAnnotation(DataSource::class.java) this.dataSource = an.value } if (EntityBase::class.java.isAssignableFrom(entityType)) { fillFields(entityType) fillAutoIds(entityType) fillColumnInfo(entityType) } } /** * 获取属性名对应的字段名 * @param fieldName * * * * * @return */ fun getFieldName(fieldName: String): String? { return fieldNames.indices .firstOrNull { fieldNames[it] == fieldName } ?.let { fields[it] } } /** 采集Entity字段信息 * <功能详细描述> * @param clazz Class<*> * * @return Unit */ private fun fillFields(clazz: Class<*>) { val fieldNameList: MutableList<String> = mutableListOf() val fieldValueList: MutableList<Any?> = mutableListOf() val typeNameList: MutableList<Class<*>> = mutableListOf() clazz.declaredFields .filterNot { it.name == "\$\$delegatedProperties" } .forEach { val fieldName = it.kotlinProperty?.name ?: it.name.replace("\$delegate", "") when (it.type) { korm::class.java -> fieldNameList.add(fieldName) else -> fieldNameList.add(fieldName) } typeNameList.add(it.type) //todo根据类型设置初始值,int->0,boolean->false fieldValueList.add(null)//设置初始值 } fields = fieldNameList.toTypedArray() fieldNames = fieldNameList.toTypedArray() fieldTypes = typeNameList.toTypedArray() fieldValues = fieldValueList.toTypedArray() } /** 采集ID主机及其生成策略 * JPA规范中的主键策略当前版本默认替换未SnowFlake替代 * @param clazz Class<*> . * * @return Unit */ private fun fillAutoIds(clazz: Class<*>) { val autoIdFieldsList: MutableMap<String, IdWorkerType> = mutableMapOf() //寻找AutoID // JPA规范中@Id 几种主键生成策略的比较 // (1)sequence,identity 两种策略针对的是一些特殊的数据库 // (2)auto自动生成策略由JPA实现,对于比较简单的主键,对主键生成策略要求较少时,采用这种策略好 // (3)table生成策略是将主键的持久化在数据库中 // 本项目中均采用snowflake替代,可以解决分布式问题,解决数据迁移问题 clazz.declaredFields .filterNot { it.name == "\$\$delegatedProperties" } .forEach { val fieldName = it.kotlinProperty?.name ?: it.name.replace("\$delegate", "") when { it.isAnnotationPresent(AutoID::class.java) -> { autoIdFieldsList.put(fieldName, it.getAnnotation(AutoID::class.java).name) } it.isAnnotationPresent(Id::class.java) -> { //兼容jpa @Id注解 if (it.isAnnotationPresent(GeneratedValue::class.java)) { //有@GeneratedValue注解 when (it.getAnnotation(GeneratedValue::class.java).strategy) { GenerationType.AUTO -> autoIdFieldsList.put(fieldName, IdWorkerType.SnowFlake) else -> autoIdFieldsList.put(fieldName, IdWorkerType.SnowFlake) } } else { //没有生成策略,默认使用snowflake算法 autoIdFieldsList.put(fieldName, IdWorkerType.SnowFlake) } } it.isAnnotationPresent(DeletedAt::class.java) -> deletedAt = "deletedAt" it.isAnnotationPresent(CreatedBy::class.java) -> createdBy = "createdBy" it.isAnnotationPresent(CreatedAt::class.java) -> createdAt = "createdAt" it.isAnnotationPresent(UpdatedBy::class.java) -> updatedBy = "updatedBy" it.isAnnotationPresent(UpdatedAt::class.java) -> updatedAt = "updatedAt" it.isAnnotationPresent(Version::class.java) -> version = "version" } } autoIdFields = autoIdFieldsList.toMap() } /** 采集Column注解参数 * <功能详细描述> * @param clazz Class<*>. * * @return Unit */ private fun fillColumnInfo(clazz: Class<*>) { val columnMap: MutableMap<String, ColumnInfo> = mutableMapOf() clazz.declaredFields .filterNot { it.name == "\$\$delegatedProperties" } .forEach { val fieldName = it.kotlinProperty?.name ?: it.name.replace("\$delegate", "") //采集注释 var comment: String? = null if (it.isAnnotationPresent(Comment::class.java)) { comment = it.getAnnotation(Comment::class.java).value } var isPk = false if (it.isAnnotationPresent(AutoID::class.java) || it.isAnnotationPresent(Id::class.java)) { isPk = true } var defaultValue: String? = null if (it.isAnnotationPresent(DefaultValue::class.java)) { defaultValue = it.getAnnotation(DefaultValue::class.java).value } val type: Any = it.kotlinProperty?.returnType?.javaType ?: it.type var column: ColumnInfo if (it.isAnnotationPresent(javax.persistence.Column::class.java)) { //使用了column注解 val an = it.getAnnotation(javax.persistence.Column::class.java) column = ColumnInfo( name = an.name, unique = an.unique, nullable = an.nullable, insertable = an.insertable, updatable = an.updatable, columnDefinition = an.columnDefinition, table = an.table, length = an.length, precision = an.precision, scale = an.scale, type = type ) } else { column = ColumnInfo( name = fieldName, type = type ) } column.isPk = isPk column.comment = comment column.defaultValue = defaultValue columnMap.put(fieldName, column) } columns = columnMap.toMap() } }
apache-2.0
3f2cbf18aca1cb9b33e35e7c7425eb5a
33.430605
114
0.52062
4.763663
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/feature/main/MainState.kt
3
1898
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS 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 3 of the License, or * (at your option) any later version. * * QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.feature.main import com.moez.QKSMS.model.Conversation import com.moez.QKSMS.model.SearchResult import com.moez.QKSMS.repository.SyncRepository import io.realm.RealmResults data class MainState( val hasError: Boolean = false, val page: MainPage = Inbox(), val drawerOpen: Boolean = false, val upgraded: Boolean = true, val showRating: Boolean = false, val syncing: SyncRepository.SyncProgress = SyncRepository.SyncProgress.Idle, val defaultSms: Boolean = true, val smsPermission: Boolean = true, val contactPermission: Boolean = true ) sealed class MainPage data class Inbox( val addContact: Boolean = false, val markPinned: Boolean = true, val markRead: Boolean = false, val data: RealmResults<Conversation>? = null, val selected: Int = 0 ) : MainPage() data class Searching( val loading: Boolean = false, val data: List<SearchResult>? = null ) : MainPage() data class Archived( val addContact: Boolean = false, val markPinned: Boolean = true, val markRead: Boolean = false, val data: RealmResults<Conversation>? = null, val selected: Int = 0 ) : MainPage()
gpl-3.0
79ced1cf5c0be496ff5460e7dee52d1e
31.169492
80
0.718651
3.987395
false
false
false
false
SirWellington/alchemy-http
src/main/java/tech/sirwellington/alchemy/http/HttpConnectionPreparer.kt
1
3776
/* * Copyright © 2019. Sir Wellington. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.sirwellington.alchemy.http import io.mikael.urlbuilder.UrlBuilder import org.slf4j.LoggerFactory import tech.sirwellington.alchemy.annotations.access.Internal import tech.sirwellington.alchemy.annotations.arguments.Required import tech.sirwellington.alchemy.annotations.designs.patterns.FactoryMethodPattern import tech.sirwellington.alchemy.annotations.designs.patterns.FactoryMethodPattern.Role.FACTORY_METHOD import tech.sirwellington.alchemy.annotations.designs.patterns.FactoryMethodPattern.Role.PRODUCT import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern.Role import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern.Role.INTERFACE import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.http.HttpAssertions.validRequest import tech.sirwellington.alchemy.http.exceptions.AlchemyHttpException import tech.sirwellington.alchemy.http.exceptions.OperationFailedException import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URISyntaxException import java.net.URL /** * * @author SirWellington */ @StrategyPattern(role = INTERFACE) @Internal internal interface HttpConnectionPreparer { fun map(request: HttpRequest) : HttpURLConnection companion object { @Throws(AlchemyHttpException::class, URISyntaxException::class, MalformedURLException::class) fun expandUrlFromRequest(@Required request: HttpRequest): URL { checkThat(request).isA(validRequest()) val url = request.url ?: throw OperationFailedException("request is missing URL") return if (!request.hasQueryParams()) { url } else { var uriBuilder = UrlBuilder.fromUrl(url) request.queryParams?. forEach { param, value -> uriBuilder = uriBuilder.addParameter(param, value) } uriBuilder.toUrl() } } @FactoryMethodPattern(role = FACTORY_METHOD) fun create(): HttpConnectionPreparer { return HttpConnectionPreparerImpl } } } @FactoryMethodPattern(role = PRODUCT) @StrategyPattern(role = Role.CONCRETE_BEHAVIOR) private object HttpConnectionPreparerImpl : HttpConnectionPreparer { private val LOG = LoggerFactory.getLogger(this::class.java) override fun map(request: HttpRequest): HttpURLConnection { val url = HttpConnectionPreparer.expandUrlFromRequest(request) val connection = url.openConnection() val http = connection as? HttpURLConnection ?: throw OperationFailedException("URL is not an HTTP URL: [$url]") http.requestMethod = request.method.asString http.doInput = true if (request.hasBody()) { http.doOutput = true } request.requestHeaders?.onEach { (key, value) -> http.setRequestProperty(key, value) } return http } }
apache-2.0
5727987e6d9c72804b63ac2e9f0f60bf
33.018018
119
0.713377
4.845956
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/sorter/RankSorter.kt
1
1831
package com.boardgamegeek.sorter import android.content.Context import android.util.SparseArray import androidx.annotation.StringRes import com.boardgamegeek.R import com.boardgamegeek.entities.CollectionItemEntity import java.text.NumberFormat class RankSorter(context: Context) : CollectionSorter(context) { private val defaultHeaderText = context.resources.getString(R.string.unranked) private val defaultText = context.resources.getString(R.string.text_not_available) @StringRes public override val typeResId = R.string.collection_sort_type_rank @StringRes override val descriptionResId = R.string.collection_sort_rank override fun sort(items: Iterable<CollectionItemEntity>) = items.sortedBy { it.rank } override fun getHeaderText(item: CollectionItemEntity): String { return (0 until ranks.size()) .map { ranks.keyAt(it) } .firstOrNull { item.rank <= it } ?.let { ranks.get(it) } ?: defaultHeaderText } override fun getDisplayInfo(item: CollectionItemEntity): String { return if (item.rank == CollectionItemEntity.RANK_UNKNOWN) { defaultText } else NumberFormat.getIntegerInstance().format(item.rank) } companion object { private val ranks = buildRanks() private fun buildRanks(): SparseArray<String> { val rankSteps = listOf(100, 250, 500, 1000, 2500, 5000, 10000) val ranks = SparseArray<String>() for (i in rankSteps.indices) { ranks.put(rankSteps[i], String.format("%,d - %,d", (rankSteps.getOrElse(i - 1) { 0 }) + 1, rankSteps[i])) } ranks.put(CollectionItemEntity.RANK_UNKNOWN - 1, String.format("%,d+", rankSteps.last() + 1)) return ranks } } }
gpl-3.0
6fd28667d31a7ec55bde7ee5413514b9
36.367347
121
0.659749
4.288056
false
false
false
false
simo-andreev/Colourizmus
app/src/main/java/bg/o/sim/colourizmus/model/LiveColour.kt
1
1716
package bg.o.sim.colourizmus.model import androidx.lifecycle.LiveData import android.graphics.Color import java.util.* /** * An implementation of the [LiveData] class, made for storing a single colour. * Intended for the ColourCreation fragments of the [bg.o.sim.colourizmus.view.ColourCreationActivity]. * It should allow a more efficient synchronisation of the current value, than the old Communicator system, * due to the Lifecycle awareness of the LiveData type. */ class LiveColour : LiveData<Int>() { init { val r = Random() value = Color.rgb(r.nextInt(256), r.nextInt(256), r.nextInt(256)) } fun getRed() = Color.red(value!!) fun getGreen() = Color.green(value!!) fun getBlue() = Color.blue(value!!) // necessary for Java inter-op. Can't use @JvmOverloads because all params are Ints with default val fun setRed(red: Int) { value = Color.rgb(red, getGreen(), getBlue()) } fun setGreen(green: Int) { value = Color.rgb(getRed(), green, getBlue()) } fun setBlue(blue: Int) { value = Color.rgb(getRed(), getGreen(), blue) } val r = getRed() val g = getGreen() val b = getBlue() val rgb = arrayOf(r, g, b) fun set(red: Int = getRed(), green: Int = getGreen(), blue: Int = getBlue()) { value = Color.rgb(red, green, blue) } fun set(rgb: Array<Int>) { if (rgb.size != 3) throw IllegalArgumentException("The rgb array MUST contain EXACTLY 3 items " + "for red, green and blue respectively. Passed array was : ${rgb.fold("") { acc, i -> "$acc, $i" }}.") value = Color.rgb(rgb[0],rgb[1],rgb[2]) } fun set(liveColour: LiveColour){ this.value = liveColour.value } }
apache-2.0
e6ce956330826c0caca3a969aaca5b09
34.040816
117
0.643357
3.605042
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/retry/RetryPolicy.kt
1
3179
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * 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 debop4k.core.retry import debop4k.core.loggerOf /** * RetryPolicy * @author debop [email protected] */ open class RetryPolicy @JvmOverloads constructor(val maxRetries: Int = Int.MAX_VALUE, val retryOn: Set<Class<out Throwable>> = emptySet(), val abortOn: Set<Class<out Throwable>> = emptySet(), val retryPredicate: (Throwable?) -> Boolean = { false }, val abortPredicate: (Throwable?) -> Boolean = { false }) { private val log = loggerOf(javaClass) companion object { @JvmField val DEFAULT: RetryPolicy = RetryPolicy() private fun matches(exception: Class<out Throwable>, set: Set<Class<out Throwable>>): Boolean = set.isEmpty() || set.any { it.isAssignableFrom(exception) } } fun retryOn(vararg retryOnExceptions: Class<out Throwable>): RetryPolicy { val retries = retryOn + retryOnExceptions return RetryPolicy(maxRetries, retries, abortOn, retryPredicate, abortPredicate) } fun abortOn(vararg abortOnExceptions: Class<out Throwable>): RetryPolicy { val aborts = abortOn + abortOnExceptions log.debug("add abortOn. aborts={}", aborts) return RetryPolicy(maxRetries, retryOn, aborts, retryPredicate, abortPredicate) } fun retryIf(retryPredicate: (Throwable?) -> Boolean): RetryPolicy = RetryPolicy(maxRetries, retryOn, abortOn, retryPredicate, abortPredicate) fun abortIf(abortPredicate: (Throwable?) -> Boolean): RetryPolicy = RetryPolicy(maxRetries, retryOn, abortOn, retryPredicate, abortPredicate) fun dontRetry(): RetryPolicy = RetryPolicy(0, retryOn, abortOn, retryPredicate, abortPredicate) fun withMaxRetry(times: Int): RetryPolicy = RetryPolicy(times, retryOn, abortOn, retryPredicate, abortPredicate) fun shouldContinue(context: RetryContext): Boolean { if (tooManyRetries(context)) { return false } if (abortPredicate(context.lastThrowable)) { return false } if (retryPredicate(context.lastThrowable)) { return true } return exceptionClassRetryable(context) } private fun tooManyRetries(context: RetryContext): Boolean = context.retryCount > maxRetries private fun exceptionClassRetryable(context: RetryContext): Boolean { if (context.lastThrowable == null) return false val e = context.lastThrowable!!.javaClass if (abortOn.isEmpty()) { return matches(e, retryOn) } return !matches(e, abortOn) && matches(e, retryOn) } }
apache-2.0
af5c284118ad0749ab832eedfdd1c84a
33.193548
97
0.696131
4.336971
false
false
false
false
21Buttons/sticky-headers
sample/src/main/java/com/a21buttons/stickyheaders/sample/DataSetChanged.kt
1
2153
package com.a21buttons.stickyheaders.sample import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.a21buttons.stickyheaders.StickyHeaderAdapter import com.a21buttons.stickyheaders.StickyHeaderLayoutManager import com.a21buttons.stickyheaders.StickyHeaderViewHolder class DataSetChanged : AppCompatActivity() { companion object { fun getCallingIntent(context: Context) = Intent(context, DataSetChanged::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.recycler_view) val recyclerView: RecyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = StickyHeaderLayoutManager() recyclerView.adapter = Adapter(layoutInflater) } class Adapter(val inflater: LayoutInflater) : StickyHeaderAdapter<Adapter.ViewHolder>() { private var list: MutableList<Int> = MutableList(100, { 0 }) override fun getItemCount() = list.count() override fun onCreateViewHolder2(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(inflater.inflate(R.layout.item, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int, sectionId: Long) { holder.bind("Update ${list[position]}\tPosition $position\tSection $sectionId", this) } override fun getSectionId(position: Int) = (position / 2).toLong() override fun getHeaderPosition(sectionId: Long) = (sectionId * 2).toInt() fun update() { list = list.map { it + 1 } .toMutableList() notifyDataSetChanged() } class ViewHolder(val v: View) : StickyHeaderViewHolder(v) { fun bind(s: String, adapter: Adapter) { val view: View = v.findViewById(R.id.text1) if (view is TextView) { view.text = s } v.setOnClickListener { adapter.update() } } } } }
apache-2.0
eeb28a8b8cd2205f7c5536e4d464ed47
31.621212
91
0.725499
4.430041
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/itemcompoundproducer/ItemCompoundProducerEntity.kt
1
7192
package net.ndrei.teslapoweredthingies.machines.itemcompoundproducer import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.item.EnumDyeColor import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraftforge.common.util.Constants import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fluids.IFluidTank import net.minecraftforge.items.ItemStackHandler import net.ndrei.teslacorelib.gui.BasicRenderedGuiPiece import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.gui.IGuiContainerPiece import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.ColoredItemHandler import net.ndrei.teslacorelib.inventory.FluidTankType import net.ndrei.teslacorelib.inventory.LockableItemHandler import net.ndrei.teslacorelib.utils.insertItems import net.ndrei.teslapoweredthingies.client.ThingiesTexture import net.ndrei.teslapoweredthingies.common.gui.* import net.ndrei.teslapoweredthingies.machines.BaseThingyMachine import net.ndrei.teslapoweredthingies.render.DualTankEntityRenderer /** * Created by CF on 2017-07-13. */ class ItemCompoundProducerEntity : BaseThingyMachine(ItemCompoundProducerEntity::class.java.name.hashCode()), IMultiTankMachine { private lateinit var inputItems: LockableItemHandler private lateinit var inputFluid: IFluidTank private lateinit var outputs: ItemStackHandler private var currentStack: ItemStack = ItemStack.EMPTY private var currentFluid: FluidStack? = null //#region inventory and gui methods override fun initializeInventories() { super.initializeInventories() this.inputItems = object: LockableItemHandler(3) { override fun onContentsChanged(slot: Int) { [email protected]() } } this.addInventory(object : ColoredItemHandler(this.inputItems, EnumDyeColor.GREEN, "Input Items", BoundingRectangle(88, 25, 18, 54)) { override fun canExtractItem(slot: Int) = false override fun canInsertItem(slot: Int, stack: ItemStack) = super.canInsertItem(slot, stack) && !stack.isEmpty && ItemCompoundProducerRegistry.hasRecipe(stack) }) this.addInventoryToStorage(this.inputItems, "inv_inputs") this.inputFluid = this.addSimpleFluidTank(5000, "Fluid Tank", EnumDyeColor.BLUE, 70, 25, FluidTankType.INPUT, { ItemCompoundProducerRegistry.hasRecipe(it) }) this.outputs = object: ItemStackHandler(6) { override fun onContentsChanged(slot: Int) { [email protected]() } } this.addInventory(object : ColoredItemHandler(this.outputs, EnumDyeColor.PURPLE, "Output Items", BoundingRectangle(133, 25, 36, 54)) { override fun canInsertItem(slot: Int, stack: ItemStack) = false }) this.addInventoryToStorage(this.outputs, "inv_outputs") } override val fluidItemsBoundingBox: BoundingRectangle get() = BoundingRectangle(52, 25, 18, 54) override fun addFluidItemsBackground(pieces: MutableList<IGuiContainerPiece>, box: BoundingRectangle) { pieces.add(BasicRenderedGuiPiece(box.left, box.top, 18, 54, ThingiesTexture.MACHINES_TEXTURES.resource, 6, 44)) } override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> { val list = super.getGuiContainerPieces(container) list.add(BasicRenderedGuiPiece(106, 32, 27, 40, ThingiesTexture.MACHINES_TEXTURES.resource, 66, 86)) list.add(FluidDisplayPiece(108, 42, 20, 20, { this.currentFluid })) list.add(ItemStackPiece(108, 42, 20, 20, object: IWorkItemProvider { override val workItem: ItemStack get() = [email protected] }, .75f)) return list } override fun getRenderers(): MutableList<TileEntitySpecialRenderer<in TileEntity>> { val list = super.getRenderers() list.add(DualTankEntityRenderer) return list } override fun getTanks() = listOf(TankInfo(13.0, 4.0, this.inputFluid.fluid, this.inputFluid.capacity)) //#endregion //#region storage override fun readFromNBT(compound: NBTTagCompound) { super.readFromNBT(compound) this.currentStack = if (compound.hasKey("current_stack", Constants.NBT.TAG_COMPOUND)) ItemStack(compound.getCompoundTag("current_stack")) else ItemStack.EMPTY this.currentFluid = if (compound.hasKey("current_fluid", Constants.NBT.TAG_COMPOUND)) FluidStack.loadFluidStackFromNBT(compound.getCompoundTag("current_fluid")) else null } override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound { if (!this.currentStack.isEmpty) { compound.setTag("current_stack", this.currentStack.writeToNBT(NBTTagCompound())) } if (this.currentFluid != null) { compound.setTag("current_fluid", this.currentFluid!!.writeToNBT(NBTTagCompound())) } return super.writeToNBT(compound) } //#endregion override fun processImmediateInventories() { super.processImmediateInventories() if (this.currentStack.isEmpty) { val fluid = this.inputFluid.fluid if ((fluid != null) && (fluid.amount > 0)) { for(slot in 0 until this.inputItems.slots) { val stack = this.inputItems.getStackInSlot(slot) if (!stack.isEmpty) { val recipe = ItemCompoundProducerRegistry.findRecipe(fluid, stack) ?: continue val drained = this.inputFluid.drain(recipe.inputFluid.amount, false) ?: continue val taken = this.inputItems.extractItem(slot, recipe.inputStack.count, true) if ((drained.amount == recipe.inputFluid.amount) && (taken.count == recipe.inputStack.count)) { this.currentFluid = this.inputFluid.drain(recipe.inputFluid.amount, true) this.currentStack = this.inputItems.extractItem(slot, recipe.inputStack.count, false) break } } } } } } override fun performWork(): Float { var result = 0.0f if (!this.currentStack.isEmpty && (this.currentFluid != null)) { val recipe = ItemCompoundProducerRegistry.findRecipe(this.currentFluid!!, this.currentStack) ?: return result val remaining = this.outputs.insertItems(recipe.result.copy(), true) if (remaining.isEmpty) { this.outputs.insertItems(recipe.result.copy(), false) this.currentFluid = null this.currentStack = ItemStack.EMPTY result = 1.0f } } return result } }
mit
2d9896c086a67ad3c2d72b8db8d3f545
40.572254
142
0.671997
4.722259
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/app/view/HistogramView.kt
1
6281
/* Copyright 2015 Andreas Würl 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 org.blitzortung.android.app.view import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.util.Log import android.view.View import org.blitzortung.android.app.Main import org.blitzortung.android.app.R import org.blitzortung.android.data.provider.result.ResultEvent import org.blitzortung.android.map.overlay.StrikesOverlay import org.blitzortung.android.protocol.Event import org.blitzortung.android.util.TabletAwareView class HistogramView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : TabletAwareView(context, attrs, defStyle) { private val backgroundPaint: Paint private val foregroundPaint: Paint private val textPaint: Paint private val defaultForegroundColor: Int private val backgroundRect: RectF private var strikesOverlay: StrikesOverlay? = null private var histogram: IntArray? = null val dataConsumer = { event: Event -> if (event is ResultEvent) { updateHistogram(event) } } init { foregroundPaint = Paint(Paint.ANTI_ALIAS_FLAG) backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG) backgroundPaint.color = context.resources.getColor(R.color.translucent_background) defaultForegroundColor = context.resources.getColor(R.color.text_foreground) textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = defaultForegroundColor textSize = [email protected] textAlign = Paint.Align.RIGHT } backgroundRect = RectF() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val getSize = fun(spec: Int) = View.MeasureSpec.getSize(spec) val parentWidth = getSize(widthMeasureSpec) * sizeFactor val parentHeight = getSize(heightMeasureSpec) * sizeFactor super.onMeasure(View.MeasureSpec.makeMeasureSpec(parentWidth.toInt(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(parentHeight.toInt(), View.MeasureSpec.EXACTLY)) } override fun onDraw(canvas: Canvas) { val strikesOverlay = strikesOverlay val histogram = histogram if (strikesOverlay != null && histogram != null && histogram.size > 0) { val colorHandler = strikesOverlay.getColorHandler() val minutesPerColor = strikesOverlay.parameters.intervalDuration / colorHandler.numberOfColors val minutesPerBin = 5 val ratio = minutesPerColor / minutesPerBin if (ratio == 0) { return } backgroundRect.set(0f, 0f, width.toFloat(), height.toFloat()) canvas.drawRect(backgroundRect, backgroundPaint) val maximumCount = histogram.max() ?: 0 canvas.drawText("%.1f/min _".format(maximumCount.toFloat() / minutesPerBin), width - 2 * padding, padding + textSize / 1.2f, textPaint) val ymax = if (maximumCount == 0) 1 else maximumCount val x0 = padding val xd = (width - 2 * padding) / (histogram.size - 1) val y0 = height - padding val yd = (height - 2 * padding - textSize) / ymax foregroundPaint.strokeWidth = 2f for (i in 0..histogram.size - 1 - 1) { foregroundPaint.color = colorHandler.getColor((histogram.size - 1 - i) / ratio) canvas.drawLine(x0 + xd * i, y0 - yd * histogram[i], x0 + xd * (i + 1), y0 - yd * histogram[i + 1], foregroundPaint) } foregroundPaint.strokeWidth = 1f foregroundPaint.color = defaultForegroundColor canvas.drawLine(padding, height - padding, width - padding, height - padding, foregroundPaint) canvas.drawLine(width - padding, padding, width - padding, height - padding, foregroundPaint) } } fun setStrikesOverlay(strikesOverlay: StrikesOverlay) { this.strikesOverlay = strikesOverlay } private fun updateHistogram(dataEvent: ResultEvent) { if (dataEvent.failed) { visibility = View.INVISIBLE histogram = null } else { val histogram = dataEvent.histogram var viewShouldBeVisible = histogram != null && histogram.size > 0 this.histogram = histogram if (!viewShouldBeVisible) { viewShouldBeVisible = createHistogram(dataEvent) } visibility = if (viewShouldBeVisible) View.VISIBLE else View.INVISIBLE if (viewShouldBeVisible) { invalidate() } } } private fun createHistogram(result: ResultEvent): Boolean { result.parameters?.let { parameters -> if (result.totalStrikes == null) { return false } Log.v(Main.LOG_TAG, "HistogramView create histogram from ${result.totalStrikes.size} total strikes") val referenceTime = result.referenceTime val binInterval = 5 val binCount = parameters.intervalDuration / binInterval val histogram = IntArray(binCount) result.totalStrikes.forEach { strike -> val binIndex = (binCount - 1) - ((referenceTime - strike.timestamp) / 1000 / 60 / binInterval).toInt() if (binIndex in 0 .. binCount - 1) histogram[binIndex]++ } this.histogram = histogram return true } return false } } data class Strike(val timestamp: Long)
apache-2.0
ee150dd3ce9ca5e8153c7068c63c4104
35.091954
147
0.646815
4.707646
false
false
false
false
LachlanMcKee/gsonpath
compiler/standard/src/main/java/gsonpath/adapter/standard/model/FieldPathFetcher.kt
1
1601
package gsonpath.adapter.standard.model import gsonpath.model.FieldInfo import gsonpath.util.FieldNamingPolicyMapper class FieldPathFetcher( private val serializedNameFetcher: SerializedNameFetcher, private val fieldNamingPolicyMapper: FieldNamingPolicyMapper) { fun getJsonFieldPath(fieldInfo: FieldInfo, metadata: GsonObjectMetadata): FieldPath { val serializedName = serializedNameFetcher.getSerializedName(fieldInfo, metadata.flattenDelimiter) val path = if (serializedName != null && serializedName.isNotBlank()) { if (metadata.pathSubstitutions.isNotEmpty()) { // Check if the serialized name needs any values to be substituted metadata.pathSubstitutions.fold(serializedName) { fieldPath, substitution -> fieldPath.replace("{${substitution.original}}", substitution.replacement) } } else { serializedName } } else { // Since the serialized annotation wasn't specified, we need to apply the naming policy instead. fieldNamingPolicyMapper.applyFieldNamingPolicy(metadata.gsonFieldNamingPolicy, fieldInfo.fieldName) } return if (path.contains(metadata.flattenDelimiter)) { FieldPath.Nested( if (path.last() == metadata.flattenDelimiter) { path + fieldInfo.fieldName } else { path } ) } else { FieldPath.Standard(path) } } }
mit
268e97379c98c5dcad253986a4c570ff
38.073171
111
0.622111
5.637324
false
false
false
false
nemerosa/ontrack
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/listener/AsyncEventListeningQueueListener.kt
1
3503
package net.nemerosa.ontrack.extension.notifications.listener import io.micrometer.core.instrument.MeterRegistry import net.nemerosa.ontrack.extension.notifications.metrics.NotificationsMetrics import net.nemerosa.ontrack.extension.notifications.metrics.incrementForEvent import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.json.parseAsJson import net.nemerosa.ontrack.model.events.EventFactory import net.nemerosa.ontrack.model.metrics.increment import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.structure.StructureService import net.nemerosa.ontrack.model.support.ApplicationLogEntry import net.nemerosa.ontrack.model.support.ApplicationLogService import org.springframework.amqp.core.Message import org.springframework.amqp.core.MessageListener import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer import org.springframework.amqp.rabbit.config.SimpleRabbitListenerEndpoint import org.springframework.amqp.rabbit.listener.RabbitListenerEndpoint import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar import org.springframework.stereotype.Component @Component class AsyncEventListeningQueueListener( private val eventFactory: EventFactory, private val structureService: StructureService, private val securityService: SecurityService, private val eventListeningService: EventListeningService, private val applicationLogService: ApplicationLogService, private val meterRegistry: MeterRegistry, ) : RabbitListenerConfigurer { override fun configureRabbitListeners(registrar: RabbitListenerEndpointRegistrar) { registrar.registerEndpoint( createDefaultListener(), ) } private fun createDefaultListener(): RabbitListenerEndpoint { val queue = "${AsyncEventListeningQueueConfig.QUEUE_PREFIX}.${AsyncEventListeningQueueConfig.DEFAULT}" return SimpleRabbitListenerEndpoint().configure(queue) } private val listener = MessageListener(::onMessage) private fun SimpleRabbitListenerEndpoint.configure( queue: String, ): SimpleRabbitListenerEndpoint { id = queue setQueueNames(queue) concurrency = "1-1" // No concurrency, we want the events to be processed in turn messageListener = listener return this } private fun onMessage(message: Message) { try { val body = message.body.toString(Charsets.UTF_8) val payload = body.parseAsJson().parse<AsyncEventListeningQueueEvent>() securityService.asAdmin(Runnable { val event = payload.toEvent(eventFactory, structureService) meterRegistry.incrementForEvent( NotificationsMetrics.event_listening_dequeued, event ) eventListeningService.onEvent(event) }) } catch (any: Throwable) { meterRegistry.increment( NotificationsMetrics.event_listening_dequeued_error ) applicationLogService.log( ApplicationLogEntry.error( any, NameDescription.nd("notifications-dispatching-error", "Catch-all error in notifications dispatching"), "Uncaught error during the notifications dispatching" ) ) } } }
mit
1180817642af063e9464b3d9409c4fe9
41.216867
110
0.728233
5.299546
false
true
false
false
aglne/mycollab
mycollab-services/src/main/java/com/mycollab/module/project/domain/criteria/ProjectMemberSearchCriteria.kt
3
1420
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.project.domain.criteria import com.mycollab.db.arguments.NumberSearchField import com.mycollab.db.arguments.SearchCriteria import com.mycollab.db.arguments.SetSearchField import com.mycollab.db.arguments.StringSearchField /** * @author MyCollab Ltd. * @since 1.0 */ class ProjectMemberSearchCriteria(var projectIds: SetSearchField<Int>? = null, var id: NumberSearchField? = null, var statuses: SetSearchField<String>? = null, var involvedMember: StringSearchField? = null, var memberFullName: StringSearchField? = null) : SearchCriteria()
agpl-3.0
3f866a26ed9c6d1f54b3cc2d0cfcdfdf
43.34375
99
0.694151
4.577419
false
false
false
false
xiaojinzi123/Component
ComponentImpl/src/main/java/com/xiaojinzi/component/support/SingletonCallable.kt
1
738
package com.xiaojinzi.component.support import com.xiaojinzi.component.anno.support.CheckClassNameAnno /** * 单例服务,这是注册服务默认的形式 */ @CheckClassNameAnno abstract class SingletonCallable<T> : Callable<T> { @Volatile private var instance: T? = null val isInit: Boolean get() = instance != null /** * 获取真正的对象 */ protected abstract val raw: T override fun get(): T { if (null == instance) { synchronized(this) { if (null == instance) { instance = raw } } } return instance!! } @Synchronized fun destroy() { instance = null } }
apache-2.0
a5878d7dfb36fa9883af2232fdccf1c1
17.289474
62
0.540346
4.231707
false
false
false
false
Ztiany/Repository
Java/Java-Socket/src/main/kotlin/me/ztiany/socket/tcp/Client.kt
2
1580
package me.ztiany.socket.tcp import java.io.BufferedReader import java.io.BufferedWriter import java.io.InputStreamReader import java.io.OutputStreamWriter import java.net.Socket import java.util.* import kotlin.concurrent.thread /** 客户端 */ fun main(args: Array<String>) { // 建立客户端 并制定连接的服务端 val socket = Socket("192.168.43.213", 10338) // 键盘录入 val scanner = Scanner(System.`in`) // 获取Socket 流的输出流 val outputStream = socket.getOutputStream() val bufferedWriter = BufferedWriter(OutputStreamWriter(outputStream)) // 获取Socket流 的 读取流 val inputStream = socket.getInputStream() val serverReader = BufferedReader(InputStreamReader(inputStream)) thread { readServerData(serverReader) } var line: String? = scanner.nextLine() while (line != null) { if ("over" == line) { //告诉服务器写完毕 // socket.shutdownOutput() break } bufferedWriter.write(line) bufferedWriter.newLine() bufferedWriter.flush() line = scanner.nextLine() } bufferedWriter.close() socket.close() } private fun readServerData(serverReader: BufferedReader) { try { var string: String? = serverReader.readLine() while (string != null) { println("收到服务端数据: $string") string = serverReader.readLine() } } catch (e: Exception) { //e.printStackTrace() } finally { serverReader.close() } }
apache-2.0
d5a8396b71ad4efe0afdd00ed7dabd27
22.09375
73
0.636671
4.06044
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/utils/Test3BitmapDecodeInterceptor.kt
1
1441
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.utils import com.github.panpf.sketch.decode.BitmapDecodeInterceptor import com.github.panpf.sketch.decode.BitmapDecodeResult class Test3BitmapDecodeInterceptor : BitmapDecodeInterceptor { override val key: String = "Test3BitmapDecodeInterceptor" override val sortWeight: Int = 0 override suspend fun intercept(chain: BitmapDecodeInterceptor.Chain): BitmapDecodeResult { return chain.proceed() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return true } override fun hashCode(): Int { return javaClass.hashCode() } override fun toString(): String { return "Test3BitmapDecodeInterceptor(sortWeight=$sortWeight)" } }
apache-2.0
a33570590c97a38420cb7b53fdc53d6b
32.534884
94
0.724497
4.517241
false
true
false
false
Cleverdesk/cleverdesk
src/main/java/net/cleverdesk/cleverdesk/web/http/Authentication.kt
1
3081
/** * This program 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 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package net.cleverdesk.cleverdesk.web.http import io.jsonwebtoken.JwtException import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import io.jsonwebtoken.impl.crypto.MacProvider import net.cleverdesk.cleverdesk.User import net.cleverdesk.cleverdesk.launcher.Launcher import org.apache.commons.lang3.time.DateUtils import java.util.* /** * Created by schulerlabor on 21.06.16. */ open class Authentication(launcher: Launcher) { private final val apiKey = MacProvider.generateKey() private final val launcher = launcher fun generateToken(username: String, password: String, liftime_seconds: Int): String { val user: User = User(launcher) user.username = username if (launcher.database == null) { throw AuthenticationException("Internal error") } launcher.database!!.download(user, user) if (user.password == null || user.password != hashPassword(password)) { throw AuthenticationException("Incorrect credentials") } val alg: SignatureAlgorithm = SignatureAlgorithm.HS256 val exp: Date = DateUtils.addSeconds(Date(), liftime_seconds) return Jwts.builder() .setId(user.uuid) .signWith(alg, apiKey) .setNotBefore(Date()) .setExpiration(exp) .setSubject(user.password) .compact() } fun authUser(token: String): User { try { val claims = Jwts.parser().setSigningKey(apiKey).parseClaimsJws(token).body val uuid = claims.id val user: User = User(launcher) user.uuid = uuid if (launcher.database == null) { throw AuthenticationException("Internal error") } launcher.database!!.download(user, user) if (user.password != claims.subject) { throw AuthenticationException("Invalid token") } return user } catch(e: JwtException) { throw AuthenticationException("Invalid token") } } private fun hashPassword(password: String): String { return password } } class AuthenticationException(override val message: String?) : Exception() { } class AuthRequest() { public var username: String? = null public var password: String? = null public var lifetime: Int? = null }
gpl-3.0
2060c76bdfb579237225897050dae39c
30.131313
89
0.654982
4.49781
false
false
false
false
AkshayChordiya/gofun-android
app/src/main/java/com/adityakamble49/ttl/ui/activity/RegisterActivity.kt
1
3671
package com.adityakamble49.ttl.ui.activity import android.app.Activity import android.content.Intent import android.os.AsyncTask import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View.GONE import android.view.View.VISIBLE import android.widget.Toast import com.adityakamble49.ttl.R import com.adityakamble49.ttl.api.RegisterService import com.adityakamble49.ttl.model.Token import com.adityakamble49.ttl.utils.NetworkUtils import com.adityakamble49.ttl.utils.isNotEmail import com.adityakamble49.ttl.utils.setToken import kotlinx.android.synthetic.main.activity_register.* import me.pushy.sdk.Pushy import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * @author Akshay Chordiya * @since 3/3/2017. */ class RegisterActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) register_button.setOnClickListener { doRegister() } go_to_login.setOnClickListener { startActivity(Intent(baseContext, LoginActivity::class.java)) finish() } } fun doRegister() { val email = register_email.text.toString() val password = register_password.text.toString() val confirmPassword = register_password_confirm.text.toString() if (email.isEmpty() || email.isNotEmail()) { register_email_layout.error = getString(R.string.invalid_email_address) return } if (password.isEmpty()) { register_password_layout.error = getString(R.string.invalid_password) return } if (password != confirmPassword) { register_password_confirm_layout.error = getString(R.string.invalid_confirm_password) return } register_form.visibility = GONE register_progress.visibility = VISIBLE RegisterForPushNotifications().execute() } private inner class RegisterForPushNotifications : AsyncTask<Void, Void, String>() { override fun doInBackground(vararg params: Void): String? { try { return Pushy.register(baseContext) } catch (exc: Exception) { exc.printStackTrace() } // Success return null } override fun onPostExecute(deviceId: String?) { if (deviceId != null) { val email = register_email.text val password = register_password.text val registerService = NetworkUtils.retrofit.create(RegisterService::class.java) val register = registerService.register(email.toString(), email.toString(), password.toString(), deviceId) register.enqueue(object : Callback<Token> { override fun onResponse(call: Call<Token>?, response: Response<Token>?) { if (response != null) { setToken(baseContext, response.body().token) startActivity(Intent(baseContext, MainActivity::class.java)) finish() } else { Toast.makeText(baseContext, getString(R.string.login_failed), Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<Token>?, t: Throwable?) { Toast.makeText(baseContext, getString(R.string.login_failed), Toast.LENGTH_SHORT).show() } }) } } } }
mit
befee59666e557e68f54f3ce2ef931a4
35.71
122
0.620539
4.843008
false
false
false
false
Popalay/Cardme
presentation/src/main/kotlin/com/popalay/cardme/utils/recycler/SpacingItemDecoration.kt
1
2664
package com.popalay.cardme.utils.recycler import android.graphics.Rect import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.OrientationHelper import android.support.v7.widget.RecyclerView import android.view.View class SpacingItemDecoration private constructor( private val betweenItems: Boolean, private val onSides: Boolean, private val onTop: Boolean, private val dividerSize: Int ) : RecyclerView.ItemDecoration() { companion object { fun create(init: Builder.() -> Unit) = Builder(init).build() } private constructor(builder: Builder) : this(builder.showBetween, builder.showOnSides, builder.onTop, builder.dividerSize) private var orientation = -1 override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) val position = parent.getChildLayoutPosition(view) if (position == RecyclerView.NO_POSITION) return getOrientation(parent) if (orientation == OrientationHelper.HORIZONTAL) { applyToHorizontalList(outRect) } else { applyToVerticalList(outRect) } } private fun applyToVerticalList(outRect: Rect) { if (betweenItems) { outRect.top = if (onTop) dividerSize / 2 else 0 outRect.bottom = dividerSize / 2 } if (onSides) { outRect.left = dividerSize outRect.right = dividerSize } } private fun applyToHorizontalList(outRect: Rect) { if (betweenItems) { outRect.left = dividerSize / 2 outRect.right = dividerSize / 2 } if (onSides) { outRect.top = if (onTop) dividerSize else 0 outRect.bottom = dividerSize } } private fun getOrientation(parent: RecyclerView) { if (orientation != -1) return if (parent.layoutManager is LinearLayoutManager) { val layoutManager = parent.layoutManager as LinearLayoutManager orientation = layoutManager.orientation } else { throw IllegalStateException("SpacingItemDecoration can only be used with a LinearLayoutManager.") } } class Builder private constructor() { constructor(init: Builder.() -> Unit) : this() { init() } var showBetween: Boolean = false var showOnSides: Boolean = false var onTop: Boolean = true var dividerSize: Int = 0 fun build() = SpacingItemDecoration(this) } }
apache-2.0
a2109125a4265ca5f3d4d90d47ea8119
29.284091
109
0.63476
4.951673
false
false
false
false
ham1/jmeter
src/core/src/main/kotlin/org/apache/jmeter/threads/openmodel/scheduleTokenizer.kt
3
3978
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you 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 org.apache.jmeter.threads.openmodel import org.apiguardian.api.API import java.util.Locale import java.util.regex.Matcher @API(status = API.Status.EXPERIMENTAL, since = "5.5") public class TokenizerException(public val input: String, public val position: Int, message: String) : Exception( "$message at position $position: " + input.substring(position until (position + 20).coerceAtMost(input.length)) ) /** * Tokenizes string with schedule like `rate(5 min) ...` into tokens * `rate`, `(`, `5`, `min`, `)`, so [ScheduleParser] can parse them and build [ThreadSchedule]. */ internal object Tokenizer { private val WHITESPACE = Regex("""(?>\s+|/\*(?:(?!\*/).)*+\*/)|//[^\n\r]*+[\n\r]*+""") private val IDENTIFIER = Regex("""\p{Alpha}(?>\p{Alnum}|_)*+""") private val NUMBER = Regex("""(?>\d++(?:\.\d++)?|\.\d++)""") data class TokenPosition(val pos: Int, val token: Token) { override fun toString() = "$token:$pos" } sealed interface Token { val image: String } data class IdentifierToken(override val image: String) : Token { override fun equals(other: Any?) = other is IdentifierToken && image.equals(other.image, ignoreCase = true) override fun hashCode() = image.lowercase(Locale.ROOT).hashCode() override fun toString() = "Identifier($image)" } data class NumberToken(override val image: String) : Token { override fun toString() = "Number($image)" } object OpenParenthesisToken : Token { override val image: String get() = "(" override fun toString() = "(" } object CloseParenthesisToken : Token { override val image: String get() = ")" override fun toString() = ")" } object DivideToken : Token { override val image: String get() = "/" override fun toString() = "/" } private fun Regex.prepareMatcher(value: String) = toPattern().matcher(value).useAnchoringBounds(false).useTransparentBounds(true).region(0, value.length) private fun Matcher.lookingAt(pos: Int): Boolean = region(pos, regionEnd()).lookingAt() fun tokenize(value: String): List<TokenPosition> { val res = mutableListOf<TokenPosition>() var pos = 0 val mWhitespace = WHITESPACE.prepareMatcher(value) val mIdentifier = IDENTIFIER.prepareMatcher(value) val mNumber = NUMBER.prepareMatcher(value) while (pos < value.length) { if (mWhitespace.lookingAt(pos)) { pos = mWhitespace.end() continue } val token = when { value[pos] == '(' -> OpenParenthesisToken value[pos] == ')' -> CloseParenthesisToken value[pos] == '/' -> DivideToken mNumber.lookingAt(pos) -> NumberToken(mNumber.group()) mIdentifier.lookingAt(pos) -> IdentifierToken(mIdentifier.group()) else -> throw TokenizerException(value, pos, "Unexpected input") } res += TokenPosition(pos, token) pos += token.image.length } return res } }
apache-2.0
e6d55de1adf4b330410cc51fd65de137
37.621359
115
0.631976
4.218452
false
false
false
false
UnsignedInt8/d.Wallet-Core
android/lib/src/main/java/dWallet/core/bitcoin/script/Interpreter.kt
1
3365
package dwallet.core.bitcoin.script import dwallet.core.extensions.* /** * Created by unsignedint8 on 8/23/17. */ class Interpreter { companion object { private val disabledCodes = Words.Disabled.Arithmetic.values().map { it.raw } + Words.Disabled.Bitwise.values().map { it.raw } + Words.Disabled.Pseudo.values().map { it.raw } + Words.Disabled.Reserved.values().map { it.raw } + Words.Disabled.Splice.values().map { it.raw } fun checkValidity(opcode: Byte) = !disabledCodes.any { it == opcode } fun checkOpsValidity(opcodes: List<Byte>) = opcodes.all { checkValidity(it) } fun scriptToOps(data: ByteArray): List<Pair<Byte, ByteArray?>> { var offset = 0 val ops = mutableListOf<Pair<Byte, ByteArray?>>() while (offset < data.size) { val (opcode, operand, length) = parse(data, offset) ops.add(Pair(opcode, operand)) offset += length } return ops } fun isP2PKHOutScript(opcodes: List<Byte>) = arrayOf(Words.Stack.OP_DUP.raw, Words.Crypto.OP_HASH160.raw, 20.toByte(), Words.Bitwise.OP_EQUALVERIFY.raw, Words.Crypto.OP_CHECKSIG.raw).contentEquals(opcodes.toTypedArray()) fun isP2SHOutScript(opcodes: List<Byte>) = arrayOf(Words.Crypto.OP_HASH160.raw, 20.toByte(), Words.Bitwise.OP_EQUAL.raw).contentEquals(opcodes.toTypedArray()) private fun parse(data: ByteArray, offset: Int = 0): Triple<Byte, ByteArray?, Int> { val opcode = data[offset] var operand: ByteArray? = null var totalLength = 1 var offset = offset when (opcode) { in Words.Constants.OP_2.raw..Words.Constants.OP_16.raw -> { operand = byteArrayOf((opcode - Words.Constants.OP_2.raw + 2.toByte()).toByte()) } in Words.Constants.NA_LOW.raw..Words.Constants.NA_HIGH.raw -> { offset += 1 operand = data.sliceArray(offset, offset + opcode) totalLength += opcode.toInt() } in Words.Constants.NA_LOW.raw..Words.Constants.NA_HIGH.raw -> { offset += 1 operand = data.sliceArray(offset, offset + opcode.toInt()) totalLength += opcode.toInt() } Words.Constants.OP_PUSHDATA1.raw -> { val dataLength = data[offset + 1].toInt() offset += 2 operand = data.sliceArray(offset, offset + dataLength) totalLength += 1 + dataLength } Words.Constants.OP_PUSHDATA2.raw -> { val dataLength = data.readInt16LE(offset + 1).toInt() offset += 3 operand = data.sliceArray(offset, offset + dataLength) totalLength += 2 + dataLength } Words.Constants.OP_PUSHDATA4.raw -> { val dataLength = data.readInt32LE(offset + 1) offset += 5 operand = data.sliceArray(offset, offset + dataLength) totalLength += 4 + dataLength } } return Triple(opcode, operand, totalLength) } } }
gpl-3.0
872fd72f3d43254f234520bba96bd356
38.6
280
0.544131
4.439314
false
false
false
false
ejeinc/VR-MultiView-UDP
controller-android/src/main/java/com/eje_c/multilink/controller/db/VideoEntity.kt
1
865
package com.eje_c.multilink.controller.db import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity /** * Represents a record in VideoEntity table in local SQLite DB. */ @Entity(primaryKeys = ["device_imei", "path"]) class VideoEntity { /** * Device's IMEI */ @ColumnInfo(name = "device_imei") var deviceImei: String = "" /** * Relative path from external storage on VR device. */ @ColumnInfo(name = "path") var path: String = "" /** * Display name. */ @ColumnInfo(name = "name") var name: String? = null /** * Content length. */ @ColumnInfo(name = "length") var length: Long = 0 /** * Update time for this record based on SystemClock.uptimeMillis(). */ @ColumnInfo(name = "updated_at") var updatedAt: Long = 0 }
apache-2.0
446e296cf07cee01c573801261334f5b
20.121951
71
0.60578
3.861607
false
false
false
false
AndroidX/androidx
compose/material/material/icons/generator/src/main/kotlin/androidx/compose/material/icons/generator/vector/PathParser.kt
3
5996
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.icons.generator.vector import kotlin.math.min /** * Trimmed down copy of PathParser that doesn't handle interacting with Paths, and only is * responsible for parsing path strings. */ object PathParser { /** * Parses the path string to create a collection of PathNode instances with their corresponding * arguments * throws an IllegalArgumentException or NumberFormatException if the parameters are invalid */ fun parsePathString(pathData: String): List<PathNode> { val nodes = mutableListOf<PathNode>() fun addNode(cmd: Char, args: FloatArray) { nodes.addAll(cmd.toPathNodes(args)) } var start = 0 var end = 1 while (end < pathData.length) { end = nextStart(pathData, end) val s = pathData.substring(start, end).trim { it <= ' ' } if (s.isNotEmpty()) { val args = getFloats(s) addNode(s[0], args) } start = end end++ } if (end - start == 1 && start < pathData.length) { addNode(pathData[start], FloatArray(0)) } return nodes } private fun nextStart(s: String, end: Int): Int { var index = end var c: Char while (index < s.length) { c = s[index] // Note that 'e' or 'E' are not valid path commands, but could be // used for floating point numbers' scientific notation. // Therefore, when searching for next command, we should ignore 'e' // and 'E'. if (((c - 'A') * (c - 'Z') <= 0 || (c - 'a') * (c - 'z') <= 0) && c != 'e' && c != 'E' ) { return index } index++ } return index } @Throws(NumberFormatException::class) private fun getFloats(s: String): FloatArray { if (s[0] == 'z' || s[0] == 'Z') { return FloatArray(0) } val results = FloatArray(s.length) var count = 0 var startPosition = 1 var endPosition: Int val result = ExtractFloatResult() val totalLength = s.length // The startPosition should always be the first character of the // current number, and endPosition is the character after the current // number. while (startPosition < totalLength) { extract(s, startPosition, result) endPosition = result.endPosition if (startPosition < endPosition) { results[count++] = java.lang.Float.parseFloat( s.substring(startPosition, endPosition) ) } startPosition = if (result.endWithNegativeOrDot) { // Keep the '-' or '.' sign with next number. endPosition } else { endPosition + 1 } } return copyOfRange(results, 0, count) } private fun copyOfRange(original: FloatArray, start: Int, end: Int): FloatArray { if (start > end) { throw IllegalArgumentException() } val originalLength = original.size if (start < 0 || start > originalLength) { throw ArrayIndexOutOfBoundsException() } val resultLength = end - start val copyLength = min(resultLength, originalLength - start) val result = FloatArray(resultLength) original.copyInto(result, 0, start, start + copyLength) return result } private fun extract(s: String, start: Int, result: ExtractFloatResult) { // Now looking for ' ', ',', '.' or '-' from the start. var currentIndex = start var foundSeparator = false result.endWithNegativeOrDot = false var secondDot = false var isExponential = false while (currentIndex < s.length) { val isPrevExponential = isExponential isExponential = false when (s[currentIndex]) { ' ', ',' -> foundSeparator = true '-' -> // The negative sign following a 'e' or 'E' is not a separator. if (currentIndex != start && !isPrevExponential) { foundSeparator = true result.endWithNegativeOrDot = true } '.' -> if (!secondDot) { secondDot = true } else { // This is the second dot, and it is considered as a separator. foundSeparator = true result.endWithNegativeOrDot = true } 'e', 'E' -> isExponential = true } if (foundSeparator) { break } currentIndex++ } // When there is nothing found, then we put the end position to the end // of the string. result.endPosition = currentIndex } private data class ExtractFloatResult( // We need to return the position of the next separator and whether the // next float starts with a '-' or a '.'. var endPosition: Int = 0, var endWithNegativeOrDot: Boolean = false ) }
apache-2.0
bff4942c4f55be259b12e3dc0cc75fcb
33.45977
99
0.546865
4.831587
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/input/pointer/PointerInteropFilter.android.kt
3
15473
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input.pointer import android.os.SystemClock import android.view.MotionEvent import android.view.MotionEvent.ACTION_CANCEL import android.view.MotionEvent.ACTION_DOWN import android.view.MotionEvent.ACTION_MOVE import android.view.MotionEvent.ACTION_OUTSIDE import android.view.MotionEvent.ACTION_POINTER_DOWN import android.view.MotionEvent.ACTION_POINTER_UP import android.view.MotionEvent.ACTION_UP import android.view.View import android.view.ViewGroup import android.view.ViewParent import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.IntSize import androidx.compose.ui.util.fastAll import androidx.compose.ui.util.fastAny import androidx.compose.ui.util.fastForEach import androidx.compose.ui.viewinterop.AndroidViewHolder /** * A special PointerInputModifier that provides access to the underlying [MotionEvent]s originally * dispatched to Compose. Prefer [pointerInput] and use this only for interoperation with * existing code that consumes [MotionEvent]s. * * While the main intent of this Modifier is to allow arbitrary code to access the original * [MotionEvent] dispatched to Compose, for completeness, analogs are provided to allow arbitrary * code to interact with the system as if it were an Android View. * * This includes 2 APIs, * * 1. [onTouchEvent] has a Boolean return type which is akin to the return type of * [View.onTouchEvent]. If the provided [onTouchEvent] returns true, it will continue to receive * the event stream (unless the event stream has been intercepted) and if it returns false, it will * not. * * 2. [requestDisallowInterceptTouchEvent] is a lambda that you can optionally provide so that * you can later call it (yes, in this case, you call the lambda that you provided) which is akin * to calling [ViewParent.requestDisallowInterceptTouchEvent]. When this is called, any * associated ancestors in the tree that abide by the contract will act accordingly and will not * intercept the even stream. * * @see [View.onTouchEvent] * @see [ViewParent.requestDisallowInterceptTouchEvent] */ @ExperimentalComposeUiApi fun Modifier.pointerInteropFilter( requestDisallowInterceptTouchEvent: (RequestDisallowInterceptTouchEvent)? = null, onTouchEvent: (MotionEvent) -> Boolean ): Modifier = composed( inspectorInfo = debugInspectorInfo { name = "pointerInteropFilter" properties["requestDisallowInterceptTouchEvent"] = requestDisallowInterceptTouchEvent properties["onTouchEvent"] = onTouchEvent } ) { val filter = remember { PointerInteropFilter() } filter.onTouchEvent = onTouchEvent filter.requestDisallowInterceptTouchEvent = requestDisallowInterceptTouchEvent filter } /** * Function that can be passed to [pointerInteropFilter] and then later invoked which provides an * analog to [ViewParent.requestDisallowInterceptTouchEvent]. */ @ExperimentalComposeUiApi class RequestDisallowInterceptTouchEvent : (Boolean) -> Unit { internal var pointerInteropFilter: PointerInteropFilter? = null override fun invoke(disallowIntercept: Boolean) { pointerInteropFilter?.disallowIntercept = disallowIntercept } } /** * Similar to the 2 argument overload of [pointerInteropFilter], but connects * directly to an [AndroidViewHolder] for more seamless interop with Android. */ @ExperimentalComposeUiApi internal fun Modifier.pointerInteropFilter(view: AndroidViewHolder): Modifier { val filter = PointerInteropFilter() filter.onTouchEvent = { motionEvent -> when (motionEvent.actionMasked) { ACTION_DOWN, ACTION_POINTER_DOWN, ACTION_MOVE, ACTION_UP, ACTION_POINTER_UP, ACTION_OUTSIDE, ACTION_CANCEL -> view.dispatchTouchEvent(motionEvent) // ACTION_HOVER_ENTER, // ACTION_HOVER_MOVE, // ACTION_HOVER_EXIT, // ACTION_BUTTON_PRESS, // ACTION_BUTTON_RELEASE, else -> view.dispatchGenericMotionEvent(motionEvent) } } val requestDisallowInterceptTouchEvent = RequestDisallowInterceptTouchEvent() filter.requestDisallowInterceptTouchEvent = requestDisallowInterceptTouchEvent view.onRequestDisallowInterceptTouchEvent = requestDisallowInterceptTouchEvent return this.then(filter) } /** * The stateful part of pointerInteropFilter that manages the interop with Android. * * The intent of this PointerInputModifier is to allow Android Views and PointerInputModifiers to * interact seamlessly despite the differences in the 2 systems. Below is a detailed explanation * for how the interop is accomplished. * * When the type of event is not a movement event, we dispatch to the Android View as soon as * possible (during [PointerEventPass.Initial]) so that the Android View can react to down * and up events before Compose PointerInputModifiers normally would. * * When the type of event is a movement event, we dispatch to the Android View during * [PointerEventPass.Final] to allow Compose PointerInputModifiers to react to movement first, * which mimics a parent [ViewGroup] intercepting the event stream. * * Whenever we are about to call [onTouchEvent], we check to see if anything in Compose * consumed any aspect of the pointer input changes, and if they did, we intercept the stream and * dispatch ACTION_CANCEL to the Android View if they have already returned true for a call to * View#dispatchTouchEvent(...). * * If we do call [onTouchEvent], and it returns true, we consume all of the changes so that * nothing in Compose also responds. * * If the [requestDisallowInterceptTouchEvent] is provided and called with true, we simply dispatch move * events during [PointerEventPass.Initial] so that normal PointerInputModifiers don't get a * chance to consume first. Note: This does mean that it is possible for a Compose * PointerInputModifier to "intercept" even after requestDisallowInterceptTouchEvent has been * called because consumption can occur during [PointerEventPass.Initial]. This may seem * like a flaw, but in reality, any PointerInputModifier that consumes that aggressively would * likely only do so after some consumption already occurred on a later pass, and this ability to * do so is on par with a [ViewGroup]'s ability to override [ViewGroup.dispatchTouchEvent] * instead of overriding the more usual [ViewGroup.onTouchEvent] and [ViewGroup * .onInterceptTouchEvent]. * * If [requestDisallowInterceptTouchEvent] is later called with false (the Android equivalent of * calling [ViewParent.requestDisallowInterceptTouchEvent] is exceedingly rare), we revert back to * the normal behavior. * * If all pointers go up on the pointer interop filter, parents will be set to be allowed to * intercept when new pointers go down. [requestDisallowInterceptTouchEvent] must be called again to * change that state. */ @ExperimentalComposeUiApi internal class PointerInteropFilter : PointerInputModifier { lateinit var onTouchEvent: (MotionEvent) -> Boolean var requestDisallowInterceptTouchEvent: RequestDisallowInterceptTouchEvent? = null set(value) { field?.pointerInteropFilter = null field = value field?.pointerInteropFilter = this } internal var disallowIntercept = false /** * The 3 possible states */ private enum class DispatchToViewState { /** * We have yet to dispatch a new event stream to the child Android View. */ Unknown, /** * We have dispatched to the child Android View and it wants to continue to receive * events for the current event stream. */ Dispatching, /** * We intercepted the event stream, or the Android View no longer wanted to receive * events for the current event stream. */ NotDispatching } override val pointerInputFilter = object : PointerInputFilter() { private var state = DispatchToViewState.Unknown override val shareWithSiblings get() = true override fun onPointerEvent( pointerEvent: PointerEvent, pass: PointerEventPass, bounds: IntSize ) { val changes = pointerEvent.changes // If we were told to disallow intercept, or if the event was a down or up event, // we dispatch to Android as early as possible. If the event is a move event and // we can still intercept, we dispatch to Android after we have a chance to // intercept due to movement. val dispatchDuringInitialTunnel = disallowIntercept || changes.fastAny { it.changedToDownIgnoreConsumed() || it.changedToUpIgnoreConsumed() } if (state !== DispatchToViewState.NotDispatching) { if (pass == PointerEventPass.Initial && dispatchDuringInitialTunnel) { dispatchToView(pointerEvent) } if (pass == PointerEventPass.Final && !dispatchDuringInitialTunnel) { dispatchToView(pointerEvent) } } if (pass == PointerEventPass.Final) { // If all of the changes were up changes, then the "event stream" has ended // and we reset. if (changes.fastAll { it.changedToUpIgnoreConsumed() }) { reset() } } } override fun onCancel() { // If we are still dispatching to the Android View, we have to send them a // cancel event, otherwise, we should not. if (state === DispatchToViewState.Dispatching) { emptyCancelMotionEventScope( SystemClock.uptimeMillis() ) { motionEvent -> onTouchEvent(motionEvent) } reset() } } /** * Resets all of our state to be ready for a "new event stream". */ private fun reset() { state = DispatchToViewState.Unknown disallowIntercept = false } /** * Dispatches to the Android View. * * Also consumes aspects of [pointerEvent] and updates our [state] accordingly. * * Will dispatch ACTION_CANCEL if any aspect of [pointerEvent] has been consumed and * update our [state] accordingly. * * @param pointerEvent The change to dispatch. * @return The resulting changes (fully consumed or untouched). */ private fun dispatchToView(pointerEvent: PointerEvent) { val changes = pointerEvent.changes if (changes.fastAny { it.isConsumed }) { // We should no longer dispatch to the Android View. if (state === DispatchToViewState.Dispatching) { // If we were dispatching, send ACTION_CANCEL. pointerEvent.toCancelMotionEventScope( this.layoutCoordinates?.localToRoot(Offset.Zero) ?: error("layoutCoordinates not set") ) { motionEvent -> onTouchEvent(motionEvent) } } state = DispatchToViewState.NotDispatching } else { // Dispatch and update our state with the result. pointerEvent.toMotionEventScope( this.layoutCoordinates?.localToRoot(Offset.Zero) ?: error("layoutCoordinates not set") ) { motionEvent -> if (motionEvent.actionMasked == MotionEvent.ACTION_DOWN) { // If the action is ACTION_DOWN, we care about the return value of // onTouchEvent and use it to set our initial dispatching state. state = if (onTouchEvent(motionEvent)) { DispatchToViewState.Dispatching } else { DispatchToViewState.NotDispatching } } else { // Otherwise, we don't care about the return value. This is intended // to be in accordance with how the Android View system works. onTouchEvent(motionEvent) } } if (state === DispatchToViewState.Dispatching) { // If the Android View claimed the event, consume all changes. changes.fastForEach { it.consume() } pointerEvent.internalPointerEvent?.suppressMovementConsumption = !disallowIntercept } } } } } /** * Calls [watcher] with each [MotionEvent] that the layout area or any child [pointerInput] * receives. The [MotionEvent] may or may not have been transformed to the local coordinate system. * The Compose View will be considered as handling the [MotionEvent] in the area that the * [motionEventSpy] is active. * * This method can only be used to observe [MotionEvent]s and can not be used to capture an event * stream. Use [pointerInteropFilter] to handle [MotionEvent]s and consume the events. * * [watcher] is called during the [PointerEventPass.Initial] pass. * * Developers should prefer to use [pointerInput] to handle pointer input processing within * Compose. [motionEventSpy] is only useful as part of Android View interoperability. */ @ExperimentalComposeUiApi fun Modifier.motionEventSpy(watcher: (motionEvent: MotionEvent) -> Unit): Modifier = this.pointerInput(watcher) { interceptOutOfBoundsChildEvents = true awaitPointerEventScope { while (true) { val event = awaitPointerEvent(PointerEventPass.Initial) event.motionEvent?.let(watcher) } } }
apache-2.0
49f99d1e78f26329d63ebadd32edfcd4
43.335244
104
0.651134
5.38566
false
false
false
false
satamas/fortran-plugin
src/main/java/org/jetbrains/fortran/lang/psi/FortranIncludeForeignLeafElement.kt
1
2076
package org.jetbrains.fortran.lang.psi import com.intellij.openapi.util.Key import com.intellij.openapi.util.Pair import com.intellij.openapi.util.TextRange import com.intellij.psi.ExternallyAnnotated import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.tree.ForeignLeafPsiElement import com.intellij.psi.util.PsiTreeUtil class FortranIncludeForeignLeafElement(type: FortranIncludeForeignLeafType, text: CharSequence) : ForeignLeafPsiElement(type, text), ExternallyAnnotated { private val startOffsetCache = Key.create<Pair<Long, Int>>("START_OFFSET") private fun getCachedStartOffset(timeStamp: Long): Int? { val pair = startOffsetCache.get(this) return if (pair != null && pair.first == timeStamp) { pair.second } else null } override fun getStartOffset(): Int { val stamp = containingFile.modificationStamp var offset = getCachedStartOffset(stamp) if (offset != null) { return offset } val array = arrayListOf(this) var cur = PsiTreeUtil.prevLeaf(this) while (offset == null && cur != null && cur !is PsiFile) { if (cur is ForeignLeafPsiElement) { if (cur is FortranIncludeForeignLeafElement) { offset = cur.getCachedStartOffset(stamp) if (offset == null) { array.add(cur) } } } else if (cur.textRange != null) { offset = cur.textRange.endOffset } cur = PsiTreeUtil.prevLeaf(cur) } if (offset == null) { return 0 } val value = Pair.create<Long, Int>(stamp, offset) for (macroForeignLeafElement in array) { startOffsetCache.set(macroForeignLeafElement, value) } return offset } override fun getTextRange(): TextRange { val start = startOffset return TextRange(start, start) } override fun getAnnotationRegion(): TextRange? = null }
apache-2.0
e10f09657db51bfb7b4c24504497bcd7
33.04918
97
0.618015
4.718182
false
false
false
false
pdvrieze/darwin-android-auth
src/main/java/uk/ac/bournemouth/darwin/auth/AccountDetailActivity.kt
1
2985
package uk.ac.bournemouth.darwin.auth import android.accounts.Account import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.NavUtils import android.support.v7.app.AppCompatActivity import android.view.MenuItem /** * An activity representing a single Account detail screen. This * activity is only used on narrow width devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a [AccountListActivity]. */ class AccountDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account_detail) actionBar?.setDisplayHomeAsUpEnabled(true) // Show the Up button in the action bar, but only if there is an account list. // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. val fragment = AccountDetailFragment().apply { arguments = Bundle().apply { putParcelable(AccountDetailFragment.ARG_ACCOUNT, intent.getParcelableExtra<Account>(AccountDetailFragment.ARG_ACCOUNT)) } } supportFragmentManager.beginTransaction() .add(R.id.account_detail_container, fragment) .commit() } } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back NavUtils.navigateUpTo(this, Intent(this, AccountListActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } } fun Context?.accountDetailIntent(account: Account): Intent { return Intent(this, AccountDetailActivity::class.java).apply { putExtra(AccountDetailFragment.ARG_ACCOUNT, account) } }
lgpl-2.1
87069ba508e523d419eeb452316314f8
40.458333
98
0.636516
5.102564
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/model/CargoProjectService.kt
2
8053
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.roots.ContentEntry import com.intellij.openapi.util.NlsContexts.Tooltip import com.intellij.openapi.util.UserDataHolderEx import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.messages.Topic import org.rust.cargo.CargoConstants import org.rust.cargo.project.model.impl.UserDisabledFeatures import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.project.workspace.FeatureState import org.rust.cargo.project.workspace.PackageFeature import org.rust.cargo.toolchain.RsToolchainBase import org.rust.cargo.toolchain.impl.RustcVersion import org.rust.cargo.toolchain.tools.isRustupAvailable import org.rust.ide.notifications.showBalloon import org.rust.openapiext.pathAsPath import java.nio.file.Path import java.util.concurrent.CompletableFuture /** * Stores a list of [CargoProject]s associated with the current IntelliJ [Project]. * Use [Project.cargoProjects] to get an instance of the service. * * See [ARCHITECTURE.md](https://github.com/intellij-rust/intellij-rust/blob/master/ARCHITECTURE.md#project-model) * for more details. */ interface CargoProjectsService { val project: Project val allProjects: Collection<CargoProject> val hasAtLeastOneValidProject: Boolean val initialized: Boolean fun findProjectForFile(file: VirtualFile): CargoProject? fun findPackageForFile(file: VirtualFile): CargoWorkspace.Package? /** * @param manifest a path to `Cargo.toml` file of the project that should be attached */ fun attachCargoProject(manifest: Path): Boolean fun attachCargoProjects(vararg manifests: Path) fun detachCargoProject(cargoProject: CargoProject) fun refreshAllProjects(): CompletableFuture<out List<CargoProject>> fun discoverAndRefresh(): CompletableFuture<out List<CargoProject>> fun suggestManifests(): Sequence<VirtualFile> fun modifyFeatures(cargoProject: CargoProject, features: Set<PackageFeature>, newState: FeatureState) companion object { val CARGO_PROJECTS_TOPIC: Topic<CargoProjectsListener> = Topic( "cargo projects changes", CargoProjectsListener::class.java ) val CARGO_PROJECTS_REFRESH_TOPIC: Topic<CargoProjectsRefreshListener> = Topic( "Cargo refresh", CargoProjectsRefreshListener::class.java ) } fun interface CargoProjectsListener { fun cargoProjectsUpdated(service: CargoProjectsService, projects: Collection<CargoProject>) } interface CargoProjectsRefreshListener { fun onRefreshStarted() fun onRefreshFinished(status: CargoRefreshStatus) } enum class CargoRefreshStatus { SUCCESS, FAILURE, CANCEL } } val Project.cargoProjects: CargoProjectsService get() = service() fun CargoProjectsService.isGeneratedFile(file: VirtualFile): Boolean { val outDir = findPackageForFile(file)?.outDir ?: return false return VfsUtil.isAncestor(outDir, file, false) } /** * See docs for [CargoProjectsService]. * * Instances of this class are immutable and will be re-created on each project refresh. * This class implements [UserDataHolderEx] interface and therefore any data can be attached * to it. Note that since instances of this class are re-created on each project refresh, * user data will be flushed on project refresh too */ interface CargoProject : UserDataHolderEx { val project: Project val manifest: Path val rootDir: VirtualFile? val workspaceRootDir: VirtualFile? val presentableName: String val workspace: CargoWorkspace? val rustcInfo: RustcInfo? val procMacroExpanderPath: Path? val workspaceStatus: UpdateStatus val stdlibStatus: UpdateStatus val rustcInfoStatus: UpdateStatus val mergedStatus: UpdateStatus get() = workspaceStatus .merge(stdlibStatus) .merge(rustcInfoStatus) val userDisabledFeatures: UserDisabledFeatures sealed class UpdateStatus(private val priority: Int) { object UpToDate : UpdateStatus(0) object NeedsUpdate : UpdateStatus(1) class UpdateFailed(@Suppress("UnstableApiUsage") @Tooltip val reason: String) : UpdateStatus(2) fun merge(status: UpdateStatus): UpdateStatus = if (priority >= status.priority) this else status } } data class RustcInfo( val sysroot: String, val version: RustcVersion?, val rustupActiveToolchain: String? = null, val targets: List<String>? = null ) fun guessAndSetupRustProject(project: Project, explicitRequest: Boolean = false): Boolean { if (!explicitRequest) { val alreadyTried = run { val key = "org.rust.cargo.project.model.PROJECT_DISCOVERY" val properties = PropertiesComponent.getInstance(project) val alreadyTried = properties.getBoolean(key) properties.setValue(key, true) alreadyTried } if (alreadyTried) return false } val toolchain = project.rustSettings.toolchain if (toolchain == null || !toolchain.looksLikeValidToolchain()) { discoverToolchain(project) return true } if (!project.cargoProjects.hasAtLeastOneValidProject) { project.cargoProjects.discoverAndRefresh() return true } return false } private fun discoverToolchain(project: Project) { val projectPath = project.guessProjectDir()?.pathAsPath val toolchain = RsToolchainBase.suggest(projectPath) ?: return invokeLater { if (project.isDisposed) return@invokeLater val oldToolchain = project.rustSettings.toolchain if (oldToolchain != null && oldToolchain.looksLikeValidToolchain()) { return@invokeLater } runWriteAction { project.rustSettings.modify { it.toolchain = toolchain } } val tool = if (toolchain.isRustupAvailable) "rustup" else "Cargo at ${toolchain.presentableLocation}" project.showBalloon("Using $tool", NotificationType.INFORMATION) project.cargoProjects.discoverAndRefresh() } } fun ContentEntry.setup(contentRoot: VirtualFile) = ContentEntryWrapper(this).setup(contentRoot) fun ContentEntryWrapper.setup(contentRoot: VirtualFile) { val makeVfsUrl = { dirName: String -> contentRoot.findChild(dirName)?.url } CargoConstants.ProjectLayout.sources.mapNotNull(makeVfsUrl).forEach { addSourceFolder(it, isTestSource = false) } CargoConstants.ProjectLayout.tests.mapNotNull(makeVfsUrl).forEach { addSourceFolder(it, isTestSource = true) } makeVfsUrl(CargoConstants.ProjectLayout.target)?.let(::addExcludeFolder) } class ContentEntryWrapper(private val contentEntry: ContentEntry) { private val knownFolders: Set<String> = contentEntry.knownFolders() fun addExcludeFolder(url: String) { if (url in knownFolders) return contentEntry.addExcludeFolder(url) } fun addSourceFolder(url: String, isTestSource: Boolean) { if (url in knownFolders) return contentEntry.addSourceFolder(url, isTestSource) } private fun ContentEntry.knownFolders(): Set<String> { val knownRoots = sourceFolders.mapTo(hashSetOf()) { it.url } knownRoots += excludeFolderUrls return knownRoots } } val isNewProjectModelImportEnabled: Boolean get() = Registry.`is`("org.rust.cargo.new.auto.import", false)
mit
04be32d643926c55577aa8ad2ec95f4f
34.791111
114
0.735502
4.695627
false
true
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/template/RsContextType.kt
2
3833
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.template import com.intellij.codeInsight.template.EverywhereContextType import com.intellij.codeInsight.template.TemplateActionContext import com.intellij.codeInsight.template.TemplateContextType import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilCore import org.rust.ide.highlight.RsHighlighter import org.rust.lang.RsLanguage import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsAttr import org.rust.lang.core.psi.ext.RsItemElement import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.ancestorStrict import org.rust.lang.doc.psi.RsDocComment import kotlin.reflect.KClass sealed class RsContextType( id: String, presentableName: String, baseContextType: KClass<out TemplateContextType> ) : TemplateContextType(id, presentableName, baseContextType.java) { final override fun isInContext(context: TemplateActionContext): Boolean { if (!PsiUtilCore.getLanguageAtOffset(context.file, context.startOffset).isKindOf(RsLanguage)) { return false } val element = context.file.findElementAt(context.startOffset) if (element == null || element is PsiComment || element.parent is RsLitExpr) { return false } return isInContext(element) } protected abstract fun isInContext(element: PsiElement): Boolean override fun createHighlighter(): SyntaxHighlighter = RsHighlighter() class Generic : RsContextType("RUST_FILE", "Rust", EverywhereContextType::class) { override fun isInContext(element: PsiElement): Boolean = true } class Statement : RsContextType("RUST_STATEMENT", "Statement", Generic::class) { override fun isInContext(element: PsiElement): Boolean { // We are inside block but there is no item nor attr between if (owner(element) !is RsBlock) return false val parent = element.parent // foo::element if (parent is RsPath && parent.coloncolon != null) return false // foo.element if (parent is RsFieldLookup) return false // foo.element() if (parent is RsMethodCall) return false return true } } class Item : RsContextType("RUST_ITEM", "Item", Generic::class) { override fun isInContext(element: PsiElement): Boolean = // We are inside item but there is no block between owner(element) is RsItemElement } class Struct : RsContextType("RUST_STRUCT", "Structure", Item::class) { override fun isInContext(element: PsiElement): Boolean = // Structs can't be nested or contain other expressions, // so it is ok to look for any Struct ancestor. element.ancestorStrict<RsStructItem>() != null } class Mod : RsContextType("RUST_MOD", "Module", Item::class) { override fun isInContext(element: PsiElement): Boolean // We are inside RsMod = owner(element) is RsMod } class Attribute : RsContextType("RUST_ATTRIBUTE", "Attribute", Item::class) { override fun isInContext(element: PsiElement): Boolean = element.ancestorStrict<RsAttr>() != null } companion object { private fun owner(element: PsiElement): PsiElement? = PsiTreeUtil.findFirstParent(element) { it is RsBlock || it is RsPat || it is RsItemElement || it is PsiFile || it is RsAttr || it is RsDocComment || it is RsMacro || it is RsMacroCall } } }
mit
5ab5f5ce8a91ccd9db157c9193ae3e29
36.213592
103
0.684842
4.573986
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/CargoTestCommandRunner.kt
2
4157
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig import com.intellij.execution.RunContentExecutor import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.configurations.RunnerSettings import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.runners.AsyncProgramRunner import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.showRunContent import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.application.invokeLater import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.rust.cargo.runconfig.buildtool.CargoBuildManager.getBuildConfiguration import org.rust.cargo.runconfig.buildtool.CargoBuildManager.isBuildToolWindowAvailable import org.rust.cargo.runconfig.buildtool.isActivateToolWindowBeforeRun import org.rust.cargo.runconfig.command.CargoCommandConfiguration import org.rust.cargo.runconfig.command.hasRemoteTarget import org.rust.openapiext.isUnitTestMode import org.rust.openapiext.saveAllDocuments class CargoTestCommandRunner : AsyncProgramRunner<RunnerSettings>() { override fun getRunnerId(): String = RUNNER_ID override fun canRun(executorId: String, profile: RunProfile): Boolean { if (executorId != DefaultRunExecutor.EXECUTOR_ID || profile !is CargoCommandConfiguration) return false val cleaned = profile.clean().ok ?: return false val isLocalRun = !profile.hasRemoteTarget || profile.buildTarget.isRemote val isLegacyTestRun = !profile.isBuildToolWindowAvailable && cleaned.cmd.command == "test" && getBuildConfiguration(profile) != null return isLocalRun && isLegacyTestRun } override fun execute(environment: ExecutionEnvironment, state: RunProfileState): Promise<RunContentDescriptor?> { saveAllDocuments() val onlyBuild = "--no-run" in (state as CargoRunStateBase).commandLine.additionalArguments return buildTests(environment, state, onlyBuild) .then { exitCode -> if (onlyBuild || exitCode != 0) return@then null showRunContent(state.execute(environment.executor, this), environment) } } companion object { const val RUNNER_ID: String = "CargoTestCommandRunner" private fun buildTests(environment: ExecutionEnvironment, state: CargoRunStateBase, cmdHasNoRun: Boolean): Promise<Int?> { val buildProcessHandler = run { val buildCmd = state.commandLine.copy(emulateTerminal = false, withSudo = false).run { if (cmdHasNoRun) this else prependArgument("--no-run") } val buildConfig = CargoCommandConfiguration.CleanConfiguration.Ok(buildCmd, state.config.toolchain) val buildState = CargoRunState(state.environment, state.runConfiguration, buildConfig) buildState.startProcess(processColors = true) } val exitCode = AsyncPromise<Int?>() if (environment.isActivateToolWindowBeforeRun && !isUnitTestMode) { RunContentExecutor(environment.project, buildProcessHandler) .apply { createFilters(state.cargoProject).forEach { withFilter(it) } } .withAfterCompletion { exitCode.setResult(buildProcessHandler.exitCode) } .run() } else { buildProcessHandler.addProcessListener(object : ProcessAdapter() { override fun processTerminated(event: ProcessEvent) { invokeLater { exitCode.setResult(buildProcessHandler.exitCode) } } }) buildProcessHandler.startNotify() } return exitCode } } }
mit
824d6cb059d287a0f0a945fb01b65ad2
47.905882
130
0.704595
5.329487
false
true
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/toolwindow/CargoToolWindow.kt
2
5948
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.toolwindow import com.intellij.ide.DefaultTreeExpander import com.intellij.ide.TreeExpander import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.invokeLater import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.util.Key import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowEP import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerEx import com.intellij.ui.ColorUtil import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.content.ContentFactory import com.intellij.util.ui.UIUtil import org.rust.cargo.project.model.CargoProject import org.rust.cargo.project.model.CargoProjectsService import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.model.guessAndSetupRustProject import org.rust.cargo.runconfig.hasCargoProject import javax.swing.JComponent import javax.swing.JEditorPane class CargoToolWindowFactory : ToolWindowFactory, DumbAware { private val lock: Any = Any() override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { guessAndSetupRustProject(project) val toolwindowPanel = CargoToolWindowPanel(project) val tab = ContentFactory.getInstance() .createContent(toolwindowPanel, "", false) toolWindow.contentManager.addContent(tab) } override fun isApplicable(project: Project): Boolean { if (CargoToolWindow.isRegistered(project)) return false val cargoProjects = project.cargoProjects if (!cargoProjects.hasAtLeastOneValidProject && cargoProjects.suggestManifests().none()) return false synchronized(lock) { val res = project.getUserData(CARGO_TOOL_WINDOW_APPLICABLE) ?: true if (res) { project.putUserData(CARGO_TOOL_WINDOW_APPLICABLE, false) } return res } } companion object { private val CARGO_TOOL_WINDOW_APPLICABLE: Key<Boolean> = Key.create("CARGO_TOOL_WINDOW_APPLICABLE") } } private class CargoToolWindowPanel(project: Project) : SimpleToolWindowPanel(true, false) { private val cargoTab = CargoToolWindow(project) init { toolbar = cargoTab.toolbar.component cargoTab.toolbar.targetComponent = this setContent(cargoTab.content) } override fun getData(dataId: String): Any? = when { CargoToolWindow.SELECTED_CARGO_PROJECT.`is`(dataId) -> cargoTab.selectedProject PlatformDataKeys.TREE_EXPANDER.`is`(dataId) -> cargoTab.treeExpander else -> super.getData(dataId) } } class CargoToolWindow( private val project: Project ) { val toolbar: ActionToolbar = run { val actionManager = ActionManager.getInstance() actionManager.createActionToolbar(CARGO_TOOLBAR_PLACE, actionManager.getAction("Rust.Cargo") as DefaultActionGroup, true) } val note = JEditorPane("text/html", html("")).apply { background = UIUtil.getTreeBackground() isEditable = false } private val projectTree = CargoProjectsTree() private val projectStructure = CargoProjectTreeStructure(projectTree, project) val treeExpander: TreeExpander = object : DefaultTreeExpander(projectTree) { override fun isCollapseAllVisible(): Boolean = project.hasCargoProject override fun isExpandAllVisible(): Boolean = project.hasCargoProject } val selectedProject: CargoProject? get() = projectTree.selectedProject val content: JComponent = ScrollPaneFactory.createScrollPane(projectTree, 0) init { with(project.messageBus.connect()) { subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, projects -> invokeLater { projectStructure.updateCargoProjects(projects.toList()) } }) } invokeLater { projectStructure.updateCargoProjects(project.cargoProjects.allProjects.toList()) } } private fun html(body: String): String = """ <html> <head> ${UIUtil.getCssFontDeclaration(UIUtil.getLabelFont())} <style>body {background: #${ColorUtil.toHex(UIUtil.getTreeBackground())}; text-align: center; }</style> </head> <body> $body </body> </html> """ companion object { private val LOG: Logger = logger<CargoToolWindow>() @JvmStatic val SELECTED_CARGO_PROJECT: DataKey<CargoProject> = DataKey.create("SELECTED_CARGO_PROJECT") const val CARGO_TOOLBAR_PLACE: String = "Cargo Toolbar" private const val ID: String = "Cargo" fun initializeToolWindow(project: Project) { try { val manager = ToolWindowManager.getInstance(project) as? ToolWindowManagerEx ?: return val bean = ToolWindowEP.EP_NAME.extensionList.find { it.id == ID } if (bean != null) { @Suppress("DEPRECATION", "UnstableApiUsage") manager.initToolWindow(bean) } } catch (e: Exception) { LOG.error("Unable to initialize $ID tool window", e) } } fun isRegistered(project: Project): Boolean { val manager = ToolWindowManager.getInstance(project) return manager.getToolWindow(ID) != null } } }
mit
4001f6aa9ba878a3b0b216adf7331dd8
35.268293
129
0.686785
4.804523
false
false
false
false
androidx/androidx
text/text/src/main/java/androidx/compose/ui/text/android/style/PlaceholderSpan.kt
3
6378
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.android.style import android.annotation.SuppressLint import android.graphics.Canvas import android.graphics.Paint import android.text.style.ReplacementSpan import androidx.annotation.IntDef import androidx.compose.ui.text.android.InternalPlatformTextApi import kotlin.math.ceil import kotlin.math.max import kotlin.math.min /** * A span that is used to reserve empty spaces for inline element. It's used only to tell the * text processor the size and vertical alignment of the inline element. * * @param width The width needed by the inline element. * @param widthUnit The unit of the [width]; can be Sp, Em or inherit, if it's inherit, by * default it will be 1.em * @param height The height needed by the inline element. * @param heightUnit The unit of the [height]; can be Sp, Em or inherit, if it's inherit, by * default it will be computed from the context FontMetrics by * height = fontMetrics.descent - fontMetrics.ascent. * @param pxPerSp The number of pixels 1 Sp equals to. * @param verticalAlign How the inline element is aligned with the text. * * @suppress */ @InternalPlatformTextApi class PlaceholderSpan( private val width: Float, @Unit private val widthUnit: Int, private val height: Float, @Unit private val heightUnit: Int, private val pxPerSp: Float, @VerticalAlign val verticalAlign: Int ) : ReplacementSpan() { companion object { const val ALIGN_ABOVE_BASELINE = 0 const val ALIGN_TOP = 1 const val ALIGN_BOTTOM = 2 const val ALIGN_CENTER = 3 const val ALIGN_TEXT_TOP = 4 const val ALIGN_TEXT_BOTTOM = 5 const val ALIGN_TEXT_CENTER = 6 @Retention(AnnotationRetention.SOURCE) @IntDef( ALIGN_ABOVE_BASELINE, ALIGN_TOP, ALIGN_BOTTOM, ALIGN_CENTER, ALIGN_TEXT_TOP, ALIGN_TEXT_BOTTOM, ALIGN_TEXT_CENTER ) internal annotation class VerticalAlign const val UNIT_SP = 0 const val UNIT_EM = 1 const val UNIT_UNSPECIFIED = 2 @Retention(AnnotationRetention.SOURCE) @IntDef( UNIT_SP, UNIT_EM, UNIT_UNSPECIFIED ) internal annotation class Unit } /* Used to compute bounding box when verticalAlign is ALIGN_TEXT_TOP / ALIGN_TEXT_BOTTOM. */ lateinit var fontMetrics: Paint.FontMetricsInt private set /* The laid out width of the placeholder, in the unit of pixel. */ var widthPx: Int = 0 private set get() { check(isLaidOut) { "PlaceholderSpan is not laid out yet." } return field } /* The laid out height of the placeholder, in the unit of pixel. */ var heightPx: Int = 0 private set get() { check(isLaidOut) { "PlaceholderSpan is not laid out yet." } return field } /* Primitives can't be "lateinit", use this boolean to work around. */ private var isLaidOut: Boolean = false @SuppressLint("DocumentExceptions") override fun getSize( paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt? ): Int { isLaidOut = true val fontSize = paint.textSize fontMetrics = paint.fontMetricsInt require(fontMetrics.descent > fontMetrics.ascent) { "Invalid fontMetrics: line height can not be negative." } widthPx = when (widthUnit) { UNIT_SP -> width * pxPerSp UNIT_EM -> width * fontSize else -> throw IllegalArgumentException("Unsupported unit.") }.ceilToInt() heightPx = when (heightUnit) { UNIT_SP -> (height * pxPerSp).ceilToInt() UNIT_EM -> (height * fontSize).ceilToInt() else -> throw IllegalArgumentException("Unsupported unit.") } fm?.apply { ascent = fontMetrics.ascent descent = fontMetrics.descent leading = fontMetrics.leading when (verticalAlign) { // If align top and inline element is too tall, expand descent. ALIGN_TOP, ALIGN_TEXT_TOP -> if (ascent + heightPx > descent) { descent = ascent + heightPx } // If align bottom and inline element is too tall, expand ascent. ALIGN_BOTTOM, ALIGN_TEXT_BOTTOM -> if (ascent > descent - heightPx) { ascent = descent - heightPx } // If align center and inline element is too tall, evenly expand ascent and descent. ALIGN_CENTER, ALIGN_TEXT_CENTER -> if (descent - ascent < heightPx) { ascent -= (heightPx - (descent - ascent)) / 2 descent = ascent + heightPx } // If align baseline and inline element is too tall, expand ascent ALIGN_ABOVE_BASELINE -> if (ascent > -heightPx) { ascent = -heightPx } else -> throw IllegalArgumentException("Unknown verticalAlign.") } // make top/bottom at least same as ascent/descent. top = min(fontMetrics.top, ascent) bottom = max(fontMetrics.bottom, descent) } return widthPx } /* Empty implementation, not used. */ override fun draw( canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint ) {} } internal fun Float.ceilToInt(): Int = ceil(this).toInt()
apache-2.0
f152aa63d46161b47e3dd04254422a81
32.925532
100
0.610693
4.70354
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/v2/RankChartEntity.kt
1
893
package taiwan.no1.app.ssfm.models.entities.v2 import android.os.Parcelable import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.rx2.structure.BaseRXModel import kotlinx.android.parcel.Parcelize import taiwan.no1.app.ssfm.models.data.local.database.MusicDatabase import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity /** * @author jieyi * @since 11/24/17 */ @Parcelize @Table(database = MusicDatabase::class, allFields = true) data class RankChartEntity(@PrimaryKey(autoincrement = true) var id: Long = 0, var rankType: Int = 0, var coverUrl: String = "", var chartName: String = "", var updateTime: String = "") : BaseRXModel(), BaseEntity, Parcelable
apache-2.0
0620e0736d9b8b3111892fe48ab37c2c
39.636364
95
0.664054
4.134259
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/glfw/GLFWTypes.kt
1
19535
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.glfw import org.lwjgl.generator.* val GLFW_PACKAGE = "org.lwjgl.glfw" fun config() { packageInfo( GLFW_PACKAGE, """ Contains bindings to the <a href="http://www.glfw.org/">GLFW</a> library. GLFW comes with extensive documentation, which you can read online <a href="http://www.glfw.org/docs/latest/">here</a>. The <a href="http://www.glfw.org/faq.html">Frequently Asked Questions</a> are also useful. On Mac OS X the JVM must be started with the {@code -XstartOnFirstThread} argument for GLFW to work. This is necessary because most GLFW functions must be called on the main thread and the Cocoa API on OS X requires that thread to be the first thread in the process. For this reason, on-screen GLFW windows and the GLFW event loop are incompatible with other window toolkits (such as AWT/Swing or JavaFX) on OS X. Off-screen GLFW windows can be used with other window toolkits, but only if the window toolkit is initialized before GLFW. """ ) } val GLFW_BINDING = simpleBinding("glfw", """Configuration.GLFW_LIBRARY_NAME.get(Platform.mapLibraryNameBundled("glfw"))""") val GLFW_BINDING_DELEGATE = GLFW_BINDING.delegate("GLFW.getLibrary()") val GLFWmonitor = "GLFWmonitor".p val GLFWmonitor_p = GLFWmonitor.p val GLFWwindow = "GLFWwindow".p val GLFWvidmode_p = struct(GLFW_PACKAGE, "GLFWVidMode", nativeName = "GLFWvidmode", mutable = false) { documentation = "Describes a single video mode." int.member("width", "the width, in screen coordinates, of the video mode") int.member("height", "the height, in screen coordinates, of the video mode") int.member("redBits", "the bit depth of the red channel of the video mode") int.member("greenBits", "the bit depth of the green channel of the video mode") int.member("blueBits", "the bit depth of the blue channel of the video mode") int.member("refreshRate", "the refresh rate, in Hz, of the video mode") }.p val GLFWgammaramp_p = struct(GLFW_PACKAGE, "GLFWGammaRamp", nativeName = "GLFWgammaramp") { documentation = "Describes the gamma ramp for a monitor." unsigned_short_p.member("red", "an array of values describing the response of the red channel") unsigned_short_p.member("green", "an array of values describing the response of the green channel") unsigned_short_p.member("blue", "an array of values describing the response of the blue channel") AutoSize("red", "green", "blue")..unsigned_int.member("size", "the number of elements in each array") }.p val GLFWcursor = "GLFWcursor".p val GLFWimage_p = struct(GLFW_PACKAGE, "GLFWImage", nativeName = "GLFWimage") { documentation = "Image data." int.member("width", "the width, in pixels, of this image") int.member("height", "the height, in pixels, of this image") unsigned_char_p.member("pixels", "the pixel data of this image, arranged left-to-right, top-to-bottom") }.p // callback functions val GLFWerrorfun = "GLFWerrorfun".callback( GLFW_PACKAGE, void, "GLFWErrorCallback", "Will be called with an error code and a human-readable description when a GLFW error occurs.", int.IN("error", "the error code"), NullTerminated..charUTF8_p.IN("description", "a pointer to a UTF-8 encoded string describing the error") ) { documentation = "Instances of this interface may be passed to the #SetErrorCallback() method." javaImport( "java.io.PrintStream", "java.util.Map", "static org.lwjgl.glfw.GLFW.*" ) additionalCode = """ /** * Converts the specified {@link GLFWErrorCallback} argument to a String. * * <p>This method may only be used inside a GLFWErrorCallback invocation.</p> * * @param description pointer to the UTF-8 encoded description string * * @return the description as a String */ public static String getDescription(long description) { return memUTF8(description); } /** * Returns a {@link GLFWErrorCallback} instance that prints the error to the {@link APIUtil#DEBUG_STREAM}. * * @return the GLFWerrorCallback */ public static GLFWErrorCallback createPrint() { return createPrint(APIUtil.DEBUG_STREAM); } /** * Returns a {@link GLFWErrorCallback} instance that prints the error in the specified {@link PrintStream}. * * @param stream the PrintStream to use * * @return the GLFWerrorCallback */ public static GLFWErrorCallback createPrint(PrintStream stream) { return new GLFWErrorCallback() { private Map<Integer, String> ERROR_CODES = APIUtil.apiClassTokens((field, value) -> 0x10000 < value && value < 0x20000, null, GLFW.class); @Override public void invoke(int error, long description) { String msg = getDescription(description); stream.printf("[LWJGL] %s error\n", ERROR_CODES.get(error)); stream.println("\tDescription : " + msg); stream.println("\tStacktrace :"); StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for ( int i = 4; i < stack.length; i++ ) { stream.print("\t\t"); stream.println(stack[i].toString()); } } }; } /** * Returns a {@link GLFWErrorCallback} instance that throws an {@link IllegalStateException} when an error occurs. * * @return the GLFWerrorCallback */ public static GLFWErrorCallback createThrow() { return new GLFWErrorCallback() { @Override public void invoke(int error, long description) { throw new IllegalStateException(String.format("GLFW error [0x%X]: %s", error, getDescription(description))); } }; } /** See {@link GLFW#glfwSetErrorCallback SetErrorCallback}. */ public GLFWErrorCallback set() { glfwSetErrorCallback(this); return this; } """ } val GLFWmonitorfun = "GLFWmonitorfun".callback( GLFW_PACKAGE, void, "GLFWMonitorCallback", "Will be called when a monitor is connected to or disconnected from the system.", GLFWmonitor.IN("monitor", "the monitor that was connected or disconnected"), int.IN("event", "one of #CONNECTED or #DISCONNECTED") ) { documentation = "Instances of this interface may be passed to the #SetMonitorCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetMonitorCallback SetMonitorCallback}. */ public GLFWMonitorCallback set() { glfwSetMonitorCallback(this); return this; } """ } val GLFWjoystickfun = "GLFWjoystickfun".callback( GLFW_PACKAGE, void, "GLFWJoystickCallback", "Will be called when a joystick is connected to or disconnected from the system.", int.IN("joy", "the joystick that was connected or disconnected"), int.IN("event", "one of #CONNECTED or #DISCONNECTED") ) { documentation = "Instances of this interface may be passed to the #SetJoystickCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetJoystickCallback SetJoystickCallback}. */ public GLFWJoystickCallback set() { glfwSetJoystickCallback(this); return this; } """ } val GLFWwindowposfun = "GLFWwindowposfun".callback( GLFW_PACKAGE, void, "GLFWWindowPosCallback", "Will be called when the specified window moves.", GLFWwindow.IN("window", "the window that was moved"), int.IN("xpos", "the new x-coordinate, in pixels, of the upper-left corner of the client area of the window"), int.IN("ypos", "the new y-coordinate, in pixels, of the upper-left corner of the client area of the window") ) { documentation = "Instances of this interface may be passed to the #SetWindowPosCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowPosCallback SetWindowPosCallback}. */ public GLFWWindowPosCallback set(long window) { glfwSetWindowPosCallback(window, this); return this; } """ } val GLFWwindowsizefun = "GLFWwindowsizefun".callback( GLFW_PACKAGE, void, "GLFWWindowSizeCallback", "Will be called when the specified window is resized.", GLFWwindow.IN("window", "the window that was resized"), int.IN("width", "the new width, in screen coordinates, of the window"), int.IN("height", "the new height, in screen coordinates, of the window") ) { documentation = "Instances of this interface may be passed to the #SetWindowSizeCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowSizeCallback SetWindowSizeCallback}. */ public GLFWWindowSizeCallback set(long window) { glfwSetWindowSizeCallback(window, this); return this; } """ } val GLFWwindowclosefun = "GLFWwindowclosefun".callback( GLFW_PACKAGE, void, "GLFWWindowCloseCallback", "Will be called when the user attempts to close the specified window, for example by clicking the close widget in the title bar.", GLFWwindow.IN("window", "the window that the user attempted to close") ) { documentation = "Instances of this interface may be passed to the #SetWindowCloseCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowCloseCallback SetWindowCloseCallback}. */ public GLFWWindowCloseCallback set(long window) { glfwSetWindowCloseCallback(window, this); return this; } """ } val GLFWwindowrefreshfun = "GLFWwindowrefreshfun".callback( GLFW_PACKAGE, void, "GLFWWindowRefreshCallback", """ Will be called when the client area of the specified window needs to be redrawn, for example if the window has been exposed after having been covered by another window. """, GLFWwindow.IN("window", "the window whose content needs to be refreshed") ) { documentation = "Instances of this interface may be passed to the #SetWindowRefreshCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowRefreshCallback SetWindowRefreshCallback}. */ public GLFWWindowRefreshCallback set(long window) { glfwSetWindowRefreshCallback(window, this); return this; } """ } val GLFWwindowfocusfun = "GLFWwindowfocusfun".callback( GLFW_PACKAGE, void, "GLFWWindowFocusCallback", "Will be called when the specified window gains or loses focus.", GLFWwindow.IN("window", "the window that was focused or defocused"), intb.IN("focused", "#TRUE if the window was focused, or #FALSE if it was defocused") ) { documentation = "Instances of this interface may be passed to the #SetWindowFocusCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowFocusCallback SetWindowFocusCallback}. */ public GLFWWindowFocusCallback set(long window) { glfwSetWindowFocusCallback(window, this); return this; } """ } val GLFWwindowiconifyfun = "GLFWwindowiconifyfun".callback( GLFW_PACKAGE, void, "GLFWWindowIconifyCallback", "Will be called when the specified window is iconified or restored.", GLFWwindow.IN("window", "the window that was iconified or restored."), intb.IN("iconified", "#TRUE if the window was iconified, or #FALSE if it was restored") ) { documentation = "Instances of this interface may be passed to the #SetWindowIconifyCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowIconifyCallback SetWindowIconifyCallback}. */ public GLFWWindowIconifyCallback set(long window) { glfwSetWindowIconifyCallback(window, this); return this; } """ } val GLFWwindowmaximizefun = "GLFWwindowmaximizefun".callback( GLFW_PACKAGE, void, "GLFWWindowMaximizeCallback", "Will be called when the specified window is maximized or restored.", GLFWwindow.IN("window", "the window that was maximized or restored."), intb.IN("maximized", "#TRUE if the window was maximized, or #FALSE if it was restored") ) { documentation = "Instances of this interface may be passed to the #SetWindowMaximizeCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetWindowMaximizeCallback SetWindowMaximizeCallback}. */ public GLFWWindowMaximizeCallback set(long window) { glfwSetWindowMaximizeCallback(window, this); return this; } """ } val GLFWframebuffersizefun = "GLFWframebuffersizefun".callback( GLFW_PACKAGE, void, "GLFWFramebufferSizeCallback", "Will be called when the framebuffer of the specified window is resized.", GLFWwindow.IN("window", "the window whose framebuffer was resized"), int.IN("width", "the new width, in pixels, of the framebuffer"), int.IN("height", "the new height, in pixels, of the framebuffer") ) { documentation = "Instances of this interface may be passed to the #SetFramebufferSizeCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetFramebufferSizeCallback SetFramebufferSizeCallback}. */ public GLFWFramebufferSizeCallback set(long window) { glfwSetFramebufferSizeCallback(window, this); return this; } """ } val GLFWkeyfun = "GLFWkeyfun".callback( GLFW_PACKAGE, void, "GLFWKeyCallback", "Will be called when a key is pressed, repeated or released.", GLFWwindow.IN("window", "the window that received the event"), int.IN("key", "the keyboard key that was pressed or released"), int.IN("scancode", "the system-specific scancode of the key"), int.IN("action", "the key action", "#PRESS #RELEASE #REPEAT"), int.IN("mods", "bitfield describing which modifiers keys were held down") ) { documentation = "Instances of this interface may be passed to the #SetKeyCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetKeyCallback SetKeyCallback}. */ public GLFWKeyCallback set(long window) { glfwSetKeyCallback(window, this); return this; } """ } val GLFWcharfun = "GLFWcharfun".callback( GLFW_PACKAGE, void, "GLFWCharCallback", "Will be called when a Unicode character is input.", GLFWwindow.IN("window", "the window that received the event"), unsigned_int.IN("codepoint", "the Unicode code point of the character") ) { documentation = "Instances of this interface may be passed to the #SetCharCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetCharCallback SetCharCallback}. */ public GLFWCharCallback set(long window) { glfwSetCharCallback(window, this); return this; } """ } val GLFWcharmodsfun = "GLFWcharmodsfun".callback( GLFW_PACKAGE, void, "GLFWCharModsCallback", "Will be called when a Unicode character is input regardless of what modifier keys are used.", GLFWwindow.IN("window", "the window that received the event"), unsigned_int.IN("codepoint", "the Unicode code point of the character"), int.IN("mods", "bitfield describing which modifier keys were held down") ) { documentation = "Instances of this interface may be passed to the #SetCharModsCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetCharModsCallback SetCharModsCallback}. */ public GLFWCharModsCallback set(long window) { glfwSetCharModsCallback(window, this); return this; } """ } val GLFWmousebuttonfun = "GLFWmousebuttonfun".callback( GLFW_PACKAGE, void, "GLFWMouseButtonCallback", "Will be called when a mouse button is pressed or released.", GLFWwindow.IN("window", "the window that received the event"), int.IN("button", "the mouse button that was pressed or released"), int.IN("action", "the button action", "#PRESS #RELEASE #REPEAT"), int.IN("mods", "bitfield describing which modifiers keys were held down") ) { documentation = "Instances of this interface may be passed to the #SetMouseButtonCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetMouseButtonCallback SetMouseButtonCallback}. */ public GLFWMouseButtonCallback set(long window) { glfwSetMouseButtonCallback(window, this); return this; } """ } val GLFWcursorposfun = "GLFWcursorposfun".callback( GLFW_PACKAGE, void, "GLFWCursorPosCallback", """ Will be called when the cursor is moved. The callback function receives the cursor position, measured in screen coordinates but relative to the top-left corner of the window client area. On platforms that provide it, the full sub-pixel cursor position is passed on. """, GLFWwindow.IN("window", "the window that received the event"), double.IN("xpos", "the new cursor x-coordinate, relative to the left edge of the client area"), double.IN("ypos", "the new cursor y-coordinate, relative to the top edge of the client area") ) { documentation = "Instances of this interface may be passed to the #SetCursorPosCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetCursorPosCallback SetCursorPosCallback}. */ public GLFWCursorPosCallback set(long window) { glfwSetCursorPosCallback(window, this); return this; } """ } val GLFWcursorenterfun = "GLFWcursorenterfun".callback( GLFW_PACKAGE, void, "GLFWCursorEnterCallback", "Will be called when the cursor enters or leaves the client area of the window.", GLFWwindow.IN("window", "the window that received the event"), intb.IN("entered", "#TRUE if the cursor entered the window's client area, or #FALSE if it left it") ) { documentation = "Instances of this interface may be passed to the #SetCursorEnterCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetCursorEnterCallback SetCursorEnterCallback}. */ public GLFWCursorEnterCallback set(long window) { glfwSetCursorEnterCallback(window, this); return this; } """ } val GLFWscrollfun = "GLFWscrollfun".callback( GLFW_PACKAGE, void, "GLFWScrollCallback", "Will be called when a scrolling device is used, such as a mouse wheel or scrolling area of a touchpad.", GLFWwindow.IN("window", "the window that received the event"), double.IN("xoffset", "the scroll offset along the x-axis"), double.IN("yoffset", "the scroll offset along the y-axis") ) { documentation = "Instances of this interface may be passed to the #SetScrollCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** See {@link GLFW#glfwSetScrollCallback SetScrollCallback}. */ public GLFWScrollCallback set(long window) { glfwSetScrollCallback(window, this); return this; } """ } val GLFWdropfun = "GLFWdropfun".callback( GLFW_PACKAGE, void, "GLFWDropCallback", "Will be called when one or more dragged files are dropped on the window.", GLFWwindow.IN("window", "the window that received the event"), AutoSize("names")..int.IN("count", "the number of dropped files"), const..char_pp.IN("names", "pointer to the array of UTF-8 encoded path names of the dropped files") ) { documentation = "Instances of this interface may be passed to the #SetDropCallback() method." javaImport("static org.lwjgl.glfw.GLFW.*") additionalCode = """ /** * Decodes the specified {@link GLFWDropCallback} arguments to a String. * * <p>This method may only be used inside a {@code GLFWDropCallback} invocation.</p> * * @param names pointer to the array of UTF-8 encoded path names of the dropped files * @param index the index to decode * * @return the name at the specified index as a String */ public static String getName(long names, int index) { return memUTF8(memGetAddress(names + Pointer.POINTER_SIZE * index)); } /** See {@link GLFW#glfwSetDropCallback SetDropCallback}. */ public GLFWDropCallback set(long window) { glfwSetDropCallback(window, this); return this; } """ } // OpenGL val GLFWglproc = "GLFWglproc".p // Vulkan val GLFWvkproc = "GLFWvkproc".p
bsd-3-clause
bc5be8039766db38efcc29bcce7911f7
38.466667
159
0.736473
3.736611
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/quickassist/KotlinConvertToBlockBodyAssistProposal.kt
1
6873
/******************************************************************************* * Copyright 2000-2016 JetBrains s.r.o. * * 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 org.jetbrains.kotlin.ui.editors.quickassist import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import org.eclipse.jface.text.IDocument import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.eclipse.ui.utils.getBindingContext import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.ui.editors.KotlinEditor import org.jetbrains.kotlin.ui.formatter.formatRange import org.jetbrains.kotlin.types.isError class KotlinConvertToBlockBodyAssistProposal(editor: KotlinEditor) : KotlinQuickAssistProposal(editor) { override fun isApplicable(psiElement: PsiElement): Boolean { val declaration = PsiTreeUtil.getParentOfType(psiElement, KtDeclarationWithBody::class.java) ?: return false if (declaration is KtFunctionLiteral || declaration.hasBlockBody() || !declaration.hasBody()) return false when (declaration) { is KtNamedFunction -> { val bindingContext = getBindingContext(declaration) ?: return false; val returnType: KotlinType = declaration.returnType(bindingContext) ?: return false // do not convert when type is implicit and unknown if (!declaration.hasDeclaredReturnType() && returnType.isError) return false return true } is KtPropertyAccessor -> return true else -> error("Unknown declaration type: $declaration") } } override fun getDisplayString() = "Convert to block body" override fun apply(document: IDocument, psiElement: PsiElement) { val declaration = PsiTreeUtil.getParentOfType(psiElement, KtDeclarationWithBody::class.java)!! val context = getBindingContext(declaration)!! val shouldSpecifyType = declaration is KtNamedFunction && !declaration.hasDeclaredReturnType() && !KotlinBuiltIns.isUnit(declaration.returnType(context)!!) val factory = KtPsiFactory(declaration) replaceBody(declaration, factory, context, editor) if (shouldSpecifyType) { specifyType(declaration, factory, context) } } private fun replaceBody(declaration: KtDeclarationWithBody, factory: KtPsiFactory, context: BindingContext, editor: KotlinEditor) { val newBody = convert(declaration, context, factory) var newBodyText = newBody.getNode().text val anchorToken = declaration.getEqualsToken() if (anchorToken!!.getNextSibling() !is PsiWhiteSpace) { newBodyText = factory.createWhiteSpace().getText() + newBodyText } replaceBetween(anchorToken, declaration.getBodyExpression()!!, newBodyText) val anchorStartOffset = anchorToken.textRange.startOffset val file = editor.eclipseFile ?: return formatRange( editor.document, TextRange(anchorStartOffset, anchorStartOffset + newBodyText.length), factory, file.name) } private fun specifyType(declaration: KtDeclarationWithBody, factory: KtPsiFactory, context: BindingContext) { val returnType = (declaration as KtNamedFunction).returnType(context).toString() val stringToInsert = listOf(factory.createColon(), factory.createWhiteSpace()) .joinToString(separator = "") { it.getText() } + returnType insertAfter(declaration.getValueParameterList()!!, stringToInsert) } private fun convert(declaration: KtDeclarationWithBody, bindingContext: BindingContext, factory: KtPsiFactory): KtExpression { val body = declaration.getBodyExpression()!! fun generateBody(returnsValue: Boolean): KtExpression { val bodyType = bindingContext.getType(body) val needReturn = returnsValue && (bodyType == null || (!KotlinBuiltIns.isUnit(bodyType) && !KotlinBuiltIns.isNothing(bodyType))) val expression = factory.createExpression(body.getText()) val block: KtBlockExpression = if (needReturn) { factory.createBlock("return xyz") } else { return factory.createBlock(expression.getText()) } val returnExpression = PsiTreeUtil.getChildOfType(block, KtReturnExpression::class.java) val returned = returnExpression?.getReturnedExpression() ?: return factory.createBlock("return ${expression.getText()}") if (KtPsiUtil.areParenthesesNecessary(expression, returned, returnExpression!!)) { return factory.createBlock("return (${expression.getText()})") } return factory.createBlock("return ${expression.getText()}") } val newBody = when (declaration) { is KtNamedFunction -> { val returnType = declaration.returnType(bindingContext)!! generateBody(!KotlinBuiltIns.isUnit(returnType) && !KotlinBuiltIns.isNothing(returnType)) } is KtPropertyAccessor -> generateBody(declaration.isGetter()) else -> throw RuntimeException("Unknown declaration type: $declaration") } return newBody } private fun KtNamedFunction.returnType(context: BindingContext): KotlinType? { val descriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return null return (descriptor as FunctionDescriptor).getReturnType() } }
apache-2.0
04972bc765abb38c323d49f13f7f3255
45.445946
135
0.684417
5.454762
false
false
false
false
edsilfer/sticky-index
library/src/main/java/br/com/stickyindex/view/StickyIndex.kt
1
2586
package br.com.stickyindex.view import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.LayoutInflater.from import android.view.MotionEvent.ACTION_MOVE import android.widget.RelativeLayout import br.com.edsilfer.toolkit.core.util.InvalidData.Companion.isInvalid import br.com.stickyindex.R import br.com.stickyindex.model.RowStyle import br.com.stickyindex.model.RowStyleMapper.map import kotlinx.android.synthetic.main.stickyindex_view.view.* /** * Created by edgarsf on 22/03/2018. */ class StickyIndex @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr) { private lateinit var adapterSticky: StickyIndexAdapter lateinit var stickyStickyIndex: StickyIndexLayoutManager init { from(context).inflate(R.layout.stickyindex_view, this, true) applyStyle(map(context, context.obtainStyledAttributes(attrs, R.styleable.StickyIndex))) } private fun applyStyle(style: RowStyle?) { renderStickyList(context, style) if (style == null) return stickyStickyIndex.applyStyle(style) renderStickyWrapper(style) if (!isInvalid(style.height)) { val params = sticky_index_wrapper.layoutParams params.height = style.height.toInt() sticky_index_wrapper.layoutParams = params } } private fun renderStickyList(context: Context, styles: RowStyle?) { index_list.layoutManager = LinearLayoutManager(context) index_list.setOnTouchListener { _, event -> event.action == ACTION_MOVE } adapterSticky = StickyIndexAdapter(charArrayOf(), styles) index_list.adapter = adapterSticky stickyStickyIndex = StickyIndexLayoutManager(this, index_list) } private fun renderStickyWrapper(styles: RowStyle) { val params = sticky_index_wrapper.layoutParams params.width = styles.width.toInt() sticky_index_wrapper.layoutParams = params invalidate() } fun refresh(dataSet: CharArray) { adapterSticky.refresh(dataSet) adapterSticky.notifyDataSetChanged() } fun bindRecyclerView(rv: RecyclerView) { rv.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) { stickyStickyIndex.update(rv, dy.toFloat()) } }) } }
apache-2.0
e1bb47858de2bdc47d3ef7302e41e79c
34.930556
96
0.706883
4.466321
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/nbt/tags/TagIntArray.kt
1
1226
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.tags import java.io.DataOutputStream class TagIntArray(override val value: IntArray) : NbtValueTag<IntArray>(IntArray::class.java) { override val payloadSize = 4 + value.size * 4 override val typeId = NbtTypeId.INT_ARRAY override fun write(stream: DataOutputStream) { stream.writeInt(value.size) for (i in value) { stream.writeInt(i) } } override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString() override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState): StringBuilder { value.joinTo(buffer = sb, separator = ", ", prefix = "ints(", postfix = ")") return sb } override fun valueEquals(otherValue: IntArray) = this.value.contentEquals(otherValue) // This makes IntelliJ happy - and angry at the same time @Suppress("RedundantOverride") override fun equals(other: Any?) = super.equals(other) override fun hashCode() = this.value.contentHashCode() override fun valueCopy() = value.copyOf(value.size) }
mit
24056843953d769a1733987bc1990339
28.190476
105
0.681077
4.114094
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/client/tools/GenerateSyntheticData.kt
1
6338
// Copyright 2022 The Cross-Media Measurement Authors // // 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 org.wfanet.panelmatch.client.tools import com.google.protobuf.kotlin.toByteString import com.google.protobuf.kotlin.toByteStringUtf8 import java.io.File import java.time.Instant import java.util.concurrent.TimeUnit import kotlin.properties.Delegates import kotlin.random.Random import org.wfanet.measurement.common.commandLineMain import org.wfanet.panelmatch.client.eventpreprocessing.UnprocessedEvent import org.wfanet.panelmatch.client.eventpreprocessing.unprocessedEvent import org.wfanet.panelmatch.client.exchangetasks.JoinKeyAndId import org.wfanet.panelmatch.client.exchangetasks.joinKey import org.wfanet.panelmatch.client.exchangetasks.joinKeyAndId import org.wfanet.panelmatch.client.exchangetasks.joinKeyAndIdCollection import org.wfanet.panelmatch.client.exchangetasks.joinKeyIdentifier import org.wfanet.panelmatch.common.compression.CompressionParametersKt.brotliCompressionParameters import org.wfanet.panelmatch.common.compression.CompressionParametersKt.noCompression import org.wfanet.panelmatch.common.compression.compressionParameters import org.wfanet.panelmatch.common.toDelimitedByteString import picocli.CommandLine.Command import picocli.CommandLine.Option import wfa_virtual_people.dataProviderEvent import wfa_virtual_people.labelerInput import wfa_virtual_people.logEvent private val FROM_TIME = TimeUnit.SECONDS.toMicros(Instant.parse("2022-01-01T00:00:00Z").epochSecond) private val UNTIL_TIME = TimeUnit.SECONDS.toMicros(Instant.parse("2022-04-04T00:00:00Z").epochSecond) @Command( name = "generate-synthetic-data", description = ["Generates synthetic data for Panel Match."] ) class GenerateSyntheticData : Runnable { @set:Option( names = ["--number_of_events"], description = ["Number of UnprocessedEvent protos to generate."], required = true, ) var numberOfEvents by Delegates.notNull<Int>() private set @Option( names = ["--unprocessed_events_output_path"], description = ["Path to the file where UnprocessedEvent protos will be written."], required = false, defaultValue = "edp-unprocessed-events" ) private lateinit var unprocessedEventsFile: File @Option( names = ["--join_keys_output_path"], description = ["Path to the file where JoinKeyAndIdCollection proto will be written."], required = false, defaultValue = "mp-plaintext-join-keys" ) private lateinit var joinKeysFile: File @set:Option( names = ["--join_key_sample_rate"], description = ["The sample rate [0, 1] used for selecting an UnprocessedEvent proto."], required = true, defaultValue = "0.0005" ) var sampleRate by Delegates.notNull<Double>() private set @Option( names = ["--brotli_dictionary_path"], description = ["Path to a file containing a Brotli dictionary."], required = false, ) private lateinit var brotliInputFile: File @Option( names = ["--compression_parameters_output_path"], description = ["Path to the file where the CompressionParameters proto will be written."], required = false ) private lateinit var brotliOutputFile: File @Option( names = ["--previous_join_keys_input_path"], description = ["Path to the file where the previous day's join keys are stored."], required = false, ) private lateinit var joinKeyInputFile: File @Option( names = ["--previous_join_keys_output_path"], description = ["Path to the file where previous day's join keys will be copied to."], required = false ) private lateinit var joinKeyOutputFile: File /** Creates a [JoinKeyAndId] proto from the given [UnprocessedEvent] proto. */ fun UnprocessedEvent.toJoinKeyAndId(): JoinKeyAndId { return joinKeyAndId { this.joinKey = joinKey { key = id } this.joinKeyIdentifier = joinKeyIdentifier { this.id = "$id-join-key-id".toByteStringUtf8() } } } fun generateSyntheticData(id: Int): UnprocessedEvent { val rawDataProviderEvent = dataProviderEvent { this.logEvent = logEvent { this.labelerInput = labelerInput { this.timestampUsec = Random.nextLong(FROM_TIME, UNTIL_TIME) } } } return unprocessedEvent { this.id = id.toString().toByteStringUtf8() this.data = rawDataProviderEvent.toByteString() } } fun writeCompressionParameters() { if (brotliOutputFile.name.isEmpty()) return val params = if (brotliInputFile.name.isEmpty()) { compressionParameters { this.uncompressed = noCompression {} } } else { compressionParameters { this.brotli = brotliCompressionParameters { this.dictionary = brotliInputFile.readBytes().toByteString() } } } brotliOutputFile.outputStream().use { outputStream -> outputStream.write(params.toByteString().toByteArray()) } } @kotlin.io.path.ExperimentalPathApi override fun run() { val joinKeyAndIdProtos = mutableListOf<JoinKeyAndId>() val events = sequence { (1..numberOfEvents).forEach { val event = generateSyntheticData(it) if (Random.nextDouble(1.0) < sampleRate) { joinKeyAndIdProtos.add(event.toJoinKeyAndId()) } yield(event) } } unprocessedEventsFile.outputStream().use { outputStream -> events.forEach { outputStream.write(it.toDelimitedByteString().toByteArray()) } } joinKeysFile.outputStream().use { outputStream -> outputStream.write( joinKeyAndIdCollection { joinKeyAndIds += joinKeyAndIdProtos }.toByteArray() ) } writeCompressionParameters() joinKeyInputFile.copyTo(joinKeyOutputFile) } } fun main(args: Array<String>) = commandLineMain(GenerateSyntheticData(), args)
apache-2.0
b3a6d8fdae3c27962bb9b30f5029e4cf
33.445652
100
0.727201
4.142484
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt
3
2965
package info.nightscout.androidaps.utils import android.app.Activity import android.app.Application import android.os.Bundle import android.text.Spanned import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L import org.slf4j.LoggerFactory object ActivityMonitor : Application.ActivityLifecycleCallbacks { private val log = LoggerFactory.getLogger(L.CORE) override fun onActivityPaused(activity: Activity?) { val name = activity?.javaClass?.simpleName ?: return val resumed = SP.getLong("Monitor_" + name + "_" + "resumed", 0) if (resumed == 0L) { log.debug("onActivityPaused: $name resumed == 0") return } val elapsed = DateUtil.now() - resumed val total = SP.getLong("Monitor_" + name + "_total", 0) if (total == 0L) { SP.putLong("Monitor_" + name + "_start", DateUtil.now()) } SP.putLong("Monitor_" + name + "_total", total + elapsed) log.debug("onActivityPaused: $name elapsed=$elapsed total=${total + elapsed}") } override fun onActivityResumed(activity: Activity?) { val name = activity?.javaClass?.simpleName ?: return log.debug("onActivityResumed: $name") SP.putLong("Monitor_" + name + "_" + "resumed", DateUtil.now()) } override fun onActivityStarted(activity: Activity?) { } override fun onActivityDestroyed(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { } fun toText(): String { val keys: Map<String, *> = SP.getAll() var result = "" for ((key, value) in keys) if (key.startsWith("Monitor") && key.endsWith("total")) { val v = if (value is Long) value else SafeParse.stringToLong(value as String) val activity = key.split("_")[1].replace("Activity", "") val duration = DateUtil.niceTimeScalar(v as Long) val start = SP.getLong(key.replace("total", "start"), 0) val days = T.msecs(DateUtil.now() - start).days() result += "<b><span style=\"color:yellow\">$activity:</span></b> <b>$duration</b> in <b>$days</b> days<br>" } return result } fun stats(): Spanned { return HtmlHelper.fromHtml("<br><b>" + MainApp.gs(R.string.activitymonitor) + ":</b><br>" + toText()) } fun reset() { val keys: Map<String, *> = SP.getAll() for ((key, _) in keys) if (key.startsWith("Monitor") && key.endsWith("total")) { SP.remove(key) SP.remove(key.replace("total", "start")) SP.remove(key.replace("total", "resumed")) } } }
agpl-3.0
dca9c32a6dd67cf3d7375f8adb8c008e
36.544304
123
0.6
4.303338
false
false
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/execution/ui/impl/ConsoleViewTokenBuffer.kt
1
1142
/* * Copyright (C) 2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.core.execution.ui.impl class ConsoleViewTokenBuffer { private val tokens: ArrayList<ConsoleViewToken> = arrayListOf() var length: Int = 0 private set fun toTypedArray(): Array<ConsoleViewToken> = tokens.toTypedArray() fun add(token: ConsoleViewToken) { tokens.add(token) length += token.text.length } fun clear() { tokens.clear() length = 0 } fun isEmpty(): Boolean = length == 0 fun isNotEmpty(): Boolean = length != 0 }
apache-2.0
4f9e2bb36c03eda3f96d050c5887794d
28.282051
75
0.690018
4.198529
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/format/obj/ObjFileData.kt
2
6355
package assimp.format.obj import assimp.AI_MAX_NUMBER_OF_TEXTURECOORDS import assimp.AiColor3D import assimp.AiPrimitiveType import assimp.AiVector3D import glm_.mat4x4.Mat4 /** * Created by elect on 21/11/2016. */ // ------------------------------------------------------------------------------------------------ //! \struct Face //! \brief Data structure for a simple obj-face, describes discredit,l.ation and materials // ------------------------------------------------------------------------------------------------ data class Face( //! Primitive Type var m_PrimitiveType: AiPrimitiveType = AiPrimitiveType.POLYGON, //! Vertex indices var m_vertices: MutableList<Int> = mutableListOf(), //! Normal indices var m_normals: MutableList<Int> = mutableListOf(), //! Texture coordinates indices var m_texturCoords: MutableList<Int> = mutableListOf(), //! Pointer to assigned material var m_pMaterial: Material? = null ) // ------------------------------------------------------------------------------------------------ //! \struct Object //! \brief Stores all objects of an obj-file object definition // ------------------------------------------------------------------------------------------------ class Object( //! Object name var m_strObjName: String = "", //! Transformation matrix, stored in OpenGL format var m_Transformation: Mat4 = Mat4(), //! All sub-objects referenced by this object var m_SubObjects: List<Object> = listOf(), /// Assigned meshes var m_Meshes: MutableList<Int> = mutableListOf() ) { enum class Type { Obj, Group } } // ------------------------------------------------------------------------------------------------ //! \struct Material //! \brief Data structure to store all material specific data // ------------------------------------------------------------------------------------------------ data class Material( //! Name of material description var materialName: String, //! Textures var textures: ArrayList<Texture> = ArrayList(), //! Ambient color var ambient: AiColor3D = AiColor3D(), //! Diffuse color var diffuse: AiColor3D = AiColor3D(0.6), //! Specular color var specular: AiColor3D = AiColor3D(), //! Emissive color var emissive: AiColor3D = AiColor3D(), //! Alpha value var alpha: Float = 1.0f, //! Shineness factor var shineness: Float = 0.0f, //! Illumination model var illumination_model: Int = 1, //! Index of refraction var ior: Float = 1.0f, //! Transparency color var transparent: AiColor3D = AiColor3D(1f) ) { class Texture( val name: String, val type: Type, val clamp: Boolean = false ) { enum class Type { diffuse, specular, ambient, emissive, bump, normal, reflectionSphere, reflectionCubeTop, reflectionCubeBottom, reflectionCubeFront, reflectionCubeBack, reflectionCubeLeft, reflectionCubeRight, specularity, opacity, disp } } } // ------------------------------------------------------------------------------------------------ //! \struct Mesh //! \brief Data structure to store a mesh // ------------------------------------------------------------------------------------------------ data class Mesh( /// The name for the mesh var m_name: String, /// Array with pointer to all stored faces var m_Faces: MutableList<Face> = mutableListOf(), /// Assigned material var m_pMaterial: Material? = null, /// Number of stored indices. var m_uiNumIndices: Int = 0, /// Number of UV var m_uiUVCoordinates: IntArray = IntArray(AI_MAX_NUMBER_OF_TEXTURECOORDS) { 0 }, /// Material index. var m_uiMaterialIndex: Int = NoMaterial, // True, if normals are stored. var m_hasNormals: Boolean = false, /// True, if vertex colors are stored. var m_hasVertexColors: Boolean = true ) { companion object { const val NoMaterial = -1 } } // ------------------------------------------------------------------------------------------------ //! \struct Model //! \brief Data structure to store all obj-specific model datas // ------------------------------------------------------------------------------------------------ data class Model( //! Model name var m_ModelName: String = "", //! List ob assigned objects var m_Objects: MutableList<Object> = mutableListOf(), //! Pointer to current object var m_pCurrent: Object? = null, //! Pointer to current material var currentMaterial: Material? = null, //! Pointer to default material var defaultMaterial: Material? = null, //! Vector with all generated materials var materialLib: MutableList<String> = mutableListOf(), //! Vector with all generated vertices var m_Vertices: MutableList<AiVector3D> = mutableListOf(), //! vector with all generated normals var m_Normals: MutableList<AiVector3D> = mutableListOf(), //! vector with all vertex colors var m_VertexColors: MutableList<AiVector3D> = mutableListOf(), //! Group map var m_Groups: MutableMap<String, MutableList<Int>> = mutableMapOf(), //! Group to face id assignment var m_pGroupFaceIDs: MutableList<Int> = mutableListOf(), //! Active group var m_strActiveGroup: String = "", //! Vector with generated texture coordinates var m_TextureCoord: MutableList<MutableList<Float>> = mutableListOf(), /** Maximum dimension of texture coordinates */ var textureCoordDim: Int = 0, //! Current mesh instance var currentMesh: Mesh? = null, //! Vector with stored meshes var m_Meshes: MutableList<Mesh> = mutableListOf(), //! Material map var materialMap: MutableMap<String, Material> = mutableMapOf() )
mit
0c500cc9ca9f7e82c0d11b08a4490304
35.528736
99
0.506373
5.166667
false
false
false
false
InsertKoinIO/koin
android/koin-android/src/main/java/org/koin/androidx/viewmodel/ext/android/FragmentVM.kt
1
2505
/* * Copyright 2017-2021 the original author or authors. * * 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 org.koin.androidx.viewmodel.ext.android import androidx.annotation.MainThread import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.CreationExtras import org.koin.android.ext.android.getKoinScope import org.koin.androidx.viewmodel.resolveViewModel import org.koin.core.annotation.KoinInternalApi import org.koin.core.parameter.ParametersHolder import org.koin.core.qualifier.Qualifier /** * ViewModel API from Fragment * * @author Arnaud Giuliani */ /** * Retrieve Lazy ViewModel instance for Fragment * @param qualifier * @param ownerProducer * @param extrasProducer * @param parameters */ @MainThread inline fun <reified T : ViewModel> Fragment.viewModel( qualifier: Qualifier? = null, noinline ownerProducer: () -> ViewModelStoreOwner = { this }, noinline extrasProducer: (() -> CreationExtras)? = null, noinline parameters: (() -> ParametersHolder)? = null, ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getViewModel(qualifier, ownerProducer, extrasProducer, parameters) } } /** * Retrieve ViewModel instance for Fragment * @param qualifier * @param ownerProducer * @param extrasProducer * @param parameters */ @OptIn(KoinInternalApi::class) @MainThread inline fun <reified T : ViewModel> Fragment.getViewModel( qualifier: Qualifier? = null, noinline ownerProducer: () -> ViewModelStoreOwner = { this }, noinline extrasProducer: (() -> CreationExtras)? = null, noinline parameters: (() -> ParametersHolder)? = null, ): T { return resolveViewModel( T::class, ownerProducer().viewModelStore, extras = extrasProducer?.invoke() ?: this.defaultViewModelCreationExtras, qualifier = qualifier, parameters = parameters, scope = getKoinScope() ) }
apache-2.0
5c1f70bae7ca3838a4de075df4ab25ff
31.545455
81
0.732934
4.457295
false
false
false
false
jdiazcano/modulartd
editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/OpenProjectDialog.kt
1
2037
package com.jdiazcano.modulartd.ui.widgets import com.jdiazcano.modulartd.bus.Bus import com.jdiazcano.modulartd.bus.BusTopic import com.jdiazcano.modulartd.config.Configs import com.jdiazcano.modulartd.plugins.bundled.LoadMapEvent import com.jdiazcano.modulartd.plugins.bundled.createBaseMapFiles import com.jdiazcano.modulartd.utils.changeListener import com.jdiazcano.modulartd.utils.createErrorDialog import com.jdiazcano.modulartd.utils.setSingleFileListener import com.jdiazcano.modulartd.utils.translate import com.kotcrab.vis.ui.widget.VisDialog import com.kotcrab.vis.ui.widget.VisTextButton import com.kotcrab.vis.ui.widget.file.FileChooser object OpenProjectDialog : VisDialog(translate("select.project")) { private val open: VisTextButton private val newMap: VisTextButton init { isModal = true val errorDialog = createErrorDialog("Failed to open", "You can only select one folder when opening or creating a project") val chooser = FileChooser(translate("select.project"), FileChooser.Mode.OPEN) chooser.setWatchingFilesEnabled(true) chooser.selectionMode = FileChooser.SelectionMode.DIRECTORIES chooser.setSingleFileListener(errorDialog) { file -> val itdFolder = file.child(Configs.editor.gameConfigFolder()) val existingMap = itdFolder.exists() if (!existingMap) { createBaseMapFiles(file) } Bus.post(LoadMapEvent(file, existingMap), BusTopic.MAP_LOAD) fadeOut() } open = VisTextButton(translate("file.open")) open.changeListener { _, _ -> Bus.post(chooser.fadeIn(), BusTopic.NEW_DIALOG) } newMap = VisTextButton(translate("file.new")) newMap.changeListener { _, _ -> Bus.post(chooser.fadeIn(), BusTopic.NEW_DIALOG) } add(open) add(newMap) isModal = true pack() centerWindow() } fun select() = Bus.post(fadeIn(), BusTopic.NEW_DIALOG) }
apache-2.0
6d587f6448460d881b2953684f7ea2a3
34.137931
130
0.69514
4.380645
false
true
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt
1
4410
package info.nightscout.androidaps.utils import android.content.Context import info.nightscout.androidaps.annotations.OpenForTesting import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject import javax.inject.Singleton import kotlin.math.max import kotlin.math.min @OpenForTesting @Singleton class HardLimits @Inject constructor( private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val sp: SP, private val rh: ResourceHelper, private val context: Context, private val repository: AppRepository ) { private val disposable = CompositeDisposable() companion object { private const val CHILD = 0 private const val TEENAGE = 1 private const val ADULT = 2 private const val RESISTANT_ADULT = 3 private const val PREGNANT = 4 private val MAX_BOLUS = doubleArrayOf(5.0, 10.0, 17.0, 25.0, 60.0) // Very Hard Limits Ranges // First value is the Lowest and second value is the Highest a Limit can define val VERY_HARD_LIMIT_MIN_BG = doubleArrayOf(80.0, 180.0) val VERY_HARD_LIMIT_MAX_BG = doubleArrayOf(90.0, 200.0) val VERY_HARD_LIMIT_TARGET_BG = doubleArrayOf(80.0, 200.0) // Very Hard Limits Ranges for Temp Targets val VERY_HARD_LIMIT_TEMP_MIN_BG = intArrayOf(72, 180) val VERY_HARD_LIMIT_TEMP_MAX_BG = intArrayOf(72, 270) val VERY_HARD_LIMIT_TEMP_TARGET_BG = intArrayOf(72, 200) val MIN_DIA = doubleArrayOf(5.0, 5.0, 5.0, 5.0, 5.0) val MAX_DIA = doubleArrayOf(9.0, 9.0, 9.0, 9.0, 10.0) val MIN_IC = doubleArrayOf(2.0, 2.0, 2.0, 2.0, 0.3) val MAX_IC = doubleArrayOf(100.0, 100.0, 100.0, 100.0, 100.0) const val MIN_ISF = 2.0 // mgdl const val MAX_ISF = 1000.0 // mgdl val MAX_IOB_AMA = doubleArrayOf(3.0, 5.0, 7.0, 12.0, 25.0) val MAX_IOB_SMB = doubleArrayOf(7.0, 13.0, 22.0, 30.0, 70.0) val MAX_BASAL = doubleArrayOf(2.0, 5.0, 10.0, 12.0, 25.0) //LGS Hard limits //No IOB at all const val MAX_IOB_LGS = 0.0 } private fun loadAge(): Int = when (sp.getString(R.string.key_age, "")) { rh.gs(R.string.key_child) -> CHILD rh.gs(R.string.key_teenage) -> TEENAGE rh.gs(R.string.key_adult) -> ADULT rh.gs(R.string.key_resistantadult) -> RESISTANT_ADULT rh.gs(R.string.key_pregnant) -> PREGNANT else -> ADULT } fun maxBolus(): Double = MAX_BOLUS[loadAge()] fun maxIobAMA(): Double = MAX_IOB_AMA[loadAge()] fun maxIobSMB(): Double = MAX_IOB_SMB[loadAge()] fun maxBasal(): Double = MAX_BASAL[loadAge()] fun minDia(): Double = MIN_DIA[loadAge()] fun maxDia(): Double = MAX_DIA[loadAge()] fun minIC(): Double = MIN_IC[loadAge()] fun maxIC(): Double = MAX_IC[loadAge()] // safety checks fun checkHardLimits(value: Double, valueName: Int, lowLimit: Double, highLimit: Double): Boolean = value == verifyHardLimits(value, valueName, lowLimit, highLimit) fun isInRange(value: Double, lowLimit: Double, highLimit: Double): Boolean = value in lowLimit..highLimit fun verifyHardLimits(value: Double, valueName: Int, lowLimit: Double, highLimit: Double): Double { var newValue = value if (newValue < lowLimit || newValue > highLimit) { newValue = max(newValue, lowLimit) newValue = min(newValue, highLimit) var msg = rh.gs(R.string.valueoutofrange, rh.gs(valueName)) msg += ".\n" msg += rh.gs(R.string.valuelimitedto, value, newValue) aapsLogger.error(msg) disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(msg)).subscribe() ToastUtils.showToastInUiThread(context, rxBus, msg, R.raw.error) } return newValue } }
agpl-3.0
3c8b7f8f2d87a61749a8d7ea35752b28
40.613208
111
0.656916
3.617719
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/crdt/testing/CrdtSetHelperTest.kt
1
2065
package arcs.core.crdt.testing import arcs.core.crdt.CrdtSet import arcs.core.crdt.VersionMap import arcs.core.data.util.ReferencablePrimitive import arcs.core.data.util.toReferencable import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class CrdtSetHelperTest { private lateinit var set: CrdtSet<ReferencablePrimitive<Int>> @Before fun setUp() { set = CrdtSet() } @Test fun add_addsElement() { val helper = CrdtSetHelper(ACTOR, set) helper.add(INT_111) assertThat(set.consumerView).containsExactly(INT_111) helper.add(INT_222) assertThat(set.consumerView).containsExactly(INT_111, INT_222) } @Test fun add_incrementsVersionMap() { val helper = CrdtSetHelper(ACTOR, set) helper.add(INT_111) assertThat(set.versionMap).isEqualTo(VersionMap(ACTOR to 1)) helper.add(INT_222) assertThat(set.versionMap).isEqualTo(VersionMap(ACTOR to 2)) } @Test fun remove_removesElement() { val helper = CrdtSetHelper(ACTOR, set) helper.add(INT_111) helper.add(INT_222) helper.remove(INT_222.id) assertThat(set.consumerView).containsExactly(INT_111) } @Test fun remove_doesNotIncrementVersionMap() { val helper = CrdtSetHelper(ACTOR, set) helper.add(INT_111) helper.remove(INT_111.id) assertThat(set.versionMap).isEqualTo(VersionMap(ACTOR to 1)) } @Test fun clear_removesAllElements() { val helper = CrdtSetHelper(ACTOR, set) helper.add(INT_111) helper.add(INT_222) helper.clear() assertThat(set.consumerView).isEmpty() } @Test fun clear_doesNotIncrementVersionMap() { val helper = CrdtSetHelper(ACTOR, set) helper.add(INT_111) helper.clear() assertThat(set.versionMap).isEqualTo(VersionMap(ACTOR to 1)) } private companion object { private const val ACTOR = "ACTOR" private val INT_111 = 111.toReferencable() private val INT_222 = 222.toReferencable() } }
bsd-3-clause
4eee24b6724f42fb7658b7a9c465458c
21.692308
66
0.713317
3.680927
false
true
false
false
unic/sledge
src/main/kotlin/io/sledge/deployer/yaml/YamlSledgeFileParser.kt
1
1933
package io.sledge.deployer.yaml import com.charleskorn.kaml.Yaml import com.github.ajalt.clikt.output.TermUi.echo import io.sledge.deployer.core.api.* import kotlinx.serialization.Serializable import java.io.File class YamlSledgeFileParser : SledgeFileParser { override fun parseSledgeFile(sledgeFile: File): SledgeFile { echo("Parsing ${sledgeFile.name}...") val result = Yaml.default.parse(YamlSledgeRoot.serializer(), sledgeFile.inputStream().readBytes().toString(Charsets.UTF_8)) return SledgeFile( result.appName ?: "default-app", getDeployerImplementation(result), result.artifactsPathPrefix, result.uninstallCleanupPaths ?: emptyList(), mapDeyplomentDefinitionsWithArtifactsPathPrefix(result.artifactsPathPrefix, result.deploymentDefs)) } private fun getDeployerImplementation(result: YamlSledgeRoot): DeployerImplementation { return if (result.deployerImplementation == null) DeployerImplementation.crx else DeployerImplementation.valueOf(result.deployerImplementation) } private fun mapDeyplomentDefinitionsWithArtifactsPathPrefix(artifactsPathPrefix: String, deploymentDefList: List<YamlDeploymentDef>): List<DeploymentDefinition> { return deploymentDefList.map { installationDefItem -> DeploymentDefinition( installationDefItem.name, installationDefItem.artifacts.map { a -> Artifact("$artifactsPathPrefix$a") }) } } } @Serializable data class YamlSledgeRoot( val appName: String? = null, val deployerImplementation: String? = null, val artifactsPathPrefix: String, val uninstallCleanupPaths: List<String>? = null, val deploymentDefs: List<YamlDeploymentDef> ) @Serializable data class YamlDeploymentDef( val name: String, val artifacts: List<String> )
apache-2.0
84e070c531b4c4a53d556e5bce1e7c09
37.66
166
0.713399
4.526932
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/util/EncryptedLogging.kt
1
3995
package org.wordpress.android.util import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode.ASYNC import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.EncryptedLogActionBuilder import org.wordpress.android.fluxc.store.EncryptedLogStore import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogFailedToUpload import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogUploadedSuccessfully import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogPayload import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import java.io.File import java.util.UUID import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class EncryptedLogging @Inject constructor( private val dispatcher: Dispatcher, private val encryptedLogStore: EncryptedLogStore, private val networkUtilsWrapper: NetworkUtilsWrapper, private val analyticsTrackerWrapper: AnalyticsTrackerWrapper, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) { private val coroutineScope = CoroutineScope(bgDispatcher) init { dispatcher.register(this) } fun start() { dispatcher.dispatch(EncryptedLogActionBuilder.newResetUploadStatesAction()) if (networkUtilsWrapper.isNetworkAvailable()) { coroutineScope.launch { encryptedLogStore.uploadQueuedEncryptedLogs() } } } /** * Dispatches a FluxC action that will queue the given log to be uploaded as soon as possible. * * @param logFile Log file to be uploaded * @param shouldStartUploadImmediately This parameter will decide whether we should try to upload the log file * immediately. After a crash, we are unlikely to have enough time to complete the upload, so we can use this * parameter to avoid the unnecessary upload failure. */ fun encryptAndUploadLogFile(logFile: File, shouldStartUploadImmediately: Boolean): String? { if (logFile.exists()) { val uuid = UUID.randomUUID().toString() val payload = UploadEncryptedLogPayload( uuid = uuid, file = logFile, // If the connection is not available, we shouldn't try to upload immediately shouldStartUploadImmediately = shouldStartUploadImmediately && networkUtilsWrapper.isNetworkAvailable() ) dispatcher.dispatch(EncryptedLogActionBuilder.newUploadLogAction(payload)) return uuid } return null } @Suppress("unused") @Subscribe(threadMode = ASYNC) fun onEncryptedLogUploaded(event: OnEncryptedLogUploaded) { when (event) { is EncryptedLogUploadedSuccessfully -> { AppLog.i(T.MAIN, "Encrypted log with uuid: ${event.uuid} uploaded successfully!") analyticsTrackerWrapper.track(Stat.ENCRYPTED_LOGGING_UPLOAD_SUCCESSFUL) } is EncryptedLogFailedToUpload -> { AppLog.e(T.MAIN, "Encrypted log with uuid: ${event.uuid} failed to upload with error: ${event.error}") // Only track final errors if (!event.willRetry) { analyticsTrackerWrapper.track( Stat.ENCRYPTED_LOGGING_UPLOAD_FAILED, mapOf("error_type" to event.error.javaClass.simpleName) ) } } } } }
gpl-2.0
4adc2964db2e17dd6272e949b99990f1
42.423913
118
0.701126
5.398649
false
false
false
false
DanielGrech/anko
utils/src/org/jetbrains/android/generator/test/generatorUtils.kt
3
4226
/* * Copyright 2015 JetBrains s.r.o. * * 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 org.jetbrains.android.generator.test import java.io.File import org.jetbrains.android.anko.utils.Buffer import org.jetbrains.android.anko.config.AnkoFile import org.jetbrains.android.anko.config.ConfigurationTune private fun Context.functionalDslTests(init: Buffer.(version: String) -> Unit) { val dir = File("./dsl/test/" + basePackage.replace('.', '/'), "/functional") for (version in testVersions) { val testFile = File(dir, "FunctionalTestsFor$version.kt") if (!testFile.exists()) { testFile.writeText(buffer { line("package $basePackage.functional\n") line("import $basePackage.*") line("import $basePackage.config.*") line("import org.junit.Test\n") line("public class FunctionalTestsFor$version : AbstractFunctionalTest() {") line("val version = \"$version\"\n").nl() init(version) line("}") }.toString()) println("File $testFile written") } } } private fun Buffer.functionalDslTest(name: String, mainAnkoFile: AnkoFile, configInit: TestConfiguration.() -> Unit = {}) { val testConfiguration = TestConfiguration() testConfiguration.configInit() line("@Test public fun test$name() {") line("runFunctionalTest(\"$name.kt\", AnkoFile.${mainAnkoFile.name()}, version) {") for (file in testConfiguration.files) { line("files.add(AnkoFile.${file.name()})") } for (tune in testConfiguration.tunes) { line("tunes.add(ConfigurationTune.${tune.name()})") } line("}") line("}").nl() } private fun Context.dslCompileTests(files: List<String>, category: String) { val dir = File("./dsl/test/" + basePackage.replace('.', '/'), "/${category.toLowerCase()}") val testFile = File(dir, "Generated${category}Test.kt") if (!testFile.exists()) { testFile.writeText(buffer { line("package $basePackage.${category.toLowerCase()}\n").nl() line("import $basePackage.*") line("import $basePackage.compile.CompileTestFixture") line("import org.junit.*\n") line("import kotlin.platform.platformStatic").nl() line("public class Generated${category}Test : Abstract${category}Test() {") for (file in files) { for (version in versions) { line("@Test public fun test${file}For$version() {") line("run${category}Test(\"$file.kt\", \"$version\")") line("}").nl() } } line("}") }.toString()) println("File $testFile written") } } fun main(args: Array<String>) { val versions = File("./workdir/original/") .listFiles { it.isDirectory() && it.name.matches("\\d+s?".toRegex()) } ?.map { it.name } ?: listOf() val testVersions = File("./dsl/testData/functional/") .listFiles { it.isDirectory() && it.name.matches("\\d+s?".toRegex()) } ?.map { it.name } ?: listOf() Context(versions, testVersions, "org.jetbrains.android.anko").generate() } private fun buffer(init: Buffer.() -> Unit) = Buffer(" ", 0, init) private class Context(val versions: List<String>, val testVersions: List<String>, val basePackage: String) private class TestConfiguration { val files = hashSetOf<AnkoFile>() val tunes = hashSetOf<ConfigurationTune>() fun tune(tune: ConfigurationTune) { tunes.add(tune) } fun file(file: AnkoFile) { files.add(file) } }
apache-2.0
868c0a39475ba1433544030feeb32eda
34.822034
123
0.61098
4.329918
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLateinitPropertyToNullableIntention.kt
1
1809
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.makeNullable class ConvertLateinitPropertyToNullableIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.nullable.var") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean = element.hasModifier(KtTokens.LATEINIT_KEYWORD) && element.isVar && element.typeReference?.typeElement !is KtNullableType && element.initializer == null override fun applyTo(element: KtProperty, editor: Editor?) { val typeReference: KtTypeReference = element.typeReference ?: return val nullableType = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference]?.makeNullable() ?: return element.removeModifier(KtTokens.LATEINIT_KEYWORD) element.setType(nullableType) element.initializer = KtPsiFactory(element).createExpression(KtTokens.NULL_KEYWORD.value) } }
apache-2.0
d4faffaf4670ca1590cd49c5a8fd277f
52.205882
158
0.793809
4.650386
false
false
false
false
hermantai/samples
kotlin/developer-android/sunflower-main/app/src/test/java/com/google/samples/apps/sunflower/data/PlantTest.kt
3
2405
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.data import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import java.util.Calendar import java.util.Calendar.DAY_OF_YEAR class PlantTest { private lateinit var plant: Plant @Before fun setUp() { plant = Plant("1", "Tomato", "A red vegetable", 1, 2, "") } @Test fun test_default_values() { val defaultPlant = Plant("2", "Apple", "Description", 1) assertEquals(7, defaultPlant.wateringInterval) assertEquals("", defaultPlant.imageUrl) } @Test fun test_shouldBeWatered() { Calendar.getInstance().let { now -> // Generate lastWateringDate from being as copy of now. val lastWateringDate = Calendar.getInstance() // Test for lastWateringDate is today. lastWateringDate.time = now.time assertFalse(plant.shouldBeWatered(now, lastWateringDate.apply { add(DAY_OF_YEAR, -0) })) // Test for lastWateringDate is yesterday. lastWateringDate.time = now.time assertFalse(plant.shouldBeWatered(now, lastWateringDate.apply { add(DAY_OF_YEAR, -1) })) // Test for lastWateringDate is the day before yesterday. lastWateringDate.time = now.time assertFalse(plant.shouldBeWatered(now, lastWateringDate.apply { add(DAY_OF_YEAR, -2) })) // Test for lastWateringDate is some days ago, three days ago, four days ago etc. lastWateringDate.time = now.time assertTrue(plant.shouldBeWatered(now, lastWateringDate.apply { add(DAY_OF_YEAR, -3) })) } } @Test fun test_toString() { assertEquals("Tomato", plant.toString()) } }
apache-2.0
0013e4fd6a6d891b3c8c3e751cc601aa
34.895522
100
0.673597
3.968647
false
true
false
false
JetBrains/teamcity-nuget-support
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/olingo/OlingoRequestHandler.kt
1
4090
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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 jetbrains.buildServer.nuget.feed.server.olingo import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.nuget.feed.server.NuGetAPIVersion import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants import jetbrains.buildServer.nuget.feed.server.cache.ResponseCache import jetbrains.buildServer.nuget.feed.server.controllers.NuGetFeedHandler import jetbrains.buildServer.nuget.feed.server.index.NuGetFeed import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedFactory import jetbrains.buildServer.nuget.feed.server.olingo.data.OlingoDataSource import jetbrains.buildServer.nuget.feed.server.olingo.processor.NuGetServiceFactory import jetbrains.buildServer.serverSide.TeamCityProperties import jetbrains.buildServer.web.util.WebUtil import org.apache.olingo.odata2.api.ODataServiceFactory import org.apache.olingo.odata2.core.servlet.ODataServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Request handler based on Olingo library. */ open class OlingoRequestHandler(private val myFeedFactory: NuGetFeedFactory, private val myCache: ResponseCache) : NuGetFeedHandler { private val myServletsCache: Cache<String, Pair<ODataServlet, NuGetFeed>> init { val cacheSize = TeamCityProperties.getInteger(NuGetFeedConstants.PROP_NUGET_FEED_CACHED_SERVLETS, 32) myServletsCache = Caffeine.newBuilder() .maximumSize(cacheSize.toLong()) .executor({ it.run() }) .build() } override fun handleRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) { if (TeamCityProperties.getBoolean(NuGetFeedConstants.PROP_NUGET_FEED_USE_CACHE)) { myCache.getOrCompute(feedData, request, response, { _, _, _ -> this.processFeedRequest(feedData, request, response) }) } else { processFeedRequest(feedData, request, response) } } private fun processFeedRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) { LOG.debug("NuGet Feed: " + WebUtil.getRequestDump(request) + "|" + request.requestURI) val (servlet, feed) = myServletsCache.get(feedData.key) { _ -> ODataServlet().apply { this.init(ODataServletConfig(mapOf( ODataServiceFactory.ACCEPT_FORM_ENCODING to "true" ))) } to myFeedFactory.createFeed(feedData) } ?: throw Exception("Failed to create servlet") val apiVersion = request.getAttribute(NuGetFeedConstants.NUGET_FEED_API_VERSION) as NuGetAPIVersion val serviceFactory = NuGetServiceFactory(OlingoDataSource(feed, apiVersion)) request.setAttribute(ODataServiceFactory.FACTORY_INSTANCE_LABEL, serviceFactory) try { servlet.service(request, response) } catch (e: Throwable) { LOG.warnAndDebugDetails("Failed to process request", e) throw e } } companion object { private val LOG = Logger.getInstance(OlingoRequestHandler::class.java.name) } }
apache-2.0
fabccd93c48977abd0ab5da5ddd39880
42.510638
109
0.70709
4.341826
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/facet/KotlinFacetType.kt
4
1245
// 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.facet import com.intellij.facet.FacetType import com.intellij.facet.FacetTypeId import com.intellij.facet.FacetTypeRegistry import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.ModuleType import com.intellij.openapi.util.NlsSafe import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.KotlinIcons import javax.swing.Icon abstract class KotlinFacetType<C : KotlinFacetConfiguration> : FacetType<KotlinFacet, C>(TYPE_ID, ID, NAME) { companion object { const val ID = "kotlin-language" val TYPE_ID = FacetTypeId<KotlinFacet>(ID) @NlsSafe const val NAME = "Kotlin" val INSTANCE get() = FacetTypeRegistry.getInstance().findFacetType(TYPE_ID) } override fun isSuitableModuleType(moduleType: ModuleType<*>): Boolean { return when { KotlinPlatformUtils.isCidr -> true else -> moduleType is JavaModuleType } } override fun getIcon(): Icon = KotlinIcons.SMALL_LOGO }
apache-2.0
90d7a27ac75cdf5adc34ff5854fe6b4f
33.583333
158
0.727711
4.368421
false
false
false
false