repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
androidx/androidx
collection/collection/src/commonMain/kotlin/androidx/collection/CircularIntArray.kt
3
6664
/* * 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.collection import androidx.collection.CollectionPlatformUtils.createIndexOutOfBoundsException import kotlin.jvm.JvmOverloads /** * [CircularIntArray] is a circular integer array data structure that provides O(1) random read, * O(1) prepend and O(1) append. The CircularIntArray automatically grows its capacity when number * of added integers is over its capacity. * * @constructor Creates a circular array with capacity for at least [minCapacity] elements. * * @param minCapacity the minimum capacity, between 1 and 2^30 inclusive */ public class CircularIntArray @JvmOverloads public constructor(minCapacity: Int = 8) { private var elements: IntArray private var head = 0 private var tail = 0 private var capacityBitmask: Int init { require(minCapacity >= 1) { "capacity must be >= 1" } require(minCapacity <= 2 shl 29) { "capacity must be <= 2^30" } // If minCapacity isn't a power of 2, round up to the next highest // power of 2. val arrayCapacity: Int = if (minCapacity.countOneBits() != 1) { (minCapacity - 1).takeHighestOneBit() shl 1 } else { minCapacity } capacityBitmask = arrayCapacity - 1 elements = IntArray(arrayCapacity) } private fun doubleCapacity() { val n = elements.size val r = n - head val newCapacity = n shl 1 if (newCapacity < 0) { throw RuntimeException("Max array capacity exceeded") } val a = IntArray(newCapacity) elements.copyInto(destination = a, destinationOffset = 0, startIndex = head, endIndex = n) elements.copyInto(destination = a, destinationOffset = r, startIndex = 0, endIndex = head) elements = a head = 0 tail = n capacityBitmask = newCapacity - 1 } /** * Add an integer in front of the [CircularIntArray]. * * @param element [Int] to add. */ public fun addFirst(element: Int) { head = (head - 1) and capacityBitmask elements[head] = element if (head == tail) { doubleCapacity() } } /** * Add an integer at end of the [CircularIntArray]. * * @param element [Int] to add. */ public fun addLast(element: Int) { elements[tail] = element tail = (tail + 1) and capacityBitmask if (tail == head) { doubleCapacity() } } /** * Remove first integer from front of the [CircularIntArray] and return it. * * @return The integer removed. * @throws IndexOutOfBoundsException if [CircularIntArray] is empty. */ public fun popFirst(): Int { if (head == tail) throw createIndexOutOfBoundsException() val result = elements[head] head = (head + 1) and capacityBitmask return result } /** * Remove last integer from end of the [CircularIntArray] and return it. * * @return The integer removed. * @throws IndexOutOfBoundsException if [CircularIntArray] is empty. */ public fun popLast(): Int { if (head == tail) throw createIndexOutOfBoundsException() val t = (tail - 1) and capacityBitmask val result = elements[t] tail = t return result } /** * Remove all integers from the [CircularIntArray]. */ public fun clear() { tail = head } /** * Remove multiple integers from front of the [CircularIntArray], ignore when [count] * is less than or equals to 0. * * @param count Number of integers to remove. * @throws IndexOutOfBoundsException if numOfElements is larger than [size] */ public fun removeFromStart(count: Int) { if (count <= 0) { return } if (count > size()) { throw createIndexOutOfBoundsException() } head = (head + count) and capacityBitmask } /** * Remove multiple elements from end of the [CircularIntArray], ignore when [count] * is less than or equals to 0. * * @param count Number of integers to remove. * @throws IndexOutOfBoundsException if [count] is larger than [size] */ public fun removeFromEnd(count: Int) { if (count <= 0) { return } if (count > size()) { throw createIndexOutOfBoundsException() } tail = (tail - count) and capacityBitmask } /** * Get first integer of the [CircularIntArray]. * * @return The first integer. * @throws [IndexOutOfBoundsException] if [CircularIntArray] is empty. */ public val first: Int get() { if (head == tail) throw createIndexOutOfBoundsException() return elements[head] } /** * Get last integer of the [CircularIntArray]. * * @return The last integer. * @throws [IndexOutOfBoundsException] if [CircularIntArray] is empty. */ public val last: Int get() { if (head == tail) throw createIndexOutOfBoundsException() return elements[(tail - 1) and capacityBitmask] } /** * Get nth (0 <= n <= size()-1) integer of the [CircularIntArray]. * * @param index The zero based element index in the [CircularIntArray]. * @return The nth integer. * @throws [IndexOutOfBoundsException] if n < 0 or n >= size(). */ public operator fun get(index: Int): Int { if (index < 0 || index >= size()) throw createIndexOutOfBoundsException() return elements[(head + index) and capacityBitmask] } /** * Get number of integers in the [CircularIntArray]. * * @return Number of integers in the [CircularIntArray]. */ public fun size(): Int { return (tail - head) and capacityBitmask } /** * Return `true` if [size] is 0. * * @return `true` if [size] is 0. */ public fun isEmpty(): Boolean = head == tail }
apache-2.0
03c6ecd9270ea79531076b6035117416
30.433962
98
0.611194
4.683064
false
false
false
false
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/common/CommonApp.kt
1
4558
package com.kingz.module.common import android.content.Context import android.content.pm.PackageManager import android.os.Handler import com.alibaba.android.arouter.launcher.ARouter import com.kingz.database.DatabaseApplication import com.kingz.module.common.utils.crash.NeverCrash import com.scwang.smart.refresh.footer.ClassicsFooter import com.scwang.smart.refresh.header.ClassicsHeader import com.scwang.smart.refresh.layout.SmartRefreshLayout import com.tencent.bugly.crashreport.CrashReport import com.zeke.kangaroo.utils.ZLog /** * author: King.Z <br> * date: 2020/5/17 22:02 <br> * description: <br> */ open class CommonApp: DatabaseApplication(){ private var _appMainHandler: Handler? = null init{ //设置全局的Header构建器 SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout -> layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white) return@setDefaultRefreshHeaderCreator ClassicsHeader(context) } //设置全局的Footer构建器 SmartRefreshLayout.setDefaultRefreshFooterCreator{ context, _ -> return@setDefaultRefreshFooterCreator ClassicsFooter(context).setDrawableSize(20f) } } companion object { private const val TAG = "CommonApp" private var INSTANCE: CommonApp? = null fun getInstance(): CommonApp { return INSTANCE!! } } override fun onCreate() { super.onCreate() INSTANCE = this // _appMainHandler = Handler(mainLooper) initARouter() initLog() initBugly() initCrashCatcher() } private fun initCrashCatcher() { NeverCrash.init(object : NeverCrash.CrashHandler { override fun uncaughtException(thread: Thread?, throwable: Throwable?) { if (BuildConfig.DEBUG) { ZLog.e(TAG, "unCaught Crash: thread=$thread", throwable) CrashReport.postCatchedException(throwable) } } } ) } private fun initBugly() { // 建议在测试阶段建议设置成true,发布时设置为false。 if (BuildConfig.DEBUG) { val buglyId = getMetaDataValue("bugly_appid") //第三个参数为SDK调试模式开关,调试模式的行为特性如下: // 输出详细的Bugly SDK的Log; // 每一条Crash都会被立即上报; // 自定义日志将会在Logcat中输出。 CrashReport.initCrashReport(applicationContext, buglyId, false) // 自定义参数---设备串号 CrashReport.putUserData(this, "DeviceId", "宇宙无敌机皇") // 自定义参数---设备机型 CrashReport.setAppChannel(this, "机型信号") } } /** * 根据元数据name获取对应value */ private fun getMetaDataValue(name: String):String?{ val applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) return applicationInfo.metaData.getString(name) } private fun initLog() { if (BuildConfig.DEBUG) { ZLog.isDebug = true } } private fun initARouter() { if (BuildConfig.DEBUG) { // 这两行必须写在init之前,否则这些配置在init过程中将无效 ARouter.openLog() // 打印日志 // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险) ARouter.openDebug() // 因为开启InstantRun之后,很多类文件不会放在原本的dex中,需要单独去加载, // ARouter默认不会去加载这些文件,因为安全原因,只有在开启了openDebug之后 ARouter才回去加载InstantRun产生的文件 } ARouter.init(this)// 尽可能早,推荐在Application中初始化 } private fun initAutoLayout(){ // AutoLayoutConifg.getInstance() // .useDeviceSize() // .init(applicationContext) } fun postToMainLooper(runnable: Runnable) { _appMainHandler?.post(runnable) } fun postDelayToMainLooper(runnable: Runnable, ms: Long) { _appMainHandler?.postDelayed(runnable, ms) } override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) // 主动加载非主dex // MultiDex.install(this) } }
gpl-2.0
0ba23b1b8591587b50caa12d02ddfcae
29.097744
94
0.635932
3.966303
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/EnableKotlinTypeHintsOption.kt
1
3470
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.hints.* import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.util.IntentionName import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.utils.addToStdlib.safeAs @Suppress("IntentionDescriptionNotFoundInspection") class EnableKotlinTypeHintsOption : IntentionAction, HighPriorityAction { @IntentionName private var lastOptionName = "" override fun getText(): String = lastOptionName override fun getFamilyName(): String = CodeInsightBundle.message("inlay.hints.intention.family.name") override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val element = findElement(editor, file) ?: return false lastOptionName = "" for (hintType in HintType.values()) { findSetting(hintType, project, element)?.let { val enabled = it.isEnabled(hintType) lastOptionName = if (enabled) hintType.hideDescription else hintType.showDescription return true } } return false } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val element = findElement(editor, file) ?: return for (hintType in HintType.values()) { findSetting(hintType, project, element)?.let { val enabled = it.isEnabled(hintType) it.enable(hintType, !enabled) InlayHintsPassFactory.forceHintsUpdateOnNextPass() return } } } override fun startInWriteAction(): Boolean = false private fun findElement(editor: Editor, file: PsiFile): PsiElement? { if (file !is KtFile) return null val offset = editor.caretModel.offset val leaf1 = file.findElementAt(offset) val leaf2 = file.findElementAt(offset - 1) return if (leaf1 != null && leaf2 != null) PsiTreeUtil.findCommonParent(leaf1, leaf2) else null } private fun findSetting(hintType: HintType, project: Project, element: PsiElement): KotlinAbstractHintsProvider.HintsSettings? { if (!hintType.isApplicable(element)) return null val hintsSettings = InlayHintsSettings.instance() val providerInfos = InlayHintsProviderFactory.EP.extensionList .flatMap { it.getProvidersInfo(project) } .filter { it.language == KotlinLanguage.INSTANCE } val provider = providerInfos .firstOrNull { val hintsProvider = it.provider as? KotlinAbstractHintsProvider ?: return@firstOrNull false hintsProvider.isHintSupported(hintType) } ?.provider?.safeAs<KotlinAbstractHintsProvider<KotlinAbstractHintsProvider.HintsSettings>>() ?: return null val settingsKey = provider.key return hintsSettings.findSettings(settingsKey, KotlinLanguage.INSTANCE, provider::createSettings) } }
apache-2.0
de59222baeb14122eac6d9ec2110c670
42.936709
132
0.704035
5.021708
false
false
false
false
jwren/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt
1
47470
// 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.openapi.vcs.impl import com.google.common.collect.HashMultiset import com.google.common.collect.Multiset import com.intellij.codeWithMe.ClientId import com.intellij.diagnostic.ThreadDumper import com.intellij.icons.AllIcons import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.notification.NotificationsManager import com.intellij.openapi.Disposable import com.intellij.openapi.application.* import com.intellij.openapi.command.CommandEvent import com.intellij.openapi.command.CommandListener import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileDocumentManagerListener import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictFileStatusProvider import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory import com.intellij.openapi.vcs.ex.* import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.ContentInfo import com.intellij.openapi.vcs.impl.LineStatusTrackerContentLoader.TrackerContent import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent import com.intellij.testFramework.LightVirtualFile import com.intellij.util.EventDispatcher import com.intellij.util.concurrency.Semaphore import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import com.intellij.vcs.commit.isNonModalCommit import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly import java.nio.charset.Charset import java.util.* import java.util.concurrent.Future import java.util.function.Supplier class LineStatusTrackerManager(private val project: Project) : LineStatusTrackerManagerI, Disposable { private val LOCK = Any() private var isDisposed = false private val trackers = HashMap<Document, TrackerData>() private val forcedDocuments = HashMap<Document, Multiset<Any>>() private val eventDispatcher = EventDispatcher.create(Listener::class.java) private var partialChangeListsEnabled: Boolean = false private val documentsInDefaultChangeList = HashSet<Document>() private var clmFreezeCounter: Int = 0 private val filesWithDamagedInactiveRanges = HashSet<VirtualFile>() private val fileStatesAwaitingRefresh = HashMap<VirtualFile, ChangelistsLocalLineStatusTracker.State>() private val loader = MyBaseRevisionLoader() companion object { private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java) @JvmStatic fun getInstance(project: Project): LineStatusTrackerManagerI = project.service() @JvmStatic fun getInstanceImpl(project: Project): LineStatusTrackerManager { return getInstance(project) as LineStatusTrackerManager } } internal class MyStartupActivity : VcsStartupActivity { override fun runActivity(project: Project) { getInstanceImpl(project).startListenForEditors() } override fun getOrder(): Int = VcsInitObject.OTHER_INITIALIZATION.order } private fun startListenForEditors() { val busConnection = project.messageBus.connect() busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener()) busConnection.subscribe(VcsFreezingProcess.Listener.TOPIC, MyFreezeListener()) busConnection.subscribe(CommandListener.TOPIC, MyCommandListener()) busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener()) busConnection.subscribe(ChangeListAvailabilityListener.TOPIC, MyChangeListAvailabilityListener()) ApplicationManager.getApplication().messageBus.connect(this) .subscribe(VirtualFileManager.VFS_CHANGES, MyVirtualFileListener()) LocalLineStatusTrackerProvider.EP_NAME.addChangeListener(Runnable { updateTrackingSettings() }, this) updatePartialChangeListsAvailability() AppUIExecutor.onUiThread().expireWith(project).execute { if (project.isDisposed) { return@execute } ApplicationManager.getApplication().addApplicationListener(MyApplicationListener(), this) FileStatusManager.getInstance(project).addFileStatusListener(MyFileStatusListener(), this) EditorFactory.getInstance().eventMulticaster.addDocumentListener(MyDocumentListener(), this) MyEditorFactoryListener().install(this) onEverythingChanged() PartialLineStatusTrackerManagerState.restoreState(project) } } override fun dispose() { isDisposed = true Disposer.dispose(loader) synchronized(LOCK) { for ((document, multiset) in forcedDocuments) { for (requester in multiset.elementSet()) { warn("Tracker is being held on dispose by $requester", document) } } forcedDocuments.clear() for (data in trackers.values) { unregisterTrackerInCLM(data) data.tracker.release() } trackers.clear() } } override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? { synchronized(LOCK) { return trackers[document]?.tracker } } override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? { val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return null return getLineStatusTracker(document) } @RequiresEdt override fun requestTrackerFor(document: Document, requester: Any) { ApplicationManager.getApplication().assertIsWriteThread() synchronized(LOCK) { if (isDisposed) { warn("Tracker is being requested after dispose by $requester", document) return } val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() } multiset.add(requester) if (trackers[document] == null) { val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return switchTracker(virtualFile, document) } } } @RequiresEdt override fun releaseTrackerFor(document: Document, requester: Any) { ApplicationManager.getApplication().assertIsWriteThread() synchronized(LOCK) { val multiset = forcedDocuments[document] if (multiset == null || !multiset.contains(requester)) { warn("Tracker release underflow by $requester", document) return } multiset.remove(requester) if (multiset.isEmpty()) { forcedDocuments.remove(document) checkIfTrackerCanBeReleased(document) } } } override fun invokeAfterUpdate(task: Runnable) { loader.addAfterUpdateRunnable(task) } fun getTrackers(): List<LineStatusTracker<*>> { synchronized(LOCK) { return trackers.values.map { it.tracker } } } fun addTrackerListener(listener: Listener, disposable: Disposable) { eventDispatcher.addListener(listener, disposable) } open class ListenerAdapter : Listener interface Listener : EventListener { fun onTrackerAdded(tracker: LineStatusTracker<*>) { } fun onTrackerRemoved(tracker: LineStatusTracker<*>) { } } @RequiresEdt private fun checkIfTrackerCanBeReleased(document: Document) { synchronized(LOCK) { val data = trackers[document] ?: return if (forcedDocuments.containsKey(document)) return if (data.tracker is ChangelistsLocalLineStatusTracker) { val hasPartialChanges = data.tracker.hasPartialState() if (hasPartialChanges) { log("checkIfTrackerCanBeReleased - hasPartialChanges", data.tracker.virtualFile) return } val isLoading = loader.hasRequestFor(document) if (isLoading) { log("checkIfTrackerCanBeReleased - isLoading", data.tracker.virtualFile) if (data.tracker.hasPendingPartialState() || fileStatesAwaitingRefresh.containsKey(data.tracker.virtualFile)) { log("checkIfTrackerCanBeReleased - has pending state", data.tracker.virtualFile) return } } } releaseTracker(document) } } @RequiresEdt private fun onEverythingChanged() { ApplicationManager.getApplication().assertIsWriteThread() synchronized(LOCK) { if (isDisposed) return log("onEverythingChanged", null) val files = HashSet<VirtualFile>() for (data in trackers.values) { files.add(data.tracker.virtualFile) } for (document in forcedDocuments.keys) { val file = FileDocumentManager.getInstance().getFile(document) if (file != null) files.add(file) } for (file in files) { onFileChanged(file) } } } @RequiresEdt private fun onFileChanged(virtualFile: VirtualFile) { val document = FileDocumentManager.getInstance().getCachedDocument(virtualFile) ?: return synchronized(LOCK) { if (isDisposed) return log("onFileChanged", virtualFile) val tracker = trackers[document]?.tracker if (tracker != null || forcedDocuments.containsKey(document)) { switchTracker(virtualFile, document, refreshExisting = true) } } } private fun registerTrackerInCLM(data: TrackerData) { val tracker = data.tracker if (tracker !is ChangelistsLocalLineStatusTracker) return val filePath = VcsUtil.getFilePath(tracker.virtualFile) if (data.clmFilePath != null) { LOG.error("[registerTrackerInCLM] tracker already registered") return } ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(filePath, tracker) data.clmFilePath = filePath } private fun unregisterTrackerInCLM(data: TrackerData, wasUnbound: Boolean = false) { val tracker = data.tracker if (tracker !is ChangelistsLocalLineStatusTracker) return val filePath = data.clmFilePath if (filePath == null) { LOG.error("[unregisterTrackerInCLM] tracker is not registered") return } ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(filePath, tracker) data.clmFilePath = null val actualFilePath = VcsUtil.getFilePath(tracker.virtualFile) if (filePath != actualFilePath && !wasUnbound) { LOG.error("[unregisterTrackerInCLM] unexpected file path: expected: $filePath, actual: $actualFilePath") } } private fun reregisterTrackerInCLM(data: TrackerData) { val tracker = data.tracker if (tracker !is ChangelistsLocalLineStatusTracker) return val oldFilePath = data.clmFilePath val newFilePath = VcsUtil.getFilePath(tracker.virtualFile) if (oldFilePath == null) { LOG.error("[reregisterTrackerInCLM] tracker is not registered") return } if (oldFilePath != newFilePath) { ChangeListManagerImpl.getInstanceImpl(project).unregisterChangeTracker(oldFilePath, tracker) ChangeListManagerImpl.getInstanceImpl(project).registerChangeTracker(newFilePath, tracker) data.clmFilePath = newFilePath } } private fun canCreateTrackerFor(virtualFile: VirtualFile?): Boolean { if (isDisposed) return false if (virtualFile == null || virtualFile is LightVirtualFile) return false if (runReadAction { !virtualFile.isValid || virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length) }) return false return true } override fun arePartialChangelistsEnabled(): Boolean = partialChangeListsEnabled override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean { if (!partialChangeListsEnabled) return false val vcs = VcsUtil.getVcsFor(project, virtualFile) return vcs != null && vcs.arePartialChangelistsSupported() } private fun switchTracker(virtualFile: VirtualFile, document: Document, refreshExisting: Boolean = false) { val provider = getTrackerProvider(virtualFile) val oldTracker = trackers[document]?.tracker if (oldTracker != null && provider != null && provider.isMyTracker(oldTracker)) { if (refreshExisting) { refreshTracker(oldTracker, provider) } } else { releaseTracker(document) if (provider != null) installTracker(virtualFile, document, provider) } } private fun installTracker(virtualFile: VirtualFile, document: Document, provider: LocalLineStatusTrackerProvider): LocalLineStatusTracker<*>? { if (isDisposed) return null if (trackers[document] != null) return null val tracker = provider.createTracker(project, virtualFile) ?: return null tracker.mode = getTrackingMode() val data = TrackerData(tracker) val replacedData = trackers.put(document, data) LOG.assertTrue(replacedData == null) registerTrackerInCLM(data) refreshTracker(tracker, provider) eventDispatcher.multicaster.onTrackerAdded(tracker) if (clmFreezeCounter > 0) { tracker.freeze() } log("Tracker installed", virtualFile) return tracker } private fun getTrackerProvider(virtualFile: VirtualFile): LocalLineStatusTrackerProvider? { if (!canCreateTrackerFor(virtualFile)) { return null } LocalLineStatusTrackerProvider.EP_NAME.findFirstSafe { it.isTrackedFile(project, virtualFile) }?.let { return it } return listOf(ChangelistsLocalStatusTrackerProvider, DefaultLocalStatusTrackerProvider).find { it.isTrackedFile(project, virtualFile) } } @RequiresEdt private fun releaseTracker(document: Document, wasUnbound: Boolean = false) { val data = trackers.remove(document) ?: return eventDispatcher.multicaster.onTrackerRemoved(data.tracker) unregisterTrackerInCLM(data, wasUnbound) data.tracker.release() log("Tracker released", data.tracker.virtualFile) } private fun updatePartialChangeListsAvailability() { partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS && ChangeListManager.getInstance(project).areChangeListsEnabled() } private fun updateTrackingSettings() { synchronized(LOCK) { if (isDisposed) return val mode = getTrackingMode() for (data in trackers.values) { data.tracker.mode = mode } } onEverythingChanged() } private fun getTrackingMode(): LocalLineStatusTracker.Mode { val settings = VcsApplicationSettings.getInstance() return LocalLineStatusTracker.Mode(settings.SHOW_LST_GUTTER_MARKERS, settings.SHOW_LST_ERROR_STRIPE_MARKERS, settings.SHOW_WHITESPACES_IN_LST) } @RequiresEdt private fun refreshTracker(tracker: LocalLineStatusTracker<*>, provider: LocalLineStatusTrackerProvider) { if (isDisposed) return if (provider !is LineStatusTrackerContentLoader) return loader.scheduleRefresh(RefreshRequest(tracker.document, provider)) log("Refresh queued", tracker.virtualFile) } private inner class MyBaseRevisionLoader : SingleThreadLoader<RefreshRequest, RefreshData>() { fun hasRequestFor(document: Document): Boolean { return hasRequest { it.document == document } } override fun loadRequest(request: RefreshRequest): Result<RefreshData> { if (isDisposed) return Result.Canceled() val document = request.document val virtualFile = FileDocumentManager.getInstance().getFile(document) val loader = request.loader log("Loading started", virtualFile) if (virtualFile == null || !virtualFile.isValid) { log("Loading error: virtual file is not valid", virtualFile) return Result.Error() } if (!canCreateTrackerFor(virtualFile) || !loader.isTrackedFile(project, virtualFile)) { log("Loading error: virtual file is not a tracked file", virtualFile) return Result.Error() } val newContentInfo = loader.getContentInfo(project, virtualFile) if (newContentInfo == null) { log("Loading error: base revision not found", virtualFile) return Result.Error() } synchronized(LOCK) { val data = trackers[document] if (data == null) { log("Loading cancelled: tracker not found", virtualFile) return Result.Canceled() } if (!loader.shouldBeUpdated(data.contentInfo, newContentInfo)) { log("Loading cancelled: no need to update", virtualFile) return Result.Canceled() } } val content = loader.loadContent(project, newContentInfo) if (content == null) { log("Loading error: provider failure", virtualFile) return Result.Error() } log("Loading successful", virtualFile) return Result.Success(RefreshData(content, newContentInfo)) } @RequiresEdt override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) { val document = request.document when (result) { is Result.Canceled -> handleCanceled(document) is Result.Error -> handleError(request, document) is Result.Success -> handleSuccess(request, document, result.data) } checkIfTrackerCanBeReleased(document) } private fun handleCanceled(document: Document) { restorePendingTrackerState(document) } private fun handleError(request: RefreshRequest, document: Document) { synchronized(LOCK) { val loader = request.loader val data = trackers[document] ?: return val tracker = data.tracker if (loader.isMyTracker(tracker)) { loader.handleLoadingError(tracker) } data.contentInfo = null } } private fun handleSuccess(request: RefreshRequest, document: Document, refreshData: RefreshData) { val virtualFile = FileDocumentManager.getInstance().getFile(document)!! val loader = request.loader val tracker: LocalLineStatusTracker<*> synchronized(LOCK) { val data = trackers[document] if (data == null) { log("Loading finished: tracker already released", virtualFile) return } if (!loader.shouldBeUpdated(data.contentInfo, refreshData.contentInfo)) { log("Loading finished: no need to update", virtualFile) return } data.contentInfo = refreshData.contentInfo tracker = data.tracker } if (loader.isMyTracker(tracker)) { loader.setLoadedContent(tracker, refreshData.content) log("Loading finished: success", virtualFile) } else { log("Loading finished: wrong tracker. tracker: $tracker, loader: $loader", virtualFile) } restorePendingTrackerState(document) } private fun restorePendingTrackerState(document: Document) { val tracker = getLineStatusTracker(document) if (tracker is ChangelistsLocalLineStatusTracker) { val virtualFile = tracker.virtualFile val state = synchronized(LOCK) { fileStatesAwaitingRefresh.remove(virtualFile) ?: return } val success = tracker.restoreState(state) log("Pending state restored. success - $success", virtualFile) } } } /** * We can speedup initial content loading if it was already loaded by someone. * We do not set 'contentInfo' here to ensure, that following refresh will fix potential inconsistency. */ @RequiresEdt @ApiStatus.Internal fun offerTrackerContent(document: Document, text: CharSequence) { try { val tracker: LocalLineStatusTracker<*> synchronized(LOCK) { val data = trackers[document] if (data == null || data.contentInfo != null) return tracker = data.tracker } if (tracker is LocalLineStatusTrackerImpl<*>) { ClientId.withClientId(ClientId.localId) { tracker.setBaseRevision(text) log("Offered content", tracker.virtualFile) } } } catch (e: Throwable) { LOG.error(e) } } private inner class MyFileStatusListener : FileStatusListener { override fun fileStatusesChanged() { onEverythingChanged() } override fun fileStatusChanged(virtualFile: VirtualFile) { onFileChanged(virtualFile) } } private inner class MyEditorFactoryListener : EditorFactoryListener { fun install(disposable: Disposable) { val editorFactory = EditorFactory.getInstance() for (editor in editorFactory.allEditors) { if (isTrackedEditor(editor)) { requestTrackerFor(editor.document, editor) } } editorFactory.addEditorFactoryListener(this, disposable) } override fun editorCreated(event: EditorFactoryEvent) { val editor = event.editor if (isTrackedEditor(editor)) { requestTrackerFor(editor.document, editor) } } override fun editorReleased(event: EditorFactoryEvent) { val editor = event.editor if (isTrackedEditor(editor)) { releaseTrackerFor(editor.document, editor) } } private fun isTrackedEditor(editor: Editor): Boolean { // can't filter out "!isInLocalFileSystem" files, custom VcsBaseContentProvider can handle them // check for isDisposed - light project in tests return !project.isDisposed && (editor.project == null || editor.project == project) && FileDocumentManager.getInstance().getFile(editor.document) != null } } private inner class MyVirtualFileListener : BulkFileListener { override fun before(events: List<VFileEvent>) { for (event in events) { when (event) { is VFileDeleteEvent -> handleFileDeletion(event.file) } } } override fun after(events: List<VFileEvent>) { for (event in events) { when (event) { is VFilePropertyChangeEvent -> when { VirtualFile.PROP_ENCODING == event.propertyName -> onFileChanged(event.file) event.isRename -> handleFileMovement(event.file) } is VFileMoveEvent -> handleFileMovement(event.file) } } } private fun handleFileMovement(file: VirtualFile) { if (!partialChangeListsEnabled) return synchronized(LOCK) { forEachTrackerUnder(file) { data -> reregisterTrackerInCLM(data) } } } private fun handleFileDeletion(file: VirtualFile) { if (!partialChangeListsEnabled) return synchronized(LOCK) { forEachTrackerUnder(file) { data -> releaseTracker(data.tracker.document) } } } private fun forEachTrackerUnder(file: VirtualFile, action: (TrackerData) -> Unit) { if (file.isDirectory) { val affected = trackers.values.filter { VfsUtil.isAncestor(file, it.tracker.virtualFile, false) } for (data in affected) { action(data) } } else { val document = FileDocumentManager.getInstance().getCachedDocument(file) ?: return val data = trackers[document] ?: return action(data) } } } internal class MyFileDocumentManagerListener : FileDocumentManagerListener { override fun afterDocumentUnbound(file: VirtualFile, document: Document) { val projectManager = ProjectManager.getInstanceIfCreated() ?: return for (project in projectManager.openProjects) { val lstm = project.getServiceIfCreated(LineStatusTrackerManagerI::class.java) as? LineStatusTrackerManager ?: continue lstm.releaseTracker(document, wasUnbound = true) } } } private inner class MyDocumentListener : DocumentListener { override fun documentChanged(event: DocumentEvent) { if (!ApplicationManager.getApplication().isDispatchThread) return // disable for documents forUseInNonAWTThread if (!partialChangeListsEnabled || project.isDisposed) return val document = event.document if (documentsInDefaultChangeList.contains(document)) return val virtualFile = FileDocumentManager.getInstance().getFile(document) ?: return if (getLineStatusTracker(document) != null) return val provider = getTrackerProvider(virtualFile) if (provider != ChangelistsLocalStatusTrackerProvider) return val changeList = ChangeListManager.getInstance(project).getChangeList(virtualFile) val inAnotherChangelist = changeList != null && !ActiveChangeListTracker.getInstance(project).isActiveChangeList(changeList) if (inAnotherChangelist) { log("Tracker install from DocumentListener: ", virtualFile) val tracker = synchronized(LOCK) { installTracker(virtualFile, document, provider) } if (tracker is ChangelistsLocalLineStatusTracker) { tracker.replayChangesFromDocumentEvents(listOf(event)) } } else { documentsInDefaultChangeList.add(document) } } } private inner class MyApplicationListener : ApplicationListener { override fun afterWriteActionFinished(action: Any) { documentsInDefaultChangeList.clear() synchronized(LOCK) { val documents = trackers.values.map { it.tracker.document } for (document in documents) { checkIfTrackerCanBeReleased(document) } } } } private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener { override fun settingsUpdated() { updatePartialChangeListsAvailability() updateTrackingSettings() } } private inner class MyChangeListListener : ChangeListAdapter() { override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) { runInEdt(ModalityState.any()) { if (project.isDisposed) return@runInEdt expireInactiveRangesDamagedNotifications() EditorFactory.getInstance().allEditors .forEach { if (it is EditorEx) it.gutterComponentEx.repaint() } } } } private inner class MyChangeListAvailabilityListener : ChangeListAvailabilityListener { override fun onBefore() { if (ChangeListManager.getInstance(project).areChangeListsEnabled()) { val fileStates = getInstanceImpl(project).collectPartiallyChangedFilesStates() if (fileStates.isNotEmpty()) { PartialLineStatusTrackerManagerState.saveCurrentState(project, fileStates) } } } override fun onAfter() { updatePartialChangeListsAvailability() onEverythingChanged() if (ChangeListManager.getInstance(project).areChangeListsEnabled()) { PartialLineStatusTrackerManagerState.restoreState(project) } } } private inner class MyCommandListener : CommandListener { override fun commandFinished(event: CommandEvent) { if (!partialChangeListsEnabled) return if (CommandProcessor.getInstance().currentCommand == null && !filesWithDamagedInactiveRanges.isEmpty()) { showInactiveRangesDamagedNotification() } } } class CheckinFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { val project = panel.project return object : CheckinHandler() { override fun checkinSuccessful() { resetExcludedFromCommit() } override fun checkinFailed(exception: MutableList<VcsException>?) { resetExcludedFromCommit() } private fun resetExcludedFromCommit() { runInEdt { // TODO Move this to SingleChangeListCommitWorkflow if (!project.isDisposed && !panel.isNonModalCommit) getInstanceImpl(project).resetExcludedFromCommitMarkers() } } } } } private inner class MyFreezeListener : VcsFreezingProcess.Listener { override fun onFreeze() { runReadAction { synchronized(LOCK) { if (clmFreezeCounter == 0) { for (data in trackers.values) { try { data.tracker.freeze() } catch (e: Throwable) { LOG.error(e) } } } clmFreezeCounter++ } } } override fun onUnfreeze() { runInEdt(ModalityState.any()) { synchronized(LOCK) { clmFreezeCounter-- if (clmFreezeCounter == 0) { for (data in trackers.values) { try { data.tracker.unfreeze() } catch (e: Throwable) { LOG.error(e) } } } } } } } private class TrackerData(val tracker: LocalLineStatusTracker<*>, var contentInfo: ContentInfo? = null, var clmFilePath: FilePath? = null) private class RefreshRequest(val document: Document, val loader: LineStatusTrackerContentLoader) { override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document override fun hashCode(): Int = document.hashCode() override fun toString(): String = "RefreshRequest: " + (FileDocumentManager.getInstance().getFile(document)?.path ?: "unknown") // NON-NLS } private class RefreshData(val content: TrackerContent, val contentInfo: ContentInfo) private fun log(@NonNls message: String, file: VirtualFile?) { if (LOG.isDebugEnabled) { if (file != null) { LOG.debug(message + "; file: " + file.path) } else { LOG.debug(message) } } } private fun warn(@NonNls message: String, document: Document?) { val file = document?.let { FileDocumentManager.getInstance().getFile(it) } warn(message, file) } private fun warn(@NonNls message: String, file: VirtualFile?) { if (file != null) { LOG.warn(message + "; file: " + file.path) } else { LOG.warn(message) } } @RequiresEdt fun resetExcludedFromCommitMarkers() { ApplicationManager.getApplication().assertIsWriteThread() synchronized(LOCK) { val documents = mutableListOf<Document>() for (data in trackers.values) { val tracker = data.tracker if (tracker is ChangelistsLocalLineStatusTracker) { tracker.resetExcludedFromCommitMarkers() documents.add(tracker.document) } } for (document in documents) { checkIfTrackerCanBeReleased(document) } } } internal fun collectPartiallyChangedFilesStates(): List<ChangelistsLocalLineStatusTracker.FullState> { ApplicationManager.getApplication().assertReadAccessAllowed() val result = mutableListOf<ChangelistsLocalLineStatusTracker.FullState>() synchronized(LOCK) { for (data in trackers.values) { val tracker = data.tracker if (tracker is ChangelistsLocalLineStatusTracker) { val hasPartialChanges = tracker.affectedChangeListsIds.size > 1 if (hasPartialChanges) { result.add(tracker.storeTrackerState()) } } } } return result } @RequiresEdt internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<ChangelistsLocalLineStatusTracker.State>) { runWriteAction { synchronized(LOCK) { if (isDisposed) return@runWriteAction for (state in trackerStates) { val virtualFile = state.virtualFile val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue val provider = getTrackerProvider(virtualFile) if (provider != ChangelistsLocalStatusTrackerProvider) continue switchTracker(virtualFile, document) val tracker = trackers[document]?.tracker if (tracker !is ChangelistsLocalLineStatusTracker) continue val isLoading = loader.hasRequestFor(document) if (isLoading) { fileStatesAwaitingRefresh.put(state.virtualFile, state) log("State restoration scheduled", virtualFile) } else { val success = tracker.restoreState(state) log("State restored. success - $success", virtualFile) } } loader.addAfterUpdateRunnable(Runnable { synchronized(LOCK) { log("State restoration finished", null) fileStatesAwaitingRefresh.clear() } }) } } onEverythingChanged() } @RequiresEdt internal fun notifyInactiveRangesDamaged(virtualFile: VirtualFile) { ApplicationManager.getApplication().assertIsWriteThread() if (filesWithDamagedInactiveRanges.contains(virtualFile) || virtualFile == FileEditorManagerEx.getInstanceEx(project).currentFile) { return } filesWithDamagedInactiveRanges.add(virtualFile) } private fun showInactiveRangesDamagedNotification() { val currentNotifications = NotificationsManager.getNotificationsManager() .getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project) val lastNotification = currentNotifications.lastOrNull { !it.isExpired } if (lastNotification != null) filesWithDamagedInactiveRanges.addAll(lastNotification.virtualFiles) currentNotifications.forEach { it.expire() } val files = filesWithDamagedInactiveRanges.toSet() filesWithDamagedInactiveRanges.clear() InactiveRangesDamagedNotification(project, files).notify(project) } @RequiresEdt private fun expireInactiveRangesDamagedNotifications() { filesWithDamagedInactiveRanges.clear() val currentNotifications = NotificationsManager.getNotificationsManager() .getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project) currentNotifications.forEach { it.expire() } } private class InactiveRangesDamagedNotification(project: Project, val virtualFiles: Set<VirtualFile>) : Notification(VcsNotifier.STANDARD_NOTIFICATION.displayId, VcsBundle.message("lst.inactive.ranges.damaged.notification"), NotificationType.INFORMATION) { init { icon = AllIcons.Toolwindows.ToolWindowChanges setDisplayId(VcsNotificationIdsHolder.INACTIVE_RANGES_DAMAGED) addAction(NotificationAction.createSimple( Supplier { VcsBundle.message("action.NotificationAction.InactiveRangesDamagedNotification.text.view.changes") }, Runnable { val defaultList = ChangeListManager.getInstance(project).defaultChangeList val changes = defaultList.changes.filter { virtualFiles.contains(it.virtualFile) } val window = getToolWindowFor(project, LOCAL_CHANGES) window?.activate { ChangesViewManager.getInstance(project).selectChanges(changes) } expire() })) } } @TestOnly fun waitUntilBaseContentsLoaded() { assert(ApplicationManager.getApplication().isUnitTestMode) if (ApplicationManager.getApplication().isDispatchThread) { UIUtil.dispatchAllInvocationEvents() } val semaphore = Semaphore() semaphore.down() loader.addAfterUpdateRunnable(Runnable { semaphore.up() }) val start = System.currentTimeMillis() while (true) { if (ApplicationManager.getApplication().isDispatchThread) { UIUtil.dispatchAllInvocationEvents() } if (semaphore.waitFor(10)) { return } if (System.currentTimeMillis() - start > 10000) { loader.dumpInternalState() System.err.println(ThreadDumper.dumpThreadsToString()) throw IllegalStateException("Couldn't await base contents") // NON-NLS } } } @TestOnly fun releaseAllTrackers() { synchronized(LOCK) { forcedDocuments.clear() for (data in trackers.values) { unregisterTrackerInCLM(data) data.tracker.release() } trackers.clear() } } } /** * Single threaded queue with the following properties: * - Ignores duplicated requests (the first queued is used). * - Allows to check whether request is scheduled or is waiting for completion. * - Notifies callbacks when queue is exhausted. */ private abstract class SingleThreadLoader<Request, T> : Disposable { companion object { private val LOG = Logger.getInstance(SingleThreadLoader::class.java) } private val LOCK: Any = Any() private val taskQueue = ArrayDeque<Request>() private val waitingForRefresh = HashSet<Request>() private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>() private var isScheduled: Boolean = false private var isDisposed: Boolean = false private var lastFuture: Future<*>? = null @RequiresBackgroundThread protected abstract fun loadRequest(request: Request): Result<T> @RequiresEdt protected abstract fun handleResult(request: Request, result: Result<T>) @RequiresEdt fun scheduleRefresh(request: Request) { if (isDisposed) return synchronized(LOCK) { if (taskQueue.contains(request)) return taskQueue.add(request) schedule() } } @RequiresEdt override fun dispose() { val callbacks = mutableListOf<Runnable>() synchronized(LOCK) { isDisposed = true taskQueue.clear() waitingForRefresh.clear() lastFuture?.cancel(true) callbacks += callbacksWaitingUpdateCompletion callbacksWaitingUpdateCompletion.clear() } executeCallbacks(callbacksWaitingUpdateCompletion) } @RequiresEdt protected fun hasRequest(condition: (Request) -> Boolean): Boolean { synchronized(LOCK) { return taskQueue.any(condition) || waitingForRefresh.any(condition) } } @CalledInAny fun addAfterUpdateRunnable(task: Runnable) { val updateScheduled = putRunnableIfUpdateScheduled(task) if (updateScheduled) return runInEdt(ModalityState.any()) { if (!putRunnableIfUpdateScheduled(task)) { task.run() } } } private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean { synchronized(LOCK) { if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false callbacksWaitingUpdateCompletion.add(task) return true } } private fun schedule() { if (isDisposed) return synchronized(LOCK) { if (isScheduled) return if (taskQueue.isEmpty()) return isScheduled = true lastFuture = ApplicationManager.getApplication().executeOnPooledThread { ClientId.withClientId(ClientId.localId) { BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, Runnable { handleRequests() }) } } } } private fun handleRequests() { while (true) { val request = synchronized(LOCK) { val request = taskQueue.poll() if (isDisposed || request == null) { isScheduled = false return } waitingForRefresh.add(request) return@synchronized request } handleSingleRequest(request) } } private fun handleSingleRequest(request: Request) { val result: Result<T> = try { loadRequest(request) } catch (e: ProcessCanceledException) { Result.Canceled() } catch (e: Throwable) { LOG.error(e) Result.Error() } runInEdt(ModalityState.any()) { try { synchronized(LOCK) { waitingForRefresh.remove(request) } handleResult(request, result) } finally { notifyTrackerRefreshed() } } } @RequiresEdt private fun notifyTrackerRefreshed() { if (isDisposed) return val callbacks = mutableListOf<Runnable>() synchronized(LOCK) { if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) { callbacks += callbacksWaitingUpdateCompletion callbacksWaitingUpdateCompletion.clear() } } executeCallbacks(callbacks) } @RequiresEdt private fun executeCallbacks(callbacks: List<Runnable>) { for (callback in callbacks) { try { callback.run() } catch (ignore: ProcessCanceledException) { } catch (e: Throwable) { LOG.error(e) } } } @TestOnly fun dumpInternalState() { synchronized(LOCK) { LOG.debug("isScheduled - $isScheduled") LOG.debug("pending callbacks: ${callbacksWaitingUpdateCompletion.size}") taskQueue.forEach { LOG.debug("pending task: ${it}") } waitingForRefresh.forEach { LOG.debug("waiting refresh: ${it}") } } } } private sealed class Result<T> { class Success<T>(val data: T) : Result<T>() class Canceled<T> : Result<T>() class Error<T> : Result<T>() } private object ChangelistsLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() { override fun isTrackedFile(project: Project, file: VirtualFile): Boolean { if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled(file)) return false if (!super.isTrackedFile(project, file)) return false val status = FileStatusManager.getInstance(project).getStatus(file) if (status != FileStatus.MODIFIED && status != ChangelistConflictFileStatusProvider.MODIFIED_OUTSIDE && status != FileStatus.NOT_CHANGED) return false val change = ChangeListManager.getInstance(project).getChange(file) return change == null || change.javaClass == Change::class.java && (change.type == Change.Type.MODIFICATION || change.type == Change.Type.MOVED) && change.afterRevision is CurrentContentRevision } override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is ChangelistsLocalLineStatusTracker override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? { val document = FileDocumentManager.getInstance().getDocument(file) ?: return null return ChangelistsLocalLineStatusTracker.createTracker(project, document, file) } } private object DefaultLocalStatusTrackerProvider : BaseRevisionStatusTrackerContentLoader() { override fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean = tracker is SimpleLocalLineStatusTracker override fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? { val document = FileDocumentManager.getInstance().getDocument(file) ?: return null return SimpleLocalLineStatusTracker.createTracker(project, document, file) } } private abstract class BaseRevisionStatusTrackerContentLoader : LineStatusTrackerContentLoader { override fun isTrackedFile(project: Project, file: VirtualFile): Boolean { if (!VcsFileStatusProvider.getInstance(project).isSupported(file)) return false val status = FileStatusManager.getInstance(project).getStatus(file) if (status == FileStatus.ADDED || status == FileStatus.DELETED || status == FileStatus.UNKNOWN || status == FileStatus.IGNORED) { return false } return true } override fun getContentInfo(project: Project, file: VirtualFile): ContentInfo? { val baseContent = VcsFileStatusProvider.getInstance(project).getBaseRevision(file) ?: return null return BaseRevisionContentInfo(baseContent, file.charset) } override fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean { newInfo as BaseRevisionContentInfo return oldInfo == null || oldInfo !is BaseRevisionContentInfo || oldInfo.baseContent.revisionNumber != newInfo.baseContent.revisionNumber || oldInfo.baseContent.revisionNumber == VcsRevisionNumber.NULL || oldInfo.charset != newInfo.charset } override fun loadContent(project: Project, info: ContentInfo): BaseRevisionContent? { info as BaseRevisionContentInfo val lastUpToDateContent = info.baseContent.loadContent() ?: return null val correctedText = StringUtil.convertLineSeparators(lastUpToDateContent) return BaseRevisionContent(correctedText) } override fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent) { tracker as LocalLineStatusTrackerImpl<*> content as BaseRevisionContent tracker.setBaseRevision(content.text) } override fun handleLoadingError(tracker: LocalLineStatusTracker<*>) { tracker as LocalLineStatusTrackerImpl<*> tracker.dropBaseRevision() } private class BaseRevisionContentInfo(val baseContent: VcsBaseContentProvider.BaseContent, val charset: Charset) : ContentInfo private class BaseRevisionContent(val text: CharSequence) : TrackerContent } interface LocalLineStatusTrackerProvider { fun isTrackedFile(project: Project, file: VirtualFile): Boolean fun isMyTracker(tracker: LocalLineStatusTracker<*>): Boolean fun createTracker(project: Project, file: VirtualFile): LocalLineStatusTracker<*>? companion object { internal val EP_NAME = ExtensionPointName<LocalLineStatusTrackerProvider>("com.intellij.openapi.vcs.impl.LocalLineStatusTrackerProvider") } } interface LineStatusTrackerContentLoader : LocalLineStatusTrackerProvider { fun getContentInfo(project: Project, file: VirtualFile): ContentInfo? fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean fun loadContent(project: Project, info: ContentInfo): TrackerContent? fun setLoadedContent(tracker: LocalLineStatusTracker<*>, content: TrackerContent) fun handleLoadingError(tracker: LocalLineStatusTracker<*>) interface ContentInfo interface TrackerContent }
apache-2.0
0cc8e28223cf244ab20b67acc86ba440
32.476728
142
0.702486
5.469524
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/util/GithubApiPagesLoader.kt
13
2635
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.util import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.plugins.github.api.GithubApiRequest import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.data.GithubResponsePage import java.io.IOException import java.util.function.Predicate object GithubApiPagesLoader { @Throws(IOException::class) @JvmStatic fun <T> loadAll(executor: GithubApiRequestExecutor, indicator: ProgressIndicator, pagesRequest: Request<T>): List<T> { val result = mutableListOf<T>() loadAll(executor, indicator, pagesRequest) { result.addAll(it) } return result } @Throws(IOException::class) @JvmStatic fun <T> loadAll(executor: GithubApiRequestExecutor, indicator: ProgressIndicator, pagesRequest: Request<T>, pageItemsConsumer: (List<T>) -> Unit) { var request: GithubApiRequest<GithubResponsePage<T>>? = pagesRequest.initialRequest while (request != null) { val page = executor.execute(indicator, request) pageItemsConsumer(page.items) request = page.nextLink?.let(pagesRequest.urlRequestProvider) } } @Throws(IOException::class) @JvmStatic fun <T> find(executor: GithubApiRequestExecutor, indicator: ProgressIndicator, pagesRequest: Request<T>, predicate: Predicate<T>): T? { var request: GithubApiRequest<GithubResponsePage<T>>? = pagesRequest.initialRequest while (request != null) { val page = executor.execute(indicator, request) page.items.find { predicate.test(it) }?.let { return it } request = page.nextLink?.let(pagesRequest.urlRequestProvider) } return null } @Throws(IOException::class) @JvmStatic fun <T> load(executor: GithubApiRequestExecutor, indicator: ProgressIndicator, pagesRequest: Request<T>, maximum: Int): List<T> { val result = mutableListOf<T>() var request: GithubApiRequest<GithubResponsePage<T>>? = pagesRequest.initialRequest while (request != null) { val page = executor.execute(indicator, request) for (item in page.items) { result.add(item) if (result.size == maximum) return result } request = page.nextLink?.let(pagesRequest.urlRequestProvider) } return result } class Request<T>(val initialRequest: GithubApiRequest<GithubResponsePage<T>>, val urlRequestProvider: (String) -> GithubApiRequest<GithubResponsePage<T>>) }
apache-2.0
7e82302027ee908e1d1a2ed8f3872e37
39.553846
140
0.719165
4.496587
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoInterfaceImpl.kt
3
3549
// FILE: smartStepIntoInterfaceImpl.kt package smartStepIntoInterfaceImpl import forTests.MyJavaClass interface I { // without params fun foo() { val a = 1 } // default param fun foo(a: Int, b: Int = 1) { val a = 1 } // checkParamNotNull fun foo(a: String) { val a = 1 } fun fooOverride() { val a = 1 } fun staticCallInOverride(s: String) = 1 } class IImpl: I { // super call in override (step into works in JVM_IR, doesn't work in the old backend) override fun fooOverride() { return super.fooOverride() } // java static call fun staticCall(s: String): Int { return MyJavaClass.staticFun(s) } // java static call in override override fun staticCallInOverride(s: String): Int { return MyJavaClass.staticFun(s) } } class IImpl2: I { // java static call in override with this param (step into doesn't work) override fun staticCallInOverride(s: String): Int { return MyJavaClass.staticFun(this) } } object Obj: I { @JvmStatic private fun staticFun(s: String): Int { return 1 } // kotlin static call fun staticCall(s: String): Int { return staticFun(s) } // kotlin static call in override override fun staticCallInOverride(s: String): Int { return staticFun(s) } } object Obj2: I { @JvmStatic private fun staticFun(s: Obj2): Int { return 1 } // kotlin static call in override with this param (step into doesn't work) override fun staticCallInOverride(s: String): Int { return staticFun(this) } } fun barI() = IImpl() fun main(args: Array<String>) { testSmartStepInto() testStepInto() } fun testSmartStepInto() { // TODO First time - doesn't work: should be smartStepIntoInterfaceImpl.kt:9 between smartStepIntoInterfaceImpl.kt:91 and 96 // SMART_STEP_INTO_BY_INDEX: 2 //Breakpoint! barI().foo() // SMART_STEP_INTO_BY_INDEX: 2 // RESUME: 1 //Breakpoint! barI().foo() // SMART_STEP_INTO_BY_INDEX: 2 // RESUME: 1 //Breakpoint! barI().foo(1) // SMART_STEP_INTO_BY_INDEX: 2 // RESUME: 1 //Breakpoint! barI().foo(1, 2) // SMART_STEP_INTO_BY_INDEX: 2 // RESUME: 1 //Breakpoint! barI().foo("a") } fun testStepInto() { val ii = IImpl() // (Fixed in JVM_IR) TODO: should be smartStepIntoInterfaceImpl.kt:32 instead of smartStepIntoInterfaceImpl.kt:23 // STEP_INTO: 1 // RESUME: 1 //Breakpoint! ii.fooOverride() // STEP_INTO: 1 // RESUME: 1 //Breakpoint! ii.staticCall("a") // STEP_INTO: 1 // RESUME: 1 //Breakpoint! ii.staticCallInOverride("a") val ii2 = IImpl2() // TODO: should be smartStepIntoInterfaceImpl.kt:49 instead of MyJavaClass.java:10 // STEP_INTO: 1 // RESUME: 1 //Breakpoint! ii2.staticCallInOverride("a") // STEP_INTO: 1 // RESUME: 1 //Breakpoint! Obj.staticCall("a") // STEP_INTO: 1 // RESUME: 1 //Breakpoint! Obj.staticCallInOverride("a") // TODO: should be smartStepIntoInterfaceImpl.kt:76 instead of smartStepIntoInterfaceImpl.kt:71 // STEP_INTO: 1 // RESUME: 1 //Breakpoint! Obj2.staticCallInOverride("a") } // FILE: forTests/MyJavaClass.java package forTests; import org.jetbrains.annotations.NotNull; import java.util.List; public class MyJavaClass { @NotNull public static int staticFun(Object s) { return 1; } }
apache-2.0
037269c639148dfecbe7229ffc83b312
20.005917
128
0.615666
3.85342
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerEx.kt
1
2332
// 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.openapi.wm.ex import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowEP import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.DesktopLayout import com.intellij.ui.AppUIUtil import org.jetbrains.annotations.ApiStatus abstract class ToolWindowManagerEx : ToolWindowManager() { companion object { @JvmStatic fun getInstanceEx(project: Project): ToolWindowManagerEx = getInstance(project) as ToolWindowManagerEx fun hideToolWindowBalloon(id: String, project: Project) { AppUIUtil.invokeLaterIfProjectAlive(project) { val balloon = getInstance(project).getToolWindowBalloon(id) balloon?.hide() } } } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use {{@link #registerToolWindow(RegisterToolWindowTask)}}") abstract fun initToolWindow(bean: ToolWindowEP) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use {@link ToolWindowManagerListener#TOPIC}") open fun addToolWindowManagerListener(listener: ToolWindowManagerListener) { } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use {@link ToolWindowManagerListener#TOPIC}") open fun addToolWindowManagerListener(listener: ToolWindowManagerListener, parentDisposable: Disposable) { } @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use {@link ToolWindowManagerListener#TOPIC}") open fun removeToolWindowManagerListener(listener: ToolWindowManagerListener) { } /** * @return layout of tool windows. */ abstract fun getLayout(): DesktopLayout abstract fun setLayout(newLayout: DesktopLayout) /** * Copied `layout` into internal layout and rearranges tool windows. */ abstract var layoutToRestoreLater: DesktopLayout? abstract fun clearSideStack() open fun shouldUpdateToolWindowContent(toolWindow: ToolWindow): Boolean = toolWindow.isVisible abstract fun hideToolWindow(id: String, hideSide: Boolean) abstract fun getIdsOn(anchor: ToolWindowAnchor): List<String?> }
apache-2.0
2dca7a777ff654a3687ffae3ffa8e6d4
34.892308
120
0.778302
4.868476
false
false
false
false
TimePath/launcher
src/main/kotlin/com/timepath/launcher/data/Repository.kt
1
6686
package com.timepath.launcher.data import com.timepath.StringUtils import com.timepath.XMLUtils import com.timepath.launcher.LauncherUtils import com.timepath.maven.Package import org.w3c.dom.Node import org.xml.sax.SAXException import java.io.BufferedInputStream import java.io.ByteArrayInputStream import java.io.IOException import java.io.InputStream import java.net.URI import java.text.MessageFormat import java.util.Collections import java.util.LinkedList import java.util.logging.Level import java.util.logging.Logger import javax.xml.parsers.DocumentBuilderFactory import javax.xml.parsers.ParserConfigurationException import javax.xml.transform.dom.DOMSource /** * A repository contains a list of multiple {@code Package}s and their {@code Program}s */ public class Repository private constructor() { /** * URL to the index file */ public var location: String? = null private set /** * The package representing this repository. Mostly only relevant to the main repository so that the main launcher * has a way of updating itself */ public var self: com.timepath.maven.Package? = null private set /** * The name of this repository */ private var name: String? = null /** * A list of all program entry points */ private var executions: MutableList<Program>? = null private var enabled: Boolean = false override fun equals(other: Any?): Boolean { if (this == other) return true if (other == null || javaClass != other.javaClass) return false val that = other as Repository if (location != that.location) return false return true } override fun hashCode(): Int { return location!!.hashCode() } /** * @return the executions */ public fun getExecutions(): List<Program> { return if (enabled) Collections.unmodifiableList<Program>(executions!!) else listOf<Program>() } override fun toString(): String { return MessageFormat.format("{0} ({1})", name, location) } /** * @return the name */ public fun getName(): String { return if (name == null) location!! else name!! } public fun isEnabled(): Boolean { return enabled } public fun setEnabled(enabled: Boolean) { this.enabled = enabled } companion object { private val LOG = Logger.getLogger(javaClass<Repository>().getName()) /** * Constructs a repository from a compatible node within a larger document * * @param location * @return */ public fun fromIndex(location: String): Repository? { val page = try { URI(location).toURL().readText() } catch (ignored: IOException) { return null } val data = page.toByteArray() val r = parse(findCompatible(ByteArrayInputStream(data))!!) r.location = location return r } /** * Constructs a repository from a root node * * @param root * @return */ private fun parse(root: Node): Repository { val r = Repository() r.name = XMLUtils.get(root, "name") r.self = Package.parse(root, null) if (r.self != null) r.self!!.setSelf(true) r.executions = LinkedList<Program>() for (entry in XMLUtils.getElements(root, "programs/program")) { val pkg = Package.parse(entry, null) if (pkg == null) { LOG.warning("Null package:\n${XMLUtils.pprint(entry)}") continue } // extended format with execution data for (execution in XMLUtils.getElements(entry, "executions/execution")) { val cfg = XMLUtils.last<Node>(XMLUtils.getElements(execution, "configuration")) val p = Program(pkg, XMLUtils.get(execution, "name"), XMLUtils.get(execution, "url"), XMLUtils.get(cfg, "main"), StringUtils.argParse(XMLUtils.get(cfg, "args")) ) r.executions!!.add(p) val daemonStr = XMLUtils.get(cfg, "daemon") if (daemonStr != null) p.setDaemon(java.lang.Boolean.parseBoolean(daemonStr)) } } return r } /** * @return a compatible configuration node */ private fun findCompatible(`is`: InputStream): Node? { try { val docBuilderFactory = DocumentBuilderFactory.newInstance() val docBuilder = docBuilderFactory.newDocumentBuilder() val doc = docBuilder.parse(BufferedInputStream(`is`)) val root = XMLUtils.getElements(doc, "root")[0] var version: Node? = null var iter: Node? = null val versions = root.getChildNodes() run { var i = 0 while (i < versions.getLength()) { if (iter != null && iter!!.hasAttributes()) { val attributes = iter!!.getAttributes() val versionAttribute = attributes.getNamedItem("version") if (versionAttribute != null) { val v = versionAttribute.getNodeValue() if (v != null) { try { if (LauncherUtils.DEBUG || (LauncherUtils.CURRENT_VERSION >= java.lang.Long.parseLong(v))) { version = iter } } catch (ignored: NumberFormatException) { } } } } iter = versions.item(i++) } } LOG.log(Level.FINE, "\n{0}", XMLUtils.pprint(DOMSource(version), 2)) return version } catch (ex: IOException) { LOG.log(Level.SEVERE, null, ex) } catch (ex: ParserConfigurationException) { LOG.log(Level.SEVERE, null, ex) } catch (ex: SAXException) { LOG.log(Level.SEVERE, null, ex) } return null } } }
artistic-2.0
0337de9fac52c37694bf2aa7563f65b2
34.005236
132
0.527969
5.115532
false
false
false
false
tlaukkan/kotlin-web-vr
client/src/vr/client/VrClient.kt
1
3185
package vr.client import vr.CLIENT import vr.network.NetworkClient import lib.threejs.Vector3 import lib.webvrapi.VRDisplay import vr.network.RestClient import vr.network.model.LinkRequest import vr.webvr.* import vr.webvr.actuators.MaterialFactory import kotlin.browser.window class VrClient(val display: VRDisplay) { var renderTime: Double = 0.0 var renderTimeDelta: Double = 0.001 val vrController: VrController val rendererController: RendererController val displayController: DisplayController val inputController: InputController val mediaController: MediaController val restClient: RestClient val materialFactory = MaterialFactory() init { CLIENT = this println("VR client startup...") rendererController = RendererController(this) displayController = DisplayController(this) inputController = InputController(this) mediaController = MediaController(this) vrController = VrController(this) val location = window.location val networkClient: NetworkClient if (location.port != null && location.port != undefined) { networkClient = NetworkClient("ws://${location.hostname}:${location.port}/ws") restClient = RestClient("http://${location.hostname}:${location.port}/api") } else { networkClient = NetworkClient("ws://${location.hostname}/ws") restClient = RestClient("http://${location.hostname}/api") } vrController!!.networkClient = networkClient networkClient.onConnected = { handshakeResponse -> println("Connected " + networkClient.url + " (" + handshakeResponse.software + ")") networkClient.send(listOf(LinkRequest(arrayOf(), arrayOf(handshakeResponse.serverCellUris[0])))) } networkClient.onLinked = { linkResponse -> vrController!!.neighbours.clear() for (neighbour in linkResponse.neighbours) { vrController!!.neighbours[neighbour.cellUriTwo] = Vector3( neighbour.oneTwoDeltaVector.x, neighbour.oneTwoDeltaVector.y, neighbour.oneTwoDeltaVector.z) } vrController!!.linkedServerCellUrl = linkResponse.serverCellUris[0] println("Linked to server cell: " + linkResponse.serverCellUris[0]) } networkClient.onReceive = { type, value -> vrController!!.onReceive(type, value) } networkClient.onDisconnected = { println("Disconnected") } mediaController.loadMedia() display.requestAnimationFrame({ time -> render() }) } fun render(): Unit { var timeMillis = Date().getTime() if (renderTime != 0.0) { renderTimeDelta = timeMillis / 1000.0 - renderTime } renderTime = timeMillis / 1000.0 inputController.render() vrController.render() rendererController.render() display.requestAnimationFrame({ time -> render() }) displayController.render(rendererController.scene, rendererController.camera) } }
mit
cc5e3ae9c776f99d68257193772ae564
31.835052
108
0.646468
5.087859
false
false
false
false
PhoenixDevTeam/Phoenix-for-VK
mvpcore/src/main/java/biz/dealnote/mvp/reflect/EventHandler.kt
1
1390
package biz.dealnote.mvp.reflect import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method /** * Created by ruslan.kolbasa on 05.10.2016. * phoenix */ class EventHandler(private val target: Any, private val method: Method) { private val hashCode: Int init { method.isAccessible = true // Compute hash code eagerly since we know it will be used frequently and we cannot estimate the runtime of the // target's hashCode call. val prime = 31 hashCode = (prime + method.hashCode()) * prime + target.hashCode() } @Throws(InvocationTargetException::class) fun handle() { try { method.invoke(target) } catch (e: IllegalAccessException) { throw AssertionError(e) } catch (e: InvocationTargetException) { if (e.cause is Error) { throw e.cause as Error } throw e } } override fun hashCode(): Int { return hashCode } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null) { return false } if (javaClass != other.javaClass) { return false } val o = other as EventHandler return method == o.method && target === o.target } }
gpl-3.0
3a6b75d291868d79cfd2c252c67547ce
23.403509
119
0.571942
4.633333
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/graphics/Bitmap.kt
1
3943
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package androidx.core.graphics import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.ColorSpace import androidx.annotation.ColorInt import androidx.annotation.RequiresApi /** * Creates a new [Canvas] to draw on this bitmap and executes the specified * [block] on the newly created canvas. Example: * * ``` * return Bitmap.createBitmap(…).applyCanvas { * drawLine(…) * translate(…) * drawRect(…) * } * ``` */ inline fun Bitmap.applyCanvas(block: Canvas.() -> Unit): Bitmap { val c = Canvas(this) c.block() return this } /** * Returns the value of the pixel at the specified location. The returned value * is a [color int][android.graphics.Color] in the sRGB color space. */ inline operator fun Bitmap.get(x: Int, y: Int) = getPixel(x, y) /** * Writes the specified [color int][android.graphics.Color] into the bitmap * (assuming it is mutable) at the specified `(x, y)` coordinate. The specified * color is converted from sRGB to the bitmap's color space if needed. */ inline operator fun Bitmap.set(x: Int, y: Int, @ColorInt color: Int) = setPixel(x, y, color) /** * Creates a new bitmap, scaled from this bitmap, when possible. If the specified * [width] and [height] are the same as the current width and height of this bitmap, * this bitmap is returned and no new bitmap is created. * * @param width The new bitmap's desired width * @param height The new bitmap's desired height * @param filter `true` if the source should be filtered (`true` by default) * * @return The new scaled bitmap or the source bitmap if no scaling is required. */ inline fun Bitmap.scale(width: Int, height: Int, filter: Boolean = true): Bitmap { return Bitmap.createScaledBitmap(this, width, height, filter) } /** * Returns a mutable bitmap with the specified [width] and [height]. A config * can be optionally specified. If not, the default config is [Bitmap.Config.ARGB_8888]. * * @param width The new bitmap's desired width * @param height The new bitmap's desired height * @param config The new bitmap's desired [config][Bitmap.Config] * * @return A new bitmap with the specified dimensions and config */ inline fun createBitmap( width: Int, height: Int, config: Bitmap.Config = Bitmap.Config.ARGB_8888 ): Bitmap { return Bitmap.createBitmap(width, height, config) } /** * Returns a mutable bitmap with the specified [width] and [height]. The config, * transparency and color space can optionally be specified. They respectively * default to [Bitmap.Config.ARGB_8888], `true` and [sRGB][ColorSpace.Named.SRGB]. * * @param width The new bitmap's desired width * @param height The new bitmap's desired height * @param config The new bitmap's desired [config][Bitmap.Config] * @param hasAlpha Whether the new bitmap is opaque or not * @param colorSpace The new bitmap's color space * * @return A new bitmap with the specified dimensions and config */ @RequiresApi(26) inline fun createBitmap( width: Int, height: Int, config: Bitmap.Config = Bitmap.Config.ARGB_8888, hasAlpha: Boolean = true, colorSpace: ColorSpace = ColorSpace.get(ColorSpace.Named.SRGB) ): Bitmap { return Bitmap.createBitmap(width, height, config, hasAlpha, colorSpace) }
apache-2.0
9bf92d34d77411ae8e4e50829bc85122
33.823009
92
0.720966
3.915423
false
true
false
false
breadwallet/breadwallet-android
app-core/src/main/java/com/breadwallet/ext/LifecycleExtensions.kt
1
5680
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 6/2/2019. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ext import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.OnLifecycleEvent import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.fragment.app.FragmentActivity import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * Returns a lazily acquired ViewModel using [factory] * as an optional factory for [T]. */ inline fun <reified T : ViewModel> FragmentActivity.viewModel( noinline factory: (() -> T)? = null ): Lazy<T> = lazy { if (factory != null) { val vmFactory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T2 : ViewModel?> create(modelClass: Class<T2>): T2 = factory() as T2 } ViewModelProvider(this, vmFactory).get(T::class.java) } else ViewModelProvider(this).get(T::class.java) } /** * Factory function for [MutableLiveData] that takes an * optional [default] parameter. */ fun <T> mutableLiveData(default: T? = null) = MutableLiveData<T>().apply { default?.let(::postValue) } /** * Turn the values emitted by this [LiveData] from [I] to [O] * using the [transformer] function. */ inline fun <I, O> LiveData<I>.map(crossinline transformer: (I) -> O): LiveData<O> = Transformations.map(this) { transformer(it) } /** * Turn the values emitted by this [LiveData] from [I] to * a new [LiveData] that emits [O] using [transformer]. */ inline fun <I, O> LiveData<I>.switchMap(crossinline transformer: (I) -> LiveData<O>): LiveData<O> = Transformations.switchMap(this) { transformer(it) } /** * Combine the latest values of two [LiveData]s using * [combineFun] when either source emits a value. */ fun <I1, I2, O> LiveData<I1>.combineLatest( second: LiveData<I2>, combineFun: (I1, I2) -> O ): LiveData<O> { val first = this return MediatorLiveData<O>().apply { var firstEmitted = false var firstValue: I1? = null var secondEmitted = false var secondValue: I2? = null addSource(first) { value -> firstEmitted = true firstValue = value if (firstEmitted && secondEmitted) { postValue(combineFun(firstValue!!, secondValue!!)) } } addSource(second) { value -> secondEmitted = true secondValue = value if (firstEmitted && secondEmitted) { postValue(combineFun(firstValue!!, secondValue!!)) } } } } /** * Returns a live data that will only emit values when * the next value is not the same as the previous. */ fun <T> LiveData<T>.distinctUntilChanged(): LiveData<T> = MediatorLiveData<T>().also { newLiveData -> var oldVal: T? = null newLiveData.addSource(this) { newVal -> if (oldVal != newVal) { oldVal = newVal newLiveData.postValue(newVal) } } } /** * Lazily call [binding] and clear it's reference with [Lifecycle.Event.ON_DESTROY] */ fun <T> FragmentActivity.bindCreated( binding: () -> T ): ReadOnlyProperty<FragmentActivity, T> = object : ReadOnlyProperty<FragmentActivity, T>, LifecycleObserver { init { [email protected](this) } private var cache: T? = null override fun getValue(thisRef: FragmentActivity, property: KProperty<*>): T = cache ?: binding().also { cache = it } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun clear() { cache = null } } /** * Lazily call [binding] and clear it's reference in [Lifecycle.Event.ON_PAUSE] */ fun <T> FragmentActivity.bindResumed( binding: () -> T ): ReadOnlyProperty<FragmentActivity, T> = object : ReadOnlyProperty<FragmentActivity, T>, LifecycleObserver { init { [email protected](this) } private var cache: T? = null override fun getValue(thisRef: FragmentActivity, property: KProperty<*>): T = cache ?: binding().also { cache = it } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun clear() { cache = null } }
mit
7637997328b1a8cd7ea319ffe51082c3
33.424242
99
0.662852
4.355828
false
false
false
false
fgsguedes/adventofcode
2015/src/main/kotlin/day1/not_quite_lisp.kt
1
805
package day1 import fromOneLineInput fun characterInstruction(char: Char) = when (char) { '(' -> 1 ')' -> -1 else -> 0 // Should never happen } fun computeFloor(input: String) = input.map(::characterInstruction).sum() fun firstBasementPosition(input: String): Int { val counter = Counter() return input.indexOfFirst { counter.compute(it) } + 1 } data class Counter(private var floor: Int = 0) { fun compute(input: Char): Boolean { floor += characterInstruction(input) return floor < 0 } } fun main(args: Array<String>) { val targetFloor = fromOneLineInput(2015, 1, "not_quite_lisp.txt", ::computeFloor) val firstBasementPosition = fromOneLineInput(2015, 1, "not_quite_lisp_part_two.txt", ::firstBasementPosition) println(targetFloor) println(firstBasementPosition) }
gpl-2.0
5358ab77f121135128462e9734ca563f
24.15625
111
0.706832
3.59375
false
false
false
false
hazuki0x0/YuzuBrowser
module/webview/src/main/java/jp/hazuki/yuzubrowser/webview/page/WebViewPage.kt
1
1163
/* * 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.webview.page import jp.hazuki.yuzubrowser.webview.CustomWebView internal class WebViewPage(val webView: CustomWebView, val page: Page) : PageInfo by page { constructor(webView: CustomWebView) : this(webView, Page(webView.identityId)) var originalUrl: String? = null get() = field ?: url fun onPageStarted(url: String) { this.url = url originalUrl = url } fun onPageFinished() { url = webView.url originalUrl = webView.originalUrl title = webView.title } }
apache-2.0
70e6cf298e93af45611559bb17103523
29.631579
91
0.702494
4.260073
false
false
false
false
ferranponsscmspain/android-cast-remote-display-sample
app/src/main/java/com/schibsted/remotedisplaysample/MainActivity.kt
1
9045
package com.schibsted.remotedisplaysample import android.app.PendingIntent import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.viewpager.widget.ViewPager import androidx.appcompat.app.AppCompatActivity import androidx.mediarouter.media.MediaRouteSelector import androidx.mediarouter.media.MediaRouter import android.view.Menu import android.widget.Toast import com.google.android.gms.cast.CastDevice import com.google.android.gms.cast.CastMediaControlIntent import com.google.android.gms.cast.CastRemoteDisplayLocalService import com.google.android.gms.cast.framework.CastButtonFactory import com.google.android.gms.common.api.Status import java.util.ArrayList class MainActivity : AppCompatActivity(), CustomSimpleOnPageChangeListener.OnPageChangePosition { private var currentPosition: Int = 0 private var fragmentStatePagerAdapter: ScreenSlidePagerAdapter? = null private var mediaRouter: MediaRouter? = null private var castDevice: CastDevice? = null private val isRemoteDisplaying: Boolean get() = CastRemoteDisplayLocalService.getInstance() != null private val mMediaRouterCallback = object : MediaRouter.Callback() { override fun onRouteSelected(router: MediaRouter?, info: MediaRouter.RouteInfo) { castDevice = CastDevice.getFromBundle(info.extras) Toast.makeText(applicationContext, getString(R.string.cast_connected_to) + info.name, Toast.LENGTH_LONG).show() startCastService(castDevice) } override fun onRouteUnselected(router: MediaRouter?, info: MediaRouter.RouteInfo?) { if (isRemoteDisplaying) { CastRemoteDisplayLocalService.stopService() } castDevice = null } } private val adViewModels: List<AdViewModel> get() { val adViewModel1 = AdViewModel("0", "Solid Strike", "$3.333", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/solid-strike.jpg") val adViewModel2 = AdViewModel("1", "YT Industries Tues", "$2.799", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/yt-tues.jpg") val adViewModel3 = AdViewModel("2", "Transition TR450", "$3.750", "https://descensonuevoleon.files.wordpress.com/2009/08/tr450_weblarge3.jpg") val adViewModel4 = AdViewModel("3", "Lapierre DH", "$5.199", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/lapierre-dh.jpg") val adViewModel5 = AdViewModel("4", "Specialized Demo", "$7.000", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/specialized-demo.jpg") val adViewModel6 = AdViewModel("5", "Trek Session 9.9", "$7.000", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/Trek-session-9.9.jpg") val adViewModel7 = AdViewModel("6", "Mondraker Summum Pro Team", "$5.799", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/mondraker-summum-pro-team.jpg") val adViewModel8 = AdViewModel("7", "Intense 951 EVO", "$5.499", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/intense-951-evo.jpg") val adViewModel9 = AdViewModel("8", "Giant Glory", "$4.749", "https://coresites-cdn.factorymedia.com/dirt_new/wp-content/uploads/2015/06/giant-glory.jpg") val list = ArrayList<AdViewModel>() list.add(adViewModel1) list.add(adViewModel2) list.add(adViewModel3) list.add(adViewModel4) list.add(adViewModel5) list.add(adViewModel6) list.add(adViewModel7) list.add(adViewModel8) list.add(adViewModel9) return list } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val list = adViewModels val viewPager = findViewById<ViewPager>(R.id.pager) fragmentStatePagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager) fragmentStatePagerAdapter?.addAds(list) val customSimpleOnPageChangeListener = CustomSimpleOnPageChangeListener(this) if (viewPager != null) { viewPager.adapter = fragmentStatePagerAdapter viewPager.addOnPageChangeListener(customSimpleOnPageChangeListener) } setupMediaRouter() } override fun onResume() { super.onResume() if (!isRemoteDisplaying) { if (castDevice != null) { startCastService(castDevice) } } } public override fun onDestroy() { if (mediaRouter != null) { mediaRouter!!.removeCallback(mMediaRouterCallback) } super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.activity_main_actions, menu) CastButtonFactory.setUpMediaRouteButton(applicationContext, menu, R.id.action_cast) return true } private fun setupMediaRouter() { mediaRouter = MediaRouter.getInstance(applicationContext) val mediaRouteSelector = MediaRouteSelector.Builder().addControlCategory( CastMediaControlIntent.categoryForCast(getString(R.string.app_cast_id))).build() if (isRemoteDisplaying) { this.castDevice = CastDevice.getFromBundle(mediaRouter!!.selectedRoute.extras) } else { val extras = intent.extras if (extras != null) { castDevice = extras.getParcelable(INTENT_EXTRA_CAST_DEVICE) } } mediaRouter!!.addCallback(mediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY) } private fun startCastService(castDevice: CastDevice?) { val intent = Intent(this@MainActivity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val notificationPendingIntent = PendingIntent.getActivity(this@MainActivity, 0, intent, 0) val settings = CastRemoteDisplayLocalService.NotificationSettings.Builder().setNotificationPendingIntent( notificationPendingIntent).build() CastRemoteDisplayLocalService.startService(this@MainActivity, PresentationService::class.java, getString(R.string.app_cast_id), castDevice!!, settings, object : CastRemoteDisplayLocalService.Callbacks { override fun onServiceCreated(service: CastRemoteDisplayLocalService) { (service as PresentationService).setAdViewModel( fragmentStatePagerAdapter!!.getAdAt(currentPosition)) } override fun onRemoteDisplaySessionStarted(service: CastRemoteDisplayLocalService) {} override fun onRemoteDisplaySessionError(errorReason: Status) { initError() [email protected] = null [email protected]() } override fun onRemoteDisplaySessionEnded(castRemoteDisplayLocalService: CastRemoteDisplayLocalService) {} }) } private fun initError() { val toast = Toast.makeText(applicationContext, R.string.toast_connection_error, Toast.LENGTH_SHORT) mediaRouter?.let { it.selectRoute(it.defaultRoute) } toast.show() } override fun onCurrentPageChange(position: Int) { currentPosition = position fragmentStatePagerAdapter?.let { if (CastRemoteDisplayLocalService.getInstance() != null) { (CastRemoteDisplayLocalService.getInstance() as PresentationService).setAdViewModel(it.getAdAt(position)) } } } private inner class ScreenSlidePagerAdapter internal constructor(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { private val ads = ArrayList<AdViewModel>() override fun getItem(position: Int): Fragment { return DetailFragment.newInstance(ads[position]) } override fun getCount(): Int { return ads.size } internal fun addAds(ads: List<AdViewModel>) { this.ads.addAll(ads) notifyDataSetChanged() } fun getAdAt(position: Int): AdViewModel { return ads[position] } } companion object { private const val INTENT_EXTRA_CAST_DEVICE = "CastDevice" } }
apache-2.0
22139a6765ebc9cf65eb168d2f7994de
42.071429
127
0.657159
4.899783
false
false
false
false
google/audio-to-tactile
extras/android/java/com/google/audio_to_tactile/SoundEventsDialogFragment.kt
1
4026
/* Copyright 2021 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.audio_to_tactile import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.TextView import androidx.core.os.bundleOf import androidx.fragment.app.activityViewModels import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.slider.Slider import com.google.android.material.switchmaterial.SwitchMaterial import com.google.android.material.textfield.TextInputLayout import dagger.hilt.android.AndroidEntryPoint import kotlin.math.roundToInt /** * Define the Sound Events Dialog fragment accessed from Sound Events fragment. This fragment allow * tuning of specific sound event. */ @AndroidEntryPoint class SoundEventsDialogFragment : BottomSheetDialogFragment() { private val bleViewModel: BleViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_sound_event_dialog, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val soundEventIndex = arguments?.getInt(SOUND_INDEX_KEY) ?: return view.findViewById<TextView>(R.id.sound_event_dialog_title).apply { text = SoundEvents.SOUND_EVENTS[soundEventIndex] } // Reset button. view.findViewById<Button>(R.id.sound_event_reset).apply { setOnClickListener { // TODO: Add action for clicking on reset button. } } // Source dropdown menu. val soundEventSourceField: TextInputLayout = view.findViewById(R.id.sound_events_source_field) val soundEventSourceDropdown: AutoCompleteTextView = view.findViewById(R.id.sound_events_source_dropdown) soundEventSourceDropdown.apply { setAdapter( ArrayAdapter( [email protected](), R.layout.sound_event_configure_menu_item, SoundEvents.TACTILE_PATTERNS ) ) setOnItemClickListener { _, _, position, _ -> // TODO: Add action for selecting a tactile pattern. } } // Gain value text. val soundEventGainValue: TextView = view.findViewById(R.id.sound_events_gain_value) // Gain slider. val soundEventGainSlider: Slider = view.findViewById(R.id.sound_event_gain_slider) soundEventGainSlider.apply { setLabelFormatter { value -> ChannelMap.gainMapping(value.roundToInt()) } addOnSliderTouchListener( object : Slider.OnSliderTouchListener { override fun onStartTrackingTouch(slider: Slider) {} override fun onStopTrackingTouch(slider: Slider) { // TODO: Add action for gain slider. } } ) } // Enable switch. val soundEventEnableSwitch: SwitchMaterial = view.findViewById(R.id.sound_event_enable_switch) soundEventEnableSwitch.setOnCheckedChangeListener { _, enabled -> // TODO: Add action for enable/disable sound events toggle switch. } } companion object { private const val SOUND_INDEX_KEY = "channel_index_key" /** Creates args Bundle for navigating to this fragment. */ fun createArgs(soundEventIndex: Int): Bundle = bundleOf(SOUND_INDEX_KEY to soundEventIndex) } }
apache-2.0
9f137b3b8d3e191b02cf0934a5c17fe3
34.315789
99
0.732986
4.559456
false
false
false
false
facebook/fresco
vito/core/src/main/java/com/facebook/fresco/vito/drawable/CircularBorderBitmapDrawable.kt
2
2463
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.fresco.vito.drawable import android.content.res.Resources import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import com.facebook.drawee.drawable.DrawableUtils import com.facebook.fresco.vito.options.BorderOptions import kotlin.math.min class CircularBorderBitmapDrawable( res: Resources?, bitmap: Bitmap?, private var borderOptions: BorderOptions? = null ) : BitmapDrawable(res, bitmap) { private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG) private var radius = 0 private var _alpha = 255 override fun draw(canvas: Canvas) { if (radius == 0) return val border = borderOptions if (border == null || border.padding < 0.0f || border.width < 0.0f) { super.draw(canvas) return } val widthReduction = if (border.scaleDownInsideBorders) border.width + border.padding else border.padding if (widthReduction > radius) return val centerX = bounds.exactCenterX() val centerY = bounds.exactCenterY() if (widthReduction > 0.0f) { val scale = (radius - widthReduction) / radius canvas.save() canvas.scale(scale, scale, centerX, centerY) super.draw(canvas) canvas.restore() } else { super.draw(canvas) } if (border.width > 0.0f) { canvas.drawCircle(centerX, centerY, radius - border.width / 2, borderPaint) } } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) radius = min(bounds.width(), bounds.height()) / 2 } var border: BorderOptions? get() = borderOptions set(borderOptions) { if (this.borderOptions == null || this.borderOptions != borderOptions) { this.borderOptions = borderOptions ensureBorderPaint() invalidateSelf() } } init { borderPaint.style = Paint.Style.STROKE ensureBorderPaint() } override fun setAlpha(alpha: Int) { super.setAlpha(alpha) _alpha = alpha ensureBorderPaint() } private fun ensureBorderPaint() { borderOptions?.let { borderPaint.strokeWidth = it.width borderPaint.color = DrawableUtils.multiplyColorAlpha(it.color, _alpha) } } }
mit
6a6a570e0dbb2328ec4abbc1dbddcc29
26.674157
92
0.688997
4.125628
false
false
false
false
tangying91/profit
src/main/java/org/profit/app/Actions.kt
1
870
package org.profit.app import org.profit.app.action.STOCK_POOL_LOAD import org.profit.server.handler.action.Action import org.profit.server.handler.communication.exception.InvalidActionException import java.util.* enum class Actions { INSTANCE; private val ACTION_MAP: MutableMap<String, Action?> @Throws(InvalidActionException::class) fun interpretCommand(actionName: String?): Action? { if (actionName == null || actionName == "") { return null } return if (ACTION_MAP.containsKey(actionName.toUpperCase())) { ACTION_MAP[actionName.toUpperCase()] } else { throw InvalidActionException("Received invalid action id: $actionName") } } init { ACTION_MAP = HashMap() ACTION_MAP["STOCK_POOL_LOAD"] = STOCK_POOL_LOAD() } }
apache-2.0
a62be2bee2e7ffda2bf6536e108af5d5
28.068966
83
0.637931
4.416244
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/extensions/models/builder/CustomUserEventBuilder.kt
1
2610
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED") package jp.nephy.penicillin.extensions.models.builder import jp.nephy.jsonkt.* import jp.nephy.penicillin.core.experimental.PenicillinExperimentalApi import jp.nephy.penicillin.core.streaming.handler.UserStreamEvent import jp.nephy.penicillin.extensions.parseModel import jp.nephy.penicillin.models.Stream import java.time.temporal.TemporalAccessor import kotlin.collections.set /** * Custom payload builder for [Stream.UserEvent]. */ class CustomUserEventBuilder(type: UserStreamEvent): JsonBuilder<Stream.UserEvent>, JsonMap by jsonMapOf( "event" to type.key, "source" to null, "target" to null, "created_at" to null ) { private var source = CustomUserBuilder() /** * Sets source. */ fun source(builder: CustomUserBuilder.() -> Unit) { source.apply(builder) } private var target = CustomUserBuilder() /** * Sets target. */ fun target(builder: CustomUserBuilder.() -> Unit) { target.apply(builder) } /** * "created_at". */ var createdAt: TemporalAccessor? = null @UseExperimental(PenicillinExperimentalApi::class) override fun build(): Stream.UserEvent { val source = source.build() val target = target.build() this["source"] = source this["target"] = target this["created_at"] = createdAt.toCreatedAt() return toJsonObject().parseModel() } }
mit
a780e6eef11778967866d703aa8d7a62
32.461538
105
0.709195
4.299835
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dev/DebugCameraScene.kt
1
2544
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dev import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.dsl.getAppHeight import com.almasb.fxgl.dsl.getAppWidth import com.almasb.fxgl.input.InputModifier import com.almasb.fxgl.input.UserAction import com.almasb.fxgl.scene.SubScene import javafx.beans.property.SimpleDoubleProperty import javafx.scene.input.KeyCode import javafx.scene.paint.Color import javafx.scene.shape.Rectangle /** * * @author Almas Baimagambetov ([email protected]) */ class DebugCameraScene : SubScene() { override val isAllowConcurrency: Boolean get() = true // negative because we want to bind to these values directly // for example, as the camera moves right, the root layout moves left private val negativeCameraX = SimpleDoubleProperty() private val negativeCameraY = SimpleDoubleProperty() init { input.addAction(object : UserAction("Right") { override fun onAction() { negativeCameraX.value -= 5 } }, KeyCode.RIGHT, InputModifier.CTRL) input.addAction(object : UserAction("Left") { override fun onAction() { negativeCameraX.value += 5 } }, KeyCode.LEFT, InputModifier.CTRL) input.addAction(object : UserAction("Up") { override fun onAction() { negativeCameraY.value += 5 } }, KeyCode.UP, InputModifier.CTRL) input.addAction(object : UserAction("Down") { override fun onAction() { negativeCameraY.value -= 5 } }, KeyCode.DOWN, InputModifier.CTRL) val viewportBoundary = Rectangle(getAppWidth().toDouble(), getAppHeight().toDouble(), null) viewportBoundary.stroke = Color.RED viewportBoundary.strokeWidth = 4.0 contentRoot.children += viewportBoundary } override fun onCreate() { FXGL.getWindowService().window.currentFXGLScene.root.translateXProperty().bind(negativeCameraX) FXGL.getWindowService().window.currentFXGLScene.root.translateYProperty().bind(negativeCameraY) } override fun onDestroy() { negativeCameraX.value = 0.0 negativeCameraY.value = 0.0 FXGL.getWindowService().window.currentFXGLScene.root.translateXProperty().unbind() FXGL.getWindowService().window.currentFXGLScene.root.translateYProperty().unbind() } }
mit
48548a23f5a33d264a446967e2e5ae7a
31.628205
103
0.670991
4.61706
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/provider/DartDocumentationElementProvider.kt
1
2407
package cn.yiiguxing.plugin.translate.provider import cn.yiiguxing.plugin.translate.util.elementType import cn.yiiguxing.plugin.translate.util.findChildOfType import cn.yiiguxing.plugin.translate.util.getNextSiblingSkippingCondition import cn.yiiguxing.plugin.translate.util.getPrevSiblingSkippingCondition import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.jetbrains.lang.dart.DartTokenTypesSets import com.jetbrains.lang.dart.psi.DartClassMembers import com.jetbrains.lang.dart.psi.DartComponent import com.jetbrains.lang.dart.psi.DartDocComment import com.jetbrains.lang.dart.psi.DartVarDeclarationList class DartDocumentationElementProvider : AbstractDocumentationElementProvider() { override val PsiComment.isDocComment: Boolean get() = this@isDocComment is DartDocComment || elementType == DartTokenTypesSets.SINGLE_LINE_DOC_COMMENT override val PsiComment.isPickAtEdge: Boolean get() = elementType == DartTokenTypesSets.SINGLE_LINE_DOC_COMMENT override val PsiComment.documentationOwner: PsiElement? get() { // 文档注释类型中,多行注释有最高的优先级。 // 如果当前注释不是多行注释(DartDocComment),则向上寻找,如果上方有多行注释,则说明当前的注释是无效的。 // 且,最下方的多行文档注释有最高的优先级,向下寻找时如遇文档注释,则当前的注释也是无效的。 if (this !is DartDocComment && !checkPreviousComments()) { return null } return when (val sibling = getNextSiblingSkippingCondition(SKIPPING_CONDITION)) { is DartComponent -> sibling.componentName is DartClassMembers, is DartVarDeclarationList -> sibling.findChildOfType(DartComponent::class.java)?.componentName else -> null } } companion object { private val SKIPPING_CONDITION: (PsiElement) -> Boolean = { it is PsiWhiteSpace || (it is PsiComment && it !is DartDocComment) } /** * 向上检查是否存在多行文档注释 */ private fun PsiComment.checkPreviousComments(): Boolean { return getPrevSiblingSkippingCondition(SKIPPING_CONDITION) !is DartDocComment } } }
mit
f644ddaa6a64b0f70c40a789d4da35dc
39.148148
112
0.712967
4.191489
false
false
false
false
commons-app/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/upload/structure/depictions/DepictedItemTest.kt
5
5622
package fr.free.nrw.commons.upload.structure.depictions import com.nhaarman.mockitokotlin2.mock import depictedItem import entity import entityId import fr.free.nrw.commons.wikidata.WikidataProperties import org.junit.Assert import org.junit.Test import place import snak import statement import valueString import wikiBaseEntityValue class DepictedItemTest { @Test fun `name and description get user language label`() { val depictedItem = DepictedItem(entity(mapOf("en" to "label"), mapOf("en" to "description"))) Assert.assertEquals(depictedItem.name, "label") Assert.assertEquals(depictedItem.description, "description") } @Test fun `name and descriptions get first language label if user language not present`() { val depictedItem = DepictedItem(entity(mapOf("" to "label"), mapOf("" to "description"))) Assert.assertEquals(depictedItem.name, "label") Assert.assertEquals(depictedItem.description, "description") } @Test fun `name and descriptions get empty if nothing present`() { val depictedItem = DepictedItem(entity()) Assert.assertEquals(depictedItem.name, "") Assert.assertEquals(depictedItem.description, "") } @Test fun `image is empty with null statements`() { Assert.assertEquals(DepictedItem(entity(statements = null)).imageUrl, null) } @Test fun `image is empty with no image statement`() { Assert.assertEquals(DepictedItem(entity()).imageUrl, null) } @Test fun `image is empty with dataValue not of ValueString type`() { Assert.assertEquals( DepictedItem( entity( statements = mapOf( WikidataProperties.IMAGE.propertyName to listOf(statement(snak(dataValue = mock()))) ) ) ).imageUrl, null ) } @Test fun `image is not empty with dataValue of ValueString type`() { Assert.assertEquals( DepictedItem( entity( statements = mapOf( WikidataProperties.IMAGE.propertyName to listOf( statement(snak(dataValue = valueString("prefix: example_"))) ) ) ) ).imageUrl, "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/_example_/70px-_example_") } @Test fun `instancesOf maps EntityIds to ids`() { Assert.assertEquals( DepictedItem( entity( statements = mapOf( WikidataProperties.INSTANCE_OF.propertyName to listOf( statement(snak(dataValue = valueString("prefix: example_"))), statement(snak(dataValue = entityId(wikiBaseEntityValue(id = "1")))), statement(snak(dataValue = entityId(wikiBaseEntityValue(id = "2")))) ) ) ) ).instanceOfs, listOf("1", "2")) } @Test fun `instancesOf is empty with no values`() { Assert.assertEquals(DepictedItem(entity()).instanceOfs, emptyList<String>()) } @Test fun `commonsCategory maps ValueString to strings`() { Assert.assertEquals( DepictedItem( entity( statements = mapOf( WikidataProperties.COMMONS_CATEGORY.propertyName to listOf( statement(snak(dataValue = valueString("1"))), statement(snak(dataValue = valueString("2"))) ) ) ) ).commonsCategories.map { it.name }, listOf("1", "2")) } @Test fun `commonsCategory is empty with no values`() { Assert.assertEquals(DepictedItem(entity()).commonsCategories, emptyList<String>()) } @Test fun `isSelected is false at creation`() { Assert.assertEquals(DepictedItem(entity()).isSelected, false) } @Test fun `id is entityId`() { Assert.assertEquals(DepictedItem(entity(id = "1")).id, "1") } @Test fun `place constructor uses place name and longDescription`() { val depictedItem = DepictedItem(entity(), place(name = "1", longDescription = "2")) Assert.assertEquals(depictedItem.name, "1") Assert.assertEquals(depictedItem.description, "2") } @Test fun `same object is Equal`() { val depictedItem = depictedItem() Assert.assertEquals(depictedItem == depictedItem, true) } @Test fun `different type is not Equal`() { Assert.assertEquals(depictedItem().equals(Unit), false) } @Test fun `if names are equal is Equal`() { Assert.assertEquals( depictedItem(name="a", id = "0") == depictedItem(name="a", id = "1"), true) } @Test fun `if names are not equal is not Equal`() { Assert.assertEquals( depictedItem(name="a") == depictedItem(name="b"), false) } @Test fun `hashCode returns same values for objects with same name`() { Assert.assertEquals(depictedItem(name="a").hashCode(), depictedItem(name="a").hashCode()) } @Test fun `hashCode returns different values for objects with different name`() { Assert.assertNotEquals(depictedItem(name="a").hashCode(), depictedItem(name="b").hashCode()) } }
apache-2.0
f8f358fb2b6437e379f9f23fee515480
31.310345
108
0.577197
5.097008
false
true
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/db/DepartmentTable.kt
1
2294
package fr.geobert.efficio.db import android.app.Activity import android.content.* import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns import fr.geobert.efficio.data.Department import fr.geobert.efficio.extensions.normalize object DepartmentTable : BaseTable() { override val TABLE_NAME = "departments" val COL_NAME = "dep_name" val COL_NORM_NAME = "dep_norm" override fun CREATE_COLUMNS() = "$COL_NORM_NAME TEXT NOT NULL UNIQUE ON CONFLICT IGNORE, " + "$COL_NAME TEXT NOT NULL" override val COLS_TO_QUERY: Array<String> = arrayOf(BaseColumns._ID, COL_NAME) val CREATE_TRIGGER_ON_DEP_DELETE by lazy { "CREATE TRIGGER on_dep_deleted " + "AFTER DELETE ON ${DepartmentTable.TABLE_NAME} BEGIN " + "DELETE FROM ${TaskTable.TABLE_NAME} WHERE " + "${TaskTable.COL_ITEM_ID} IN " + "(SELECT ${ItemDepTable.COL_ITEM_ID} FROM ${ItemDepTable.TABLE_NAME} WHERE " + "${ItemDepTable.TABLE_NAME}.${ItemDepTable.COL_DEP_ID} = old.${BaseColumns._ID});" + "DELETE FROM ${StoreCompositionTable.TABLE_NAME} WHERE " + "${StoreCompositionTable.COL_DEP_ID} = old.${BaseColumns._ID};" + "DELETE FROM ${ItemDepTable.TABLE_NAME} WHERE " + "${ItemDepTable.COL_DEP_ID} = old.${BaseColumns._ID};" + "END" } fun getAllDepLoader(activity: Context): CursorLoader { return CursorLoader(activity, CONTENT_URI, COLS_TO_QUERY, null, null, "dep_name desc") } fun create(ctx: Context, department: Department): Long { val v = ContentValues() v.put(COL_NORM_NAME, department.name.normalize()) v.put(COL_NAME, department.name) return insert(ctx, v) } fun updateDepartment(activity: Activity, depId: Long, s: String): Int { val v = ContentValues() v.put(COL_NAME, s) v.put(COL_NORM_NAME, s.normalize()) return update(activity, depId, v) } fun deleteDep(activity: Activity, depId: Long): Int { return delete(activity, depId) } fun upgradeFromV1(db: SQLiteDatabase) { db.execSQL("DROP TRIGGER on_dep_deleted") db.execSQL(CREATE_TRIGGER_ON_DEP_DELETE) } }
gpl-2.0
e779d2dcf380e11e3a73d738c1d96565
36.622951
100
0.628596
3.914676
false
false
false
false
waicool20/SKrypton
src/main/kotlin/com/waicool20/skrypton/sikulix/input/SKryptonKeyboard.kt
1
4755
/* * The MIT License (MIT) * * Copyright (c) SKrypton by waicool20 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.waicool20.skrypton.sikulix.input import org.sikuli.basics.Settings import org.sikuli.script.Key import org.sikuli.script.KeyModifier import org.sikuli.script.Location /** * Class representing a virtual keyboard for a [com.waicool20.skrypton.sikulix.SKryptonScreen] * This class is also in charge of coordinating keyboard actions between threads, unlike [SKryptonRobot] * all functions are synchronized and thus only one thread may have access to keyboard actions. * * @property robot [SKryptonRobot] used for generating actions. * @constructor Main constructor * @param robot [SKryptonRobot] to use for generating actions. */ class SKryptonKeyboard(val robot: SKryptonRobot) { companion object { /** * Parses the given modifiers string and returns corresponding [KeyModifier]. * * @param modifiers String of modifiers. * @return Corresponding [KeyModifier]. */ fun parseModifiers(modifiers: String): Int { var mods = 0 modifiers.toCharArray().forEach { mods = mods.or(when (it) { Key.C_CTRL -> KeyModifier.CTRL Key.C_ALT -> KeyModifier.ALT Key.C_SHIFT -> KeyModifier.SHIFT Key.C_META -> KeyModifier.META Key.C_ALTGR -> KeyModifier.ALTGR Key.C_WIN -> KeyModifier.WIN else -> 0 }) } return mods } } /** * Types text at a given location * * @param location Location to type to, can be null to just type directly into the screen. * @param text The text to type. * @param modifiers Key modifiers to press during typing. */ @Synchronized fun type(location: Location?, text: String, modifiers: Int) = synchronized(this) { if (location != null) robot.screen.click(location) val pause = if (Settings.TypeDelay > 1) 1 else (Settings.TypeDelay * 1000).toInt() robot.pressModifiers(modifiers) text.toCharArray().map(Char::toInt).forEach { robot.typeKey(it) robot.delay(if (pause < 80) 80 else pause) } Settings.TypeDelay = 0.0 } /** * Releases all keys */ @Synchronized fun keyUp() = synchronized(this) { robot.keyUp() } /** * Releases a specific key. * * @param keycode The key to release. */ @Synchronized fun keyUp(keycode: Int) = synchronized(this) { robot.keyUp(keycode) } /** * Releases the keys specified by the string. * * @param keys Keys to be released. */ @Synchronized fun keyUp(keys: String) = synchronized(this) { robot.keyUp(keys) } /** * Presses a specific key. * * @param keycode The key to press. */ @Synchronized fun keyDown(keycode: Int) = synchronized(this) { robot.keyDown(keycode) } /** * Presses the keys specified by the string. * * @param keys Keys to be pressed. */ @Synchronized fun keyDown(keys: String) = synchronized(this) { robot.keyDown(keys) } /** * Executes an action atomically while keeping the synchronized lock to this object. * Useful if you want to do multiple actions in one go without the possibility of a thread * stealing ownership. * * @param action Action to execute while keeping the lock this object. * @return Result of [action] */ @Synchronized inline fun <T> atomicAction(action: () -> T): T = synchronized(this) { action() } }
mit
da2a61f075ef929919e61014dfa89b74
35.022727
104
0.64858
4.415042
false
false
false
false
mabels/ipaddress
kotlin/lib/src/main/kotlin/com/adviser/ipaddress/Result.kt
1
747
package com.adviser.ipaddress.kotlin import java.io.IOException /** * Created by menabe on 19.06.17. */ class Result<T>(val value: T?, val msg: String?) { fun isOk(): Boolean { return msg === null } fun isErr(): Boolean { return msg !== null } fun text(): String { if (isOk()) { throw IOException("try to access text") } return msg!! } fun unwrap(): T { return value!! } fun unwrapErr(): String { return msg!! } companion object { fun <T> Ok(t: T): Result<T> { return Result<T>(t, null) } fun <T> Err(str: String): Result<T> { return Result<T>(null, str) } } }
mit
c94b3072b20fb1bc3dd8335fbb6ef732
15.6
51
0.487282
3.772727
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/loritta/GetCommandsRoute.kt
1
2234
package net.perfectdreams.loritta.morenitta.website.routes.api.v1.loritta import io.ktor.server.application.* import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordCommand import net.perfectdreams.loritta.serializable.CommandInfo import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson import net.perfectdreams.sequins.ktor.BaseRoute class GetCommandsRoute(val loritta: LorittaBot) : BaseRoute("/api/v1/loritta/commands/{localeId}") { override suspend fun onRequest(call: ApplicationCall) { val localeId = call.parameters["localeId"] ?: return val locale = loritta.localeManager.getLocaleById(localeId) val commands = loritta.legacyCommandManager.commandMap.map { CommandInfo( it::class.java.simpleName, it.label, it.aliases, it.category, it.getDescriptionKey(), it.getUsage(), it.getExamplesKey(), it.cooldown, it.canUseInPrivateChannel(), it.getDiscordPermissions().map { it.name }, it.lorittaPermissions.map { it.name }, it.getBotPermissions().map { it.name }, listOf() // Old API doesn't has SimilarCommands ) } + loritta.commandMap.commands.filter { !it.hideInHelp }.map { var botRequiredPermissions = listOf<String>() var userRequiredPermissions = listOf<String>() var userRequiredLorittaPermissions = listOf<String>() if (it is DiscordCommand) { botRequiredPermissions = it.botRequiredPermissions.map { it.name } userRequiredPermissions = it.userRequiredPermissions.map { it.name } userRequiredLorittaPermissions = it.userRequiredLorittaPermissions.map { it.name } } CommandInfo( it.commandName, it.labels.first(), it.labels.drop(1).toList(), it.category, it.descriptionKey, it.usage, it.examplesKey, it.cooldown, it.canUseInPrivateChannel, userRequiredPermissions, userRequiredLorittaPermissions, botRequiredPermissions, it.similarCommands ) } call.respondJson(Json.encodeToString(ListSerializer(CommandInfo.serializer()), commands)) } }
agpl-3.0
575ca3c64142a6cb8d9e343ba652ac78
33.921875
100
0.746643
4.025225
false
false
false
false
kohesive/keplin
keplin-jsr223-kotlin-engine/src/test/kotlin/uy/kohesive/keplin/kotlin/script/jsr223/TestCompilableReplEngine.kt
1
3252
package uy.kohesive.keplin.kotlin.script.jsr223 import org.junit.Ignore import org.junit.Test import java.io.StringWriter import javax.script.Compilable import javax.script.ScriptEngine import javax.script.ScriptEngineManager import kotlin.test.assertEquals import kotlin.test.assertTrue class TestCompilableReplEngine { fun forEachEngine(f: (ScriptEngine) -> Unit) { val factory = ScriptEngineManager() listOf(CompilableJsr223ReplEngineFactory.jsr223EngineName).forEach { engineName -> val engine = factory.getEngineByName(engineName) f(engine) } } @Test fun testJsr223CompilableEngineEvalOnlyParts() { forEachEngine { engine -> val capture = StringWriter() engine.context.writer = capture engine.put("z", 33) engine.eval("""println("Hello keplin-kotin-compilable engine")""") engine.eval("""val x = 10 + context.getAttribute("z") as Int""") engine.eval("""println(x)""") val result = engine.eval("""x + 20""") assertEquals(63, result) val checkEngine = engine.eval("""kotlinScript != null""") as Boolean assertTrue(checkEngine) val result2 = engine.eval("""x + context.getAttribute("boundValue") as Int""", engine.createBindings().apply { put("boundValue", 100) }) assertEquals(143, result2) assertEquals("Hello keplin-kotin-compilable engine\n43\n", capture.toString()) } } @Test @Ignore("Check this again, what is correct intended behavior") fun testJsr223CompilableEngineExecuteManyTimes() { forEachEngine { engine -> if (engine is Compilable) { val compiler = engine as Compilable val capture = StringWriter() engine.context.writer = capture engine.eval("""println("Hello keplin-kotin-compilable engine")""") val compiled1 = compiler.compile("""listOf(1,2,3).joinToString(",")""") val compiled2 = compiler.compile("""val x = context.getAttribute("boundValue") as Int + context.getAttribute("z") as Int""") val compiled3 = compiler.compile("""x""") assertEquals("1,2,3", compiled1.eval()) assertEquals("1,2,3", compiled1.eval()) assertEquals("1,2,3", compiled1.eval()) assertEquals("1,2,3", compiled1.eval()) compiled2.eval(engine.createBindings().apply { put("boundValue", 100) put("z", 33) }) assertEquals(133, compiled3.eval()) assertEquals(133, compiled3.eval()) assertEquals(133, compiled3.eval()) assertEquals("1,2,3", compiled1.eval()) engine.put("whatever", 999) assertEquals(999, engine.eval("""context.getAttribute("whatever")""")) compiled2.eval(engine.createBindings().apply { put("boundValue", 200) put("z", 33) }) assertEquals(233, compiled3.eval()) } } } }
mit
1850092f48f9538d8ea614d0be601bf9
34.358696
140
0.571648
4.719884
false
true
false
false
google/xplat
j2kt/jre/java/native/java/util/concurrent/atomic/AtomicReferenceArray.kt
1
1621
// CHECKSTYLE_OFF: Copyrighted to Guava Authors. /* * Copyright (C) 2015 The Guava 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. */ // CHECKSTYLE_ON package java.util.concurrent.atomic /** * GWT emulated version of {@link AtomicReferenceArray}. * * @param <V> the element type. */ class AtomicReferenceArray<V> internal constructor(private val values: List<AtomicReference<V>>) { constructor(array: Array<V>) : this(array.map { AtomicReference<V>(it) }) fun compareAndSet(i: Int, expect: V, update: V) = values[i].compareAndSet(expect, update) fun get(i: Int) = values[i].get() fun getAndSet(i: Int, x: V) = values[i].getAndSet(x) fun lazySet(i: Int, x: V) = values[i].lazySet(x) fun length(): Int = values.size fun set(i: Int, x: V) = values[i].set(x) fun weakCompareAndSet(i: Int, expect: V, update: V): Boolean = compareAndSet(i, expect, update) override fun toString(): String = values.toString() companion object { operator fun <V> invoke(length: Int): AtomicReferenceArray<V?> = AtomicReferenceArray<V?>((1..length).map { AtomicReference<V>() }) } }
apache-2.0
cdfcb5d4528b4e8366b79888c27e38dc
32.081633
98
0.70327
3.675737
false
false
false
false
emilybache/Racing-Car-Katas
kotlin/TelemetrySystem/src/main/kotlin/tddmicroexercises/telemetrysystem/TelemetryClient.kt
1
2621
package tddmicroexercises.telemetrysystem import java.util.* class TelemetryClient { var onlineStatus: Boolean = false private set private var diagnosticMessageResult: String = "" private val connectionEventsSimulator = Random(42) fun connect(telemetryServerConnectionString: String?) { if (telemetryServerConnectionString == null || "" == telemetryServerConnectionString) { throw IllegalArgumentException() } // simulate the operation on a real modem val success = connectionEventsSimulator.nextInt(10) <= 8 onlineStatus = success } fun disconnect() { onlineStatus = false } fun send(message: String?) { if (message == null || "" == message) { throw IllegalArgumentException() } if (message === DIAGNOSTIC_MESSAGE) { // simulate a status report diagnosticMessageResult = ("LAST TX rate................ 100 MBPS\r\n" + "HIGHEST TX rate............. 100 MBPS\r\n" + "LAST RX rate................ 100 MBPS\r\n" + "HIGHEST RX rate............. 100 MBPS\r\n" + "BIT RATE.................... 100000000\r\n" + "WORD LEN.................... 16\r\n" + "WORD/FRAME.................. 511\r\n" + "BITS/FRAME.................. 8192\r\n" + "MODULATION TYPE............. PCM/FM\r\n" + "TX Digital Los.............. 0.75\r\n" + "RX Digital Los.............. 0.10\r\n" + "BEP Test.................... -5\r\n" + "Local Rtrn Count............ 00\r\n" + "Remote Rtrn Count........... 00") return } // here should go the real Send operation (not needed for this exercise) } fun receive(): String { var message: String if (diagnosticMessageResult == null || "" == diagnosticMessageResult) { // simulate a received message (just for illustration - not needed for this exercise) message = "" val messageLength = connectionEventsSimulator.nextInt(50) + 60 for (i in messageLength downTo 0) { message += connectionEventsSimulator.nextInt(40).toChar().toInt() + 86 } } else { message = diagnosticMessageResult diagnosticMessageResult = "" } return message } companion object { val DIAGNOSTIC_MESSAGE = "AT#UD" } }
mit
f3f4ef91382f5143d123a4308e1b2cc1
32.602564
97
0.496757
4.917448
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/weekdone/WeekdoneAuthInterceptor.kt
1
2037
package com.baulsupp.okurl.services.weekdone import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.kotlin.query import com.baulsupp.okurl.kotlin.request import okhttp3.FormBody import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response data class RefreshResponse(val access_token: String) class WeekdoneAuthInterceptor : Oauth2AuthInterceptor() { override suspend fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response { var request = chain.request() val signedUrl = request.url.newBuilder().addQueryParameter("token", credentials.accessToken).build() request = request.newBuilder().url(signedUrl).build() return chain.proceed(request) } override val serviceDefinition = Oauth2ServiceDefinition( "api.weekdone.com", "Weekdone", "weekdone", "https://weekdone.com/developer/", "https://weekdone.com/settings?tab=applications" ) override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { return WeekdoneAuthFlow.login(client, outputHandler) } override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token { val response = client.query<RefreshResponse>(request("https://weekdone.com/oauth_token") { post( FormBody.Builder().add("refresh_token", credentials.refreshToken!!).add( "grant_type", "refresh_token" ).add("redirect_uri", "http://localhost:3000/callback").add( "client_id", credentials.clientId!! ).add("client_secret", credentials.clientSecret!!).build() ) }) return Oauth2Token( response.access_token, credentials.refreshToken, credentials.clientId, credentials.clientSecret ) } }
apache-2.0
3134777349dc28042344ba76de0e0457
32.393443
104
0.734413
4.390086
false
false
false
false
nisrulz/android-examples
ViewPager/app/src/main/java/github/nisrulz/example/viewpager/Page.kt
1
1337
package github.nisrulz.example.viewpager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import github.nisrulz.example.viewpager.databinding.FragmentPageBinding class Page : Fragment() { // Store instance variables private var title: String? = null private var page = 0 private lateinit var binding: FragmentPageBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.apply { page = getInt("page", 0) title = getString("title") } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentPageBinding.inflate(inflater, container, false) with(binding) { textView.text = "$page - $title" } return binding.root } companion object { fun newInstance(page_number: Int, title: String?): Page { val fragment = Page() val args = Bundle().apply { putInt("page", page_number) putString("title", title) } fragment.arguments = args return fragment } } }
apache-2.0
6a6be1e285ef9a190268ff96d9ed7a5c
27.468085
73
0.626028
4.988806
false
false
false
false
wireapp/wire-android
app/src/main/kotlin/com/waz/zclient/core/backend/mapper/BackendMapper.kt
1
1742
package com.waz.zclient.core.backend.mapper import com.waz.zclient.core.backend.BackendItem import com.waz.zclient.core.backend.datasources.local.CustomBackendPrefEndpoints import com.waz.zclient.core.backend.datasources.local.CustomBackendPreferences import com.waz.zclient.core.backend.datasources.remote.CustomBackendResponse class BackendMapper { fun toBackendItem(backendPreferences: CustomBackendPreferences): BackendItem = with(backendPreferences.prefEndpoints) { BackendItem( environment = backendPreferences.title, baseUrl = backendUrl, websocketUrl = websocketUrl, blacklistHost = blacklistUrl, teamsUrl = teamsUrl, accountsUrl = accountsUrl, websiteUrl = websiteUrl ) } fun toBackendItem(response: CustomBackendResponse): BackendItem = with(response.endpoints) { BackendItem( environment = response.title, baseUrl = backendUrl, websocketUrl = backendWsUrl, blacklistHost = blacklistUrl, teamsUrl = teamsUrl, accountsUrl = accountsUrl, websiteUrl = websiteUrl ) } fun toPreference(backendItem: BackendItem): CustomBackendPreferences = with(backendItem) { CustomBackendPreferences( title = environment, prefEndpoints = CustomBackendPrefEndpoints( backendUrl = baseUrl, websocketUrl = websocketUrl, blacklistUrl = blacklistHost, teamsUrl = teamsUrl, accountsUrl = accountsUrl, websiteUrl = websiteUrl ) ) } }
gpl-3.0
1f4a96c399dec832c431ddfb9573a1b7
35.291667
96
0.628014
5.768212
false
false
false
false
epabst/kotlin-showcase
src/jsMain/kotlin/pouchdb/query/index.PouchDB.Query.module_pouchdb-mapreduce.kt
1
2372
@file:JsQualifier("PouchDB.Query") @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") package pouchdb.query import pouchdb.Content import pouchdb.ExistingDocument import kotlin.js.* external interface Options<Content, Reduction> { var reduce: dynamic /* Reducer<Content, Reduction> | '_sum' | '_count' | '_stats' | Boolean */ get() = definedExternally set(value) = definedExternally var include_docs: Boolean? get() = definedExternally set(value) = definedExternally var conflicts: Boolean? get() = definedExternally set(value) = definedExternally var attachments: Boolean? get() = definedExternally set(value) = definedExternally var binary: Boolean? get() = definedExternally set(value) = definedExternally var startkey: Any? get() = definedExternally set(value) = definedExternally var endkey: Any? get() = definedExternally set(value) = definedExternally var inclusive_end: Boolean? get() = definedExternally set(value) = definedExternally var limit: Number? get() = definedExternally set(value) = definedExternally var skip: Number? get() = definedExternally set(value) = definedExternally var descending: Boolean? get() = definedExternally set(value) = definedExternally var key: Any? get() = definedExternally set(value) = definedExternally var keys: Array<Any>? get() = definedExternally set(value) = definedExternally var group: Boolean? get() = definedExternally set(value) = definedExternally var group_level: Number? get() = definedExternally set(value) = definedExternally var stale: dynamic /* 'ok' | 'update_after' */ get() = definedExternally set(value) = definedExternally } external interface `T$0` { var id: Any var key: Any var value: Any var doc: ExistingDocument<Content /* Content & PouchDB.Core.AllDocsMeta */>? get() = definedExternally set(value) = definedExternally } external interface Response<Content> { var total_rows: Number var offset: Number var rows: Array<`T$0`> }
apache-2.0
d8b0d6e12d636ae42e64c6a7c4dc8e8f
31.506849
154
0.647976
4.605825
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/objects/compound/Compound.kt
1
4330
package net.dinkla.raytracer.objects.compound import net.dinkla.raytracer.hits.Hit import net.dinkla.raytracer.hits.Shade import net.dinkla.raytracer.hits.ShadowHit import net.dinkla.raytracer.materials.IMaterial import net.dinkla.raytracer.math.BBox import net.dinkla.raytracer.math.PointUtilities import net.dinkla.raytracer.math.Ray import net.dinkla.raytracer.math.WrappedFloat import net.dinkla.raytracer.objects.GeometricObject import net.dinkla.raytracer.utilities.Counter import net.dinkla.raytracer.worlds.World import java.util.* open class Compound : GeometricObject() { open var objects: ArrayList<GeometricObject> = ArrayList() var isUnit: Boolean = false init { objects = ArrayList() isUnit = false } override var material: IMaterial? get() = super.material set(material) { super.material = material for (geoObj in objects) { geoObj.material = material } } override var isShadows: Boolean get() = super.isShadows set(shadows) { super.isShadows = shadows for (geoObj in objects) { geoObj.isShadows = shadows } } override fun hit(ray: Ray, sr: Hit): Boolean { if (!boundingBox.hit(ray)) { Counter.count("Compound.hit.bbox") return false } Counter.count("Compound.hit") var hit = false for (geoObj in objects) { Counter.count("Compound.hit.object") val sr2 = Hit(sr.t) val b = geoObj.hit(ray, sr2) if (b && sr2.t < sr.t) { hit = true sr.t = sr2.t sr.normal = sr2.normal if (geoObj !is Compound) { sr.`object` = geoObj } else { sr.`object` = sr2.`object` } } } return hit } fun hitObjects(world: World, ray: Ray): Shade { Counter.count("Compound.hitObjects") val tmin = WrappedFloat.createMax() val sr = Shade() val b = hit(ray, sr) return sr } override fun shadowHit(ray: Ray, tmin: ShadowHit): Boolean { Counter.count("Compound.shadowHit") //WrappedFloat t = WrappedFloat.createMax(); for (geoObj in objects) { Counter.count("Compound.shadowHit.object") if (geoObj.shadowHit(ray, tmin)) { // tmin.setT(t.getValue()); return true } } return false } fun inShadow(ray: Ray, sr: Shade, d: Double): Boolean { Counter.count("Compound.inShadow") //TODO: Wieso hier createMax ? ShadowHit t = ShadowHit.createMax(); val t = ShadowHit(d) for (geoObj in objects) { val b = geoObj.shadowHit(ray, t) if (b && t.t < d) { return true } } return false } fun add(`object`: GeometricObject) { isInitialized = false `object`.initialize() objects.add(`object`) calcBoundingBox() } fun add(objects: List<GeometricObject>) { isInitialized = false this.objects.addAll(objects) for (`object` in this.objects) { `object`.initialize() } calcBoundingBox() } override fun initialize() { super.initialize() for (`object` in objects) { `object`.initialize() } // TODO Warum wird das vorberechnet? Warum nicht lazy? calcBoundingBox() } fun size(): Int { if (isUnit) { return 1 } else { var size = 0 for (geoObj in objects) { if (geoObj is Compound) { size += geoObj.size() } else { size += 1 } } return size } } fun calcBoundingBox() { boundingBox = BBox() if (objects.size > 0) { val p0 = PointUtilities.minCoordinates(objects) val p1 = PointUtilities.maxCoordinates(objects) boundingBox = BBox(p0, p1) } else { boundingBox = BBox() } } }
apache-2.0
95762c80f07ec69427e5af7e73e1d762
26.579618
75
0.528868
4.387031
false
false
false
false
notion/Plumb
compiler/src/main/kotlin/rxjoin/internal/codegen/validator/InValidator.kt
2
3040
package rxjoin.internal.codegen.validator import rx.subjects.Subject import rxjoin.annotation.In import rxjoin.internal.codegen.Model import rxjoin.internal.codegen.Model.JoinerModel import rxjoin.internal.codegen.error import javax.annotation.processing.Messager import javax.lang.model.element.Element import javax.lang.model.element.ElementKind.FIELD import javax.lang.model.type.TypeKind.DECLARED import javax.lang.model.util.Elements import javax.lang.model.util.Types object InValidator : Validator { private lateinit var types: Types private lateinit var elements: Elements private lateinit var messager: Messager // Error messages fun elementNotFieldError(element: Element) = "@In-annotated element ${element.simpleName} must be a FIELD. It is a ${element.kind}" fun fieldNotSubjectError(element: Element) = "@In-annotated element ${element.simpleName} must extend Subject<*, *>." fun fieldNotParameterizedSubject(element: Element) = "@In-annotated element ${element.simpleName} must be declared Subject<T, R>." fun noCorrespondingRegistryError(element: Element) = "@In-annotated element ${element.simpleName} has no corresponding @Out-annotated element." override fun validate(element: Element, model: Model): Boolean { types = model.types elements = model.elements messager = model.messager val isValidField = when (element.kind) { FIELD -> { validateField(element) } else -> { messager.error(elementNotFieldError(element)) false } } return isValidField && validateMatchingJoiner(element, model.joinerModels) } private fun declaredSubjectType() = types.getDeclaredType( elements.getTypeElement(Subject::class.java.canonicalName), types.getWildcardType(null, null), types.getWildcardType(null, null)) private fun validateField(element: Element): Boolean { return if (element.asType().kind == DECLARED) { val type = element.asType() if (types.isAssignable(type, declaredSubjectType())) { true } else { messager.error(fieldNotSubjectError(element)) false } } else { messager.error(fieldNotParameterizedSubject(element)) false } } private fun validateMatchingJoiner(element: Element, models: MutableList<JoinerModel>): Boolean { val annotationValue = element.getAnnotation(In::class.java).value val matchingRegistry = models.firstOrNull{ it.registry.firstOrNull { it.id == annotationValue } != null } return if (matchingRegistry != null) { true } else { messager.error(noCorrespondingRegistryError(element)) false } } }
apache-2.0
fb85dc3b91463baf125ed8d678ccc8f2
33.157303
102
0.636842
4.943089
false
false
false
false
Kotlin/dokka
plugins/base/src/test/kotlin/basic/DokkaBasicTests.kt
1
1290
package basic import org.jetbrains.dokka.pages.ClasslikePageNode import org.jetbrains.dokka.pages.ModulePageNode import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest import kotlin.test.assertEquals class DokkaBasicTests : BaseAbstractTest() { @Test fun basic1() { val configuration = dokkaConfiguration { sourceSets { sourceSet { sourceRoots = listOf("src/main/kotlin/basic/Test.kt") } } } testInline( """ |/src/main/kotlin/basic/Test.kt |package basic | |class Test { | val tI = 1 | fun tF() = 2 |} """.trimMargin(), configuration ) { pagesGenerationStage = { val root = it as ModulePageNode assertEquals(3, root.getClasslikeToMemberMap().filterKeys { it.name == "Test" }.entries.firstOrNull()?.value?.size) } } } private fun ModulePageNode.getClasslikeToMemberMap() = this.parentMap.filterValues { it is ClasslikePageNode }.entries.groupBy({ it.value }) { it.key } }
apache-2.0
d4ba48a024a7f259ac4b32935f4c8163
29
131
0.575969
4.640288
false
true
false
false
ronaldsmartin/20twenty20
app/src/main/java/com/itsronald/twenty2020/base/Presenter.kt
1
372
package com.itsronald.twenty2020.base import android.os.Bundle /** * Base interface for Presenters. */ interface Presenter<View> { var view: View fun onCreate(bundle: Bundle?) = Unit fun onStart() = Unit fun onStop() = Unit fun onSaveInstanceState(outState: Bundle?) = Unit fun onRestoreInstanceState(savedInstanceState: Bundle?) = Unit }
gpl-3.0
1771b68c9c2516edb22244c098a0db8e
16.761905
66
0.698925
4.227273
false
false
false
false
canou/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/activities/LicenseActivity.kt
1
3410
package com.simplemobiletools.commons.activities import android.os.Bundle import android.text.SpannableString import android.text.style.UnderlineSpan import android.view.LayoutInflater import com.simplemobiletools.commons.R import com.simplemobiletools.commons.extensions.baseConfig import com.simplemobiletools.commons.extensions.getLinkTextColor import com.simplemobiletools.commons.extensions.launchViewIntent import com.simplemobiletools.commons.extensions.updateTextColors import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.License import kotlinx.android.synthetic.main.activity_license.* import kotlinx.android.synthetic.main.license_item.view.* class LicenseActivity : BaseSimpleActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_license) val linkTextColor = getLinkTextColor() updateTextColors(licenses_holder) val inflater = LayoutInflater.from(this) val licenses = initLicenses() val licenseMask = intent.getIntExtra(APP_LICENSES, 0) licenses.filter { licenseMask and it.id != 0 }.forEach { val license = it val view = inflater.inflate(R.layout.license_item, null) view.apply { license_title.text = getUnderlinedTitle(getString(license.titleId)) license_title.setOnClickListener { launchViewIntent(license.urlId) } license_title.setTextColor(linkTextColor) license_text.text = getString(license.textId) license_text.setTextColor(baseConfig.textColor) licenses_holder.addView(this) } } } fun getUnderlinedTitle(title: String): SpannableString { val underlined = SpannableString(title) underlined.setSpan(UnderlineSpan(), 0, title.length, 0) return underlined } fun initLicenses() = arrayOf( License(LICENSE_KOTLIN, R.string.kotlin_title, R.string.kotlin_text, R.string.kotlin_url), License(LICENSE_SUBSAMPLING, R.string.subsampling_title, R.string.subsampling_text, R.string.subsampling_url), License(LICENSE_GLIDE, R.string.glide_title, R.string.glide_text, R.string.glide_url), License(LICENSE_CROPPER, R.string.cropper_title, R.string.cropper_text, R.string.cropper_url), License(LICENSE_MULTISELECT, R.string.multiselect_title, R.string.multiselect_text, R.string.multiselect_url), License(LICENSE_RTL, R.string.rtl_viewpager_title, R.string.rtl_viewpager_text, R.string.rtl_viewpager_url), License(LICENSE_JODA, R.string.joda_title, R.string.joda_text, R.string.joda_url), License(LICENSE_STETHO, R.string.stetho_title, R.string.stetho_text, R.string.stetho_url), License(LICENSE_OTTO, R.string.otto_title, R.string.otto_text, R.string.otto_url), License(LICENSE_PHOTOVIEW, R.string.photoview_title, R.string.photoview_text, R.string.photoview_url), License(LICENSE_PICASSO, R.string.picasso_title, R.string.picasso_text, R.string.picasso_url), License(LICENSE_PATTERN, R.string.pattern_title, R.string.pattern_text, R.string.pattern_url) ) }
apache-2.0
6e8c04967417df5c3dbf1af75176cd61
53.126984
130
0.689443
4.236025
false
false
false
false
aldoram5/SimpleHTMLTesterAndroid
app/src/main/java/com/crimsonrgames/titanium/htmltester/AddTagDialogFragment.kt
1
3115
/*** * * AddTagDialogFragment.java * * Copyright 2016 Aldo Pedro Rangel Montiel * * 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.crimsonrgames.titanium.htmltester import android.content.Context import android.os.Bundle import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView import androidx.fragment.app.DialogFragment /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [OnAddTagDialogFragmentInteractionListener] interface * to handle interaction events. */ class AddTagDialogFragment : DialogFragment(), TextView.OnEditorActionListener { private var mListener: OnAddTagDialogFragmentInteractionListener? = null private var mEditText: EditText? = null interface OnAddTagDialogFragmentInteractionListener { fun onFinishTagEditDialog(tag: String) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_add_tag_dialog, container) mEditText = view.findViewById<View>(R.id.editTagName) as EditText dialog?.setTitle(TITLE) mEditText!!.requestFocus() dialog?.window!!.setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) mEditText!!.setOnEditorActionListener(this) return view } override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent): Boolean { if (EditorInfo.IME_ACTION_DONE == actionId) { // Return input text to activity val activity = activity as OnAddTagDialogFragmentInteractionListener? activity!!.onFinishTagEditDialog(mEditText!!.text.toString()) this.dismiss() return true } return false } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnAddTagDialogFragmentInteractionListener) { mListener = context } else { throw RuntimeException(context.toString() + " must implement OnAddTagDialogFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } companion object { val TITLE = "Add Tag" } }// Required empty public constructor
apache-2.0
37ef6af24a58cf675ee5264bb4e666cc
32.138298
116
0.707223
5.07329
false
false
false
false
camdenorrb/KPortals
src/main/kotlin/me/camdenorrb/kportals/cache/SelectionCache.kt
1
2587
package me.camdenorrb.kportals.cache import me.camdenorrb.kcommons.base.ModuleBase import me.camdenorrb.kportals.KPortals import me.camdenorrb.kportals.portal.Portal import org.bukkit.ChatColor import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.HandlerList import org.bukkit.event.Listener import org.bukkit.event.block.Action import org.bukkit.event.block.BlockBreakEvent import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.event.player.PlayerQuitEvent import java.util.* class SelectionCache(val plugin: KPortals) : ModuleBase, Listener { override val name = "Selection Cache" val selections = mutableMapOf<UUID, Portal.Selection>() var isEnabled = false private set override fun enable() { assert(!isEnabled) { "$name tried to enable while already being enabled!" } plugin.server.pluginManager.registerEvents(this, plugin) } override fun disable() { assert(isEnabled) { "$name tried to disable while already being disabled!" } HandlerList.unregisterAll(this) selections.clear() } @EventHandler fun onHitBlock(event: PlayerInteractEvent) { // We don't want offhand events nor ones not for selection if (event.item != plugin.selectionItem) { return } val player = event.player val hitBlock = event.clickedBlock ?: return when (event.action) { Action.LEFT_CLICK_BLOCK -> { selections.getOrPut(player.uniqueId, { Portal.Selection() }).sel1 = hitBlock.location.toVector() player.sendMessage("${ChatColor.GREEN}You have selected position one.") } Action.RIGHT_CLICK_BLOCK -> { selections.getOrPut(player.uniqueId, { Portal.Selection() }).sel2 = hitBlock.location.toVector() player.sendMessage("${ChatColor.GREEN}You have selected position two.") } else -> return } event.isCancelled = true } @EventHandler(ignoreCancelled = true) fun onBreakBlock(event: BlockBreakEvent) { event.isCancelled = event.player.inventory.itemInHand == plugin.selectionItem } @EventHandler fun onQuit(event: PlayerQuitEvent) { selections.remove(event.player.uniqueId) } operator fun get(key: Player): Portal.Selection? { return get(key.uniqueId) } operator fun get(key: UUID): Portal.Selection? { return selections[key] } }
mit
09d29f0b11872e9444878b496f0d8ea0
25.141414
112
0.659451
4.554577
false
false
false
false
EPadronU/balin
src/test/kotlin/com/github/epadronu/balin/config/ConfigurationTests.kt
1
9712
/****************************************************************************** * Copyright 2016 Edinson E. Padrón Urdaneta * * 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.epadronu.balin.config /* ***************************************************************************/ /* ***************************************************************************/ import com.github.epadronu.balin.core.Browser import org.openqa.selenium.WebDriver import org.openqa.selenium.htmlunit.HtmlUnitDriver import org.testng.Assert import org.testng.annotations.AfterMethod import org.testng.annotations.DataProvider import org.testng.annotations.Test import com.gargoylesoftware.htmlunit.BrowserVersion.FIREFOX_60 as BROWSER_VERSION /* ***************************************************************************/ /* ***************************************************************************/ class ConfigurationTests { @DataProvider(name = "JavaScript-incapable WebDriver factory", parallel = true) fun `Create a JavaScript-incapable WebDriver factory`() = arrayOf( arrayOf({ HtmlUnitDriver(BROWSER_VERSION) }) ) @AfterMethod fun cleanup() { Browser.configure { autoQuit = ConfigurationSetup.Default.autoQuit driverFactory = ConfigurationSetup.Default.driverFactory setups = mapOf() } System.clearProperty(Browser.BALIN_SETUP_NAME_PROPERTY) } @Test fun `Use the default configuration`() { Assert.assertEquals(Browser.desiredConfiguration, ConfigurationSetup.Default) } @Test fun `Call the configure method but don't modify a thing`() { Browser.configure { } Assert.assertEquals(Browser.desiredConfiguration, ConfigurationSetup.Default) } @Test(description = "Call the configure method and make changes", dataProvider = "JavaScript-incapable WebDriver factory") fun call_the_configure_method_and_make_changes(testFactory: () -> WebDriver) { val desiredConfigurationSetup = Configuration(false, testFactory) Browser.configure { autoQuit = desiredConfigurationSetup.autoQuit driverFactory = desiredConfigurationSetup.driverFactory } Assert.assertEquals(Browser.desiredConfiguration, desiredConfigurationSetup) } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the configure method with a default setup and use it implicitly`(testFactory: () -> WebDriver) { val defaultConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) Browser.configure { setups = mapOf( "default" to setup { autoQuit = defaultConfigurationSetup.autoQuit driverFactory = defaultConfigurationSetup.driverFactory } ) } Assert.assertEquals(Browser.desiredConfiguration, defaultConfigurationSetup) } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the configure method with a default setup and use it explicitly`(testFactory: () -> WebDriver) { val defaultConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) Browser.configure { setups = mapOf( "default" to setup { autoQuit = defaultConfigurationSetup.autoQuit driverFactory = defaultConfigurationSetup.driverFactory } ) } System.setProperty(Browser.BALIN_SETUP_NAME_PROPERTY, "default") Assert.assertEquals(Browser.desiredConfiguration, defaultConfigurationSetup) } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the configure method with a development setup and don't use it`(testFactory: () -> WebDriver) { val developmentConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) Browser.configure { driverFactory = testFactory setups = mapOf( "development" to setup { autoQuit = developmentConfigurationSetup.autoQuit driverFactory = developmentConfigurationSetup.driverFactory } ) } Assert.assertNotEquals(Browser.desiredConfiguration, developmentConfigurationSetup) } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the configure method with a development setup and use it`(testFactory: () -> WebDriver) { val developmentConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) Browser.configure { driverFactory = testFactory setups = mapOf( "development" to setup { autoQuit = developmentConfigurationSetup.autoQuit driverFactory = developmentConfigurationSetup.driverFactory } ) } System.setProperty(Browser.BALIN_SETUP_NAME_PROPERTY, "development") Assert.assertEquals(Browser.desiredConfiguration, developmentConfigurationSetup) } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the drive method with a desired configuration`(testFactory: () -> WebDriver) { val desiredConfigurationSetup = Configuration(false, testFactory) Browser.drive(desiredConfigurationSetup) { Assert.assertEquals(configurationSetup, desiredConfigurationSetup) } } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the drive method with a default setup configuration and use it implicitly`(testFactory: () -> WebDriver) { val defaultConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) val desiredConfigurationSetup = ConfigurationBuilder().apply { setups = mapOf( "default" to setup { autoQuit = defaultConfigurationSetup.autoQuit driverFactory = defaultConfigurationSetup.driverFactory } ) }.build() Browser.drive(desiredConfigurationSetup) { Assert.assertEquals(configurationSetup, defaultConfigurationSetup) } } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the drive method with a default setup configuration and use it explicitly`(testFactory: () -> WebDriver) { val defaultConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) val desiredConfigurationSetup = ConfigurationBuilder().apply { setups = mapOf( "default" to setup { autoQuit = defaultConfigurationSetup.autoQuit driverFactory = defaultConfigurationSetup.driverFactory } ) }.build() System.setProperty(Browser.BALIN_SETUP_NAME_PROPERTY, "default") Browser.drive(desiredConfigurationSetup) { Assert.assertEquals(configurationSetup, defaultConfigurationSetup) } } @Test(dataProvider = "JavaScript-incapable WebDriver factory") fun `Call the drive method with a development setup configuration and don't use it`(testFactory: () -> WebDriver) { val developmentConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) val desiredConfigurationSetup = ConfigurationBuilder().apply { driverFactory = testFactory setups = mapOf( "development" to setup { autoQuit = developmentConfigurationSetup.autoQuit driverFactory = developmentConfigurationSetup.driverFactory } ) }.build() Browser.drive(desiredConfigurationSetup) { Assert.assertEquals(configurationSetup, desiredConfigurationSetup) } } @Test(description = "Call the drive method with a development setup configuration and use it", dataProvider = "JavaScript-incapable WebDriver factory") fun call_the_drive_method_with_a_development_setup_configuration_and_use_it(testFactory: () -> WebDriver) { val developmentConfigurationSetup: ConfigurationSetup = Configuration(false, testFactory) val desiredConfigurationSetup = ConfigurationBuilder().apply { driverFactory = testFactory setups = mapOf( "development" to setup { autoQuit = developmentConfigurationSetup.autoQuit driverFactory = developmentConfigurationSetup.driverFactory } ) }.build() System.setProperty(Browser.BALIN_SETUP_NAME_PROPERTY, "development") Browser.drive(desiredConfigurationSetup) { Assert.assertEquals(configurationSetup, developmentConfigurationSetup) } } } /* ***************************************************************************/
apache-2.0
604cbca0b534dfb92a1ed954354805d1
39.294606
120
0.628154
6.330508
false
true
false
false
jjoller/foxinabox
src/jjoller/foxinabox/MultiArmedBandit.kt
1
1753
package jjoller.foxinabox import java.util.* /** * Find the best option in an unknown environment */ public class MultiArmedBandit<T>(val options: Set<T>, val e: Int = 2) { private val totalReward: MutableMap<T, Double> private val visits: MutableMap<T, Int> private var totalVisits: Int init { this.totalReward = HashMap() this.visits = HashMap() this.totalVisits = 0 } public fun update(option: T, outcome: Double) { visits.increment(option, 1) totalReward.increment(option, outcome) totalVisits++ } /** * Get an option using the bandit formula, applying an exploration exploitation trade-off. */ public fun option(greedy: Boolean = false): T { var max = Double.NEGATIVE_INFINITY var bestOption: T? = null for (o in options) { if (visits[o] == null) return o; val ni = visits[o]!!.toDouble() var v = totalReward[o]!! / ni if (!greedy) // apply exploration exploitation trade-off v = v * Math.sqrt(e * Math.log(ni) / totalVisits.toDouble()) if (v > max) { max = v bestOption = o } } return bestOption!! } /** * Get the option with the highest average reward */ public fun greedyOption() { } fun MutableMap<T, Int>.increment(key: T, i: Int) { var old = this[key] if (old == null) old = 0 this[key] = old + i; } fun MutableMap<T, Double>.increment(key: T, i: Double) { var old = this[key] if (old == null) old = 0.0 this[key] = old + i; } }
mit
6e83131ce04ccabcb576c7831aaf5e91
22.702703
94
0.53109
3.912946
false
false
false
false
rascarlo/AURdroid
app/src/main/java/com/rascarlo/aurdroid/utils/Constants.kt
1
551
package com.rascarlo.aurdroid.utils class Constants { companion object { const val BASE_URL = "https://aur.archlinux.org/" const val PACKAGE_LOG_BASE_URL = "https://aur.archlinux.org/cgit/aur.git/log/" const val PACKAGE_SNAPSHOT_BASE_URL = "https://aur.archlinux.org" const val PACKAGES_BASE_URL = "https://aur.archlinux.org/packages/" const val PACKAGES_GIT_CLONE_BASE_URL = "https://aur.archlinux.org/" const val PKGBUILD_BASE_URL = "https://aur.archlinux.org/cgit/aur.git/tree/PKGBUILD" } }
gpl-3.0
a712325279e09ec002750064fee9c840
41.461538
92
0.671506
3.339394
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/shared/models/dsl/Delete.kt
1
918
package com.infinum.dbinspector.domain.shared.models.dsl import com.infinum.dbinspector.domain.shared.models.dsl.conditions.And import com.infinum.dbinspector.domain.shared.models.dsl.shared.Condition internal class Delete { companion object { val pattern = "\\s+".toRegex() } private lateinit var table: String private var condition: Condition? = null fun from(table: String) { this.table = "\"$table\"" } fun where(initializer: Condition.() -> Unit) { condition = And().apply(initializer) } fun build(): String { if (!::table.isInitialized) { error("Failed to build - target table is undefined") } return toString() } override fun toString(): String { val conditions = condition?.let { "WHERE $it" }.orEmpty() return "DELETE FROM $table $conditions".replace(pattern, " ").trim() } }
apache-2.0
3edd32d36321364889fd9b59de53a43d
25.228571
76
0.630719
4.330189
false
false
false
false
JetBrains/anko
anko/idea-plugin/preview/src/org/jetbrains/kotlin/android/dslpreview/DslPreviewClassResolver.kt
2
7646
package org.jetbrains.kotlin.android.dslpreview import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ClassInheritorsSearch import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.codegen.ClassBuilderMode import org.jetbrains.kotlin.codegen.state.IncompatibleClassTracker import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.lazy.ResolveSession import org.jetbrains.kotlin.types.typeUtil.supertypes import java.util.* internal class DslPreviewClassResolver(private val project: Project) { private fun getKtClass(psiElement: PsiElement?): KtClass? { return if (psiElement is KtLightElement<*, *>) { getKtClass(psiElement.kotlinOrigin) } else if (psiElement is KtClass && !psiElement.isEnum() && !psiElement.isInterface() && !psiElement.isAnnotation() && !psiElement.isSealed()) { psiElement } else { val parent = psiElement?.parent ?: return null return getKtClass(parent) } } fun getOnCursorPreviewClassDescription(): PreviewClassDescription? { val editor = ApplicationManager.getApplication().runReadAction(Computable { FileEditorManager.getInstance(project).selectedTextEditor }) ?: return null val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) if (psiFile !is KtFile || editor !is EditorEx) return null val selectionStart = editor.caretModel.primaryCaret.selectionStart val psiElement = psiFile.findElementAt(selectionStart) ?: return null val cacheService = KotlinCacheService.getInstance(project) return resolveClassDescription(psiElement, cacheService) } fun getAncestors(baseClassName: String): Collection<PreviewClassDescription> { if (DumbService.isDumb(project)) return emptyList() val baseClasses = JavaPsiFacade.getInstance(project) .findClasses(baseClassName, GlobalSearchScope.allScope(project)) if (baseClasses.isEmpty()) return emptyList() return try { val cacheService = KotlinCacheService.getInstance(project) val previewClasses = ArrayList<PreviewClassDescription>(0) for (element in ClassInheritorsSearch.search(baseClasses[0]).findAll()) { resolveClassDescription(element, cacheService)?.let { previewClasses += it } } previewClasses } catch (e: IndexNotReadyException) { emptyList() } } private fun isZeroParameterConstructor(constructor: KtConstructor<*>?): Boolean { if (constructor == null) return false val parameters = constructor.getValueParameters() return parameters.isEmpty() || parameters.all { it.hasDefaultValue() } } fun isClassApplicableForPreview(clazz: KtClass): Boolean { val primaryConstructor = clazz.primaryConstructor val secondaryConstructors = clazz.secondaryConstructors return (primaryConstructor == null && secondaryConstructors.isEmpty()) || isZeroParameterConstructor(primaryConstructor) || secondaryConstructors.any(this::isZeroParameterConstructor) } fun resolveClassDescription(element: PsiElement, cacheService: KotlinCacheService): PreviewClassDescription? { if (DumbService.isDumb(element.project)) return null val ktClass = getKtClass(element) ?: return null if (!isClassApplicableForPreview(ktClass)) return null val resolveSession = cacheService.getResolutionFacade(listOf(ktClass)) .getFrontendService(ResolveSession::class.java) val classDescriptor = resolveSession.getClassDescriptor(ktClass, NoLookupLocation.FROM_IDE) if (!classDescriptor.defaultType.supertypes().any { val fqName = it.constructor.declarationDescriptor?.fqNameUnsafe?.asString() ?: "" fqName == ANKO_COMPONENT_CLASS_NAME }) { return null } val typeMapper = createTypeMapper(resolveSession.bindingContext) return PreviewClassDescription(ktClass, classDescriptor.fqNameSafe.asString(), typeMapper.mapType(classDescriptor).internalName) } companion object { val ANKO_COMPONENT_CLASS_NAME = "org.jetbrains.anko.AnkoComponent" private fun createTypeMapper(bindingContext: BindingContext): KotlinTypeMapper { // TODO: Add stable constructor to KotlinTypeMapper val typeMapperConstructor7 = KotlinTypeMapper::class.java.constructors.find { it.parameterCount == 7 } if (typeMapperConstructor7 != null) { if (typeMapperConstructor7.parameterTypes[4].isAssignableFrom(JvmTarget::class.java)) return typeMapperConstructor7 .newInstance( bindingContext, ClassBuilderMode.LIGHT_CLASSES, IncompatibleClassTracker.DoNothing, "main", JvmTarget.DEFAULT, false, false) as KotlinTypeMapper else return typeMapperConstructor7 .newInstance( bindingContext, ClassBuilderMode.LIGHT_CLASSES, IncompatibleClassTracker.DoNothing, "main", false, false, false) as KotlinTypeMapper } val typeMapperConstructor6 = KotlinTypeMapper::class.java.constructors.find { it.parameterCount == 6 } if (typeMapperConstructor6 != null) { return typeMapperConstructor6 .newInstance( bindingContext, ClassBuilderMode.LIGHT_CLASSES, IncompatibleClassTracker.DoNothing, "main", false, false) as KotlinTypeMapper } return KotlinTypeMapper( bindingContext, ClassBuilderMode.LIGHT_CLASSES, IncompatibleClassTracker.DoNothing, "main", false) } } }
apache-2.0
b0727eeb68f8b1121d29749b855645f5
43.459302
114
0.645043
6.082737
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/user/LinksFragment.kt
1
3265
package de.westnordost.streetcomplete.user import android.content.Intent import android.os.Bundle import android.view.View import androidx.core.net.toUri import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.user.achievements.AchievementsSource import de.westnordost.streetcomplete.data.user.statistics.StatisticsSource import de.westnordost.streetcomplete.databinding.FragmentLinksBinding import de.westnordost.streetcomplete.ktx.* import de.westnordost.streetcomplete.view.GridLayoutSpacingItemDecoration import kotlinx.coroutines.* import javax.inject.Inject /** Shows the user's unlocked links */ class LinksFragment : Fragment(R.layout.fragment_links) { @Inject internal lateinit var achievementsSource: AchievementsSource @Inject internal lateinit var statisticsSource: StatisticsSource private val binding by viewBinding(FragmentLinksBinding::bind) init { Injector.applicationComponent.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val ctx = requireContext() val minCellWidth = 280f val itemSpacing = ctx.resources.getDimensionPixelSize(R.dimen.links_item_margin) viewLifecycleScope.launch { view.awaitLayout() binding.emptyText.visibility = View.GONE val viewWidth = view.width.toFloat().toDp(ctx) val spanCount = (viewWidth / minCellWidth).toInt() val links = withContext(Dispatchers.IO) { achievementsSource.getLinks() } val adapter = GroupedLinksAdapter(links, this@LinksFragment::openUrl) // headers should span the whole width val spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int = if (adapter.shouldItemSpanFullWidth(position)) spanCount else 1 } spanSizeLookup.isSpanGroupIndexCacheEnabled = true spanSizeLookup.isSpanIndexCacheEnabled = true // vertical grid layout val layoutManager = GridLayoutManager(ctx, spanCount, RecyclerView.VERTICAL, false) layoutManager.spanSizeLookup = spanSizeLookup // spacing *between* the items binding.linksList.addItemDecoration(GridLayoutSpacingItemDecoration(itemSpacing)) binding.linksList.layoutManager = layoutManager binding.linksList.adapter = adapter binding.linksList.clipToPadding = false binding.emptyText.isGone = links.isNotEmpty() } } override fun onStart() { super.onStart() if (statisticsSource.isSynchronizing) { binding.emptyText.setText(R.string.stats_are_syncing) } else { binding.emptyText.setText(R.string.links_empty) } } private fun openUrl(url: String) { val intent = Intent(Intent.ACTION_VIEW, url.toUri()) tryStartActivity(intent) } }
gpl-3.0
6e3ef10eb221e08f14e5247791c722cf
38.337349
95
0.714548
5.08567
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeViewModel.kt
1
18336
package org.fossasia.openevent.general.attendees import android.util.Patterns import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.R import org.fossasia.openevent.general.attendees.forms.CustomForm import org.fossasia.openevent.general.auth.AuthHolder import org.fossasia.openevent.general.auth.AuthService import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.event.EventService import org.fossasia.openevent.general.order.Charge import org.fossasia.openevent.general.order.ConfirmOrder import org.fossasia.openevent.general.order.Order import org.fossasia.openevent.general.order.OrderService import org.fossasia.openevent.general.settings.SettingsService import org.fossasia.openevent.general.ticket.Ticket import org.fossasia.openevent.general.ticket.TicketService import org.fossasia.openevent.general.utils.ErrorUtils import org.fossasia.openevent.general.utils.HttpErrors import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import retrofit2.HttpException import timber.log.Timber const val ORDER_STATUS_PENDING = "pending" const val ORDER_STATUS_COMPLETED = "completed" const val ORDER_STATUS_PLACED = "placed" const val ORDER_STATUS_CANCELLED = "cancelled" const val ORDER_STATUS_INITIALIZING = "initializing" const val PAYMENT_MODE_FREE = "free" const val PAYMENT_MODE_BANK = "bank" const val PAYMENT_MODE_ONSITE = "onsite" const val PAYMENT_MODE_CHEQUE = "cheque" const val PAYMENT_MODE_PAYPAL = "paypal" const val PAYMENT_MODE_STRIPE = "stripe" private const val ERRORS = "errors" private const val DETAIL = "detail" private const val UNVERIFIED_USER = "unverified-user" private const val ORDER_EXPIRY_TIME = 15 class AttendeeViewModel( private val attendeeService: AttendeeService, private val authHolder: AuthHolder, private val eventService: EventService, private val orderService: OrderService, private val ticketService: TicketService, private val authService: AuthService, private val settingsService: SettingsService, private val resource: Resource ) : ViewModel() { private val compositeDisposable = CompositeDisposable() private val mutableProgress = MutableLiveData<Boolean>() val progress: LiveData<Boolean> = mutableProgress private val mutableTicketSoldOut = MutableLiveData<Boolean>() val ticketSoldOut: LiveData<Boolean> = mutableTicketSoldOut private val mutableMessage = SingleLiveEvent<String>() val message: SingleLiveEvent<String> = mutableMessage private val mutableEvent = MutableLiveData<Event>() val event: LiveData<Event> = mutableEvent private val mutableUser = MutableLiveData<User>() val user: LiveData<User> = mutableUser val orderCompleted = MutableLiveData<Boolean>() val totalAmount = MutableLiveData(0F) private val mutableTickets = MutableLiveData<List<Ticket>>() val tickets: LiveData<List<Ticket>> = mutableTickets private val mutableForms = MutableLiveData<List<CustomForm>>() val forms: LiveData<List<CustomForm>> = mutableForms private val mutablePendingOrder = MutableLiveData<Order>() val pendingOrder: LiveData<Order> = mutablePendingOrder private val mutableStripeOrderMade = MutableLiveData<Boolean>() val stripeOrderMade: LiveData<Boolean> = mutableStripeOrderMade private val mutableOrderExpiryTime = MutableLiveData<Int>() val orderExpiryTime: LiveData<Int> = mutableOrderExpiryTime private val mutableRedirectToProfile = SingleLiveEvent<Boolean>() val redirectToProfile = mutableRedirectToProfile private val mutablePaypalOrderMade = MutableLiveData<Boolean>() val paypalOrderMade: LiveData<Boolean> = mutablePaypalOrderMade val attendees = ArrayList<Attendee>() private val attendeesForOrder = ArrayList<Attendee>() private val ticketsForOrder = ArrayList<Ticket>() private var paymentModeForOrder: String = PAYMENT_MODE_FREE private var countryForOrder: String = "" private var companyForOrder: String = "" private var taxIdForOrder: String = "" private var addressForOrder: String = "" private var cityForOrder: String = "" private var postalCodeForOrder: String = "" private var stateForOrder: String = "" private var createAttendeeIterations = 0 var orderIdentifier: String? = null private set private lateinit var confirmOrder: ConfirmOrder // Retained information var countryPosition: Int = -1 var ticketIdAndQty: List<Triple<Int, Int, Float>>? = null var selectedPaymentMode: String = "" var singleTicket = false var monthSelectedPosition: Int = 0 var yearSelectedPosition: Int = 0 var paymentCurrency: String = "" var timeout: Long = -1L var ticketDetailsVisible = false var billingEnabled = false // Log in Information private val mutableSignedIn = MutableLiveData(true) val signedIn: LiveData<Boolean> = mutableSignedIn var isShowingSignInText = true fun getId() = authHolder.getId() fun isLoggedIn() = authHolder.isLoggedIn() fun login(email: String, password: String) { compositeDisposable += authService.login(email, password) .withDefaultSchedulers() .subscribe({ mutableSignedIn.value = true }, { mutableMessage.value = resource.getString(R.string.login_fail_message) }) } fun logOut() { compositeDisposable += authService.logout() .withDefaultSchedulers() .subscribe({ mutableSignedIn.value = false mutableUser.value = null }) { Timber.e(it, "Failure Logging out!") } } fun getTickets() { val ticketIds = ArrayList<Int>() ticketIdAndQty?.forEach { if (it.second > 0) { ticketIds.add(it.first) } } compositeDisposable += ticketService.getTicketsWithIds(ticketIds) .withDefaultSchedulers() .subscribe({ tickets -> mutableTickets.value = tickets }, { Timber.e(it, "Error Loading tickets!") }) } fun initializeOrder(eventId: Long) { val emptyOrder = Order(id = getId(), status = ORDER_STATUS_INITIALIZING, event = EventId(eventId)) compositeDisposable += orderService.placeOrder(emptyOrder) .withDefaultSchedulers() .subscribe({ mutablePendingOrder.value = it orderIdentifier = it.identifier.toString() }, { if (it is HttpException) { if (ErrorUtils.getErrorDetails(it).code == UNVERIFIED_USER) { mutableRedirectToProfile.value = true } } Timber.e(it, "Fail on creating pending order") }) } private fun createAttendee(attendee: Attendee, totalAttendee: Int) { compositeDisposable += attendeeService.postAttendee(attendee) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.subscribe({ attendeesForOrder.add(it) if (attendeesForOrder.size == totalAttendee) { loadTicketsAndCreateOrder() mutableMessage.value = resource.getString(R.string.create_attendee_success_message) } Timber.d("Success! %s", attendeesForOrder.toList().toString()) }, { mutableProgress.value = false if (createAttendeeIterations + 1 == totalAttendee) if (it is HttpException) { if (it.code() == HttpErrors.CONFLICT) mutableTicketSoldOut.value = true } else { mutableMessage.value = resource.getString(R.string.create_attendee_fail_message) Timber.d(it, "Failed") mutableTicketSoldOut.value = false } }) } fun createAttendees( attendees: List<Attendee>, country: String?, company: String, taxId: String, address: String, city: String, postalCode: String, state: String, paymentMode: String ) { attendeesForOrder.clear() countryForOrder = country ?: "" companyForOrder = company taxIdForOrder = taxId addressForOrder = address cityForOrder = city postalCodeForOrder = postalCode stateForOrder = state paymentModeForOrder = paymentMode var isAllDetailsFilled = true createAttendeeIterations = 0 attendees.forEach { if (it.email.isNullOrBlank() || it.firstname.isNullOrBlank() || it.lastname.isNullOrBlank()) { if (isAllDetailsFilled) mutableMessage.value = resource.getString(R.string.fill_all_fields_message) isAllDetailsFilled = false return } } if (isAllDetailsFilled) { attendees.forEach { createAttendee(it, attendees.size) } } } private fun loadTicketsAndCreateOrder() { ticketsForOrder.clear() attendeesForOrder.forEach { loadTicket(it.ticket?.id) } } private fun loadTicket(ticketId: Long?) { if (ticketId == null) { Timber.e("TicketId cannot be null") return } compositeDisposable += ticketService.getTicketDetails(ticketId) .withDefaultSchedulers() .subscribe({ ticketsForOrder.add(it) Timber.d("Loaded tickets! %s", ticketsForOrder.toList().toString()) if (ticketsForOrder.size == attendeesForOrder.size) { createOrder() } }, { Timber.d(it, "Error loading Ticket!") }) } private fun createOrder() { var order = mutablePendingOrder.value val identifier: String? = orderIdentifier if (order == null || identifier == null) { mutableMessage.value = resource.getString(R.string.order_fail_message) return } val amount: Float = totalAmount.value ?: 0F if (amount <= 0) { paymentModeForOrder = PAYMENT_MODE_FREE } order = order.copy(attendees = attendeesForOrder, paymentMode = paymentModeForOrder, amount = amount) if (billingEnabled) { order = order.copy(isBillingEnabled = true, company = companyForOrder, taxBusinessInfo = taxIdForOrder, address = addressForOrder, city = cityForOrder, zipcode = postalCodeForOrder, country = countryForOrder, state = stateForOrder) } compositeDisposable += orderService.placeOrder(order) .withDefaultSchedulers() .subscribe({ orderIdentifier = it.identifier.toString() Timber.d("Success placing order!") when (it.paymentMode) { PAYMENT_MODE_FREE -> { confirmOrder = ConfirmOrder(it.id.toString(), ORDER_STATUS_COMPLETED) confirmOrderStatus(it.identifier.toString(), confirmOrder) } PAYMENT_MODE_CHEQUE, PAYMENT_MODE_BANK, PAYMENT_MODE_ONSITE -> { confirmOrder = ConfirmOrder(it.id.toString(), ORDER_STATUS_PLACED) confirmOrderStatus(it.identifier.toString(), confirmOrder) } PAYMENT_MODE_STRIPE -> { mutableStripeOrderMade.value = true } PAYMENT_MODE_PAYPAL -> { mutablePendingOrder.value = it mutablePaypalOrderMade.value = true mutableProgress.value = false } else -> mutableMessage.value = resource.getString(R.string.order_success_message) } }, { mutableMessage.value = resource.getString(R.string.order_fail_message) Timber.d(it, "Failed creating Order") mutableProgress.value = false deleteAttendees(order.attendees) }) } fun sendPaypalConfirm(paymentId: String) { pendingOrder.value?.let { order -> compositeDisposable += orderService.verifyPaypalPayment(order.identifier.toString(), paymentId) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.subscribe({ if (it.status) { confirmOrder = ConfirmOrder(order.id.toString(), ORDER_STATUS_COMPLETED) confirmOrderStatus(order.identifier.toString(), confirmOrder) } else { mutableMessage.value = it.error mutableProgress.value = false } }, { Timber.e(it, "Error verifying paypal payment") mutableMessage.value = resource.getString(R.string.error_making_paypal_payment_message) mutableProgress.value = false }) } } private fun confirmOrderStatus(identifier: String, order: ConfirmOrder) { compositeDisposable += orderService.confirmOrder(identifier, order) .withDefaultSchedulers() .doFinally { mutableProgress.value = false }.subscribe({ mutableMessage.value = resource.getString(R.string.order_success_message) Timber.d("Updated order status successfully !") orderCompleted.value = true }, { mutableMessage.value = resource.getString(R.string.order_fail_message) Timber.d(it, "Failed updating order status") }) } fun getCustomFormsForAttendees(eventId: Long) { compositeDisposable += attendeeService.getCustomFormsForAttendees(eventId) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.subscribe({ mutableProgress.value = false mutableForms.value = it Timber.d("Forms fetched successfully !") }, { Timber.d(it, "Failed fetching forms") }) } private fun deleteAttendees(attendees: List<Attendee>?) { attendees?.forEach { attendee -> compositeDisposable += attendeeService.deleteAttendee(attendee.id) .withDefaultSchedulers() .subscribe({ Timber.d("Deleted attendee ${attendee.id}") }, { Timber.d("Failed to delete attendee $it.id") }) } } fun chargeOrder(charge: Charge) { compositeDisposable += orderService.chargeOrder(orderIdentifier.toString(), charge) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ mutableMessage.value = it.message if (it.status != null && it.status) { confirmOrder = ConfirmOrder(it.id.toString(), ORDER_STATUS_COMPLETED) confirmOrderStatus(orderIdentifier.toString(), confirmOrder) Timber.d("Successfully charged for the order!") } else { Timber.d("Failed charging the user") } }, { mutableMessage.value = ErrorUtils.getErrorDetails(it).detail Timber.d(it, "Failed charging the user") }) } fun loadEvent(id: Long) { if (id == -1L) { throw IllegalStateException("ID should never be -1") } compositeDisposable += eventService.getEvent(id) .withDefaultSchedulers() .subscribe({ mutableEvent.value = it }, { Timber.e(it, "Error fetching event %d", id) mutableMessage.value = resource.getString(R.string.error_fetching_event_message) }) } fun loadUser() { val id = getId() if (id == -1L) { throw IllegalStateException("ID should never be -1") } compositeDisposable += attendeeService.getAttendeeDetails(id) .withDefaultSchedulers() .subscribe({ mutableUser.value = it }, { Timber.e(it, "Error fetching user %d", id) }) } fun areAttendeeEmailsValid(attendees: ArrayList<Attendee>): Boolean { /**Checks for correct pattern in email*/ attendees.forEach { if (it.email.isNullOrEmpty()) return false else if (!Patterns.EMAIL_ADDRESS.matcher(it.email).matches()) return false } return true } fun getSettings() { compositeDisposable += settingsService.fetchSettings() .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ mutableOrderExpiryTime.value = it.orderExpiryTime }, { mutableOrderExpiryTime.value = ORDER_EXPIRY_TIME Timber.e(it, "Error fetching settings") }) } override fun onCleared() { super.onCleared() compositeDisposable.clear() } }
apache-2.0
e3dbcac4175fa620268143d7f764a3f9
38.774403
120
0.607984
5.324042
false
false
false
false
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/RecipeRegistry.kt
1
2945
package antimattermod.core import antimattermod.core.crafting.AlloySmelterRecipe import net.minecraft.item.ItemStack import java.util.* /** * @author C6H2Cl2 */ object RecipeRegistry { private val alloySmelterRecipes : HashMap<String, AlloySmelterRecipe> = HashMap() fun addAlloySmelterRecipe(name : String,alloySmelterRecipe: AlloySmelterRecipe){ alloySmelterRecipes.put(name,alloySmelterRecipe) } //ForgeのGameRegistry.addRecipe()形式でレシピ受付したいなぁ fun addAlloySmelterRecipe(name: String,tier : Int,isShapeless:Boolean,vararg recipeShape : Any){ val size = recipeShape.size var numRecipe = 0 val recipeShapeString = arrayOfNulls<String?>(3) //numRecipeは、RecipeのStringの数と同じ recipeShape.forEachIndexed { i, obj -> if (obj !is String) { numRecipe = i return@forEachIndexed } } //Stringが一つもなかったら例外投げる。サイズがおかしくても例外投げる。 if (numRecipe == 0 || numRecipe > 3 || size-numRecipe%2 == 1){ throw IllegalArgumentException() } //String移す for (i in 0..2){ if(i <= numRecipe-1){ recipeShapeString[i] = recipeShape[i] as String } } //CharArrayに変換 val shape : CharArray= CharArray(9)//kotlin.arrayOfNulls<Char?>(numRecipe+1) for (i in 0..recipeShapeString.size-1){ (recipeShapeString[i] as String).toCharArray().forEachIndexed { j, c -> shape[i*3+j] = c } } //文字とItemStackの変換表 val recipeStacks : HashMap<Char, ItemStack> = HashMap() //後半部分のチェック for (i in 0..(recipeShape.size-numRecipe)/2){ //Char・ItemStackのペアでなければ例外 if (recipeShape[i+numRecipe] !is Char || recipeShape[i+numRecipe+1] !is ItemStack){ throw IllegalArgumentException() } recipeStacks.put(recipeShape[i+numRecipe] as Char,recipeShape[i+numRecipe+1] as ItemStack) } //CharArrayから参照して置き換え作業 val recipe : LinkedList<ItemStack> = LinkedList() shape.forEachIndexed({ i, c -> val itemStack = recipeStacks[c] ?: throw IllegalArgumentException() recipe[i] = itemStack }) alloySmelterRecipes[name] = AlloySmelterRecipe(recipe.toTypedArray(),tier,!isShapeless) } //ラッパ達 //不定形 fun addAlloySmelterRecipeShapeless(name: String,tier: Int,vararg recipeShape: Array<out Any>){ addAlloySmelterRecipe(name,tier,true,recipeShape) } //定形 fun addAlloySmelterRecipeShaped(name: String,tier: Int,vararg recipeShape: Array<out Any>){ addAlloySmelterRecipe(name,tier,false,recipeShape) } }
gpl-3.0
610cc5bbd2593c3127a8d8e3ad1173d4
35.945946
102
0.628613
4.140909
false
false
false
false
Shoebill/streamer-wrapper
src/main/java/net/gtaun/shoebill/streamer/Callbacks.kt
1
11256
package net.gtaun.shoebill.streamer import net.gtaun.shoebill.Shoebill import net.gtaun.shoebill.entities.Player import net.gtaun.shoebill.amx.AmxInstanceManager import net.gtaun.shoebill.constant.WeaponModel import net.gtaun.shoebill.data.Vector3D import net.gtaun.shoebill.streamer.data.* import net.gtaun.shoebill.streamer.event.actor.DynamicActorStreamInEvent import net.gtaun.shoebill.streamer.event.actor.DynamicActorStreamOutEvent import net.gtaun.shoebill.streamer.event.actor.PlayerGiveDamageDynamicActorEvent import net.gtaun.shoebill.streamer.event.area.PlayerEnterDynamicAreaEvent import net.gtaun.shoebill.streamer.event.area.PlayerLeaveDynamicAreaEvent import net.gtaun.shoebill.streamer.event.checkpoint.PlayerEnterDynamicCheckpointEvent import net.gtaun.shoebill.streamer.event.checkpoint.PlayerLeaveDynamicCheckpointEvent import net.gtaun.shoebill.streamer.event.obj.DynamicObjectMovedEvent import net.gtaun.shoebill.streamer.event.obj.PlayerEditDynamicObjectEvent import net.gtaun.shoebill.streamer.event.obj.PlayerSelectDynamicObjectEvent import net.gtaun.shoebill.streamer.event.obj.PlayerShootDynamicObjectEvent import net.gtaun.shoebill.streamer.event.pickup.PlayerPickUpDynamicPickupEvent import net.gtaun.shoebill.streamer.event.racecheckpoint.PlayerEnterDynamicRaceCheckpointEvent import net.gtaun.shoebill.streamer.event.racecheckpoint.PlayerLeaveDynamicRaceCheckpointEvent import net.gtaun.shoebill.streamer.event.streamer.ItemStreamInEvent import net.gtaun.shoebill.streamer.event.streamer.ItemStreamOutEvent import net.gtaun.shoebill.streamer.event.streamer.PluginErrorEvent import net.gtaun.util.event.EventManager /** * @author Marvin Haschker */ object Callbacks { private val amxInstanceManager: AmxInstanceManager get() = Shoebill.get().amxInstanceManager fun registerHandlers(eventManager: EventManager) { amxInstanceManager.apply { hookCallback("OnDynamicObjectMoved", { amxCallEvent -> val `object` = DynamicObject[amxCallEvent.parameters[0] as Int] ?: return@hookCallback val event = DynamicObjectMovedEvent(`object`) eventManager.dispatchEvent(event, `object`) }, "i") hookCallback("OnPlayerEditDynamicObject", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val `object` = DynamicObject[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerEditDynamicObjectEvent(`object`, player, amxCallEvent.parameters[2] as Int, Vector3D(amxCallEvent.parameters[3] as Float, amxCallEvent.parameters[4] as Float, amxCallEvent.parameters[5] as Float), Vector3D(amxCallEvent.parameters[6] as Float, amxCallEvent.parameters[7] as Float, amxCallEvent.parameters[8] as Float)) eventManager.dispatchEvent(event, player, `object`) }, "i", "i", "i", "f", "f", "f", "f", "f", "f") hookCallback("OnPlayerSelectDynamicObject", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val `object` = DynamicObject[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val modelid = amxCallEvent.parameters[2] as Int val event = PlayerSelectDynamicObjectEvent(`object`, player, modelid, Vector3D(amxCallEvent.parameters[3] as Float, amxCallEvent.parameters[4] as Float, amxCallEvent.parameters[5] as Float)) eventManager.dispatchEvent(event, player, `object`, modelid) }, "i", "i", "i", "f", "f", "f") hookCallback("OnPlayerShootDynamicObject", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int)!! val weaponModel = WeaponModel.get(amxCallEvent.parameters[1] as Int) ?: return@hookCallback val dynamicObject = DynamicObject[amxCallEvent.parameters[2] as Int] ?: return@hookCallback val event = PlayerShootDynamicObjectEvent(dynamicObject, player, weaponModel, Vector3D(amxCallEvent.parameters[3] as Float, amxCallEvent.parameters[4] as Float, amxCallEvent.parameters[5] as Float)) eventManager.dispatchEvent(event, player, dynamicObject, weaponModel) }, "i", "i", "i", "f", "f", "f") hookCallback("OnPlayerEnterDynamicArea", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val area = DynamicArea[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerEnterDynamicAreaEvent(player, area) eventManager.dispatchEvent(event, player, area) }, "i", "i") hookCallback("OnPlayerLeaveDynamicArea", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val area = DynamicArea[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerLeaveDynamicAreaEvent(player, area) eventManager.dispatchEvent(event, player, area) }, "i", "i") hookCallback("OnPlayerPickUpDynamicPickup", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val pickup = DynamicPickup[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerPickUpDynamicPickupEvent(player, pickup) eventManager.dispatchEvent(event, player, pickup) }, "i", "i") hookCallback("OnPlayerEnterDynamicCP", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val dynamicCp = DynamicCheckpoint[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerEnterDynamicCheckpointEvent(player, dynamicCp) eventManager.dispatchEvent(event, player, dynamicCp) }, "i", "i") hookCallback("OnPlayerLeaveDynamicCP", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val dynamicCp = DynamicCheckpoint[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerLeaveDynamicCheckpointEvent(player, dynamicCp) eventManager.dispatchEvent(event, player, dynamicCp) }, "i", "i") hookCallback("OnPlayerEnterDynamicRaceCP", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val dynamicCp = DynamicRaceCheckpoint[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerEnterDynamicRaceCheckpointEvent(player, dynamicCp) eventManager.dispatchEvent(event, player, dynamicCp) }, "i", "i") hookCallback("OnPlayerLeaveDynamicRaceCP", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val dynamicCp = DynamicRaceCheckpoint[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val event = PlayerLeaveDynamicRaceCheckpointEvent(player, dynamicCp) eventManager.dispatchEvent(event, player, dynamicCp) }, "i", "i") hookCallback("OnPlayerGiveDamageDynamicActor", { amxCallEvent -> val player = Player.get(amxCallEvent.parameters[0] as Int) ?: return@hookCallback val actor = DynamicActor[amxCallEvent.parameters[1] as Int] ?: return@hookCallback val amount = amxCallEvent.parameters[2] as Float val model = WeaponModel.get(amxCallEvent.parameters[3] as Int) ?: return@hookCallback val bodyPart = amxCallEvent.parameters[4] as Int val event = PlayerGiveDamageDynamicActorEvent(player, actor, amount, model, bodyPart) eventManager.dispatchEvent(event, player, actor, amount, model, bodyPart) }, "i", "i", "f", "i", "i") hookCallback("OnDynamicActorStreamIn", { amxCallEvent -> val actor = DynamicActor[amxCallEvent.parameters[0] as Int] ?: return@hookCallback val player = Player.get(amxCallEvent.parameters[1] as Int) ?: return@hookCallback val event = DynamicActorStreamInEvent(actor, player) eventManager.dispatchEvent(event, actor, player) }, "i", "i") hookCallback("OnDynamicActorStreamOut", { amxCallEvent -> val actor = DynamicActor[amxCallEvent.parameters[0] as Int] ?: return@hookCallback val player = Player.get(amxCallEvent.parameters[1] as Int) ?: return@hookCallback val event = DynamicActorStreamOutEvent(actor, player) eventManager.dispatchEvent(event, actor, player) }, "i", "i") hookCallback("Streamer_OnItemStreamIn", { amxCallEvent -> val type = StreamerType[amxCallEvent.parameters[0] as Int] ?: return@hookCallback val id = amxCallEvent.parameters[1] as Int val event = ItemStreamInEvent(type, id) eventManager.dispatchEvent(event, type, id) }, "i", "i") hookCallback("Streamer_OnItemStreamOut", { amxCallEvent -> val type = StreamerType[amxCallEvent.parameters[0] as Int] ?: return@hookCallback val id = amxCallEvent.parameters[1] as Int val event = ItemStreamOutEvent(type, id) eventManager.dispatchEvent(event, type, id) }, "i", "i") hookCallback("Streamer_OnPluginError", { amxCallEvent -> val error = amxCallEvent.parameters[0] as String val event = PluginErrorEvent(error) eventManager.dispatchEvent(event, error) }, "s") } } fun unregisterHandlers() { amxInstanceManager.apply { unhookCallback("OnDynamicObjectMoved") unhookCallback("OnPlayerEditDynamicObject") unhookCallback("OnPlayerSelectDynamicObject") unhookCallback("OnPlayerShootDynamicObject") unhookCallback("OnPlayerPickUpDynamicPickup") unhookCallback("OnPlayerEnterDynamicArea") unhookCallback("OnPlayerLeaveDynamicArea") unhookCallback("OnPlayerPickUpDynamicPickup") unhookCallback("OnPlayerEnterDynamicCP") unhookCallback("OnPlayerLeaveDynamicCP") unhookCallback("OnPlayerEnterDynamicRaceCP") unhookCallback("OnPlayerLeaveDynamicRaceCP") unhookCallback("OnPlayerGiveDamageDynamicActor") unhookCallback("OnDynamicActorStreamIn") unhookCallback("OnDynamicActorStreamOut") unhookCallback("Streamer_OnItemStreamIn") unhookCallback("Streamer_OnItemStreamOut") unhookCallback("Streamer_OnPluginError") } } }
agpl-3.0
9f3e36b34ce53285689b6bf9a8db352e
59.197861
144
0.668088
5.100136
false
false
false
false
Kushki/kushki-android
app/src/main/java/com/kushkipagos/kushkidemo/contracts/AbstractRequestTransferSubscriptionTokenAsyncTask.kt
1
1641
package com.kushkipagos.kushkidemo.contracts import android.content.Context import android.widget.Toast import com.kushkipagos.exceptions.KushkiException import com.kushkipagos.kushki.Kushki import com.kushkipagos.kushki.KushkiEnvironment import com.kushkipagos.kushkidemo.helpers.CoroutineTask import com.kushkipagos.models.Transaction import com.kushkipagos.models.TransferSubscriptions abstract class AbstractRequestTransferSubscriptionTokenAsyncTask: CoroutineTask<TransferSubscriptions, Void, Transaction> { protected var _kushki: Kushki private var _context: Context var _result: Transaction? = null constructor(context: Context){ _context = context _kushki = Kushki("c308a8af32114b8c97f8ba191149df9b", "COP", KushkiEnvironment.QA) } @Throws(KushkiException::class) abstract fun requestTransferToken(transferSubscriptions: TransferSubscriptions): Transaction override fun doInBackground(vararg args: TransferSubscriptions?): Transaction { try { return requestTransferToken(args[0]!!) } catch (kushkiException: KushkiException) { throw RuntimeException(kushkiException) } } override fun onPostExecute(param: Transaction?) { val transaction = param!! if (transaction.isSuccessful) { _result = transaction showToast(transaction.token) } else { showToast("ERROR: Code: ${transaction.code} ${transaction.message}") } } fun showToast(text: String) { val toast = Toast.makeText(_context, text, Toast.LENGTH_SHORT) toast.show() } }
mit
715c1c73d29298f0bb2fea8a8fb2a8cf
32.510204
96
0.716027
4.826471
false
false
false
false
if710/if710.github.io
2019-08-21/Lifecycle/app/src/main/java/br/ufpe/cin/android/lifecycle/LifecycleActivity.kt
1
2655
package br.ufpe.cin.android.lifecycle import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.PersistableBundle import android.util.Log import android.widget.Toast import kotlinx.android.synthetic.main.activity_lifecycle.* import org.jetbrains.anko.alert class LifecycleActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lifecycle) //val teste = "Leopoldo" //teste.loucura() textoDigitado.text = savedInstanceState?.getString("oQueFoiDigitado") lifecycleLog.text = savedInstanceState?.getString("lifeCycleLog") atualizaLifecycle("onCreate()") botaoAdicionaTexto.setOnClickListener { val oQueFoiDigitado = campoTexto.text if (oQueFoiDigitado.isEmpty()) { toast("Digite algo, por favor") } else { textoDigitado.text = oQueFoiDigitado } } botaoDialog.setOnClickListener { alert ("Alguma mensagem") { title = "Titulo" positiveButton("OK!") { toast("clicou em beleza!") } } } } override fun onSaveInstanceState(outState: Bundle) { outState.putString("oQueFoiDigitado",textoDigitado.text.toString()) outState.putString("lifeCycleLog",lifecycleLog.text.toString()) super.onSaveInstanceState(outState) } override fun onStart() { super.onStart() atualizaLifecycle("onStart()") } override fun onResume() { super.onResume() atualizaLifecycle("onResume()") } override fun onRestart() { super.onRestart() atualizaLifecycle("onRestart()") } override fun onPause() { atualizaLifecycle("onPause()") super.onPause() } override fun onStop() { atualizaLifecycle("onStop()") super.onStop() } override fun onDestroy() { atualizaLifecycle("onDestroy()") // Não faça isso -> super.onCreate(null) super.onDestroy() } override fun onBackPressed() { super.onBackPressed() } private fun atualizaLifecycle(msg: String) { val m = lifecycleLog.text.toString() Log.d("LifecycleActivity",msg) lifecycleLog.text = "$msg \n $m" } fun String.loucura() { //this //aospdoaispdoaisd } fun Any.toast(msg:String) { Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show() } }
mit
ff77691690b286af39c9e775226d9a6a
26.071429
77
0.61176
4.695575
false
false
false
false
FHannes/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/values/ValueType.kt
7
722
package org.jetbrains.debugger.values private val VALUE_TYPES = ValueType.values() /** * Don't forget to update NashornDebuggerSupport.ValueType and DebuggerSupport.ts respectively also */ enum class ValueType { OBJECT, NUMBER, STRING, FUNCTION, BOOLEAN, ARRAY, NODE, UNDEFINED, NULL, SYMBOL; /** * Returns whether `type` corresponds to a JsObject. Note that while 'null' is an object * in JavaScript world, here for API consistency it has bogus type [.NULL] and is * not a [ObjectValue] */ val isObjectType: Boolean get() = this == OBJECT || this == ARRAY || this == FUNCTION || this == NODE companion object { fun fromIndex(index: Int) = VALUE_TYPES.get(index) } }
apache-2.0
9f7e8e6a3b04506411b141fd10aa6962
20.909091
99
0.68144
3.967033
false
false
false
false
FHannes/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/BinaryXmlOutputter.kt
11
2842
/* * 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 com.intellij.configurationStore import com.intellij.util.io.DataOutputStream import com.intellij.util.io.IOUtil import org.jdom.Attribute import org.jdom.CDATA import org.jdom.Element import org.jdom.Text import java.io.DataInputStream import java.io.InputStream import java.io.OutputStream import java.util.* internal enum class TypeMarker { ELEMENT, CDATA, TEXT, ELEMENT_END } fun serializeElementToBinary(element: Element, out: OutputStream) { BinaryXmlWriter(DataOutputStream(out)).write(element) } fun deserializeElementFromBinary(input: InputStream) = BinaryXmlReader(DataInputStream(input)).read() private class BinaryXmlReader(private val input: DataInputStream) { private val strings = ArrayList<String>() fun read() = readElement() private fun readString(): String { val lengthOrIndex = readUInt29() if (lengthOrIndex == 1) { return "" } if ((lengthOrIndex and 1) == 1) { val string = IOUtil.readUTF(input) strings.add(string) return string } return strings.get(lengthOrIndex shr 1) } private fun readElement(): Element { val element = Element(readString()) readAttributes(element) readContent(element) return element } private fun readContent(element: Element) { while (true) { when (input.read()) { TypeMarker.ELEMENT.ordinal -> element.addContent(readElement()) TypeMarker.TEXT.ordinal -> element.addContent(Text(readString())) TypeMarker.CDATA.ordinal -> element.addContent(CDATA(readString())) TypeMarker.ELEMENT_END.ordinal -> return } } } private fun readAttributes(element: Element) { val size = input.readUnsignedByte() for (i in 0..size - 1) { element.setAttribute(Attribute(readString(), readString())) } } private fun readUInt29(): Int { var value: Int var b = input.read() if ((b and 0xFF) < 128) { return b } value = b and 0x7F shl 7 b = input.read() if ((b and 0xFF) < 128) { return value or b } value = value or (b and 0x7F) shl 7 b = input.read() if ((b and 0xFF) < 128) { return value or b } return value or (b and 0x7F) shl 8 or (input.read() and 0xFF) } }
apache-2.0
b9d3e8198a6cd21ef4ddec61b45aa7d1
26.07619
101
0.686137
3.958217
false
false
false
false
CharlieZheng/NestedGridViewByListView
app/src/main/java/com/cdc/androidsamples/renderer/MyFirstRajawaliRenderer.kt
1
2039
package com.cdc.androidsamples.renderer import android.view.MotionEvent import org.rajawali3d.renderer.Renderer import org.rajawali3d.util.egl.RajawaliEGLConfigChooser import android.content.Context import android.util.Log import com.cdc.R import org.rajawali3d.lights.DirectionalLight import org.rajawali3d.materials.Material import org.rajawali3d.materials.methods.DiffuseMethod import org.rajawali3d.materials.textures.ATexture import org.rajawali3d.materials.textures.Texture import org.rajawali3d.math.vector.Vector3 import org.rajawali3d.primitives.Sphere /** * @author zhenghanrong on 2017/10/29. */ class MyFirstRajawaliRenderer(context: Context) : Renderer(context) { private var earthSphere: Sphere? = null private var directionalLight: DirectionalLight? = null override fun onOffsetsChanged(xOffset: Float, yOffset: Float, xOffsetStep: Float, yOffsetStep: Float, xPixelOffset: Int, yPixelOffset: Int) { } override fun onTouchEvent(event: MotionEvent?) { } override fun initScene() { directionalLight = DirectionalLight(1.toDouble(), .2, -1.toDouble()) directionalLight?.setColor(1f, 1f, 1f) directionalLight?.power = 2f currentScene.addLight(directionalLight) val earthTexture = Texture("Earth", R.drawable.earthtruecolor_nasa_big) val material = Material() material.enableLighting(true) material.diffuseMethod = DiffuseMethod.Lambert() material.colorInfluence = 0f try { material.addTexture(earthTexture) } catch (err: ATexture.TextureException) { Log.d(Thread.currentThread().stackTrace[2].methodName, err.toString()) } earthSphere = Sphere(1f, 24, 24) earthSphere?.material = material currentScene.addChild(earthSphere) currentCamera.z = 4.2 } override fun onRender(ellapsedRealtime: Long, deltaTime: Double) { super.onRender(ellapsedRealtime, deltaTime) earthSphere?.rotate(Vector3.Axis.Y, 1.toDouble()) } }
apache-2.0
9b01108b6801ee471b56178c7b870fc7
35.428571
145
0.725356
3.928709
false
false
false
false
JurajBegovac/RxKotlinTraits
rxkotlin-traits/src/main/kotlin/com/jurajbegovac/rxkotlin/traits/system/SystemOperator.kt
1
1659
package com.jurajbegovac.rxkotlin.traits.system import com.jurajbegovac.rxkotlin.traits.driver.Driver import com.jurajbegovac.rxkotlin.traits.driver.DriverSharingStrategy import com.jurajbegovac.rxkotlin.traits.driver.asDriverCompleteOnError import com.jurajbegovac.rxkotlin.traits.shared_sequence.SharedSequence import com.jurajbegovac.rxkotlin.traits.shared_sequence.defer import com.jurajbegovac.rxkotlin.traits.shared_sequence.merge import rx.Observable import rx.Scheduler import rx.subjects.ReplaySubject /** Created by juraj on 23/05/2017. */ object Observables { fun <S, C> system( initState: S, accumulator: (S, C) -> S, scheduler: Scheduler, vararg feedbacks: (Observable<S>) -> Observable<C>): Observable<S> { return Observable.defer { val replaySubject: ReplaySubject<S> = ReplaySubject.createWithSize(1) val command = Observable.merge(feedbacks.map { it(replaySubject) }) .observeOn(scheduler) command.scan(initState, accumulator) .doOnNext { replaySubject.onNext(it) } } } } fun <S, C> SharedSequence.Companion.system( initialState: S, accumulator: (S, C) -> S, vararg feedback: (Driver<S>) -> Driver<C>): Driver<S> { return DriverSharingStrategy.defer { val replaySubject: ReplaySubject<S> = ReplaySubject.createWithSize(1) val outputDriver = replaySubject.asDriverCompleteOnError() val command = DriverSharingStrategy.merge(feedback.map { it(outputDriver) }) command.asObservable() .scan(initialState, accumulator) .doOnNext { replaySubject.onNext(it) } .asDriverCompleteOnError() } }
mit
93c86bfecbc2649acd6cd332b0afaf4a
33.5625
80
0.721519
4.086207
false
false
false
false
arturbosch/detekt
detekt-rules-complexity/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/NestedBlockDepth.kt
1
4572
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Metric import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell import io.gitlab.arturbosch.detekt.api.config import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import io.gitlab.arturbosch.detekt.api.internal.Configuration import io.gitlab.arturbosch.detekt.rules.isUsedForNesting import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtContainerNodeForControlStructureBody import org.jetbrains.kotlin.psi.KtIfExpression import org.jetbrains.kotlin.psi.KtLambdaArgument import org.jetbrains.kotlin.psi.KtLoopExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtTryExpression import org.jetbrains.kotlin.psi.KtWhenExpression /** * This rule reports excessive nesting depth in functions. Excessively nested code becomes harder to read and increases * its hidden complexity. It might become harder to understand edge-cases of the function. * * Prefer extracting the nested code into well-named functions to make it easier to understand. */ @ActiveByDefault(since = "1.0.0") class NestedBlockDepth(config: Config = Config.empty) : Rule(config) { override val issue = Issue( "NestedBlockDepth", Severity.Maintainability, "Excessive nesting leads to hidden complexity. " + "Prefer extracting code to make it easier to understand.", Debt.TWENTY_MINS ) @Configuration("the nested depth required to trigger rule") private val threshold: Int by config(defaultValue = 4) override fun visitNamedFunction(function: KtNamedFunction) { val visitor = FunctionDepthVisitor(threshold) visitor.visitNamedFunction(function) if (visitor.isTooDeep) { @Suppress("UnsafeCallOnNullableType") report( ThresholdedCodeSmell( issue, Entity.atName(function), Metric("SIZE", visitor.maxDepth, threshold), "Function ${function.name} is nested too deeply." ) ) } } private class FunctionDepthVisitor(val threshold: Int) : DetektVisitor() { var depth = 0 var maxDepth = 0 var isTooDeep = false private fun inc() { depth++ if (depth >= threshold) { isTooDeep = true if (depth > maxDepth) maxDepth = depth } } private fun dec() { depth-- } override fun visitIfExpression(expression: KtIfExpression) { // Prevents else if (...) to count as two - #51 if (expression.parent !is KtContainerNodeForControlStructureBody) { inc() super.visitIfExpression(expression) dec() } else { super.visitIfExpression(expression) } } override fun visitLoopExpression(loopExpression: KtLoopExpression) { inc() super.visitLoopExpression(loopExpression) dec() } override fun visitWhenExpression(expression: KtWhenExpression) { inc() super.visitWhenExpression(expression) dec() } override fun visitTryExpression(expression: KtTryExpression) { inc() super.visitTryExpression(expression) dec() } override fun visitCallExpression(expression: KtCallExpression) { val lambdaArguments = expression.lambdaArguments if (expression.isUsedForNesting()) { insideLambdaDo(lambdaArguments) { inc() } super.visitCallExpression(expression) insideLambdaDo(lambdaArguments) { dec() } } } private fun insideLambdaDo(lambdaArguments: List<KtLambdaArgument>, function: () -> Unit) { if (lambdaArguments.isNotEmpty()) { val lambdaArgument = lambdaArguments[0] if (lambdaArgument.getLambdaExpression()?.bodyExpression != null) { function() } } } } }
apache-2.0
7eb540ccf5058166d2a693c6ee3e12af
35.576
119
0.647638
5.125561
false
true
false
false
googlecodelabs/kotlin-coroutines
coroutines-codelab/finished_code/src/main/java/com/example/android/kotlincoroutines/util/SkipNetworkInterceptor.kt
1
3246
/* * Copyright (C) 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.kotlincoroutines.util import com.google.gson.Gson import okhttp3.* /** * A list of fake results to return. */ private val FAKE_RESULTS = listOf( "Hello, coroutines!", "My favorite feature", "Async made easy", "Coroutines by example", "Check out the Advanced Coroutines codelab next!" ) /** * This class will return fake [Response] objects to Retrofit, without actually using the network. */ class SkipNetworkInterceptor : Interceptor { private var lastResult: String = "" val gson = Gson() private var attempts = 0 /** * Return true iff this request should error. */ private fun wantRandomError() = attempts++ % 5 == 0 /** * Stop the request from actually going out to the network. */ override fun intercept(chain: Interceptor.Chain): Response { pretendToBlockForNetworkRequest() return if (wantRandomError()) { makeErrorResult(chain.request()) } else { makeOkResult(chain.request()) } } /** * Pretend to "block" interacting with the network. * * Really: sleep for 500ms. */ private fun pretendToBlockForNetworkRequest() = Thread.sleep(500) /** * Generate an error result. * * ``` * HTTP/1.1 500 Bad server day * Content-type: application/json * * {"cause": "not sure"} * ``` */ private fun makeErrorResult(request: Request): Response { return Response.Builder() .code(500) .request(request) .protocol(Protocol.HTTP_1_1) .message("Bad server day") .body(ResponseBody.create( MediaType.get("application/json"), gson.toJson(mapOf("cause" to "not sure")))) .build() } /** * Generate a success response. * * ``` * HTTP/1.1 200 OK * Content-type: application/json * * "$random_string" * ``` */ private fun makeOkResult(request: Request): Response { var nextResult = lastResult while (nextResult == lastResult) { nextResult = FAKE_RESULTS.random() } lastResult = nextResult return Response.Builder() .code(200) .request(request) .protocol(Protocol.HTTP_1_1) .message("OK") .body(ResponseBody.create( MediaType.get("application/json"), gson.toJson(nextResult))) .build() } }
apache-2.0
7dc8907e8fdce5ce43d9eff67add7ddd
27.482456
98
0.581331
4.552595
false
false
false
false
nemerosa/ontrack
ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/context/core/admin/AccountGroupMappingsAdminContext.kt
1
5148
package net.nemerosa.ontrack.extension.casc.context.core.admin import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.common.syncForward import net.nemerosa.ontrack.extension.casc.context.AbstractCascContext import net.nemerosa.ontrack.extension.casc.schema.CascType import net.nemerosa.ontrack.extension.casc.schema.cascArray import net.nemerosa.ontrack.extension.casc.schema.cascObject import net.nemerosa.ontrack.json.JsonParseException import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.security.AccountGroupMappingInput import net.nemerosa.ontrack.model.security.AccountGroupMappingService import net.nemerosa.ontrack.model.security.AccountService import net.nemerosa.ontrack.model.security.AuthenticationSourceRepository import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Component class AccountGroupMappingsAdminContext( private val accountGroupMappingService: AccountGroupMappingService, private val authenticationSourceRepository: AuthenticationSourceRepository, private val accountService: AccountService, ) : AbstractCascContext(), SubAdminContext { private val logger: Logger = LoggerFactory.getLogger(AccountGroupMappingsAdminContext::class.java) override val field: String = "group-mappings" /** * Group mappings must be processed _after_ the creation of the groups */ override val priority: Int = AccountGroupsAdminContext.PRIORITY - 5 override val type: CascType get() = cascArray( "List of group mappings", cascObject(CascMapping::class) ) override fun run(node: JsonNode, paths: List<String>) { // Items to provision val items = node.mapIndexed { index, child -> try { child.parse<CascMapping>() } catch (ex: JsonParseException) { throw IllegalStateException( "Cannot parse into ${CascMapping::class.qualifiedName}: ${path(paths + index.toString())}", ex ) } } // Existing items val existing = existingMappings() // Synchronizing, preserving the existing groups syncForward( from = items, to = existing ) { equality { a, b -> a == b } onCreation { item -> logger.info("Creating account group mapping: $item") createGroupMapping(item) } onModification { item, existing -> logger.info("Updating account group mapping: $item --> $existing") updateGroupMapping(item) } onDeletion { existing -> logger.info("Preserving existing group mapping: ${existing}") } } } private fun updateGroupMapping(item: CascMapping) { // Deletes any existing mapping val existing = accountGroupMappingService.mappings.firstOrNull { CascMapping( provider = it.authenticationSource.provider, providerKey = it.authenticationSource.key, providerGroup = it.name, group = it.group.name, ) == item } if (existing != null) { accountGroupMappingService.deleteMapping( authenticationSource = existing.authenticationSource, id = existing.id, ) } // Recreates the mapping createGroupMapping(item) } private fun createGroupMapping(mapping: CascMapping) { accountGroupMappingService.newMapping( authenticationSource = authenticationSourceRepository.getRequiredAuthenticationSource( mapping.provider, mapping.providerKey, ), input = AccountGroupMappingInput( name = mapping.providerGroup, group = accountService.findAccountGroupByName(mapping.group) ?.id ?: throw IllegalStateException("Cannot find account group with name: ${mapping.group}") ) ) } override fun render(): JsonNode = existingMappings().asJson() private fun existingMappings() = accountGroupMappingService.mappings.map { CascMapping( provider = it.authenticationSource.provider, providerKey = it.authenticationSource.key, providerGroup = it.name, group = it.group.name, ) } private data class CascMapping( @APIDescription("ID of the authentication provider: oidc, ldap, ...") val provider: String, @APIDescription("Identifier of the exact provider source (name of the OIDC provider, leave blank for LDAP)") val providerKey: String, @APIDescription("Name of the group in the provider") val providerGroup: String, @APIDescription("Name of the group in Ontrack") val group: String, ) }
mit
e8f25d4127cdf8e9e91c09b861bcabaf
37.140741
116
0.646465
5.329193
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/AccountOutParser.kt
2
3479
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2021 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.util.Xml import edu.berkeley.boinc.utils.Logging import org.xml.sax.Attributes import org.xml.sax.SAXException class AccountOutParser : BaseParser() { lateinit var accountOut: AccountOut private set @Throws(SAXException::class) override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) { super.startElement(uri, localName, qName, attributes) if (localName.equalsAny(ERROR_NUM, AccountOut.Fields.ERROR_MSG, AccountOut.Fields.AUTHENTICATOR, ignoreCase = true)) { if (!this::accountOut.isInitialized) { accountOut = AccountOut() } } mElementStarted = true mCurrentElement.setLength(0) } @Throws(SAXException::class) override fun endElement(uri: String?, localName: String, qName: String?) { super.endElement(uri, localName, qName) try { trimEnd() when { localName.equals(ERROR_NUM, ignoreCase = true) -> { accountOut.errorNum = mCurrentElement.toInt() } localName.equals(AccountOut.Fields.ERROR_MSG, ignoreCase = true) -> { accountOut.errorMsg = mCurrentElement.toString() } localName.equals(AccountOut.Fields.AUTHENTICATOR, ignoreCase = true) -> { accountOut.authenticator = mCurrentElement.toString() } } } catch (e: NumberFormatException) { Logging.logException(Logging.Category.XML, "AccountOutParser.endElement error: ", e) } mElementStarted = false } companion object { @JvmStatic fun parse(rpcResult: String): AccountOut? { return try { var outResult: String? val xmlHeaderStart = rpcResult.indexOf("<?xml") if (xmlHeaderStart != -1) { val xmlHeaderEnd = rpcResult.indexOf("?>") outResult = rpcResult.substring(0, xmlHeaderStart) outResult += rpcResult.substring(xmlHeaderEnd + 2) } else { outResult = rpcResult } val parser = AccountOutParser() Xml.parse(outResult, parser) parser.accountOut } catch (e: SAXException) { Logging.logException(Logging.Category.RPC, "AccountOutParser: malformed XML ", e) Logging.logDebug(Logging.Category.XML, "AccountOutParser: $rpcResult") null } } } }
lgpl-3.0
d49f2c9699317862b61c306f632ba1a5
38.089888
105
0.602472
4.865734
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/insight/MixinLineMarkerProvider.kt
1
2296
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.asset.MixinAssets import com.demonwav.mcdev.platform.mixin.util.findSourceClass import com.demonwav.mcdev.platform.mixin.util.isMixin import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator import com.intellij.ide.util.PsiClassListCellRenderer import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import java.awt.event.MouseEvent class MixinLineMarkerProvider : LineMarkerProviderDescriptor(), GutterIconNavigationHandler<PsiIdentifier> { override fun getName() = "Mixin line marker" override fun getIcon() = MixinAssets.MIXIN_CLASS_ICON override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiIdentifier>? { if (element !is PsiClass) { return null } val identifier = element.nameIdentifier ?: return null if (!element.isMixin) { return null } return LineMarkerInfo( identifier, identifier.textRange, icon, { "Go to target class" }, this, GutterIconRenderer.Alignment.LEFT, { "mixin target class indicator" } ) } override fun navigate(e: MouseEvent, elt: PsiIdentifier) { val psiClass = elt.parent as? PsiClass ?: return val name = psiClass.name ?: return val targets = psiClass.mixinTargets .mapNotNull { it.findSourceClass(psiClass.project, psiClass.resolveScope, canDecompile = true) } if (targets.isNotEmpty()) { PsiElementListNavigator.openTargets( e, targets.toTypedArray(), "Choose target class of $name", null, PsiClassListCellRenderer() ) } } }
mit
9225a5f358a8f5673ae50dae69f3a12a
32.275362
108
0.68554
4.905983
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/autorefresh/RefreshNotification.kt
1
6491
package com.emogoth.android.phone.mimi.autorefresh import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Log import androidx.core.app.NotificationCompat import com.emogoth.android.phone.mimi.BuildConfig import com.emogoth.android.phone.mimi.R import com.emogoth.android.phone.mimi.activity.StartupActivity import com.emogoth.android.phone.mimi.app.MimiApplication.Companion.instance import com.emogoth.android.phone.mimi.db.DatabaseUtils import com.emogoth.android.phone.mimi.db.RefreshQueueTableConnection import com.emogoth.android.phone.mimi.db.models.QueueItem import com.emogoth.android.phone.mimi.util.Extras import com.emogoth.android.phone.mimi.util.MimiPrefs import com.emogoth.android.phone.mimi.util.Pages import io.reactivex.Flowable import io.reactivex.SingleObserver import io.reactivex.disposables.Disposable object RefreshNotification { private val LOG_DEBUG = BuildConfig.DEBUG private val LOG_TAG = RefreshNotification::class.java.simpleName const val NOTIFICATION_GROUP = "mimi_autorefresh" const val NOTIFICATION_ID = 1013 const val REFRESH_CHANNEL_ID = "mimi_autorefresh_channel" const val NOTIFICATIONS_NONE = 1 const val NOTIFICATIONS_ONLY_ME = 2 const val NOTIFICATIONS_ALL = 3 const val NOTIFICATIONS_KEY_THREAD_SIZE = "mimi_thread_size" private fun bookmarksPendingIntent(context: Context): PendingIntent { val openActivityIntent = Intent(context, StartupActivity::class.java) val args = Bundle() args.putString(Extras.OPEN_PAGE, Pages.BOOKMARKS.name) openActivityIntent.putExtras(args) return PendingIntent.getActivity( context, 0, openActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT ) } fun show() { if (!instance.background) { return } val notificationLevel = MimiPrefs.refreshNotificationLevel() if (notificationLevel == NOTIFICATIONS_NONE) { return } buildNotification(notificationLevel) } private fun buildNotification(notificationLevel: Int = NOTIFICATIONS_ALL) { val context = instance.applicationContext val notificationBuilder = NotificationCompat.Builder(instance, REFRESH_CHANNEL_ID) val style = NotificationCompat.InboxStyle() notificationBuilder.setStyle(style) notificationBuilder.setContentIntent(bookmarksPendingIntent(context)) notificationBuilder.setSmallIcon(R.drawable.ic_stat_leaf_icon) RefreshQueueTableConnection.fetchAllItems() .compose(DatabaseUtils.applySingleSchedulers()) .toFlowable() .flatMapIterable { it } .flatMap { if (it.unread > 0) { val c = instance.applicationContext val hasUnread: String = c.resources.getQuantityString(R.plurals.has_unread_plural, it.unread, it.unread) val notificationTitle = "/${it.boardName}/${it.threadId} $hasUnread" style.addLine(notificationTitle) if (LOG_DEBUG) { Log.d(LOG_TAG, "Creating notification for /" + it.boardName + "/" + it.threadId + ": id=" + NOTIFICATION_ID) } } Flowable.just(it) } .toList() .subscribe(object : SingleObserver<List<QueueItem>> { override fun onSuccess(queueItems: List<QueueItem>) { var totalThreads = 0 var totalReplyCount = 0 var newPostCount = 0 for (queueItem in queueItems) { if (queueItem.unread > 0) totalThreads++ totalReplyCount += queueItem.replyCount newPostCount += queueItem.unread } if (notificationLevel == NOTIFICATIONS_ONLY_ME && totalReplyCount <= 0) { return } val threadsUpdated: String = context.resources.getQuantityString(R.plurals.threads_updated_plural, totalThreads, totalThreads) val repliesToYou: String = context.resources.getQuantityString(R.plurals.replies_to_you_plurals, totalReplyCount, totalReplyCount) val newPostsText: String = context.resources.getQuantityString(R.plurals.new_post_plural, newPostCount, newPostCount) val contentTitle = "$threadsUpdated with $newPostsText" notificationBuilder.setContentTitle(newPostsText) notificationBuilder.setContentText(context.getString(R.string.tap_to_open_bookmarks)) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager? if (notificationManager != null) { style.setBigContentTitle(contentTitle) style.setSummaryText(repliesToYou) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelName: String = context.getString(R.string.mimi_thread_watcher) val autoRefreshChannel = NotificationChannel(REFRESH_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT) notificationBuilder.setChannelId(REFRESH_CHANNEL_ID) notificationManager.createNotificationChannel(autoRefreshChannel) } val notification: Notification = notificationBuilder.build() notificationManager.notify(NOTIFICATION_ID, notification) } } override fun onSubscribe(d: Disposable) { // no op } override fun onError(e: Throwable) { Log.e(LOG_TAG, "Error building notification", e) } }) } }
apache-2.0
4aed41ac2f3e70d645c56cc635ea6d27
42.864865
154
0.611924
5.454622
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/o/katydid/vdom/builders/miscellaneous/KatydidDescriptionListContentBuilder.kt
1
5976
// // (C) Copyright 2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.vdom.builders.miscellaneous import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.builders.KatydidFlowContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Builder DSL to create the contents of a `<dl>` element. */ interface KatydidDescriptionListContentBuilder<in Msg> : KatydidAttributesContentBuilder<Msg> { /** * Adds a comment node as the next child of the element under construction. * @param nodeValue the text within the node. * @param key unique key for this comment within its parent node. */ fun comment( nodeValue: String, key: Any? = null ) /** * Adds a `<dd>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun dd( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit ) /** * Adds a `<div>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun div( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidDescriptionListContentBuilder<Msg>.() -> Unit ) /** * Adds a `<dt>` element with its attributes as the next child of the element under construction. * The value of the option is the required text inside the element. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun dt( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit ) } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
6f75c12042402db56c3cb0577419b2b5
43.597015
119
0.637718
4.632558
false
false
false
false
cashapp/sqldelight
dialects/sqlite-3-18/src/main/kotlin/app/cash/sqldelight/dialects/sqlite_3_18/SelectConnectionTypeDialog.kt
1
2637
package app.cash.sqldelight.dialects.sqlite_3_18 import app.cash.sqldelight.dialect.api.ConnectionManager.ConnectionProperties import com.intellij.openapi.fileChooser.FileTypeDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.RecentsManager import com.intellij.ui.TextFieldWithHistoryWithBrowseButton import com.intellij.ui.layout.ValidationInfoBuilder import com.intellij.ui.layout.panel import java.io.File import javax.swing.JComponent import javax.swing.JTextField private const val RECENT_DB_PATH = "app.cash.sqldelight.recentPath" internal class SelectConnectionTypeDialog( project: Project, ) : DialogWrapper(project) { private val recentsManager: RecentsManager = RecentsManager.getInstance(project) private var connectionName: String = "" private var filePath: String = "" init { title = "Create SQLite Connection" init() } fun connectionProperties(): ConnectionProperties { return ConnectionProperties(connectionName, filePath) } override fun createCenterPanel(): JComponent { return panel { row("Connection Name") { textField( getter = { connectionName }, setter = { connectionName = it }, ).withValidationOnApply(validateKey()) .withValidationOnInput(validateKey()) } row(label = "DB File Path") { textFieldWithHistoryWithBrowseButton( browseDialogTitle = "Choose File", getter = { filePath }, setter = { filePath = it }, fileChooserDescriptor = FileTypeDescriptor("Choose File", "db"), historyProvider = { recentsManager.getRecentEntries(RECENT_DB_PATH).orEmpty() }, fileChosen = { vFile -> vFile.path.also { path -> filePath = path recentsManager.registerRecentEntry(RECENT_DB_PATH, path) } }, ) .withValidationOnInput(validateFilePath()) .withValidationOnApply(validateFilePath()) } }.also { validate() } } } private fun validateKey(): ValidationInfoBuilder.(JTextField) -> ValidationInfo? = { if (it.text.isNullOrEmpty()) { error("You must supply a connection key.") } else { null } } private fun validateFilePath(): ValidationInfoBuilder.(TextFieldWithHistoryWithBrowseButton) -> ValidationInfo? = { if (it.text.isEmpty()) { error("The file path is empty.") } else if (!File(it.text).exists()) { error("This file does not exist.") } else { null } }
apache-2.0
53532d5e18a7502d0d0045790565762f
30.023529
113
0.679939
4.777174
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/Properties.kt
1
37997
package tornadofx import javafx.beans.Observable import javafx.beans.binding.* import javafx.beans.property.* import javafx.beans.property.adapter.JavaBeanObjectPropertyBuilder import javafx.beans.value.* import javafx.collections.* import java.lang.reflect.Field import java.lang.reflect.Method import java.util.concurrent.Callable import kotlin.properties.ReadWriteProperty import kotlin.reflect.* import kotlin.reflect.jvm.javaMethod fun <T> ViewModel.property(value: T? = null) = PropertyDelegate(SimpleObjectProperty<T>(this, "ViewModelProperty", value)) fun <T> property(value: T? = null) = PropertyDelegate(SimpleObjectProperty<T>(value)) fun <T> property(block: () -> Property<T>) = PropertyDelegate(block()) class PropertyDelegate<T>(val fxProperty: Property<T>) : ReadWriteProperty<Any, T> { override fun getValue(thisRef: Any, property: KProperty<*>) = fxProperty.value override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { fxProperty.value = value } } fun <T> Any.getProperty(prop: KMutableProperty1<*, T>): ObjectProperty<T> { // avoid kotlin-reflect dependency val field = requireNotNull(javaClass.findFieldByName("${prop.name}\$delegate")) { "No delegate field with name '${prop.name}' found" } field.isAccessible = true @Suppress("UNCHECKED_CAST") val delegate = field.get(this) as PropertyDelegate<T> return delegate.fxProperty as ObjectProperty<T> } fun Class<*>.findFieldByName(name: String): Field? { val field = (declaredFields + fields).find { it.name == name } if (field != null) return field @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") if (superclass == java.lang.Object::class.java) return null return superclass.findFieldByName(name) } fun Class<*>.findMethodByName(name: String): Method? { val method = (declaredMethods + methods).find { it.name == name } if (method != null) return method @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") if (superclass == java.lang.Object::class.java) return null return superclass.findMethodByName(name) } /** * Convert an owner instance and a corresponding property reference into an observable */ fun <S, T> S.observable(prop: KMutableProperty1<S, T>) = observable(this, prop) /** * Convert an owner instance and a corresponding property reference into an observable */ @JvmName("observableFromMutableProperty") fun <S, T> observable(owner: S, prop: KMutableProperty1<S, T>): ObjectProperty<T> { return object : SimpleObjectProperty<T>(owner, prop.name) { override fun get() = prop.get(owner) override fun set(v: T) = prop.set(owner, v) } } /** * Convert an owner instance and a corresponding property reference into a readonly observable */ fun <S, T> observable(owner: S, prop: KProperty1<S, T>): ReadOnlyObjectProperty<T> { return object : ReadOnlyObjectWrapper<T>(owner, prop.name) { override fun get() = prop.get(owner) } } /** * Convert an bean instance and a corresponding getter/setter reference into a writable observable. * * Example: val observableName = observable(myPojo, MyPojo::getName, MyPojo::setName) */ fun <S : Any, T> observable(bean: S, getter: KFunction<T>, setter: KFunction2<S, T, Unit>): PojoProperty<T> { val propName = getter.name.substring(3).decapitalize() return object : PojoProperty<T>(bean, propName) { override fun get() = getter.call(bean) override fun set(newValue: T) { setter.invoke(bean, newValue) } } } open class PojoProperty<T>(bean: Any, propName: String) : SimpleObjectProperty<T>(bean, propName) { fun refresh() { fireValueChangedEvent() } } @JvmName("pojoObservable") inline fun <reified T : Any> Any.observable(propName: String) = this.observable(propertyName = propName, propertyType = T::class) /** * Convert a pojo bean instance into a writable observable. * * Example: val observableName = myPojo.observable(MyPojo::getName, MyPojo::setName) * or * val observableName = myPojo.observable(MyPojo::getName) * or * val observableName = myPojo.observable("name") */ @Suppress("UNCHECKED_CAST") fun <S : Any, T : Any> S.observable( getter: KFunction<T>? = null, setter: KFunction2<S, T, Unit>? = null, propertyName: String? = null, @Suppress("UNUSED_PARAMETER") propertyType: KClass<T>? = null ): ObjectProperty<T> { if (getter == null && propertyName == null) throw AssertionError("Either getter or propertyName must be provided") val propName = propertyName ?: getter?.name?.substring(3)?.decapitalize() return JavaBeanObjectPropertyBuilder.create().apply { bean(this@observable) this.name(propName) if (getter != null) this.getter(getter.javaMethod) if (setter != null) this.setter(setter.javaMethod) }.build() as ObjectProperty<T> } enum class SingleAssignThreadSafetyMode { SYNCHRONIZED, NONE } fun <T> singleAssign(threadSafetyMode: SingleAssignThreadSafetyMode = SingleAssignThreadSafetyMode.SYNCHRONIZED): SingleAssign<T> = if (threadSafetyMode == SingleAssignThreadSafetyMode.SYNCHRONIZED) SynchronizedSingleAssign() else UnsynchronizedSingleAssign() interface SingleAssign<T> { fun isInitialized(): Boolean operator fun getValue(thisRef: Any?, property: KProperty<*>): T operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) } private class SynchronizedSingleAssign<T> : UnsynchronizedSingleAssign<T>() { @Volatile override var _value: Any? = UNINITIALIZED_VALUE override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) { super.setValue(thisRef, property, value) } } private open class UnsynchronizedSingleAssign<T> : SingleAssign<T> { protected object UNINITIALIZED_VALUE protected open var _value: Any? = UNINITIALIZED_VALUE override operator fun getValue(thisRef: Any?, property: KProperty<*>): T { if (!isInitialized()) throw UninitializedPropertyAccessException("Value has not been assigned yet!") @Suppress("UNCHECKED_CAST") return _value as T } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { if (isInitialized()) throw Exception("Value has already been assigned!") _value = value } override fun isInitialized() = _value != UNINITIALIZED_VALUE } /** * Binds this property to an observable, automatically unbinding it before if already bound. */ fun <T> Property<T>.cleanBind(observable: ObservableValue<T>) { unbind() bind(observable) } operator fun <T> ObservableValue<T>.getValue(thisRef: Any, property: KProperty<*>) = value operator fun <T> Property<T>.setValue(thisRef: Any, property: KProperty<*>, value: T?) = setValue(value) fun ObservableValue<String>.matches(pattern: Regex): BooleanBinding { return booleanBinding { it?.matches(pattern) ?: false } } operator fun ObservableDoubleValue.getValue(thisRef: Any, property: KProperty<*>) = get() operator fun DoubleProperty.setValue(thisRef: Any, property: KProperty<*>, value: Double) = set(value) operator fun ObservableFloatValue.getValue(thisRef: Any, property: KProperty<*>) = get() operator fun FloatProperty.setValue(thisRef: Any, property: KProperty<*>, value: Float) = set(value) operator fun ObservableLongValue.getValue(thisRef: Any, property: KProperty<*>) = get() operator fun LongProperty.setValue(thisRef: Any, property: KProperty<*>, value: Long) = set(value) operator fun ObservableIntegerValue.getValue(thisRef: Any, property: KProperty<*>) = get() operator fun IntegerProperty.setValue(thisRef: Any, property: KProperty<*>, value: Int) = set(value) operator fun ObservableBooleanValue.getValue(thisRef: Any, property: KProperty<*>) = get() operator fun BooleanProperty.setValue(thisRef: Any, property: KProperty<*>, value: Boolean) = set(value) // These were removed because they shadow observable properties. For example "someVar by SimpleListProperty<E>" would // have type MutableList<E> instead of ObservableList<E>. //operator fun <E> ObservableListValue<E>.getValue(thisRef: Any, property: KProperty<*>): MutableList<E> = value //operator fun <E> ListProperty<E>.setValue(thisRef: Any, property: KProperty<*>, list: List<E>) = set(FXCollections.observableList(list)) // //operator fun <E> ObservableSetValue<E>.getValue(thisRef: Any, property: KProperty<*>): MutableSet<E> = value //operator fun <E> SetProperty<E>.setValue(thisRef: Any, property: KProperty<*>, set: Set<E>) = set(FXCollections.observableSet(set)) // //operator fun <K, V> ObservableMapValue<K, V>.getValue(thisRef: Any, property: KProperty<*>): MutableMap<K, V> = value //operator fun <K, V> MapProperty<K, V>.setValue(thisRef: Any, property: KProperty<*>, map: Map<K, V>) = set(FXCollections.observableMap(map)) operator fun DoubleExpression.plus(other: Number): DoubleBinding = add(other.toDouble()) operator fun DoubleExpression.plus(other: ObservableNumberValue): DoubleBinding = add(other) operator fun DoubleProperty.plusAssign(other: Number) { value += other.toDouble() } operator fun DoubleProperty.plusAssign(other: ObservableNumberValue) { value += other.doubleValue() } operator fun DoubleExpression.minus(other: Number): DoubleBinding = subtract(other.toDouble()) operator fun DoubleExpression.minus(other: ObservableNumberValue): DoubleBinding = subtract(other) operator fun DoubleProperty.minusAssign(other: Number) { value -= other.toDouble() } operator fun DoubleProperty.minusAssign(other: ObservableNumberValue) { value -= other.doubleValue() } operator fun DoubleExpression.unaryMinus(): DoubleBinding = negate() operator fun DoubleExpression.times(other: Number): DoubleBinding = multiply(other.toDouble()) operator fun DoubleExpression.times(other: ObservableNumberValue): DoubleBinding = multiply(other) operator fun DoubleProperty.timesAssign(other: Number) { value *= other.toDouble() } operator fun DoubleProperty.timesAssign(other: ObservableNumberValue) { value *= other.doubleValue() } operator fun DoubleExpression.div(other: Number): DoubleBinding = divide(other.toDouble()) operator fun DoubleExpression.div(other: ObservableNumberValue): DoubleBinding = divide(other) operator fun DoubleProperty.divAssign(other: Number) { value /= other.toDouble() } operator fun DoubleProperty.divAssign(other: ObservableNumberValue) { value /= other.doubleValue() } operator fun DoubleExpression.rem(other: Number): DoubleBinding = doubleBinding(this) { get() % other.toDouble() } operator fun DoubleExpression.rem(other: ObservableNumberValue): DoubleBinding = doubleBinding(this, other) { get() % other.doubleValue() } operator fun DoubleProperty.remAssign(other: Number) { value %= other.toDouble() } operator fun DoubleProperty.remAssign(other: ObservableNumberValue) { value %= other.doubleValue() } operator fun ObservableDoubleValue.compareTo(other: Number) = get().compareTo(other.toDouble()) operator fun ObservableDoubleValue.compareTo(other: ObservableNumberValue) = get().compareTo(other.doubleValue()) operator fun FloatExpression.plus(other: Number): FloatBinding = add(other.toFloat()) operator fun FloatExpression.plus(other: Double): DoubleBinding = add(other) operator fun FloatExpression.plus(other: ObservableNumberValue): FloatBinding = add(other) as FloatBinding operator fun FloatExpression.plus(other: ObservableDoubleValue): DoubleBinding = add(other) as DoubleBinding operator fun FloatProperty.plusAssign(other: Number) { value += other.toFloat() } operator fun FloatProperty.plusAssign(other: ObservableNumberValue) { value += other.floatValue() } operator fun FloatExpression.minus(other: Number): FloatBinding = subtract(other.toFloat()) operator fun FloatExpression.minus(other: Double): DoubleBinding = subtract(other) operator fun FloatExpression.minus(other: ObservableNumberValue): FloatBinding = subtract(other) as FloatBinding operator fun FloatExpression.minus(other: ObservableDoubleValue): DoubleBinding = subtract(other) as DoubleBinding operator fun FloatProperty.minusAssign(other: Number) { value -= other.toFloat() } operator fun FloatProperty.minusAssign(other: ObservableNumberValue) { value -= other.floatValue() } operator fun FloatExpression.unaryMinus(): FloatBinding = negate() operator fun FloatExpression.times(other: Number): FloatBinding = multiply(other.toFloat()) operator fun FloatExpression.times(other: Double): DoubleBinding = multiply(other) operator fun FloatExpression.times(other: ObservableNumberValue): FloatBinding = multiply(other) as FloatBinding operator fun FloatExpression.times(other: ObservableDoubleValue): DoubleBinding = multiply(other) as DoubleBinding operator fun FloatProperty.timesAssign(other: Number) { value *= other.toFloat() } operator fun FloatProperty.timesAssign(other: ObservableNumberValue) { value *= other.floatValue() } operator fun FloatExpression.div(other: Number): FloatBinding = divide(other.toFloat()) operator fun FloatExpression.div(other: Double): DoubleBinding = divide(other) operator fun FloatExpression.div(other: ObservableNumberValue): FloatBinding = divide(other) as FloatBinding operator fun FloatExpression.div(other: ObservableDoubleValue): DoubleBinding = divide(other) as DoubleBinding operator fun FloatProperty.divAssign(other: Number) { value /= other.toFloat() } operator fun FloatProperty.divAssign(other: ObservableNumberValue) { value /= other.floatValue() } operator fun FloatExpression.rem(other: Number): FloatBinding = floatBinding(this) { get() % other.toFloat() } operator fun FloatExpression.rem(other: Double): DoubleBinding = doubleBinding(this) { get() % other } operator fun FloatExpression.rem(other: ObservableNumberValue): FloatBinding = floatBinding(this, other) { get() % other.floatValue() } operator fun FloatExpression.rem(other: ObservableDoubleValue): DoubleBinding = doubleBinding(this, other) { get() % other.get() } operator fun FloatProperty.remAssign(other: Number) { value %= other.toFloat() } operator fun FloatProperty.remAssign(other: ObservableNumberValue) { value %= other.floatValue() } operator fun ObservableFloatValue.compareTo(other: Number) = get().compareTo(other.toFloat()) operator fun ObservableFloatValue.compareTo(other: ObservableNumberValue) = get().compareTo(other.floatValue()) operator fun IntegerExpression.plus(other: Int): IntegerBinding = add(other) operator fun IntegerExpression.plus(other: Long): LongBinding = add(other) operator fun IntegerExpression.plus(other: Float): FloatBinding = add(other) operator fun IntegerExpression.plus(other: Double): DoubleBinding = add(other) operator fun IntegerExpression.plus(other: ObservableIntegerValue): IntegerBinding = add(other) as IntegerBinding operator fun IntegerExpression.plus(other: ObservableLongValue): LongBinding = add(other) as LongBinding operator fun IntegerExpression.plus(other: ObservableFloatValue): FloatBinding = add(other) as FloatBinding operator fun IntegerExpression.plus(other: ObservableDoubleValue): DoubleBinding = add(other) as DoubleBinding operator fun IntegerProperty.plusAssign(other: Number) { value += other.toInt() } operator fun IntegerProperty.plusAssign(other: ObservableNumberValue) { value += other.intValue() } operator fun IntegerExpression.minus(other: Int): IntegerBinding = subtract(other) operator fun IntegerExpression.minus(other: Long): LongBinding = subtract(other) operator fun IntegerExpression.minus(other: Float): FloatBinding = subtract(other) operator fun IntegerExpression.minus(other: Double): DoubleBinding = subtract(other) operator fun IntegerExpression.minus(other: ObservableIntegerValue): IntegerBinding = subtract(other) as IntegerBinding operator fun IntegerExpression.minus(other: ObservableLongValue): LongBinding = subtract(other) as LongBinding operator fun IntegerExpression.minus(other: ObservableFloatValue): FloatBinding = subtract(other) as FloatBinding operator fun IntegerExpression.minus(other: ObservableDoubleValue): DoubleBinding = subtract(other) as DoubleBinding operator fun IntegerProperty.minusAssign(other: Number) { value -= other.toInt() } operator fun IntegerProperty.minusAssign(other: ObservableNumberValue) { value -= other.intValue() } operator fun IntegerExpression.unaryMinus(): IntegerBinding = negate() operator fun IntegerExpression.times(other: Int): IntegerBinding = multiply(other) operator fun IntegerExpression.times(other: Long): LongBinding = multiply(other) operator fun IntegerExpression.times(other: Float): FloatBinding = multiply(other) operator fun IntegerExpression.times(other: Double): DoubleBinding = multiply(other) operator fun IntegerExpression.times(other: ObservableIntegerValue): IntegerBinding = multiply(other) as IntegerBinding operator fun IntegerExpression.times(other: ObservableLongValue): LongBinding = multiply(other) as LongBinding operator fun IntegerExpression.times(other: ObservableFloatValue): FloatBinding = multiply(other) as FloatBinding operator fun IntegerExpression.times(other: ObservableDoubleValue): DoubleBinding = multiply(other) as DoubleBinding operator fun IntegerProperty.timesAssign(other: Number) { value *= other.toInt() } operator fun IntegerProperty.timesAssign(other: ObservableNumberValue) { value *= other.intValue() } operator fun IntegerExpression.div(other: Int): IntegerBinding = divide(other) operator fun IntegerExpression.div(other: Long): LongBinding = divide(other) operator fun IntegerExpression.div(other: Float): FloatBinding = divide(other) operator fun IntegerExpression.div(other: Double): DoubleBinding = divide(other) operator fun IntegerExpression.div(other: ObservableIntegerValue): IntegerBinding = divide(other) as IntegerBinding operator fun IntegerExpression.div(other: ObservableLongValue): LongBinding = divide(other) as LongBinding operator fun IntegerExpression.div(other: ObservableFloatValue): FloatBinding = divide(other) as FloatBinding operator fun IntegerExpression.div(other: ObservableDoubleValue): DoubleBinding = divide(other) as DoubleBinding operator fun IntegerProperty.divAssign(other: Number) { value /= other.toInt() } operator fun IntegerProperty.divAssign(other: ObservableNumberValue) { value /= other.intValue() } operator fun IntegerExpression.rem(other: Int): IntegerBinding = integerBinding(this) { get() % other } operator fun IntegerExpression.rem(other: Long): LongBinding = longBinding(this) { get() % other } operator fun IntegerExpression.rem(other: Float): FloatBinding = floatBinding(this) { get() % other } operator fun IntegerExpression.rem(other: Double): DoubleBinding = doubleBinding(this) { get() % other } operator fun IntegerExpression.rem(other: ObservableIntegerValue): IntegerBinding = integerBinding(this, other) { get() % other.get() } operator fun IntegerExpression.rem(other: ObservableLongValue): LongBinding = longBinding(this, other) { get() % other.get() } operator fun IntegerExpression.rem(other: ObservableFloatValue): FloatBinding = floatBinding(this, other) { get() % other.get() } operator fun IntegerExpression.rem(other: ObservableDoubleValue): DoubleBinding = doubleBinding(this, other) { get() % other.get() } operator fun IntegerProperty.remAssign(other: Number) { value %= other.toInt() } operator fun IntegerProperty.remAssign(other: ObservableNumberValue) { value %= other.intValue() } operator fun ObservableIntegerValue.rangeTo(other: ObservableIntegerValue): Sequence<IntegerProperty> = get().rangeTo(other.get()).asSequence().map(::SimpleIntegerProperty) operator fun ObservableIntegerValue.rangeTo(other: Int): Sequence<IntegerProperty> = get().rangeTo(other).asSequence().map(::SimpleIntegerProperty) operator fun ObservableIntegerValue.rangeTo(other: ObservableLongValue): Sequence<LongProperty> = get().rangeTo(other.get()).asSequence().map(::SimpleLongProperty) operator fun ObservableIntegerValue.rangeTo(other: Long): Sequence<LongProperty> = get().rangeTo(other).asSequence().map(::SimpleLongProperty) operator fun ObservableIntegerValue.compareTo(other: Number) = get().compareTo(other.toDouble()) operator fun ObservableIntegerValue.compareTo(other: ObservableNumberValue) = get().compareTo(other.doubleValue()) operator fun LongExpression.plus(other: Number): LongBinding = add(other.toLong()) operator fun LongExpression.plus(other: Float): FloatBinding = add(other) operator fun LongExpression.plus(other: Double): DoubleBinding = add(other) operator fun LongExpression.plus(other: ObservableNumberValue): LongBinding = add(other) as LongBinding operator fun LongExpression.plus(other: ObservableFloatValue): FloatBinding = add(other) as FloatBinding operator fun LongExpression.plus(other: ObservableDoubleValue): DoubleBinding = add(other) as DoubleBinding operator fun LongProperty.plusAssign(other: Number) { value += other.toLong() } operator fun LongProperty.plusAssign(other: ObservableNumberValue) { value += other.longValue() } operator fun LongExpression.minus(other: Number): LongBinding = subtract(other.toLong()) operator fun LongExpression.minus(other: Float): FloatBinding = subtract(other) operator fun LongExpression.minus(other: Double): DoubleBinding = subtract(other) operator fun LongExpression.minus(other: ObservableNumberValue): LongBinding = subtract(other) as LongBinding operator fun LongExpression.minus(other: ObservableFloatValue): FloatBinding = subtract(other) as FloatBinding operator fun LongExpression.minus(other: ObservableDoubleValue): DoubleBinding = subtract(other) as DoubleBinding operator fun LongProperty.minusAssign(other: Number) { value -= other.toLong() } operator fun LongProperty.minusAssign(other: ObservableNumberValue) { value -= other.longValue() } operator fun LongExpression.unaryMinus(): LongBinding = negate() operator fun LongExpression.times(other: Number): LongBinding = multiply(other.toLong()) operator fun LongExpression.times(other: Float): FloatBinding = multiply(other) operator fun LongExpression.times(other: Double): DoubleBinding = multiply(other) operator fun LongExpression.times(other: ObservableNumberValue): LongBinding = multiply(other) as LongBinding operator fun LongExpression.times(other: ObservableFloatValue): FloatBinding = multiply(other) as FloatBinding operator fun LongExpression.times(other: ObservableDoubleValue): DoubleBinding = multiply(other) as DoubleBinding operator fun LongProperty.timesAssign(other: Number) { value *= other.toLong() } operator fun LongProperty.timesAssign(other: ObservableNumberValue) { value *= other.longValue() } operator fun LongExpression.div(other: Number): LongBinding = divide(other.toLong()) operator fun LongExpression.div(other: Float): FloatBinding = divide(other) operator fun LongExpression.div(other: Double): DoubleBinding = divide(other) operator fun LongExpression.div(other: ObservableNumberValue): LongBinding = divide(other) as LongBinding operator fun LongExpression.div(other: ObservableFloatValue): FloatBinding = divide(other) as FloatBinding operator fun LongExpression.div(other: ObservableDoubleValue): DoubleBinding = divide(other) as DoubleBinding operator fun LongProperty.divAssign(other: Number) { value /= other.toLong() } operator fun LongProperty.divAssign(other: ObservableNumberValue) { value /= other.longValue() } operator fun LongExpression.rem(other: Number): LongBinding = longBinding(this) { get() % other.toLong() } operator fun LongExpression.rem(other: Float): FloatBinding = floatBinding(this) { get() % other } operator fun LongExpression.rem(other: Double): DoubleBinding = doubleBinding(this) { get() % other } operator fun LongExpression.rem(other: ObservableNumberValue): LongBinding = longBinding(this, other) { this.get() % other.longValue() } operator fun LongExpression.rem(other: ObservableFloatValue): FloatBinding = floatBinding(this, other) { this.get() % other.get() } operator fun LongExpression.rem(other: ObservableDoubleValue): DoubleBinding = doubleBinding(this, other) { this.get() % other.get() } operator fun LongProperty.remAssign(other: Number) { value %= other.toLong() } operator fun LongProperty.remAssign(other: ObservableNumberValue) { value %= other.longValue() } operator fun ObservableLongValue.rangeTo(other: ObservableLongValue): Sequence<LongProperty> = get().rangeTo(other.get()).asSequence().map { SimpleLongProperty(it) } operator fun ObservableLongValue.rangeTo(other: Long): Sequence<LongProperty> = get().rangeTo(other).asSequence().map(::SimpleLongProperty) operator fun ObservableLongValue.rangeTo(other: ObservableIntegerValue): Sequence<LongProperty> = get().rangeTo(other.get()).asSequence().map(::SimpleLongProperty) operator fun ObservableLongValue.rangeTo(other: Int): Sequence<LongProperty> = get().rangeTo(other).asSequence().map(::SimpleLongProperty) operator fun ObservableLongValue.compareTo(other: Number) = get().compareTo(other.toDouble()) operator fun ObservableLongValue.compareTo(other: ObservableNumberValue) = get().compareTo(other.doubleValue()) infix fun NumberExpression.gt(other: Int): BooleanBinding = greaterThan(other) infix fun NumberExpression.gt(other: Long): BooleanBinding = greaterThan(other) infix fun NumberExpression.gt(other: Float): BooleanBinding = greaterThan(other) infix fun NumberExpression.gt(other: Double): BooleanBinding = greaterThan(other) infix fun NumberExpression.gt(other: ObservableNumberValue): BooleanBinding = greaterThan(other) infix fun NumberExpression.ge(other: Int): BooleanBinding = greaterThanOrEqualTo(other) infix fun NumberExpression.ge(other: Long): BooleanBinding = greaterThanOrEqualTo(other) infix fun NumberExpression.ge(other: Float): BooleanBinding = greaterThanOrEqualTo(other) infix fun NumberExpression.ge(other: Double): BooleanBinding = greaterThanOrEqualTo(other) infix fun NumberExpression.ge(other: ObservableNumberValue): BooleanBinding = greaterThanOrEqualTo(other) infix fun NumberExpression.eq(other: Int): BooleanBinding = isEqualTo(other) infix fun NumberExpression.eq(other: Long): BooleanBinding = isEqualTo(other) infix fun NumberExpression.eq(other: ObservableNumberValue): BooleanBinding = isEqualTo(other) infix fun NumberExpression.le(other: Int): BooleanBinding = lessThanOrEqualTo(other) infix fun NumberExpression.le(other: Long): BooleanBinding = lessThanOrEqualTo(other) infix fun NumberExpression.le(other: Float): BooleanBinding = lessThanOrEqualTo(other) infix fun NumberExpression.le(other: Double): BooleanBinding = lessThanOrEqualTo(other) infix fun NumberExpression.le(other: ObservableNumberValue): BooleanBinding = lessThanOrEqualTo(other) infix fun NumberExpression.lt(other: Int): BooleanBinding = lessThan(other) infix fun NumberExpression.lt(other: Long): BooleanBinding = lessThan(other) infix fun NumberExpression.lt(other: Float): BooleanBinding = lessThan(other) infix fun NumberExpression.lt(other: Double): BooleanBinding = lessThan(other) infix fun NumberExpression.lt(other: ObservableNumberValue): BooleanBinding = lessThan(other) @Suppress("EXTENSION_SHADOWED_BY_MEMBER") operator fun BooleanExpression.not(): BooleanBinding = not() infix fun BooleanExpression.and(other: Boolean): BooleanBinding = and(SimpleBooleanProperty(other)) infix fun BooleanExpression.and(other: ObservableBooleanValue): BooleanBinding = and(other) infix fun BooleanExpression.or(other: Boolean): BooleanBinding = or(SimpleBooleanProperty(other)) infix fun BooleanExpression.or(other: ObservableBooleanValue): BooleanBinding = or(other) infix fun BooleanExpression.xor(other: Boolean): BooleanBinding = booleanBinding(this) { get() xor other } infix fun BooleanExpression.xor(other: ObservableBooleanValue): BooleanBinding = booleanBinding(this, other) { get() xor other.get() } infix fun BooleanExpression.eq(other: Boolean): BooleanBinding = isEqualTo(SimpleBooleanProperty(other)) infix fun BooleanExpression.eq(other: ObservableBooleanValue): BooleanBinding = isEqualTo(other) operator fun StringExpression.plus(other: Any): StringExpression = concat(other) operator fun StringProperty.plusAssign(other: Any) { value += other } operator fun StringExpression.get(index: Int): Binding<Char?> = objectBinding(this) { if (index < get().length) get()[index] else null } operator fun StringExpression.get(index: ObservableIntegerValue): Binding<Char?> = objectBinding(this, index) { if (index < get().length) get()[index.get()] else null } operator fun StringExpression.get(start: Int, end: Int): StringBinding = stringBinding(this) { get().subSequence(start, end).toString() } operator fun StringExpression.get(start: ObservableIntegerValue, end: Int): StringBinding = stringBinding(this, start) { get().subSequence(start.get(), end).toString() } operator fun StringExpression.get(start: Int, end: ObservableIntegerValue): StringBinding = stringBinding(this, end) { get().subSequence(start, end.get()).toString() } operator fun StringExpression.get(start: ObservableIntegerValue, end: ObservableIntegerValue): StringBinding = stringBinding(this, start, end) { get().subSequence(start.get(), end.get()).toString() } operator fun StringExpression.unaryMinus(): StringBinding = stringBinding(this) { get().reversed() } operator fun StringExpression.compareTo(other: String): Int = get().compareTo(other) operator fun StringExpression.compareTo(other: ObservableStringValue): Int = get().compareTo(other.get()) infix fun StringExpression.gt(other: String): BooleanBinding = greaterThan(other) infix fun StringExpression.gt(other: ObservableStringValue): BooleanBinding = greaterThan(other) infix fun StringExpression.ge(other: String): BooleanBinding = greaterThanOrEqualTo(other) infix fun StringExpression.ge(other: ObservableStringValue): BooleanBinding = greaterThanOrEqualTo(other) infix fun StringExpression.eq(other: String): BooleanBinding = isEqualTo(other) infix fun StringExpression.eq(other: ObservableStringValue): BooleanBinding = isEqualTo(other) infix fun StringExpression.le(other: String): BooleanBinding = lessThanOrEqualTo(other) infix fun StringExpression.le(other: ObservableStringValue): BooleanBinding = lessThanOrEqualTo(other) infix fun StringExpression.lt(other: String): BooleanBinding = lessThan(other) infix fun StringExpression.lt(other: ObservableStringValue): BooleanBinding = lessThan(other) fun ObservableValue<String>.isBlank(): BooleanBinding = booleanBinding { it?.isBlank() ?: true } fun ObservableValue<String>.isNotBlank(): BooleanBinding = booleanBinding { it?.isNotBlank() ?: false } infix fun StringExpression.eqIgnoreCase(other: String): BooleanBinding = isEqualToIgnoreCase(other) infix fun StringExpression.eqIgnoreCase(other: ObservableStringValue): BooleanBinding = isEqualToIgnoreCase(other) fun <T> ObservableValue<T>.integerBinding(vararg dependencies: Observable, op: (T?) -> Int): IntegerBinding = Bindings.createIntegerBinding(Callable { op(value) }, this, *dependencies) fun <T : Any> integerBinding(receiver: T, vararg dependencies: Observable, op: T.() -> Int): IntegerBinding = Bindings.createIntegerBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) fun <T> ObservableValue<T>.longBinding(vararg dependencies: Observable, op: (T?) -> Long): LongBinding = Bindings.createLongBinding(Callable { op(value) }, this, *dependencies) fun <T : Any> longBinding(receiver: T, vararg dependencies: Observable, op: T.() -> Long): LongBinding = Bindings.createLongBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) fun <T> ObservableValue<T>.doubleBinding(vararg dependencies: Observable, op: (T?) -> Double): DoubleBinding = Bindings.createDoubleBinding(Callable { op(value) }, this, *dependencies) fun <T : Any> doubleBinding(receiver: T, vararg dependencies: Observable, op: T.() -> Double): DoubleBinding = Bindings.createDoubleBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) fun <T> ObservableValue<T>.floatBinding(vararg dependencies: Observable, op: (T?) -> Float): FloatBinding = Bindings.createFloatBinding(Callable { op(value) }, this, *dependencies) fun <T : Any> floatBinding(receiver: T, vararg dependencies: Observable, op: T.() -> Float): FloatBinding = Bindings.createFloatBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) fun <T> ObservableValue<T>.booleanBinding(vararg dependencies: Observable, op: (T?) -> Boolean): BooleanBinding = Bindings.createBooleanBinding(Callable { op(value) }, this, *dependencies) fun <T : Any> booleanBinding(receiver: T, vararg dependencies: Observable, op: T.() -> Boolean): BooleanBinding = Bindings.createBooleanBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) /** * A Boolean binding that tracks all items in an observable list and create an observable boolean * value by anding together an observable boolean representing each element in the observable list. * Whenever the list changes, the binding is updated as well */ fun <T : Any> booleanListBinding(list: ObservableList<T>, defaultValue: Boolean = false, itemToBooleanExpr: T.() -> BooleanExpression): BooleanExpression { val facade = SimpleBooleanProperty() fun rebind() { if (list.isEmpty()) { facade.unbind() facade.value = defaultValue } else { facade.cleanBind(list.map(itemToBooleanExpr).reduce { a, b -> a.and(b) }) } } list.onChange { rebind() } rebind() return facade } fun <T> ObservableValue<T>.stringBinding(vararg dependencies: Observable, op: (T?) -> String?): StringBinding = Bindings.createStringBinding(Callable { op(value) }, this, *dependencies) fun <T : Any> stringBinding(receiver: T, vararg dependencies: Observable, op: T.() -> String?): StringBinding = Bindings.createStringBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) fun <T, R> ObservableValue<T>.objectBinding(vararg dependencies: Observable, op: (T?) -> R?): Binding<R?> = Bindings.createObjectBinding(Callable { op(value) }, this, *dependencies) fun <T : Any, R> objectBinding(receiver: T, vararg dependencies: Observable, op: T.() -> R?): ObjectBinding<R?> = Bindings.createObjectBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) fun <T : Any, R> nonNullObjectBinding(receiver: T, vararg dependencies: Observable, op: T.() -> R): ObjectBinding<R> = Bindings.createObjectBinding(Callable { receiver.op() }, *createObservableArray(receiver, *dependencies)) private fun <T> createObservableArray(receiver: T, vararg dependencies: Observable): Array<out Observable> = if (receiver is Observable) arrayOf(receiver, *dependencies) else dependencies /* Generate a calculated IntegerProperty that keeps track of the number of items in this ObservableList */ val ObservableList<*>.sizeProperty: IntegerBinding get() = integerBinding(this) { size } /** * Assign the value from the creator to this WritableValue if and only if it is currently null */ fun <T> WritableValue<T>.assignIfNull(creator: () -> T) { if (value == null) value = creator() } fun Double.toProperty(): DoubleProperty = SimpleDoubleProperty(this) fun Float.toProperty(): FloatProperty = SimpleFloatProperty(this) fun Long.toProperty(): LongProperty = SimpleLongProperty(this) fun Int.toProperty(): IntegerProperty = SimpleIntegerProperty(this) fun Boolean.toProperty(): BooleanProperty = SimpleBooleanProperty(this) fun String.toProperty(): StringProperty = SimpleStringProperty(this) fun String?.toProperty() = SimpleStringProperty(this ?: "") fun Double?.toProperty() = SimpleDoubleProperty(this ?: 0.0) fun Float?.toProperty() = SimpleFloatProperty(this ?: 0.0F) fun Long?.toProperty() = SimpleLongProperty(this ?: 0L) fun Boolean?.toProperty() = SimpleBooleanProperty(this ?: false) fun <T : Any> T?.toProperty() = SimpleObjectProperty<T>(this) /** * Convert the given key in this map to a Property using the given propertyGenerator function. * * The generator is passed the initial value corresponding to the given key. * * Changes to the generated Property will automatically be written back into the map. */ @Suppress("UNCHECKED_CAST") fun <S, V, X : V> MutableMap<S, V>.toProperty(key: S, propertyGenerator: (X?) -> Property<X>): Property<X> { val initialValue = this[key] as X? val property = propertyGenerator(initialValue) property.onChange { this[key] = it as X } return property } /** * Convenience SimpleXXXProperty function builders */ fun booleanProperty(value: Boolean = false): BooleanProperty = SimpleBooleanProperty(value) fun doubleProperty(value: Double = 0.0): DoubleProperty = SimpleDoubleProperty(value) fun floatProperty(value: Float = 0F): FloatProperty = SimpleFloatProperty(value) fun intProperty(value: Int = 0): IntegerProperty = SimpleIntegerProperty(value) fun <V> listProperty(value: ObservableList<V>? = null): ListProperty<V> = SimpleListProperty(value) fun <V> listProperty(vararg values: V): ListProperty<V> = SimpleListProperty(values.toMutableList().asObservable()) fun longProperty(value: Long): LongProperty = SimpleLongProperty(value) fun <K, V> mapProperty(value: ObservableMap<K, V>? = null): MapProperty<K, V> = SimpleMapProperty(value) fun <T> objectProperty(value: T? = null): ObjectProperty<T> = SimpleObjectProperty(value) fun <V> setProperty(value: ObservableSet<V>? = null): SetProperty<V> = SimpleSetProperty(value) fun stringProperty(value: String? = null): StringProperty = SimpleStringProperty(value)
apache-2.0
e2fda57f7165906466a66b468eea62c1
48.093023
199
0.762639
4.591228
false
false
false
false
apixandru/intellij-community
java/java-analysis-api/src/com/intellij/codeInsight/intention/JvmCommonIntentionActionsFactory.kt
3
4718
/* * 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 com.intellij.codeInsight.intention import com.intellij.lang.Language import com.intellij.lang.LanguageExtension import com.intellij.psi.PsiModifier import com.intellij.psi.PsiType import com.intellij.psi.PsiTypeParameter import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UClass import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UParameter /** * Extension Point provides language-abstracted code modifications for JVM-based languages. * * Each method should return nullable code modification ([IntentionAction]) or list of code modifications which could be empty. * If method returns `null` or empty list this means that operation on given elements is not supported or not yet implemented for a language. * * Every new added method should return `null` or empty list by default and then be overridden in implementations for each language if it is possible. * * @since 2017.2 */ @ApiStatus.Experimental @Deprecated("to be removed in 2017.3", ReplaceWith("com.intellij.lang.jvm.actions.JvmCommonIntentionActionsFactory")) abstract class JvmCommonIntentionActionsFactory { open fun createChangeModifierAction(declaration: UDeclaration, @PsiModifier.ModifierConstant modifier: String, shouldPresent: Boolean): IntentionAction? = null open fun createAddCallableMemberActions(info: MethodInsertionInfo): List<IntentionAction> = emptyList() open fun createAddBeanPropertyActions(uClass: UClass, propertyName: String, @PsiModifier.ModifierConstant visibilityModifier: String, propertyType: PsiType, setterRequired: Boolean, getterRequired: Boolean): List<IntentionAction> = emptyList() companion object : LanguageExtension<JvmCommonIntentionActionsFactory>( "com.intellij.codeInsight.intention.jvmCommonIntentionActionsFactory") { @JvmStatic override fun forLanguage(l: Language): JvmCommonIntentionActionsFactory? = super.forLanguage(l) } } @Deprecated("to be removed in 2017.3", ReplaceWith("com.intellij.lang.jvm.actions.JvmCommonIntentionActionsFactory")) sealed class MethodInsertionInfo( val containingClass: UClass, @PsiModifier.ModifierConstant val modifiers: List<String> = emptyList(), val typeParams: List<PsiTypeParameter> = emptyList(), val parameters: List<UParameter> = emptyList() ) { companion object { @JvmStatic fun constructorInfo(containingClass: UClass, parameters: List<UParameter>) = Constructor(containingClass = containingClass, parameters = parameters) @JvmStatic fun simpleMethodInfo(containingClass: UClass, methodName: String, @PsiModifier.ModifierConstant modifier: String, returnType: PsiType, parameters: List<UParameter>) = Method(name = methodName, modifiers = listOf(modifier), containingClass = containingClass, returnType = returnType, parameters = parameters) } @Deprecated("to be removed in 2017.3", ReplaceWith("com.intellij.lang.jvm.actions.JvmCommonIntentionActionsFactory")) class Method( containingClass: UClass, val name: String, modifiers: List<String> = emptyList(), typeParams: List<PsiTypeParameter> = emptyList(), val returnType: PsiType, parameters: List<UParameter> = emptyList(), val isAbstract: Boolean = false ) : MethodInsertionInfo(containingClass, modifiers, typeParams, parameters) @Deprecated("to be removed in 2017.3", ReplaceWith("com.intellij.lang.jvm.actions.JvmCommonIntentionActionsFactory")) class Constructor( containingClass: UClass, modifiers: List<String> = emptyList(), typeParams: List<PsiTypeParameter> = emptyList(), parameters: List<UParameter> = emptyList() ) : MethodInsertionInfo(containingClass, modifiers, typeParams, parameters) }
apache-2.0
1ae25ba3ae53e49593adff46ec2c1fa9
41.9
150
0.708775
5.271508
false
false
false
false
icapps/niddler-ui
client-lib/src/main/kotlin/com/icapps/niddler/lib/export/har/Model.kt
1
4165
package com.icapps.niddler.lib.export.har import java.text.SimpleDateFormat import java.util.* /** * @author Nicola Verbeeck * @date 09/11/2017. */ data class Creator( val name: String, val version: String = "1.2", val comment: String? = null ) data class Header( val name: String, val value: String, val comment: String? = null ) typealias QueryParameter = Header data class Param( val name: String, val value: String? = null, val fileName: String? = null, val contentType: String? = null, val comment: String? = null ) data class PostData( val mimeType: String, val params: List<Param>, val text: String, val comment: String? = null ) class PostDataBuilder { var mimeType: String? = null var params: List<Param> = emptyList() var text: String? = null var comment: String? = null fun withMime(mime: String): PostDataBuilder { mimeType = mime return this } fun withParams(params: List<Param>): PostDataBuilder { this.params = params return this } fun withText(text: String): PostDataBuilder { this.text = text return this } fun withComment(comment: String?): PostDataBuilder { this.comment = comment return this } fun build(): PostData { return PostData(mimeType = mimeType ?: "", params = params, text = text ?: "", comment = comment) } } data class Request( val method: String, val url: String, val httpVersion: String, val headers: List<Header>, val queryString: List<QueryParameter>, val postData: PostData?, val cookies: List<Any> = emptyList(), val headersSize: Long = -1, val bodySize: Long = -1, val comment: String? = null ) data class Content( val size: Long, val mimeType: String, val text: String?, val encoding: String?, val comment: String? = null ) class ContentBuilder { var size: Long? = null var mimeType: String? = null var text: String? = null var encoding: String? = null var comment: String? = null fun withSize(size: Long): ContentBuilder { this.size = size return this } fun withMime(mime: String): ContentBuilder { this.mimeType = mime return this } fun withText(text: String?): ContentBuilder { this.text = text return this } fun withEncoding(encoding: String?): ContentBuilder { this.encoding = encoding return this } fun comment(comment: String?): ContentBuilder { this.comment = comment return this } fun build(): Content { return Content( size = size ?: -1, mimeType = mimeType ?: "", text = text, encoding = encoding, comment = comment ) } } data class Response( val status: Int, val statusText: String, val httpVersion: String, val content: Content, val headers: List<Header>, val redirectURL: String = "", val cookies: List<Any> = emptyList(), val headersSize: Long = -1, val bodySize: Long = -1, val comment: String? = null ) class Cache data class Timings( val send: Double, val wait: Double, val receive: Double, val comment: String? = null ) data class Entry( val startedDateTime: String, val time: Double, val request: Request, val response: Response, val cache: Cache, val timings: Timings, val comment: String? = null ) { companion object { val TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" fun format(date: Date): String { return SimpleDateFormat(TIME_FORMAT).format(date) } } } data class Log( val version: String, val creator: Creator, val entries: List<Entry>, val comment: String? = null )
apache-2.0
b925592ba255bab54be42f07ab25c9a2
21.89011
61
0.565426
4.361257
false
false
false
false
mihmuh/IntelliJConsole
Konsole/src/com/intellij/idekonsole/KToolWindow.kt
1
1699
package com.intellij.idekonsole import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import java.awt.BorderLayout import javax.swing.JPanel class KToolWindow(val project: Project) : JPanel(), Disposable { companion object { val LOG = Logger.getInstance(KToolWindow::class.java) } init { layout = BorderLayout() val actionGroup = ActionManager.getInstance().getAction("KToolWindow.Toolbar") as ActionGroup val toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLBAR, actionGroup, false) toolbar.setTargetComponent(this) add(toolbar.component, BorderLayout.WEST) for (action in actionGroup.getChildren(null)) { action.registerCustomShortcutSet(action.shortcutSet, this) } try { val editor = KEditor(project) Disposer.register(this, editor) DataManager.registerDataProvider(this, { key -> if (KDataKeys.K_TOOL_WINDOW.`is`(key)) { this@KToolWindow } else if (KDataKeys.K_EDITOR.`is`(key)) { editor } else { null } }) add(editor.getComponent(), BorderLayout.CENTER) } catch(e: Exception) { LOG.error(e) } } override fun dispose() { } }
gpl-3.0
a3cef86bb9450d1e309932c68cec66a6
31.056604
111
0.64744
4.813031
false
false
false
false
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/synclog/SyncLogFragment.kt
1
4185
/* * LaaNo Android application * * @author Aleksandr Borisenko <[email protected]> * Copyright (C) 2017 Aleksandr Borisenko * * 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 com.bytesforge.linkasanote.synclog import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bytesforge.linkasanote.data.SyncResult import com.bytesforge.linkasanote.databinding.FragmentSyncLogBinding class SyncLogFragment : Fragment(), SyncLogContract.View { private var presenter: SyncLogContract.Presenter? = null private var viewModel: SyncLogContract.ViewModel? = null var adapter: SyncLogAdapter? = null var rvLayoutManager: LinearLayoutManager? = null private var rvLayoutState: Parcelable? = null override fun onResume() { super.onResume() presenter!!.subscribe() } override fun onPause() { super.onPause() presenter!!.unsubscribe() } override val isActive: Boolean get() = isAdded override fun setPresenter(presenter: SyncLogContract.Presenter) { this.presenter = presenter } override fun setViewModel(viewModel: SyncLogContract.ViewModel) { this.viewModel = viewModel } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentSyncLogBinding.inflate(inflater, container, false) viewModel!!.setInstanceState(savedInstanceState) setRvLayoutState(savedInstanceState) binding.viewModel = viewModel as SyncLogViewModel? setupSyncLogRecyclerView(binding.rvSyncLog) return binding.root } private fun setupSyncLogRecyclerView(rvSyncLog: RecyclerView) { val syncResults: List<SyncResult> = ArrayList() adapter = SyncLogAdapter(syncResults, (viewModel as SyncLogViewModel?)!!) rvSyncLog.adapter = adapter rvLayoutManager = LinearLayoutManager(context) rvSyncLog.layoutManager = rvLayoutManager } private fun setRvLayoutState(savedInstanceState: Bundle?) { if (savedInstanceState != null) { rvLayoutState = savedInstanceState.getParcelable( SyncLogViewModel.STATE_RECYCLER_LAYOUT ) } } private fun saveRvLayoutState(outState: Bundle) { outState.putParcelable( SyncLogViewModel.STATE_RECYCLER_LAYOUT, rvLayoutManager!!.onSaveInstanceState() ) } private fun applyRvLayoutState() { if (rvLayoutManager != null && rvLayoutState != null) { rvLayoutManager!!.onRestoreInstanceState(rvLayoutState) rvLayoutState = null } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) viewModel!!.saveInstanceState(outState) saveRvLayoutState(outState) } override fun showSyncResults(syncResults: List<SyncResult>) { adapter!!.swapItems(syncResults) viewModel!!.setListSize(syncResults.size) applyRvLayoutState() } companion object { private val TAG = SyncLogFragment::class.java.simpleName private val TAG_E = SyncLogFragment::class.java.canonicalName fun newInstance(): SyncLogFragment { return SyncLogFragment() } } }
gpl-3.0
4967e478eeaeafda052e4a3ff43f8213
32.758065
81
0.703704
5.205224
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/core/settings/Settings.kt
1
7609
package com.peterlaurence.trekme.core.settings import com.peterlaurence.trekme.core.TrekMeContext import com.peterlaurence.trekme.util.FileUtils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.serialization.Serializable import kotlinx.serialization.UnstableDefault import kotlinx.serialization.json.Json import java.io.File /** * Holds global settings of TrekMe and exposes public methods to read/update those settings. * This class is thread safe (as its internal [FileSettingsHandler] is specifically designed * to have no shared mutable state). */ object Settings { private val settingsHandler = FileSettingsHandler() /** * Get the current application directory as [File]. * This implementation tries to get it from the configuration file. Since this file might have * been modified by an human, a check is done to fallback to the default application directory * if the path isn't among the list of possible paths. * It's also a security in the case the application directories change across versions. */ suspend fun getAppDir(): File? { return settingsHandler.getLastSetting().appDir.let { if (checkAppPath(it)) { File(it) } else { TrekMeContext.defaultAppDir } } } /** * Set the application directory. * This implementation first reads the current settings, creates a new instance of * [SettingsData], then then gives it to the [SettingsHandler] for write. */ suspend fun setAppDir(file: File) { if (checkAppPath(file.absolutePath)) { val new = settingsHandler.getLastSetting().copy(appDir = file.absolutePath) settingsHandler.writeSetting(new) } } private fun checkAppPath(path: String): Boolean { return TrekMeContext.mapsDirList?.map { it.absolutePath }?.contains(path) ?: false } suspend fun getStartOnPolicy(): StartOnPolicy { return settingsHandler.getLastSetting().startOnPolicy } suspend fun setStartOnPolicy(policy: StartOnPolicy) { val new = settingsHandler.getLastSetting().copy(startOnPolicy = policy) settingsHandler.writeSetting(new) } suspend fun setMagnifyingFactor(factor: Int) { val new = settingsHandler.getLastSetting().copy(magnifyingFactor = factor) settingsHandler.writeSetting(new) } suspend fun getMagnifyingFactor(): Int = settingsHandler.getLastSetting().magnifyingFactor suspend fun getRotationMode(): RotationMode { return settingsHandler.getLastSetting().rotationMode } suspend fun setRotationMode(mode: RotationMode) { val new = settingsHandler.getLastSetting().copy(rotationMode = mode) settingsHandler.writeSetting(new) } /** * @return The last map id, or null if it's undefined. The returned id is guarantied to be not * empty. */ suspend fun getLastMapId(): Int? { val id = settingsHandler.getLastSetting().lastMapId return if (id != -1) { id } else { null } } /** * Set and saves the last map id, for further use. */ suspend fun setLastMapId(id: Int) { val new = settingsHandler.getLastSetting().copy(lastMapId = id) settingsHandler.writeSetting(new) } } @Serializable private data class SettingsData(val appDir: String, val startOnPolicy: StartOnPolicy = StartOnPolicy.MAP_LIST, val lastMapId: Int = -1, val magnifyingFactor: Int = 0, val rotationMode: RotationMode = RotationMode.NONE) enum class StartOnPolicy { MAP_LIST, LAST_MAP } enum class RotationMode { NONE, FOLLOW_ORIENTATION, FREE } private interface SettingsHandler { suspend fun writeSetting(settingsData: SettingsData) suspend fun getLastSetting(): SettingsData } private class FileSettingsHandler : SettingsHandler { private val settingsFile = TrekMeContext.getSettingsFile() /* Channels */ private val settingsToWrite = Channel<SettingsData>() private val requests = Channel<Unit>(capacity = 1) private val lastSettings = Channel<SettingsData>() init { GlobalScope.actor(settingsToWrite, requests, lastSettings) } override suspend fun writeSetting(settingsData: SettingsData) { settingsToWrite.send(settingsData) } /** * The internal [requests] channel having a capacity of 1, the order in which this method * returns a [SettingsData] instance is preserved. For example, if two consumers call * [getLastSetting] at approximately the same time, the first one which adds an element to * [requests] is guaranteed to receive a [SettingsData] instance before the other consumer which * is then suspended trying to send an element to [requests]. */ override suspend fun getLastSetting(): SettingsData { requests.send(Unit) return lastSettings.receive() } /** * The core coroutine that enables concurrent read/write of [SettingsData]. * * [settingsToWrite] is the receive channel that is consumed to write into the config file * * [requests] is the receive channel that is consumed to update the last value of the * [lastSettings] channel. * * This way, the last value of [SettingsData] is stored in a thread-safe way. */ private fun CoroutineScope.actor(settingsToWrite: ReceiveChannel<SettingsData>, requests: ReceiveChannel<Unit>, lastSettings: SendChannel<SettingsData>) { launch { var lastSetting = readSettingsOrDefault() lastSettings.send(lastSetting) while (true) { select<Unit> { settingsToWrite.onReceive { lastSetting = it it.save() } requests.onReceive { lastSettings.send(lastSetting) } } } } } private fun readSettingsOrDefault(): SettingsData { return try { readSettings() } catch (e: Exception) { e.printStackTrace() /* In case of any error, return default settings */ SettingsData(TrekMeContext.defaultAppDir?.absolutePath ?: "error") } } @UnstableDefault private fun readSettings(): SettingsData { // 1- get the settings file from TrekMeContext val file = settingsFile ?: throw Exception("No settings file") // 2- if it exists, read it if (file.exists()) { val json = FileUtils.getStringFromFile(file) /* This may throw Exceptions */ return Json.parse(SettingsData.serializer(), json) } throw Exception("Settings file path is wrong") } @UnstableDefault private fun SettingsData.save(): Boolean { return try { val st = Json.stringify(SettingsData.serializer(), this) FileUtils.writeToFile(st, settingsFile) true } catch (e: Exception) { false } } }
gpl-3.0
149fcb303ec8be7f79c408c4fdcc58e2
33.748858
100
0.643711
5.186776
false
false
false
false
TeamWizardry/LibrarianLib
modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/kotlin/Collections.kt
1
5038
@file:Suppress("unused") package com.teamwizardry.librarianlib.core.util.kotlin import java.util.Collections import java.util.IdentityHashMap import java.util.NavigableMap import java.util.NavigableSet import java.util.SortedMap import java.util.SortedSet import java.util.TreeMap import java.util.TreeSet import java.util.WeakHashMap // Unmodifiable/synchronized wrappers ================================================================================== public fun <T> Collection<T>.unmodifiableView(): Collection<T> = Collections.unmodifiableCollection(this) public fun <T> Set<T>.unmodifiableView(): Set<T> = Collections.unmodifiableSet(this) public fun <T> SortedSet<T>.unmodifiableView(): SortedSet<T> = Collections.unmodifiableSortedSet(this) public fun <T> NavigableSet<T>.unmodifiableView(): NavigableSet<T> = Collections.unmodifiableNavigableSet(this) public fun <T> List<T>.unmodifiableView(): List<T> = Collections.unmodifiableList(this) public fun <K, V> Map<K, V>.unmodifiableView(): Map<K, V> = Collections.unmodifiableMap(this) public fun <K, V> SortedMap<K, V>.unmodifiableView(): SortedMap<K, V> = Collections.unmodifiableSortedMap(this) public fun <K, V> NavigableMap<K, V>.unmodifiableView(): NavigableMap<K, V> = Collections.unmodifiableNavigableMap(this) public fun <T> Collection<T>.unmodifiableCopy(): Collection<T> = Collections.unmodifiableCollection(this.toList()) public fun <T> Set<T>.unmodifiableCopy(): Set<T> = Collections.unmodifiableSet(this.toSet()) public fun <T> SortedSet<T>.unmodifiableCopy(): SortedSet<T> = Collections.unmodifiableSortedSet(this.toSortedSet(this.comparator())) public fun <T> NavigableSet<T>.unmodifiableCopy(): NavigableSet<T> = Collections.unmodifiableNavigableSet(TreeSet(this)) public fun <T> List<T>.unmodifiableCopy(): List<T> = Collections.unmodifiableList(this.toList()) public fun <K, V> Map<K, V>.unmodifiableCopy(): Map<K, V> = Collections.unmodifiableMap(this.toMap()) public fun <K, V> SortedMap<K, V>.unmodifiableCopy(): SortedMap<K, V> = Collections.unmodifiableSortedMap(this.toSortedMap(this.comparator())) public fun <K, V> NavigableMap<K, V>.unmodifiableCopy(): NavigableMap<K, V> = Collections.unmodifiableNavigableMap(TreeMap(this)) public fun <T> MutableCollection<T>.synchronized(): MutableCollection<T> = Collections.synchronizedCollection(this) public fun <T> MutableSet<T>.synchronized(): MutableSet<T> = Collections.synchronizedSet(this) public fun <T> SortedSet<T>.synchronized(): SortedSet<T> = Collections.synchronizedSortedSet(this) public fun <T> NavigableSet<T>.synchronized(): NavigableSet<T> = Collections.synchronizedNavigableSet(this) public fun <T> MutableList<T>.synchronized(): MutableList<T> = Collections.synchronizedList(this) public fun <K, V> MutableMap<K, V>.synchronized(): MutableMap<K, V> = Collections.synchronizedMap(this) public fun <K, V> SortedMap<K, V>.synchronized(): SortedMap<K, V> = Collections.synchronizedSortedMap(this) public fun <K, V> NavigableMap<K, V>.synchronized(): NavigableMap<K, V> = Collections.synchronizedNavigableMap(this) // Identity map ======================================================================================================== public fun <K, V> identityMapOf(): MutableMap<K, V> = IdentityHashMap() public fun <K, V> identityMapOf(vararg pairs: Pair<K, V>): MutableMap<K, V> { return IdentityHashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) } } public fun <T> identitySetOf(): MutableSet<T> = Collections.newSetFromMap(IdentityHashMap()) public fun <T> identitySetOf(vararg elements: T): MutableSet<T> { val map = IdentityHashMap<T, Boolean>(mapCapacity(elements.size)) return elements.toCollection(Collections.newSetFromMap(map)) } public fun <K, V> Map<K, V>.toIdentityMap(): MutableMap<K, V> = IdentityHashMap(this) public fun <T> Set<T>.toIdentitySet(): MutableSet<T> = identitySetOf<T>().also { it.addAll(this) } public fun <K, V> Map<K, V>.unmodifiableIdentityCopy(): Map<K, V> = Collections.unmodifiableMap(this.toIdentityMap()) public fun <T> Set<T>.unmodifiableIdentityCopy(): Set<T> = Collections.unmodifiableSet(this.toIdentitySet()) // Weak set ============================================================================================================ public fun <T> weakSetOf(): MutableSet<T> = Collections.newSetFromMap(WeakHashMap()) public fun <T> weakSetOf(vararg elements: T): MutableSet<T> { val set: MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>(mapCapacity(elements.size))) return elements.toCollection(set) } // Private utils ======================================================================================================= // ripped from the Kotlin runtime: private fun mapCapacity(expectedSize: Int): Int { if (expectedSize < 3) { return expectedSize + 1 } if (expectedSize < INT_MAX_POWER_OF_TWO) { return expectedSize + expectedSize / 3 } return Int.MAX_VALUE // any large value } private const val INT_MAX_POWER_OF_TWO: Int = Int.MAX_VALUE / 2 + 1
lgpl-3.0
70d6b6ca55a09b28e6733c467a580ef7
58.97619
142
0.697102
4.156766
false
false
false
false
mvarnagiris/expensius
app-core/src/test/kotlin/com/mvcoding/expensius/feature/tag/TagsPresenterTest.kt
1
6958
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.feature.tag import com.mvcoding.expensius.data.DataSource import com.mvcoding.expensius.data.DataWriter import com.mvcoding.expensius.data.RealtimeData import com.mvcoding.expensius.data.RealtimeData.* import com.mvcoding.expensius.feature.ModelDisplayType import com.mvcoding.expensius.feature.ModelDisplayType.VIEW_ARCHIVED import com.mvcoding.expensius.feature.ModelDisplayType.VIEW_NOT_ARCHIVED import com.mvcoding.expensius.feature.tag.TagsPresenter.TagMove import com.mvcoding.expensius.model.NullModels.noTag import com.mvcoding.expensius.model.Tag import com.mvcoding.expensius.model.Title import com.mvcoding.expensius.model.extensions.aString import com.mvcoding.expensius.model.extensions.aTag import com.mvcoding.expensius.model.extensions.withOrder import com.mvcoding.expensius.rxSchedulers import com.nhaarman.mockito_kotlin.* import org.junit.Before import org.junit.Test import rx.lang.kotlin.BehaviorSubject import rx.lang.kotlin.PublishSubject class TagsPresenterTest { val tagsSubject = BehaviorSubject<RealtimeData<Tag>>() val tagSelectsSubject = PublishSubject<Tag>() val createTagRequestsSubject = PublishSubject<Unit>() val displayArchivedTagsSubject = PublishSubject<Unit>() val tagMovesSubject = PublishSubject<TagsPresenter.TagMove>() val tagsSource = mock<DataSource<RealtimeData<Tag>>>() val tagsWriter = mock<DataWriter<Set<Tag>>>() val view: TagsPresenter.View = mock() val inOrder = inOrder(view) @Before fun setUp() { whenever(view.tagSelects()).thenReturn(tagSelectsSubject) whenever(view.createTagRequests()).thenReturn(createTagRequestsSubject) whenever(view.archivedTagsRequests()).thenReturn(displayArchivedTagsSubject) whenever(view.tagMoves()).thenReturn(tagMovesSubject) whenever(tagsSource.data()).thenReturn(tagsSubject) } @Test fun `shows model display type not archived and show archived tags request`() { presenter(VIEW_NOT_ARCHIVED).attach(view) verify(view).showModelDisplayType(VIEW_NOT_ARCHIVED) verify(view).showArchivedTagsRequest() } @Test fun `shows model display type archived and does not show archived tags request`() { presenter(VIEW_ARCHIVED).attach(view) verify(view).showModelDisplayType(VIEW_ARCHIVED) verify(view, never()).showArchivedTagsRequest() } @Test fun `shows loading until first data comes and then displays all types of realtime data as it comes`() { val tags = listOf(aTag(), aTag(), aTag()) val addedTags = listOf(aTag(), aTag(), aTag()) val changedTags = listOf(addedTags.first().copy(title = Title(aString()))) val removedTags = listOf(addedTags.last()) val movedTags = listOf(tags.first()) presenter().attach(view) inOrder.verify(view).showLoading() receiveTags(tags) inOrder.verify(view).hideLoading() inOrder.verify(view).showItems(tags) receiveTagsAdded(addedTags, 3) inOrder.verify(view).showAddedItems(addedTags, 3) receiveTagsChanged(changedTags, 3) inOrder.verify(view).showChangedItems(changedTags, 3) receiveTagsChanged(changedTags, 3) inOrder.verify(view).showChangedItems(changedTags, 3) receiveTagsRemoved(removedTags, 5) inOrder.verify(view).showRemovedItems(removedTags, 5) receiveTagsMoved(movedTags, 0, 5) inOrder.verify(view).showMovedItems(movedTags, 0, 5) } @Test fun `displays tag edit when selecting a tag and display type is view`() { val tag = aTag() presenter().attach(view) selectTag(tag) verify(view).displayTagEdit(tag) } @Test fun `displays tag edit when create tag is requested`() { presenter().attach(view) requestCreateTag() verify(view).displayTagEdit(noTag) } @Test fun `displays archived tags`() { presenter().attach(view) requestArchivedTags() verify(view).displayArchivedTags() } @Test fun `reorders all tags when one tag was moved up`() { val tags = listOf(aTag(), aTag(), aTag(), aTag()) val reorderedTags = listOf(tags[2].withOrder(0), tags[0].withOrder(1), tags[1].withOrder(2), tags[3].withOrder(3)) val movedItems = listOf(reorderedTags[0]) presenter().attach(view) receiveTags(tags) moveTag(2, 0) receiveTagsMoved(movedItems, 2, 0) verify(tagsWriter).write(reorderedTags.toSet()) verify(view).showMovedItems(movedItems, 2, 0) } @Test fun `reorders all tags when one tag was moved down`() { val tags = listOf(aTag(), aTag(), aTag(), aTag()) val reorderedTags = listOf(tags[1].withOrder(0), tags[2].withOrder(1), tags[0].withOrder(2), tags[3].withOrder(3)) presenter().attach(view) receiveTags(tags) moveTag(0, 2) receiveTagsMoved(listOf(reorderedTags[0]), 1, 0) receiveTagsMoved(listOf(reorderedTags[1]), 2, 1) verify(tagsWriter).write(reorderedTags.toSet()) verify(view).showMovedItems(listOf(reorderedTags[0]), 1, 0) verify(view).showMovedItems(listOf(reorderedTags[1]), 2, 1) } private fun moveTag(fromPosition: Int, toPosition: Int) = tagMovesSubject.onNext(TagMove(fromPosition, toPosition)) private fun receiveTags(tags: List<Tag>) = tagsSubject.onNext(AllItems(tags)) private fun requestCreateTag() = createTagRequestsSubject.onNext(Unit) private fun requestArchivedTags() = displayArchivedTagsSubject.onNext(Unit) private fun receiveTagsAdded(tags: List<Tag>, position: Int) = tagsSubject.onNext(AddedItems(tags, tags, position)) private fun receiveTagsChanged(tags: List<Tag>, position: Int) = tagsSubject.onNext(ChangedItems(tags, tags, position)) private fun receiveTagsRemoved(tags: List<Tag>, position: Int) = tagsSubject.onNext(RemovedItems(tags, tags, position)) private fun receiveTagsMoved(tags: List<Tag>, fromPosition: Int, toPosition: Int) = tagsSubject.onNext(MovedItems(tags, tags, fromPosition, toPosition)) private fun selectTag(tagToSelect: Tag) = tagSelectsSubject.onNext(tagToSelect) private fun presenter(modelViewType: ModelDisplayType = VIEW_NOT_ARCHIVED) = TagsPresenter(modelViewType, tagsSource, tagsWriter, rxSchedulers()) }
gpl-3.0
0de42dc3b7fd951f823c6602f3dd4299
38.765714
156
0.712705
4.321739
false
true
false
false
applivery/applivery-android-sdk
sample/src/main/java/com/applivery/sample/UserActivity.kt
1
2781
package com.applivery.sample import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.applivery.applvsdklib.Applivery import com.applivery.applvsdklib.BindUserCallback import com.applivery.applvsdklib.GetUserCallback import com.applivery.base.domain.model.UserProfile import kotlinx.android.synthetic.main.activity_user.* class UserActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user) initViews() getUser() } private fun initViews() { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) toolbar.setNavigationOnClickListener { onBackPressed() } bindUserButton.setOnClickListener { bindUser() } unBindUserButton.setOnClickListener { Applivery.unbindUser() } } private fun bindUser() { if (emailEditText.text.isEmpty()) { emailEditText.error = getString(R.string.field_required) return } val email = emailEditText.text.toString() val firstName = if (firstNameEditText.text.isNotEmpty()) { firstNameEditText.text.toString() } else { null } val lastName = if (lastNameEditText.text.isNotEmpty()) { lastNameEditText.text.toString() } else { null } val tags = if (tagsEditText.text.isNotEmpty()) { tagsEditText.text.toString().split(",") } else { null } Applivery.bindUser(email, firstName, lastName, tags, object : BindUserCallback { override fun onSuccess() { Toast.makeText(this@UserActivity, "Success", Toast.LENGTH_SHORT).show() } override fun onError(message: String) { Toast.makeText(this@UserActivity, "Error: $message", Toast.LENGTH_SHORT).show() } }) } private fun getUser() { Applivery.getUser(object : GetUserCallback { override fun onSuccess(userProfile: UserProfile) { emailEditText.setText(userProfile.email) firstNameEditText.setText(userProfile.firstName) lastNameEditText.setText(userProfile.lastName) } override fun onError(message: String) = Unit }) } companion object Navigator { fun open(context: Context) { val intent = Intent(context, UserActivity::class.java) context.startActivity(intent) } } }
apache-2.0
538c7921247a09c37f90aac8fb320a58
29.228261
95
0.639338
5.140481
false
false
false
false
TheFakeMontyOnTheRun/nehe-ndk-gles20
lesson10/app/src/main/java/br/odb/nehe/lesson10/GL2JNIActivity.kt
1
2172
package br.odb.nehe.lesson10 import android.app.Activity import android.graphics.BitmapFactory import android.view.KeyEvent import android.view.MotionEvent import java.io.IOException class GL2JNIActivity : Activity() { private var mView: GL2JNIView? = null private var running = false private var fingerX = 0f private var fingerY = 0f private var touching = false override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { when (keyCode) { KeyEvent.KEYCODE_T -> return true KeyEvent.KEYCODE_DPAD_UP -> { GL2JNILib.moveForward() return true } KeyEvent.KEYCODE_DPAD_RIGHT -> { GL2JNILib.turnRight() return true } KeyEvent.KEYCODE_DPAD_DOWN -> { GL2JNILib.moveBackward() return true } KeyEvent.KEYCODE_DPAD_LEFT -> { GL2JNILib.turnLeft() return true } KeyEvent.KEYCODE_R -> { GL2JNILib.reset() return true } } return super.onKeyDown(keyCode, event) } override fun onPause() { super.onPause() running = false mView!!.onPause() GL2JNILib.onDestroy() } override fun onResume() { super.onResume() GL2JNILib.onCreate(assets) try { GL2JNILib.setTexture( arrayOf( BitmapFactory.decodeStream(assets.open("mud.png")), BitmapFactory.decodeStream(assets.open("bricks.png")), BitmapFactory.decodeStream(assets.open("grass.png")) ) ) } catch (ignored: IOException) { } mView = GL2JNIView(application) setContentView(mView) mView!!.setOnTouchListener { v, event -> when (event.action) { MotionEvent.ACTION_UP -> { touching = false true } MotionEvent.ACTION_DOWN -> { touching = true fingerX = event.x / v.width fingerY = event.y / v.height true } MotionEvent.ACTION_MOVE -> { fingerX = event.x / v.width fingerY = event.y / v.height true } else -> false } } mView!!.onResume() Thread { running = true while (running) { try { Thread.sleep(20) if (touching) { GL2JNILib.onTouchNormalized(fingerX, fingerY) } } catch (e: InterruptedException) { e.printStackTrace() } GL2JNILib.tick() } }.start() } }
bsd-2-clause
c0975af68a58d2be2ea246b159328e62
20.303922
65
0.650092
3.23696
false
false
false
false
androidx/androidx
compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/Vertices.kt
3
2485
/* * Copyright 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.compose.ui.graphics import androidx.compose.ui.geometry.Offset import androidx.compose.ui.util.fastAny /** A set of vertex data used by [Canvas.drawVertices]. */ class Vertices( val vertexMode: VertexMode, positions: List<Offset>, textureCoordinates: List<Offset>, colors: List<Color>, indices: List<Int> ) /*extends NativeFieldWrapperClass2*/ { val positions: FloatArray val textureCoordinates: FloatArray val colors: IntArray val indices: ShortArray init { val outOfBounds: (Int) -> Boolean = { it < 0 || it >= positions.size } if (textureCoordinates.size != positions.size) throw IllegalArgumentException("positions and textureCoordinates lengths must match.") if (colors.size != positions.size) throw IllegalArgumentException("positions and colors lengths must match.") if (indices.fastAny(outOfBounds)) throw IllegalArgumentException( "indices values must be valid indices " + "in the positions list." ) this.positions = encodePointList(positions) this.textureCoordinates = encodePointList(textureCoordinates) this.colors = encodeColorList(colors) this.indices = ShortArray(indices.size) { i -> indices[i].toShort() } } private fun encodeColorList(colors: List<Color>): IntArray { return IntArray(colors.size) { i -> colors[i].toArgb() } } private fun encodePointList(points: List<Offset>): FloatArray { return FloatArray(points.size * 2) { i -> val pointIndex = i / 2 val point = points[pointIndex] if (i % 2 == 0) { point.x } else { point.y } } } }
apache-2.0
71c4398bf9a68df082c055fad27c76e2
32.146667
98
0.635412
4.601852
false
false
false
false
dropbox/Store
store/src/main/java/com/dropbox/android/external/store4/impl/FetcherController.kt
1
5592
/* * 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.dropbox.android.external.store4.impl import com.dropbox.android.external.store4.Fetcher import com.dropbox.android.external.store4.FetcherResult import com.dropbox.android.external.store4.ResponseOrigin import com.dropbox.android.external.store4.SourceOfTruth import com.dropbox.android.external.store4.StoreResponse import com.dropbox.flow.multicast.Multicaster import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEmpty import kotlinx.coroutines.withContext /** * This class maintains one and only 1 fetcher for a given [Key]. * * Any value emitted by the fetcher is sent into the [sourceOfTruth] before it is dispatched. * If [sourceOfTruth] is `null`, [enablePiggyback] is set to true by default so that previous * fetcher requests receives values dispatched by later requests even if they don't share the * request. */ internal class FetcherController<Key : Any, Input : Any, Output : Any>( /** * The [CoroutineScope] to use when collecting from the fetcher */ private val scope: CoroutineScope, /** * The function that provides the actualy fetcher flow when needed */ private val realFetcher: Fetcher<Key, Input>, /** * [SourceOfTruth] to send the data each time fetcher dispatches a value. Can be `null` if * no [SourceOfTruth] is available. */ private val sourceOfTruth: SourceOfTruthWithBarrier<Key, Input, Output>?, ) { @Suppress("USELESS_CAST") // needed for multicaster source private val fetchers = RefCountedResource( create = { key: Key -> Multicaster( scope = scope, bufferSize = 0, source = flow { emitAll(realFetcher(key)) }.map { when (it) { is FetcherResult.Data -> StoreResponse.Data( it.value, origin = ResponseOrigin.Fetcher ) as StoreResponse<Input> is FetcherResult.Error.Message -> StoreResponse.Error.Message( it.message, origin = ResponseOrigin.Fetcher ) is FetcherResult.Error.Exception -> StoreResponse.Error.Exception( it.error, origin = ResponseOrigin.Fetcher ) } }.onEmpty { emit(StoreResponse.NoNewData(ResponseOrigin.Fetcher)) }, /** * When enabled, downstream collectors are never closed, instead, they are kept active to * receive values dispatched by fetchers created after them. This makes [FetcherController] * act like a [SourceOfTruth] in the lack of a [SourceOfTruth] provided by the developer. */ piggybackingDownstream = true, onEach = { response -> response.dataOrNull()?.let { input -> sourceOfTruth?.write(key, input) } } ) }, onRelease = { _: Key, multicaster: Multicaster<StoreResponse<Input>> -> multicaster.close() } ) fun getFetcher(key: Key, piggybackOnly: Boolean = false): Flow<StoreResponse<Input>> { return flow { val fetcher = acquireFetcher(key) try { emitAll(fetcher.newDownstream(piggybackOnly)) } finally { withContext(NonCancellable) { fetchers.release(key, fetcher) } } } } /** * This functions goes to great length to prevent capturing the calling context from * [getFetcher]. The reason being that the [Flow] returned by [getFetcher] is collected on the * user's context and [acquireFetcher] will, optionally, launch a long running coroutine on the * [FetcherController]'s [scope]. In order to avoid capturing a reference to the scope we need * to: * 1) Not inline this function as that will cause the lambda to capture a reference to the * surrounding suspend lambda which, in turn, holds a reference to the user's coroutine context. * 2) Use [async]-[await] instead of * [kotlinx.coroutines.withContext] as [kotlinx.coroutines.withContext] will also hold onto a * reference to the caller's context (the LHS parameter of the new context which is used to run * the operation). */ private suspend fun acquireFetcher(key: Key) = scope.async { fetchers.acquire(key) }.await() // visible for testing internal suspend fun fetcherSize() = fetchers.size() }
apache-2.0
979c8728a632db6cb8e9942de286506d
41.687023
107
0.630186
4.849957
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/work/responses/WorkResponsesFragment.kt
2
7018
package ru.fantlab.android.ui.modules.work.responses import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.annotation.StringRes import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.ContextMenuBuilder import ru.fantlab.android.data.dao.model.ContextMenus import ru.fantlab.android.data.dao.model.Response import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.helper.PrefGetter import ru.fantlab.android.provider.rest.loadmore.OnLoadMore import ru.fantlab.android.ui.adapter.WorkResponsesAdapter import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.editor.EditorActivity import ru.fantlab.android.ui.modules.user.UserPagerActivity import ru.fantlab.android.ui.modules.work.WorkPagerMvp import ru.fantlab.android.ui.modules.work.responses.overview.ResponseOverviewActivity import ru.fantlab.android.ui.widgets.dialog.ContextMenuDialogView class WorkResponsesFragment : BaseFragment<WorkResponsesMvp.View, WorkResponsesPresenter>(), WorkResponsesMvp.View { private var workId = -1 private val onLoadMore: OnLoadMore<Int> by lazy { OnLoadMore(presenter, workId) } private val adapter: WorkResponsesAdapter by lazy { WorkResponsesAdapter(arrayListOf()) } private var workCallback: WorkPagerMvp.View? = null override fun fragmentLayout(): Int = R.layout.micro_grid_refresh_list override fun providePresenter(): WorkResponsesPresenter = WorkResponsesPresenter() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { if (savedInstanceState == null) { stateLayout.hideProgress() } stateLayout.setEmptyText(R.string.no_responses) stateLayout.setOnReloadListener(this) refresh.setOnRefreshListener(this) recycler.setEmptyView(stateLayout, refresh) adapter.listener = presenter recycler.adapter = adapter workId = arguments!!.getInt(BundleConstant.EXTRA) getLoadMore().initialize(presenter.getCurrentPage() - 1, presenter.getPreviousTotal()) recycler.addOnScrollListener(getLoadMore()) presenter.onCallApi(1, workId) fastScroller.attachRecyclerView(recycler) } override fun onAttach(context: Context) { super.onAttach(context) if (context is WorkPagerMvp.View) { workCallback = context } } override fun onDetach() { workCallback = null super.onDetach() } override fun onDestroyView() { recycler.removeOnScrollListener(getLoadMore()) super.onDestroyView() } override fun onNotifyAdapter(items: ArrayList<Response>, page: Int) { hideProgress() if (items.isEmpty()) { adapter.clear() stateLayout.showEmptyState() return } if (page <= 1) { adapter.insertItems(items) } else { adapter.addItems(items) } } override fun getLoadMore() = onLoadMore override fun onSetTabCount(count: Int) { workCallback?.onSetBadge(1, count) } override fun onItemClicked(item: Response) { ResponseOverviewActivity.startActivity(context!!, item) } override fun onItemLongClicked(position: Int, v: View?, item: Response) { if (isLoggedIn() && PrefGetter.getLoggedUser()?.id == item.userId) { val dialogView = ContextMenuDialogView() dialogView.initArguments("main", ContextMenuBuilder.buildForUserResponse(recycler.context), item, position) dialogView.show(childFragmentManager, "ContextMenuDialogView") } } override fun onItemSelected(parent: String, item: ContextMenus.MenuItem, position: Int, listItem: Any) { if (listItem is Response) when (item.id) { "vote" -> { presenter.onSendVote(listItem, position, if (item.title.contains("+")) "plus" else "minus") } "profile" -> { UserPagerActivity.startActivity(recycler.context, listItem.userName, listItem.userId, 0) } "message" -> { startActivity(Intent(activity, EditorActivity::class.java) .putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_NEW_MESSAGE) .putExtra(BundleConstant.ID, listItem.userId) ) } "edit" -> { startActivityForResult(Intent(activity, EditorActivity::class.java) .putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_EDIT_RESPONSE) .putExtra(BundleConstant.EXTRA, listItem.text) .putExtra(BundleConstant.EXTRA_TWO, listItem.id) .putExtra(BundleConstant.EXTRA_THREE, position) .putExtra(BundleConstant.ID, listItem.workId), BundleConstant.REFRESH_RESPONSE_CODE) } "delete" -> { presenter.onDeleteResponse(listItem.workId, listItem.id, position) } } else { presenter.setCurrentSort(item.id) } } override fun onResponseDelete(position: Int) { hideProgress() adapter.removeItem(position) onSetTabCount(adapter.itemCount) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { BundleConstant.REFRESH_RESPONSE_CODE -> { if (data != null) { val position = data.extras?.getInt(BundleConstant.ID) if (position != null && position != -1) { val responseNewText = data.extras?.getCharSequence(BundleConstant.EXTRA) adapter.data[position].text = responseNewText.toString() adapter.notifyItemChanged(position) } } } } } override fun onRefresh() { presenter.getResponses(1, true) } override fun onClick(v: View?) { onRefresh() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun showErrorMessage(msgRes: String?) { callback?.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { showReload() super.showMessage(titleRes, msgRes) } private fun showReload() { hideProgress() stateLayout.showReload(adapter.itemCount) } fun showSortDialog() { val dialogView = ContextMenuDialogView() val sort = presenter.getCurrentSort() dialogView.initArguments("main", ContextMenuBuilder.buildForResponseSorting(recycler.context, sort)) dialogView.show(childFragmentManager, "ContextMenuDialogView") } companion object { fun newInstance(workId: Int): WorkResponsesFragment { val view = WorkResponsesFragment() view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end() return view } } override fun onSetVote(position: Int, votesCount: String) { hideProgress() adapter.getItem(position).voteCount = votesCount.toInt() adapter.notifyItemChanged(position) } override fun onOpenContextMenu(userItem: Response) { val dialogView = ContextMenuDialogView() dialogView.initArguments("main", ContextMenuBuilder.buildForProfile(recycler.context), userItem, 0) dialogView.show(childFragmentManager, "ContextMenuDialogView") } override fun onStart() { if (presenter != null) adapter.setOnContextMenuListener(this) super.onStart() } }
gpl-3.0
1b246cc0ee2607a13ad8215b2fdc542d
30.904545
110
0.757623
3.894562
false
false
false
false
bastman/kotlin-spring-jpa-examples
src/main/kotlin/com/example/demo/api/realestate/handler/properties/crud/search/SearchPropertiesHandler.kt
1
1636
package com.example.demo.api.realestate.handler.properties.crud.search import com.example.demo.api.common.validation.validateRequest import com.example.demo.api.realestate.domain.jpa.entities.Property import com.example.demo.api.realestate.domain.jpa.entities.QueryDslEntity.qProperty import com.example.demo.querydsl.andAllOf import com.example.demo.querydsl.andAnyOf import com.example.demo.querydsl.orderBy import com.querydsl.jpa.impl.JPAQuery import org.springframework.stereotype.Component import org.springframework.validation.Validator import javax.persistence.EntityManager @Component class SearchPropertiesHandler( private val validator: Validator, private val entityManager: EntityManager ) { fun handle(request: SearchPropertiesRequest): SearchPropertiesResponse = execute(request = validator.validateRequest(request, "request")) private fun execute(request: SearchPropertiesRequest): SearchPropertiesResponse { val filters = request.filter.toWhereExpressionDsl() val search = request.search.toWhereExpressionDsl() val order = request.orderBy.toOrderByExpressionDsl() val query = JPAQuery<Property>(entityManager) val resultSet = query.from(qProperty) .where( qProperty.isNotNull .andAllOf(filters) .andAnyOf(search) ) .orderBy(order) .offset(request.offset) .limit(request.limit) .fetchResults() return SearchPropertiesResponse.of(resultSet) } }
mit
15e097882f65506e78adcf1e026f07d7
38.902439
85
0.698044
4.883582
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/getPropertiesMutableVsReadonly.kt
1
734
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.* class A(val readonly: String) { var mutable: String = "before" } fun box(): String { val props = A::class.java.kotlin.memberProperties val readonly = props.single { it.name == "readonly" } assert(readonly !is KMutableProperty1<A, *>) { "Fail 1: $readonly" } val mutable = props.single { it.name == "mutable" } assert(mutable is KMutableProperty1<A, *>) { "Fail 2: $mutable" } val a = A("") mutable as KMutableProperty1<A, String> assert(mutable.get(a) == "before") { "Fail 3: ${mutable.get(a)}" } mutable.set(a, "OK") return mutable.get(a) }
apache-2.0
1ca2ecf3a01645c87b3a0d96d41dffb9
29.583333
72
0.644414
3.413953
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/component/KoinComponent.kt
1
2110
/* * 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.core.component import org.koin.core.Koin import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import org.koin.mp.KoinPlatformTools /** * KoinComponent interface marker to bring Koin extensions features * * @author Arnaud Giuliani */ interface KoinComponent { /** * Get the associated Koin instance */ fun getKoin(): Koin = KoinPlatformTools.defaultContext().get() } /** * Get instance instance from Koin * @param qualifier * @param parameters */ inline fun <reified T : Any> KoinComponent.get( qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): T { return if (this is KoinScopeComponent) { scope.get(qualifier, parameters) } else getKoin().get(qualifier, parameters) } /** * Lazy inject instance from Koin * @param qualifier * @param mode - LazyThreadSafetyMode * @param parameters */ inline fun <reified T : Any> KoinComponent.inject( qualifier: Qualifier? = null, mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(), noinline parameters: ParametersDefinition? = null ): Lazy<T> = lazy(mode) { get<T>(qualifier, parameters) } ///** // * Get instance instance from Koin by Primary Type P, as secondary type S // * @param parameters // */ //inline fun <reified S : Any, reified P : Any> KoinComponent.bind( // noinline parameters: ParametersDefinition? = null //): S = // getKoin().bind<S, P>(parameters)
apache-2.0
71a1193ee2f4b2dd40884fc8e79b3060
29.142857
75
0.715166
4.16996
false
false
false
false
K0zka/wikistat
src/main/kotlin/org/dictat/wikistat/services/mongodb/MongoStatDaoImpl.kt
1
2437
package org.dictat.wikistat.services.mongodb import org.dictat.wikistat.services.StatDao import java.util.Date import com.mongodb.DB import com.mongodb.BasicDBObject import org.dictat.wikistat.model.PageActivity import java.util.ArrayList import com.mongodb.DBObject import org.dictat.wikistat.model.TimeFrame import java.util.Collections import com.mongodb.DBCollection public class MongoStatDaoImpl(db: DB): AbstractMongoDao(db), StatDao { override fun setDateCompression(date: Date, tf: TimeFrame) { getCollection().update( BasicDBObject("_id", DateUtil.dateToString(date, TimeFrame.Hour)), BasicDBObject("c",tf.symbol)) } override fun getDateCompression(date: Date): TimeFrame? { val result = getCollection().find(BasicDBObject("_id", DateUtil.dateToString(date, TimeFrame.Hour)), BasicDBObject("c",1))!! val obj = result.next() return TimeFrame.Day } override fun getCollectionNames(): List<String> { return Collections.singletonList("totals"); } override fun getIndices(): List<String> { return Collections.emptyList() } protected fun getCollection() : DBCollection { return db.getCollection("totals")!! } override fun getStatistics(site: String): List<PageActivity> { val stats = ArrayList<PageActivity>() for (x in getCollection().find(BasicDBObject(), BasicDBObject("e." + site, 1))) { val allSites = x.get("e") as DBObject if(allSites.containsField(site)) { val activity = PageActivity() activity.time = DateUtil.stringToDate(x.get("_id") as String, TimeFrame.Hour) activity.activity = allSites.get(site) as Int stats.add(activity) } } return stats } override fun isLoaded(date: Date): Boolean { return db.getCollection("totals")!!.find(BasicDBObject("_id", DateUtil.dateToString(date, TimeFrame.Hour)))!!.count() > 0; } override fun saveStatistics(wikiact: Map<String, Long>, total: Long, date: Date) { val stats = BasicDBObject() for (x in wikiact) { stats.append(x.component1().replaceAll("\\.", "_"), x.component2().toInt()) } val doc = BasicDBObject("_id", DateUtil.dateToString(date, TimeFrame.Hour)).append("e", stats)!!.append("t", total); getCollection().insert(doc) } }
apache-2.0
54e0c7e909ca58864b2767418401fb27
39.633333
132
0.651621
4.406872
false
false
false
false
zlyne0/colonization
core/src/net/sf/freecol/common/model/ai/missions/transportunit/TransportUnitRequestMissionHandler.kt
1
7018
package net.sf.freecol.common.model.ai.missions.transportunit import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.MoveType import net.sf.freecol.common.model.Specification import net.sf.freecol.common.model.UnitType import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.findParentMission import net.sf.freecol.common.model.map.path.Path import net.sf.freecol.common.model.map.path.PathFinder import net.sf.freecol.common.util.CollectionUtils import promitech.colonization.ai.MissionExecutor import promitech.colonization.ai.MissionHandler import promitech.colonization.ai.MissionHandlerLogger.logger import promitech.colonization.ai.findShipsTileLocations import promitech.colonization.orders.move.MoveContext import promitech.colonization.orders.move.MoveService class TransportUnitRequestMissionHandler( private val game: Game, private val moveService: MoveService, private val pathFinder: PathFinder, private val pathFinder2: PathFinder, private val missionExecutor: MissionExecutor ) : MissionHandler<TransportUnitRequestMission> { override fun handle( playerMissionsContainer: PlayerMissionsContainer, mission: TransportUnitRequestMission ) { val player = playerMissionsContainer.player if (!player.units.containsId(mission.unit)) { logger.debug( "player[%s].TransportUnitRequestMission no unit %s", player.getId(), mission.unit.id ) mission.setDone() return } mission.resetTransportMissionIdWhenDoNotExists(playerMissionsContainer) // Do nothing. Transport request handled by transport unit handler and planer. if (mission.allowMoveToDestination && !mission.hasTransportUnitMission() && mission.isUnitAtTileLocation()) { if (mission.isDestinationOnTheSameIsland(game.map)) { moveToDestination(playerMissionsContainer, mission, { mission.setDone() }) } else { // move to sea side and wait for ship moveToOtherIsland(mission) } } if (mission.checkAvailability && !mission.hasTransportUnitMission()) { checkAvailabilityOnParentMission(playerMissionsContainer, mission) } } private fun moveToOtherIsland(mission: TransportUnitRequestMission) { val recommendEmbarkLocationPath = recommendEmbarkLocationPath(mission) if (recommendEmbarkLocationPath != null) { val moveContext = MoveContext(mission.unit, recommendEmbarkLocationPath) moveService.aiConfirmedMovePath(moveContext) } } private fun recommendEmbarkLocationPath(mission: TransportUnitRequestMission): Path? { val unitEmbarkGenerateRangeFlags = CollectionUtils.enumSum( PathFinder.includeUnexploredTiles, PathFinder.FlagTypes.AllowEmbark ) pathFinder.generateRangeMap(game.map, mission.unit, unitEmbarkGenerateRangeFlags) val shipsTileLocations = mission.unit.owner.findShipsTileLocations(game.map) if (shipsTileLocations.isEmpty()) { return null } pathFinder2.generateRangeMap( game.map, shipsTileLocations, pathFinder2.createPathUnit( mission.unit.owner, Specification.instance.unitTypes.getById(UnitType.CARAVEL) ), CollectionUtils.enumSum( PathFinder.includeUnexploredTiles, PathFinder.FlagTypes.AvoidDisembark ) ) val embarkLocation = pathFinder2.findFirstTheBestSumTurnCost(pathFinder, PathFinder.SumPolicy.PRIORITY_SUM) if (embarkLocation == null || mission.isUnitAt(embarkLocation)) { return null } return pathFinder.createPath(embarkLocation) } private inline fun moveToDestination( playerMissionsContainer: PlayerMissionsContainer, mission: TransportUnitRequestMission, actionOnDestination: () -> kotlin.Unit = {} ) { if (mission.isUnitAtDestination()) { actionOnDestination() return } if (!mission.unit.hasMovesPoints()) { return } val path: Path = pathFinder.findToTile( game.map, mission.unit, mission.destination, PathFinder.includeUnexploredTiles ) if (path.reachTile(mission.destination)) { mission.recalculateWorthEmbark(pathFinder.turnsCost(mission.destination)) val moveContext = MoveContext(mission.unit, path) val lastMoveType = moveService.aiConfirmedMovePath(moveContext) if (lastMoveType.isProgress || MoveType.MOVE_NO_MOVES.equals(lastMoveType)) { if (mission.isUnitAtDestination()) { actionOnDestination() } } else { notifyParentMissionMoveNoAccess(playerMissionsContainer, mission, lastMoveType) } } else { notifyParentMissionMoveNoAccess(playerMissionsContainer, mission, MoveType.MOVE_ILLEGAL) } } private fun notifyParentMissionMoveNoAccess( playerMissionsContainer: PlayerMissionsContainer, mission: TransportUnitRequestMission, moveType: MoveType ) { val parentMission = playerMissionsContainer.findParentMission(mission) if (parentMission == null) { logger.debug( "player[%s].TransportUnitRequestMission.unit[%s].destination[%s] no access moveType[%s] no parent mission", playerMissionsContainer.player.getId(), mission.unit.id, mission.destination.toPrettyString(), moveType ) mission.setDone() return } val parentMissionHandler = missionExecutor.findMissionHandler(parentMission) if (parentMissionHandler is MoveNoAccessNotificationMissionHandler) { parentMissionHandler.moveNoAccessNotification( playerMissionsContainer, parentMission, mission, moveType ) } } private fun checkAvailabilityOnParentMission( playerMissionsContainer: PlayerMissionsContainer, transportRequestMission: TransportUnitRequestMission ) { val parentMission = playerMissionsContainer.findParentMission(transportRequestMission) if (parentMission != null) { val parentMissionHandler = missionExecutor.findMissionHandler(parentMission) if (parentMissionHandler is CheckAvailabilityMissionHandler) { parentMissionHandler.checkAvailability(playerMissionsContainer, parentMission, transportRequestMission) } } } }
gpl-2.0
0aa77d27e1058c0e321e2d2d569bd93d
38.655367
123
0.666429
5.37366
false
false
false
false
y20k/trackbook
app/src/main/java/org/y20k/trackbook/helpers/PreferencesHelper.kt
1
6603
/* * PreferencesHelper.kt * Implements the PreferencesHelper object * A PreferencesHelper provides helper methods for the saving and loading values from shared preferences * * This file is part of * TRACKBOOK - Movement Recorder for Android * * Copyright (c) 2016-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT * * Trackbook uses osmdroid - OpenStreetMap-Tools for Android * https://github.com/osmdroid/osmdroid */ package org.y20k.trackbook.helpers import android.content.Context import android.content.SharedPreferences import android.location.Location import android.location.LocationManager import androidx.core.content.edit import androidx.preference.PreferenceManager import org.y20k.trackbook.Keys import org.y20k.trackbook.extensions.getDouble import org.y20k.trackbook.extensions.putDouble /* * PreferencesHelper object */ object PreferencesHelper { /* Define log tag */ private val TAG: String = LogHelper.makeLogTag(PreferencesHelper::class.java) /* The sharedPreferences object to be initialized */ private lateinit var sharedPreferences: SharedPreferences /* Initialize a single sharedPreferences object when the app is launched */ fun Context.initPreferences() { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) } /* Loads zoom level of map */ fun loadZoomLevel(): Double { // load zoom level return sharedPreferences.getDouble(Keys.PREF_MAP_ZOOM_LEVEL, Keys.DEFAULT_ZOOM_LEVEL) } /* Saves zoom level of map */ fun saveZoomLevel(zoomLevel: Double) { // save zoom level sharedPreferences.edit { putDouble(Keys.PREF_MAP_ZOOM_LEVEL, zoomLevel) } } /* Loads tracking state */ fun loadTrackingState(): Int { // load tracking state return sharedPreferences.getInt(Keys.PREF_TRACKING_STATE, Keys.STATE_TRACKING_NOT) } /* Saves tracking state */ fun saveTrackingState(trackingState: Int) { // save tracking state sharedPreferences.edit { putInt(Keys.PREF_TRACKING_STATE, trackingState) } } /* Loads length unit system - metric or imperial */ fun loadUseImperialUnits(): Boolean { // load length unit system return sharedPreferences.getBoolean(Keys.PREF_USE_IMPERIAL_UNITS, LengthUnitHelper.useImperialUnits()) } /* Loads length unit system - metric or imperial */ fun loadGpsOnly(): Boolean { // load length unit system return sharedPreferences.getBoolean(Keys.PREF_GPS_ONLY, false) } // /* Loads accuracy threshold used to determine if location is good enough */ // fun loadAccuracyThreshold(): Int { // // load tracking state // return sharedPreferences.getInt(Keys.PREF_LOCATION_ACCURACY_THRESHOLD, Keys.DEFAULT_THRESHOLD_LOCATION_ACCURACY) // } // /* Loads state of recording accuracy */ // fun loadRecordingAccuracyHigh(): Boolean { // // load current setting // return sharedPreferences.getBoolean(Keys.PREF_RECORDING_ACCURACY_HIGH, false) // } /* Loads current accuracy multiplier */ fun loadAccuracyMultiplier(): Int { // load current setting val recordingAccuracyHigh: Boolean = sharedPreferences.getBoolean(Keys.PREF_RECORDING_ACCURACY_HIGH, false) // return multiplier based on state return if (recordingAccuracyHigh) 2 else 1 } // /* Load altitude smoothing value */ // fun loadAltitudeSmoothingValue(): Int { // // load current setting // return sharedPreferences.getInt(Keys.PREF_ALTITUDE_SMOOTHING_VALUE, Keys.DEFAULT_ALTITUDE_SMOOTHING_VALUE) // } /* Loads the state of a map */ fun loadCurrentBestLocation(): Location { val provider: String = sharedPreferences.getString(Keys.PREF_CURRENT_BEST_LOCATION_PROVIDER, LocationManager.NETWORK_PROVIDER) ?: LocationManager.NETWORK_PROVIDER // create location return Location(provider).apply { // load location attributes latitude = sharedPreferences.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, Keys.DEFAULT_LATITUDE) longitude = sharedPreferences.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LONGITUDE, Keys.DEFAULT_LONGITUDE) accuracy = sharedPreferences.getFloat(Keys.PREF_CURRENT_BEST_LOCATION_ACCURACY, Keys.DEFAULT_ACCURACY) altitude = sharedPreferences.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_ALTITUDE, Keys.DEFAULT_ALTITUDE) time = sharedPreferences.getLong(Keys.PREF_CURRENT_BEST_LOCATION_TIME, Keys.DEFAULT_TIME) } } /* Saves the state of a map */ fun saveCurrentBestLocation(currentBestLocation: Location) { sharedPreferences.edit { // save location putDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, currentBestLocation.latitude) putDouble(Keys.PREF_CURRENT_BEST_LOCATION_LONGITUDE, currentBestLocation.longitude) putFloat(Keys.PREF_CURRENT_BEST_LOCATION_ACCURACY, currentBestLocation.accuracy) putDouble(Keys.PREF_CURRENT_BEST_LOCATION_ALTITUDE, currentBestLocation.altitude) putLong(Keys.PREF_CURRENT_BEST_LOCATION_TIME, currentBestLocation.time) } } /* Load currently selected app theme */ fun loadThemeSelection(): String { return sharedPreferences.getString(Keys.PREF_THEME_SELECTION, Keys.STATE_THEME_FOLLOW_SYSTEM) ?: Keys.STATE_THEME_FOLLOW_SYSTEM } /* Checks if housekeeping work needs to be done - used usually in DownloadWorker "REQUEST_UPDATE_COLLECTION" */ fun isHouseKeepingNecessary(): Boolean { return sharedPreferences.getBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, true) } /* Saves state of housekeeping */ fun saveHouseKeepingNecessaryState(state: Boolean = false) { sharedPreferences.edit { putBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, state) } } /* Start watching for changes in shared preferences - context must implement OnSharedPreferenceChangeListener */ fun registerPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { sharedPreferences.registerOnSharedPreferenceChangeListener(listener) } /* Stop watching for changes in shared preferences - context must implement OnSharedPreferenceChangeListener */ fun unregisterPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) } }
mit
5faee540eadf587ad340bc2317f86718
36.305085
170
0.720127
4.873063
false
false
false
false
jdiazcano/modulartd
plugin/src/main/kotlin/com/jdiazcano/modulartd/plugins/actions/Menus.kt
1
319
package com.jdiazcano.modulartd.plugins.actions object Menus { // If a value is added here, remember to add it to the MainMenu class from the core const val FILE = "root.file" const val VIEW = "root.view" const val EDIT = "root.edit" const val GAME = "root.game" const val HELP = "root.help" }
apache-2.0
b36dadeea5a6d229f7827755e2c46d2e
28.090909
87
0.677116
3.625
false
false
false
false
Heiner1/AndroidAPS
pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.kt
1
1586
package info.nightscout.androidaps.plugins.pump.common.data import info.nightscout.androidaps.plugins.pump.common.defs.PumpRunningState import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import java.util.* /** * Created by andy on 4/28/18. */ abstract class PumpStatus(var pumpType: PumpType) { // connection var lastDataTime: Long = 0 var lastConnection = 0L var previousConnection = 0L // here should be stored last connection of previous session (so needs to be // read before lastConnection is modified for first time). // last bolus var lastBolusTime: Date? = null var lastBolusAmount: Double? = null // other pump settings var activeProfileName = "0" var reservoirRemainingUnits = 0.0 var reservoirFullUnits = 0 var batteryRemaining = 0 // percent, so 0-100 var batteryVoltage: Double? = null // iob var iob: String? = null // TDD var dailyTotalUnits: Double? = null var maxDailyTotalUnits: String? = null var units: String? = null // Constants.MGDL or Constants.MMOL var pumpRunningState = PumpRunningState.Running var basalsByHour: DoubleArray? = null var tempBasalStart: Long? = null var tempBasalAmount: Double? = 0.0 var tempBasalLength: Int? = 0 var tempBasalEnd: Long? = null var pumpTime: PumpTimeDifferenceDto? = null abstract fun initSettings() fun setLastCommunicationToNow() { lastDataTime = System.currentTimeMillis() lastConnection = System.currentTimeMillis() } abstract val errorInfo: String? }
agpl-3.0
44d0772638ff5d1764ad58ed4ba3438e
28.943396
108
0.70681
4.357143
false
false
false
false
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplatesLoader.kt
4
14266
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.ide.fileTemplates.impl import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.getOrLogException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.objectTree.ThrowableInterner import com.intellij.openapi.util.text.StringUtil import com.intellij.project.stateStore import com.intellij.util.ReflectionUtil import com.intellij.util.ResourceUtil import com.intellij.util.concurrency.SynchronizedClearableLazy import com.intellij.util.io.URLUtil import com.intellij.util.lang.UrlClassLoader import org.apache.velocity.runtime.ParserPool import org.apache.velocity.runtime.RuntimeSingleton import org.apache.velocity.runtime.directive.Stop import java.io.File import java.io.IOException import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.text.MessageFormat import java.util.* import java.util.function.BiPredicate import java.util.function.Function import java.util.function.Supplier private const val DEFAULT_TEMPLATES_ROOT = FileTemplatesLoader.TEMPLATES_DIR private const val DESCRIPTION_FILE_EXTENSION = "html" private const val DESCRIPTION_EXTENSION_SUFFIX = ".$DESCRIPTION_FILE_EXTENSION" /** * Serves as a container for all existing template manager types and loads corresponding templates lazily. * Reloads templates on plugins change. */ internal open class FileTemplatesLoader(project: Project?) : Disposable { companion object { const val TEMPLATES_DIR = "fileTemplates" } private val managers = SynchronizedClearableLazy { loadConfiguration(project) } val allManagers: Collection<FTManager> get() = managers.value.managers.values val defaultTemplatesManager: FTManager get() = FTManager(managers.value.getManager(FileTemplateManager.DEFAULT_TEMPLATES_CATEGORY)) val internalTemplatesManager: FTManager get() = FTManager(managers.value.getManager(FileTemplateManager.INTERNAL_TEMPLATES_CATEGORY)) val patternsManager: FTManager get() = FTManager(managers.value.getManager(FileTemplateManager.INCLUDES_TEMPLATES_CATEGORY)) val codeTemplatesManager: FTManager get() = FTManager(managers.value.getManager(FileTemplateManager.CODE_TEMPLATES_CATEGORY)) val j2eeTemplatesManager: FTManager get() = FTManager(managers.value.getManager(FileTemplateManager.J2EE_TEMPLATES_CATEGORY)) val defaultTemplateDescription: Supplier<String>? get() = managers.value.defaultTemplateDescription val defaultIncludeDescription: Supplier<String>? get() = managers.value.defaultIncludeDescription init { @Suppress("LeakingThis") ApplicationManager.getApplication().messageBus.connect(this).subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { // this shouldn't be necessary once we update to a new Velocity Engine with this leak fixed (IDEA-240449, IDEABKL-7932) clearClassLeakViaStaticExceptionTrace() resetParserPool() } private fun clearClassLeakViaStaticExceptionTrace() { val field = ReflectionUtil.getDeclaredField(Stop::class.java, "STOP_ALL") ?: return runCatching { ThrowableInterner.clearBacktrace((field.get(null) as Throwable)) }.getOrLogException(logger<FileTemplatesLoader>()) } private fun resetParserPool() { runCatching { val ppField = ReflectionUtil.getDeclaredField(RuntimeSingleton.getRuntimeServices().javaClass, "parserPool") ?: return (ppField.get(RuntimeSingleton.getRuntimeServices()) as? ParserPool)?.initialize(RuntimeSingleton.getRuntimeServices()) }.getOrLogException(logger<FileTemplatesLoader>()) } override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) { managers.drop() } override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { managers.drop() } }) } override fun dispose() { } } // example: templateName="NewClass" templateExtension="java" private fun getDescriptionPath(pathPrefix: String, templateName: String, templateExtension: String, descriptionPaths: Set<String>): String? { val locale = Locale.getDefault() var name = MessageFormat.format("{0}.{1}_{2}_{3}$DESCRIPTION_EXTENSION_SUFFIX", templateName, templateExtension, locale.language, locale.country) var path = if (pathPrefix.isEmpty()) name else "$pathPrefix/$name" if (descriptionPaths.contains(path)) { return path } name = MessageFormat.format("{0}.{1}_{2}$DESCRIPTION_EXTENSION_SUFFIX", templateName, templateExtension, locale.language) path = if (pathPrefix.isEmpty()) name else "$pathPrefix/$name" if (descriptionPaths.contains(path)) { return path } name = "$templateName.$templateExtension$DESCRIPTION_EXTENSION_SUFFIX" path = if (pathPrefix.isEmpty()) name else "$pathPrefix/$name" return if (descriptionPaths.contains(path)) path else null } private fun loadConfiguration(project: Project?): LoadedConfiguration { val configDir = if (project == null || project.isDefault) { PathManager.getConfigDir().resolve(FileTemplatesLoader.TEMPLATES_DIR) } else { project.stateStore.projectFilePath.parent.resolve(FileTemplatesLoader.TEMPLATES_DIR) } // not a map - force predefined order for stable performance results val managerToDir = listOf( FileTemplateManager.DEFAULT_TEMPLATES_CATEGORY to "", FileTemplateManager.INTERNAL_TEMPLATES_CATEGORY to "internal", FileTemplateManager.INCLUDES_TEMPLATES_CATEGORY to "includes", FileTemplateManager.CODE_TEMPLATES_CATEGORY to "code", FileTemplateManager.J2EE_TEMPLATES_CATEGORY to "j2ee" ) val result = loadDefaultTemplates(managerToDir.map { it.second }) val managers = HashMap<String, FTManager>(managerToDir.size) for ((name, pathPrefix) in managerToDir) { val manager = FTManager(name, configDir.resolve(pathPrefix), result.prefixToTemplates.get(pathPrefix) ?: emptyList(), name == FileTemplateManager.INTERNAL_TEMPLATES_CATEGORY) manager.loadCustomizedContent() managers.put(name, manager) } return LoadedConfiguration(managers = managers, defaultTemplateDescription = result.defaultTemplateDescription, defaultIncludeDescription = result.defaultIncludeDescription) } private fun loadDefaultTemplates(prefixes: List<String>): FileTemplateLoadResult { val result = FileTemplateLoadResult(HashMap()) val processedUrls = HashSet<URL>() val processedLoaders = Collections.newSetFromMap(IdentityHashMap<ClassLoader, Boolean>()) for (plugin in PluginManagerCore.getPluginSet().enabledPlugins) { val loader = plugin.classLoader if (loader is PluginAwareClassLoader && (loader as PluginAwareClassLoader).files.isEmpty() || !processedLoaders.add(loader)) { // test or development mode, when IDEA_CORE's loader contains all the classpath continue } try { val resourceUrls = if (loader is UrlClassLoader) { // don't use parents from plugin class loader - we process all plugins loader.classPath.getResources(DEFAULT_TEMPLATES_ROOT) } else { loader.getResources(DEFAULT_TEMPLATES_ROOT) } while (resourceUrls.hasMoreElements()) { val url = resourceUrls.nextElement() if (!processedUrls.add(url)) { continue } val protocol = url.protocol if (URLUtil.JAR_PROTOCOL.equals(protocol, ignoreCase = true)) { loadDefaultsFromJar(url, prefixes, result) } else if (URLUtil.FILE_PROTOCOL.equals(protocol, ignoreCase = true)) { loadDefaultsFromDirectory(url, result, prefixes) } } } catch (e: IOException) { logger<FileTemplatesLoader>().error(e) } } return result } private fun loadDefaultsFromJar(url: URL, prefixes: List<String>, result: FileTemplateLoadResult) { val children = UrlUtil.getChildPathsFromJar(url) if (children.isEmpty()) { return } val descriptionPaths: MutableSet<String> = HashSet() for (path in children) { if (path == "default.html") { result.defaultTemplateDescription = createSupplierForUrlSource(url, path) } else if (path == "includes/default.html") { result.defaultIncludeDescription = createSupplierForUrlSource(url, path) } else if (path.endsWith(DESCRIPTION_EXTENSION_SUFFIX)) { descriptionPaths.add(path) } } processTemplates(files = children.asSequence().filter { it.endsWith(FTManager.TEMPLATE_EXTENSION_SUFFIX) }, prefixes = prefixes, descriptionPaths = descriptionPaths, result = result, descriptionLoader = { loadTemplate(url, it) }) { createSupplierForUrlSource(url, it) } } private inline fun processTemplates(files: Sequence<String>, prefixes: List<String>, descriptionPaths: MutableSet<String>, result: FileTemplateLoadResult, descriptionLoader: Function<String, String>, dataLoader: (path: String) -> Supplier<String>) { for (path in files) { val prefix = prefixes.firstOrNull { if (it.isEmpty()) { !path.contains('/') } else { path.length > it.length && path[it.length] == '/' && path.startsWith(it) && path.indexOf('/', it.length + 1) == -1 } } ?: continue val filename = path.substring(if (prefix.isEmpty()) 0 else prefix.length + 1, path.length - FTManager.TEMPLATE_EXTENSION_SUFFIX.length) val extension = FileUtilRt.getExtension(filename) val templateName = filename.substring(0, filename.length - extension.length - 1) val descriptionPath = getDescriptionPath(prefix, templateName, extension, descriptionPaths) val template = DefaultTemplate(name = templateName, extension = extension, textSupplier = dataLoader(path), descriptionLoader = descriptionLoader.takeIf { descriptionPath != null }, descriptionPath = descriptionPath) result.prefixToTemplates.computeIfAbsent(prefix) { mutableListOf() }.add(template) } } private fun loadDefaultsFromDirectory(root: URL, result: FileTemplateLoadResult, prefixes: List<String>) { val descriptionPaths = HashSet<String>() val templateFiles = mutableListOf<String>() val rootFile = urlToPath(root) Files.find(rootFile, Int.MAX_VALUE, BiPredicate { _, a -> a.isRegularFile }).use { it.forEach { file -> val path = rootFile.relativize(file).toString().replace(File.separatorChar, '/') if (path.endsWith("/default.html")) { result.defaultTemplateDescription = Supplier { Files.readString(file) } } else if (path.endsWith("/includes/default.html")) { result.defaultIncludeDescription = Supplier { Files.readString(file) } } else if (path.endsWith(".html")) { descriptionPaths.add(path) } else if (path.endsWith(FTManager.TEMPLATE_EXTENSION_SUFFIX)) { templateFiles.add(path) } } } processTemplates(files = templateFiles.asSequence(), prefixes = prefixes, descriptionPaths = descriptionPaths, result = result, descriptionLoader = { Files.readString(rootFile.resolve(it)) }) { Supplier { Files.readString(rootFile.resolve(it)) } } } private fun urlToPath(root: URL): Path { var path = root.toURI().path if (SystemInfoRt.isWindows && path.startsWith("/")) { // trim leading slashes before drive letter val position = path.indexOf(':') if (position > 1) { path = path.substring(position - 1) } } return Path.of(path) } private class FileTemplateLoadResult(@JvmField val prefixToTemplates: MutableMap<String, MutableList<DefaultTemplate>>) { @JvmField var defaultTemplateDescription: Supplier<String>? = null @JvmField var defaultIncludeDescription: Supplier<String>? = null } private class LoadedConfiguration(@JvmField val managers: Map<String, FTManager>, @JvmField val defaultTemplateDescription: Supplier<String>?, @JvmField val defaultIncludeDescription: Supplier<String>?) { fun getManager(kind: String) = managers.get(kind)!! } private fun createSupplierForUrlSource(root: URL, path: String): Supplier<String> { // no need to cache the result - it is client responsibility, see DefaultTemplate.getDescriptionText for example return object : Supplier<String> { override fun get() = loadTemplate(root, path) override fun toString() = "(root=$root, path=$path)" } } private fun loadTemplate(root: URL, path: String): String { // root url should be used as context to use provided handler to load data to avoid using a generic one return try { ResourceUtil.loadText(URL(root, "${FileTemplatesLoader.TEMPLATES_DIR}/${path.trimEnd('/')}").openStream()) } catch (e: IOException) { logger<FileTemplatesLoader>().error(e) "" } }
apache-2.0
193d154de85c96efac2cec30977890ed
39.879656
139
0.697883
4.834293
false
false
false
false
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/MainMenuButton.kt
3
3261
// 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.openapi.wm.impl.customFrameDecorations.header.toolbar import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.PresentationFactory import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.CheckedDisposable import com.intellij.openapi.util.Disposer import com.intellij.ui.IconManager import com.intellij.util.ui.JBUI import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import javax.swing.JComponent @ApiStatus.Internal internal class MainMenuButton { private val menuAction = ShowMenuAction() val button: ActionButton = createMenuButton(menuAction) val menuShortcutHandler = MainMenuMnemonicHandler(menuAction) private inner class ShowMenuAction : DumbAwareAction() { private val icon = IconManager.getInstance().getIcon("expui/general/[email protected]", AllIcons::class.java) override fun update(e: AnActionEvent) { e.presentation.icon = icon e.presentation.text = IdeBundle.message("main.toolbar.menu.button") } override fun actionPerformed(e: AnActionEvent) = createPopup(e.dataContext).showUnderneathOf(button) private fun createPopup(context: DataContext): JBPopup { val mainMenu = ActionManager.getInstance().getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup return JBPopupFactory.getInstance() .createActionGroupPopup(null, mainMenu, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true, ActionPlaces.MAIN_MENU_IN_POPUP) .apply { setShowSubmenuOnHover(true) } .apply { setMinimumSize(Dimension(JBUI.CurrentTheme.CustomFrameDecorations.menuPopupMinWidth(), 0)) } } } companion object { private fun createMenuButton(action: AnAction): ActionButton { val button = object: ActionButton(action, PresentationFactory().getPresentation(action), ActionPlaces.MAIN_MENU_IN_POPUP, Dimension(40, 40)) { override fun getDataContext(): DataContext { return DataManager.getInstance().dataContextFromFocusAsync.blockingGet(200) ?: super.getDataContext() } } button.setLook(HeaderToolbarButtonLook()) return button } } } class MainMenuMnemonicHandler(val action: AnAction) : Disposable { private var disposable: CheckedDisposable? = null fun registerShortcuts(component: JComponent) { if (disposable?.isDisposed != false) disposable = Disposer.newCheckedDisposable() val shortcutSet = ActionUtil.getShortcutSet("MainMenuButton.ShowMenu") action.registerCustomShortcutSet(shortcutSet, component, disposable) } fun unregisterShortcuts() { disposable?.let { Disposer.dispose(it) } } override fun dispose() = unregisterShortcuts() }
apache-2.0
9028a6809e98d7401a9760e7ab1852bf
38.289157
120
0.762036
4.698847
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/SmartStepTargetVisitor.kt
3
15526
// 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.debugger.stepping.smartStepInto import com.intellij.debugger.actions.MethodSmartStepTarget import com.intellij.debugger.actions.SmartStepTarget import com.intellij.psi.PsiMethod import com.intellij.util.Range import com.intellij.util.containers.OrderedSet import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.debugger.breakpoints.isInlineOnly import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.isFromJava import org.jetbrains.kotlin.platform.jvm.JdkPlatform import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getParentCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.isInlineClassType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.SimpleType import org.jetbrains.kotlin.types.checker.isSingleClassifierType import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull // TODO support class initializers, local functions, delegated properties with specified type, setter for properties class SmartStepTargetVisitor( private val element: KtElement, private val lines: Range<Int>, private val consumer: OrderedSet<SmartStepTarget> ) : KtTreeVisitorVoid() { private fun append(target: SmartStepTarget) { consumer += target } private val intrinsicMethods = run { val jvmTarget = element.platform.firstIsInstanceOrNull<JdkPlatform>()?.targetVersion ?: JvmTarget.DEFAULT IntrinsicMethods(jvmTarget) } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { recordFunction(lambdaExpression.functionLiteral) } override fun visitNamedFunction(function: KtNamedFunction) { if (!recordFunction(function)) { super.visitNamedFunction(function) } } override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) { recordCallableReference(expression) super.visitCallableReferenceExpression(expression) } private fun recordCallableReference(expression: KtCallableReferenceExpression) { val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val resolvedCall = expression.callableReference.getResolvedCall(bindingContext) ?: return when (val descriptor = resolvedCall.resultingDescriptor) { is FunctionDescriptor -> recordFunctionReference(expression, descriptor) is PropertyDescriptor -> recordGetter(expression, descriptor, bindingContext) } } private fun recordFunctionReference(expression: KtCallableReferenceExpression, descriptor: FunctionDescriptor) { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor) if (descriptor.isFromJava && declaration is PsiMethod) { append(MethodSmartStepTarget(declaration, null, expression, true, lines)) } else if (declaration is KtNamedFunction) { val label = KotlinMethodSmartStepTarget.calcLabel(descriptor) append( KotlinMethodReferenceSmartStepTarget( lines, expression, label, declaration, CallableMemberInfo(descriptor) ) ) } } private fun recordGetter(expression: KtExpression, descriptor: PropertyDescriptor, bindingContext: BindingContext) { val getterDescriptor = descriptor.getter if (getterDescriptor == null || getterDescriptor.isDefault) return val ktDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, getterDescriptor) as? KtDeclaration ?: return val delegatedResolvedCall = bindingContext[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getterDescriptor] if (delegatedResolvedCall != null) { val delegatedPropertyGetterDescriptor = delegatedResolvedCall.resultingDescriptor val delegateDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration( element.project, delegatedPropertyGetterDescriptor ) as? KtDeclarationWithBody ?: return val label = "${descriptor.name}." + KotlinMethodSmartStepTarget.calcLabel(delegatedPropertyGetterDescriptor) appendPropertyFilter(delegatedPropertyGetterDescriptor, delegateDeclaration, label, expression, lines) } else { if (ktDeclaration is KtPropertyAccessor && ktDeclaration.hasBody()) { val label = KotlinMethodSmartStepTarget.calcLabel(getterDescriptor) appendPropertyFilter(getterDescriptor, ktDeclaration, label, expression, lines) } } } private fun appendPropertyFilter( descriptor: CallableMemberDescriptor, declaration: KtDeclarationWithBody, label: String, expression: KtExpression, lines: Range<Int> ) { val methodInfo = CallableMemberInfo(descriptor) when (expression) { is KtCallableReferenceExpression -> append( KotlinMethodReferenceSmartStepTarget( lines, expression, label, declaration, methodInfo ) ) else -> { val ordinal = countExistingMethodCalls(declaration) append( KotlinMethodSmartStepTarget( lines, expression, label, declaration, ordinal, methodInfo ) ) } } } private fun recordFunction(function: KtFunction): Boolean { val (parameter, resultingDescriptor) = function.getParameterAndResolvedCallDescriptor() ?: return false val target = createSmartStepTarget(function, parameter, resultingDescriptor) if (target != null) { append(target) return true } return false } private fun createSmartStepTarget( function: KtFunction, parameter: ValueParameterDescriptor, resultingDescriptor: CallableMemberDescriptor ): KotlinLambdaSmartStepTarget? { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, resultingDescriptor) as? KtDeclaration ?: return null val callerMethodOrdinal = countExistingMethodCalls(declaration) if (parameter.isSamLambdaParameterDescriptor()) { val methodDescriptor = parameter.type.getFirstAbstractMethodDescriptor() ?: return null return KotlinLambdaSmartStepTarget( function, declaration, lines, KotlinLambdaInfo( resultingDescriptor, parameter, callerMethodOrdinal, methodDescriptor.containsInlineClassInValueArguments(), true, methodDescriptor.getMethodName() ) ) } return KotlinLambdaSmartStepTarget( function, declaration, lines, KotlinLambdaInfo( resultingDescriptor, parameter, callerMethodOrdinal, parameter.type.arguments.any { it.type.isInlineClassType() } ) ) } private fun countExistingMethodCalls(declaration: KtDeclaration): Int { return consumer .filterIsInstance<KotlinMethodSmartStepTarget>() .count { val targetDeclaration = it.getDeclaration() targetDeclaration != null && targetDeclaration === declaration } } override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) { // Skip calls in object declarations } override fun visitIfExpression(expression: KtIfExpression) { expression.condition?.accept(this) } override fun visitWhileExpression(expression: KtWhileExpression) { expression.condition?.accept(this) } override fun visitDoWhileExpression(expression: KtDoWhileExpression) { expression.condition?.accept(this) } override fun visitForExpression(expression: KtForExpression) { expression.loopRange?.accept(this) } override fun visitWhenExpression(expression: KtWhenExpression) { expression.subjectExpression?.accept(this) } override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) { super.visitArrayAccessExpression(expression) recordFunctionCall(expression) } override fun visitUnaryExpression(expression: KtUnaryExpression) { super.visitUnaryExpression(expression) recordFunctionCall(expression.operationReference) } override fun visitBinaryExpression(expression: KtBinaryExpression) { super.visitBinaryExpression(expression) recordFunctionCall(expression.operationReference) } override fun visitCallExpression(expression: KtCallExpression) { val calleeExpression = expression.calleeExpression if (calleeExpression != null) { recordFunctionCall(calleeExpression) } super.visitCallExpression(expression) } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val propertyDescriptor = resolvedCall.resultingDescriptor as? PropertyDescriptor ?: return recordGetter(expression, propertyDescriptor, bindingContext) super.visitSimpleNameExpression(expression) } private fun recordFunctionCall(expression: KtExpression) { val resolvedCall = expression.resolveToCall() ?: return val descriptor = resolvedCall.resultingDescriptor if (descriptor !is FunctionDescriptor || isIntrinsic(descriptor)) return val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor) if (descriptor.isFromJava) { if (declaration is PsiMethod) { append(MethodSmartStepTarget(declaration, null, expression, false, lines)) } } else { if (declaration == null && !isInvokeInBuiltinFunction(descriptor)) { return } if (declaration !is KtDeclaration?) return if (descriptor is ConstructorDescriptor && descriptor.isPrimary) { if (declaration is KtClass && declaration.getAnonymousInitializers().isEmpty()) { // There is no constructor or init block, so do not show it in smart step into return } } // We can't step into @InlineOnly callables as there is no LVT, so skip them if (declaration is KtCallableDeclaration && declaration.isInlineOnly()) { return } val callLabel = KotlinMethodSmartStepTarget.calcLabel(descriptor) val label = when (descriptor) { is FunctionInvokeDescriptor -> { when (expression) { is KtSimpleNameExpression -> "${runReadAction { expression.text }}.$callLabel" else -> callLabel } } else -> callLabel } val ordinal = if (declaration == null) 0 else countExistingMethodCalls(declaration) append( KotlinMethodSmartStepTarget( lines, expression, label, declaration, ordinal, CallableMemberInfo(descriptor) ) ) } } private fun isIntrinsic(descriptor: CallableMemberDescriptor): Boolean { return intrinsicMethods.getIntrinsic(descriptor) != null } } private fun PropertyAccessorDescriptor.getJvmMethodName(): String { return DescriptorUtils.getJvmName(this) ?: JvmAbi.getterName(correspondingProperty.name.asString()) } fun DeclarationDescriptor.getMethodName() = when (this) { is ClassDescriptor, is ConstructorDescriptor -> "<init>" is PropertyAccessorDescriptor -> getJvmMethodName() else -> name.asString() } fun KtFunction.isSamLambda(): Boolean { val (parameter, _) = getParameterAndResolvedCallDescriptor() ?: return false return parameter.isSamLambdaParameterDescriptor() } private fun ValueParameterDescriptor.isSamLambdaParameterDescriptor(): Boolean { val type = type return !type.isFunctionType && type is SimpleType && type.isSingleClassifierType } private fun KtFunction.getParameterAndResolvedCallDescriptor(): Pair<ValueParameterDescriptor, CallableMemberDescriptor>? { val context = analyze() val resolvedCall = getParentCall(context).getResolvedCall(context) ?: return null val descriptor = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return null val arguments = resolvedCall.valueArguments for ((param, argument) in arguments) { if (argument.arguments.any { getArgumentExpression(it) == this }) { return Pair(param, descriptor) } } return null } private fun getArgumentExpression(it: ValueArgument): KtExpression? { return (it.getArgumentExpression() as? KtLambdaExpression)?.functionLiteral ?: it.getArgumentExpression() } private fun KotlinType.getFirstAbstractMethodDescriptor(): CallableMemberDescriptor? = memberScope .getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS) .asSequence() .filterIsInstance<CallableMemberDescriptor>() .firstOrNull { it.modality == Modality.ABSTRACT } private fun isInvokeInBuiltinFunction(descriptor: DeclarationDescriptor): Boolean { if (descriptor !is FunctionInvokeDescriptor) return false val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return false return classDescriptor.defaultType.isBuiltinFunctionalType }
apache-2.0
b85c7a668bd6d0e20f148f536adbdafe
40.513369
158
0.679312
6.163557
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/essentials/RemindersCommand.kt
1
4940
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * 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 <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.essentials import me.duncte123.botcommons.messaging.EmbedUtils import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed import me.duncte123.botcommons.messaging.MessageUtils.sendMsg import ml.duncte123.skybot.objects.api.Reminder import ml.duncte123.skybot.objects.command.Command import ml.duncte123.skybot.objects.command.CommandContext import ml.duncte123.skybot.utils.AirUtils import net.dv8tion.jda.api.utils.TimeFormat class RemindersCommand : Command() { init { this.name = "reminders" this.aliases = arrayOf("remindmanager", "reminder") this.help = "Shows the reminders that are currently active for you and allows you to manage your reminders" this.usage = "[list/cancel/delete/show/info] [reminder id]" } override fun execute(ctx: CommandContext) { val args = ctx.args if (args.isEmpty()) { showRemindersList(ctx) return } val action = args[0].lowercase() if (action == "list") { showRemindersList(ctx) return } if (args.size < 2) { sendUsageInstructions(ctx) return } val actions = arrayOf("cancel", "delete", "show", "info") if (!actions.contains(action)) { sendMsg(ctx, "`$action` is an unknown action, available actions are ${actions.joinToString()}") return } val reminderIdStr = args[1] if (!AirUtils.isInt(reminderIdStr)) { sendMsg(ctx, "`$reminderIdStr` is not a valid id (the id is the number you see in `${ctx.prefix}reminders list`)") return } val reminderId = reminderIdStr.toInt() ensureReminderExists(reminderId, ctx) { when (action) { "info", "show" -> showReminder(it, ctx) "cancel", "delete" -> deleteReminder(it, ctx) } } } private fun showRemindersList(ctx: CommandContext) { ctx.databaseAdapter.listReminders(ctx.author.idLong) { if (it.isEmpty()) { sendMsg(ctx, "You do not have any currently active reminders") return@listReminders } sendEmbed(ctx, EmbedUtils.embedMessage(it.joinToString(separator = "\n"))) } } private fun ensureReminderExists(reminderId: Int, ctx: CommandContext, callback: (Reminder) -> Unit) { ctx.databaseAdapter.showReminder(reminderId, ctx.author.idLong) { if (it == null) { sendMsg(ctx, "Reminder with id `$reminderId` was not found") return@showReminder } callback(it) } } private fun showReminder(reminder: Reminder, ctx: CommandContext) { val remindChannel = if (reminder.in_channel) "<#${reminder.channel_id}>" else "Direct Messages" val reminderInfo = """**Id:** ${reminder.id} |**Message:** ${reminder.reminder} |**Remind in:** $remindChannel |**Created:** ${reminder.reminderCreateDateDate} |**Remind on:** ${reminder.reminderDateDate} (${TimeFormat.RELATIVE.format(reminder.reminder_date)}) |** Message link:** ${reminder.jumpUrl} """.trimMargin() sendEmbed(ctx, EmbedUtils.embedMessage(reminderInfo)) } private fun deleteReminder(reminder: Reminder, ctx: CommandContext) { val args = ctx.args if (args.size >= 3 && args[2].lowercase() == "--just-honking-do-it") { ctx.databaseAdapter.removeReminder(reminder) { sendMsg(ctx, "Successfully deleted reminder with id `${reminder.id}`") } return } sendMsg( ctx, "To prevent accidental deleting of reminders, you will need to confirm that you want to delete this reminder.\n" + "To confirm that you want to delete the reminder please run the following command" + "`${ctx.prefix}reminders delete ${reminder.id} --just-honking-do-it`" ) } }
agpl-3.0
df212d13b431aa7042e2f0fe7801d8f8
35.323529
126
0.624494
4.418605
false
false
false
false
NCBSinfo/NCBSinfo
app/src/main/java/com/rohitsuratekar/NCBSinfo/adapters/LocationAdapter.kt
2
1645
package com.rohitsuratekar.NCBSinfo.adapters import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.rohitsuratekar.NCBSinfo.R import com.rohitsuratekar.NCBSinfo.common.inflate import com.rohitsuratekar.NCBSinfo.models.Location class LocationAdapter(private val locationList: List<Location>) : RecyclerView.Adapter<LocationAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(parent.inflate(R.layout.fragment_location_item)) } override fun getItemCount(): Int { return locationList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val loc = locationList[position] holder.apply { name.text = loc.name oldName.text = loc.oldName details.text = loc.details floor.text = loc.floor.toString() building.text = loc.building } } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var name: TextView = itemView.findViewById(R.id.loc_item_name) var oldName: TextView = itemView.findViewById(R.id.loc_item_old_name) var details: TextView = itemView.findViewById(R.id.loc_item_details) var floor: TextView = itemView.findViewById(R.id.loc_item_floor) var building: TextView = itemView.findViewById(R.id.loc_item_building) var icon: ImageView = itemView.findViewById(R.id.loc_item_icon) } }
mit
40d97e79003d6172bf06c350b2a9aa4d
38.170732
118
0.69848
4.340369
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stories/media/StoryEditorMedia.kt
1
5880
package org.wordpress.android.ui.stories.media import android.net.Uri import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import org.wordpress.android.R import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.pages.SnackbarMessageHolder import org.wordpress.android.ui.posts.ProgressDialogUiState import org.wordpress.android.ui.posts.ProgressDialogUiState.HiddenProgressDialog import org.wordpress.android.ui.posts.ProgressDialogUiState.VisibleProgressDialog import org.wordpress.android.ui.posts.editor.media.AddExistingMediaSource import org.wordpress.android.ui.posts.editor.media.AddExistingMediaToPostUseCase import org.wordpress.android.ui.posts.editor.media.AddLocalMediaToPostUseCase import org.wordpress.android.ui.posts.editor.media.EditorMediaListener import org.wordpress.android.ui.stories.media.StoryEditorMedia.AddMediaToStoryPostUiState.AddingMediaToStoryIdle import org.wordpress.android.ui.stories.media.StoryEditorMedia.AddMediaToStoryPostUiState.AddingMultipleMediaToStory import org.wordpress.android.ui.stories.media.StoryEditorMedia.AddMediaToStoryPostUiState.AddingSingleMediaToStory import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.util.MediaUtilsWrapper import org.wordpress.android.viewmodel.Event import javax.inject.Inject import javax.inject.Named import kotlin.coroutines.CoroutineContext class StoryEditorMedia @Inject constructor( private val mediaUtilsWrapper: MediaUtilsWrapper, private val addLocalMediaToPostUseCase: AddLocalMediaToPostUseCase, private val addExistingMediaToPostUseCase: AddExistingMediaToPostUseCase, @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher ) : CoroutineScope { // region Fields private var job: Job = Job() override val coroutineContext: CoroutineContext get() = mainDispatcher + job private lateinit var site: SiteModel private lateinit var editorMediaListener: EditorMediaListener private val _uiState: MutableLiveData<AddMediaToStoryPostUiState> = MutableLiveData() val uiState: LiveData<AddMediaToStoryPostUiState> = _uiState private val _snackBarMessage = MutableLiveData<Event<SnackbarMessageHolder>>() val snackBarMessage = _snackBarMessage as LiveData<Event<SnackbarMessageHolder>> fun start(site: SiteModel, editorMediaListener: EditorMediaListener) { this.site = site this.editorMediaListener = editorMediaListener _uiState.value = AddingMediaToStoryIdle } // region Adding new media to a post fun advertiseImageOptimisationAndAddMedia(uriList: List<Uri>) { if (mediaUtilsWrapper.shouldAdvertiseImageOptimization()) { editorMediaListener.advertiseImageOptimization { addNewMediaItemsToEditorAsync( uriList, false ) } } else { addNewMediaItemsToEditorAsync(uriList, false) } } fun addNewMediaItemsToEditorAsync(uriList: List<Uri>, freshlyTaken: Boolean) { launch { _uiState.value = if (uriList.size > 1) { AddingMultipleMediaToStory } else { AddingSingleMediaToStory } val allMediaSucceed = addLocalMediaToPostUseCase.addNewMediaToEditorAsync( uriList, site, freshlyTaken, editorMediaListener, false // don't start upload for StoryComposer, that'll be all started // when finished composing ) if (!allMediaSucceed) { _snackBarMessage.value = Event(SnackbarMessageHolder(UiStringRes(R.string.gallery_error))) } _uiState.value = AddingMediaToStoryIdle } } fun onPhotoPickerMediaChosen(uriList: List<Uri>) { val onlyVideos = uriList.all { mediaUtilsWrapper.isVideo(it.toString()) } if (onlyVideos) { addNewMediaItemsToEditorAsync(uriList, false) } else { advertiseImageOptimisationAndAddMedia(uriList) } } // endregion fun addExistingMediaToEditorAsync(source: AddExistingMediaSource, mediaIdList: List<Long>) { launch { addExistingMediaToPostUseCase.addMediaExistingInRemoteToEditorAsync( site, source, mediaIdList, editorMediaListener ) } } fun cancelAddMediaToEditorActions() { job.cancel() } sealed class AddMediaToStoryPostUiState( val editorOverlayVisibility: Boolean, val progressDialogUiState: ProgressDialogUiState ) { /** * Adding multiple media items at once can take several seconds on slower devices, so we show a blocking * progress dialog in this situation - otherwise the user could accidentally back out of the process * before all items were added */ object AddingMultipleMediaToStory : AddMediaToStoryPostUiState( editorOverlayVisibility = true, progressDialogUiState = VisibleProgressDialog( messageString = UiStringRes(R.string.add_media_progress), cancelable = false, indeterminate = true ) ) object AddingSingleMediaToStory : AddMediaToStoryPostUiState(true, HiddenProgressDialog) object AddingMediaToStoryIdle : AddMediaToStoryPostUiState(false, HiddenProgressDialog) } }
gpl-2.0
445748a220bf6a7229b9bc69f6512b4e
40.702128
116
0.702211
5.54717
false
false
false
false
syler/heroku-lab
src/main/kotlin/com/_1few/lab/Controllers/UserController.kt
1
1167
package com._1few.lab.Controllers import com._1few.lab.EmployeeRepository import com._1few.lab.Model.Employee import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping @Controller @RequestMapping("/users") class UserController { @Autowired lateinit var repo: EmployeeRepository @RequestMapping("") fun index(model: Model): String { val employees = repo.findAll().toMutableList() if (employees.count() == 0) { val zxc = Employee(id = 1, firstName = "zhou", lastName = "xing xing") repo.save(zxc) employees.add(zxc) } model.addAttribute("users", employees) return "users/index" } @GetMapping("get/{id}") fun getbyId(model: Model, @PathVariable("id") id: Long): String { val employee = repo.findOne(id) model.addAttribute("user", employee) return "users/detail" } }
gpl-3.0
5afe406f66aa8f0f0d2ec55d8629d1ca
31.444444
82
0.694944
4.138298
false
false
false
false
leantechstacks/jcart-backoffice-service
src/main/kotlin/com/leantechstacks/jcart/bo/web/controllers/ProductController.kt
1
3187
package com.leantechstacks.jcart.bo.web.controllers import com.leantechstacks.jcart.bo.entities.Product import com.leantechstacks.jcart.bo.exceptions.InvalidCategoryException import com.leantechstacks.jcart.bo.exceptions.InvalidProductException import com.leantechstacks.jcart.bo.repositories.CategoryRepository import com.leantechstacks.jcart.bo.repositories.ProductRepository import com.leantechstacks.jcart.bo.repositories.VendorRepository import com.leantechstacks.jcart.bo.web.model.ProductModel import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.math.BigDecimal @RestController class ProductController(private val productRepository: ProductRepository, private val vendorRepository: VendorRepository, private val categoryRepository: CategoryRepository) { @GetMapping("/products") fun listProducts(): List<ProductModel> { return productRepository.findAll().map { p -> map(p) } } private fun map(product: Product): ProductModel { return ProductModel( product.id, product.name, product.description, product.price, product.vendor, product.category.id ) } @PostMapping("/products") fun createProduct(@RequestBody product: ProductModel): ResponseEntity<ProductModel> { validateProduct(product) val productEntity = productRepository.save(product.toEntity()) return ResponseEntity(ProductModel(productEntity), HttpStatus.CREATED) } @PutMapping("/products/{productId}") fun updateProduct(@RequestBody product: ProductModel, @PathVariable productId: Long): ResponseEntity<ProductModel> { if (productRepository.findOne(productId) == null) { throw InvalidProductException() } product.id = productId validateProduct(product) val productEntity = productRepository.save(product.toEntity()) return ResponseEntity(ProductModel(productEntity), HttpStatus.OK) } @DeleteMapping("/products/{productId}") fun deleteProduct(@PathVariable productId: Long): ResponseEntity<ProductModel> { if (productRepository.findOne(productId) == null) { throw InvalidProductException() } productRepository.delete(productId) return ResponseEntity(HttpStatus.OK) } @GetMapping("/products/category/{categoryId}") fun getProductByCategory(@PathVariable categoryId: Long): List<ProductModel> { if (categoryRepository.findOne(categoryId) == null) { throw InvalidCategoryException() } return productRepository.findByCategoryId(categoryId).map {p-> map(p)} } private fun validateProduct(product: ProductModel) { if (product.name.trim().isEmpty() || product.price < BigDecimal.ZERO || vendorRepository.findOne(product.vendor.id) == null || categoryRepository.findOne(product.categoryId) == null) { throw InvalidProductException() } } }
apache-2.0
fc8216030c0b06548956a9b620276268
39.341772
120
0.694697
5.207516
false
false
false
false
ingokegel/intellij-community
platform/ml-impl/src/com/intellij/filePrediction/features/history/FileHistoryManagerWrapper.kt
6
3017
// 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 com.intellij.filePrediction.features.history import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.fileEditor.FileEditorManagerEvent import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.SequentialTaskExecutor @Service(Service.Level.PROJECT) class FileHistoryManagerWrapper(private val project: Project) : Disposable { companion object { private const val MAX_NGRAM_SEQUENCE = 3 fun getInstance(project: Project) = project.service<FileHistoryManagerWrapper>() fun getInstanceIfCreated(project: Project) = project.serviceIfCreated<FileHistoryManagerWrapper>() } private val executor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor("NextFilePrediction") private val lazyManager: Lazy<FileHistoryManager> = lazy { FileHistoryManager(FileHistoryPersistence.loadNGrams(project, MAX_NGRAM_SEQUENCE)) } private fun getManagerIfInitialized(): FileHistoryManager? { return if (lazyManager.isInitialized()) lazyManager.value else null } fun calcNGramFeatures(candidates: List<VirtualFile>): FilePredictionNGramFeatures? { val managerIfInitialized = getManagerIfInitialized() return managerIfInitialized?.calcNGramFeatures(candidates.map { it.url }) } fun calcNextFileProbability(file: VirtualFile): Double { return getManagerIfInitialized()?.calcNextFileProbability(file.url) ?: 0.0 } private fun onFileOpened(file: VirtualFile) { if (ProjectManagerImpl.isLight(project)) { return } executor.submit { BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, Runnable { lazyManager.value.onFileOpened(file.url) }) } } private fun onProjectClosed(project: Project) { ApplicationManager.getApplication().executeOnPooledThread { getManagerIfInitialized()?.saveFileHistory(project) } } override fun dispose() { executor.shutdown() } internal class ProjectClosureListener : ProjectManagerListener { override fun projectClosing(project: Project) { getInstanceIfCreated(project)?.onProjectClosed(project) } } internal class EditorManagerListener : FileEditorManagerListener { override fun selectionChanged(event: FileEditorManagerEvent) { val newFile = event.newFile ?: return getInstance(event.manager.project).onFileOpened(newFile) } } }
apache-2.0
e64684c0013fd42c458b4895d5c09053
38.181818
158
0.79052
5.019967
false
false
false
false
android/nowinandroid
core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/ConnectivityManagerNetworkMonitor.kt
1
3279
/* * 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 * * 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.nowinandroid.core.data.util import android.content.Context import android.net.ConnectivityManager import android.net.ConnectivityManager.NetworkCallback import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest.Builder import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.core.content.getSystemService import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate class ConnectivityManagerNetworkMonitor @Inject constructor( @ApplicationContext private val context: Context ) : NetworkMonitor { override val isOnline: Flow<Boolean> = callbackFlow { val connectivityManager = context.getSystemService<ConnectivityManager>() /** * The callback's methods are invoked on changes to *any* network, not just the active * network. So to check for network connectivity, one must query the active network of the * ConnectivityManager. */ val callback = object : NetworkCallback() { override fun onAvailable(network: Network) { channel.trySend(connectivityManager.isCurrentlyConnected()) } override fun onLost(network: Network) { channel.trySend(connectivityManager.isCurrentlyConnected()) } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { channel.trySend(connectivityManager.isCurrentlyConnected()) } } connectivityManager?.registerNetworkCallback( Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(), callback ) channel.trySend(connectivityManager.isCurrentlyConnected()) awaitClose { connectivityManager?.unregisterNetworkCallback(callback) } } .conflate() @Suppress("DEPRECATION") private fun ConnectivityManager?.isCurrentlyConnected() = when (this) { null -> false else -> when { VERSION.SDK_INT >= VERSION_CODES.M -> activeNetwork ?.let(::getNetworkCapabilities) ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false else -> activeNetworkInfo?.isConnected ?: false } } }
apache-2.0
f3c76d56e59522e27f9df0689e8e7924
35.433333
98
0.683135
5.384236
false
false
false
false
WeltN24/WidgetAdapter
library/src/main/java/de/welt/widgetadapter/SimpleDiffCallback.kt
1
1082
package de.welt.widgetadapter import android.support.v7.util.DiffUtil interface Diffable { fun isItemTheSame(other: Any): Boolean = other == this fun isContentTheSame(other: Any): Boolean = other == this } class SimpleDiffCallback( val newItems: List<Any>, val oldItems: List<Any> ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = oldItems[oldItemPosition] val newItem = newItems[newItemPosition] return if (oldItem is Diffable) oldItem.isItemTheSame(newItem) else oldItem == newItem } override fun getOldListSize() = oldItems.size override fun getNewListSize() = newItems.size override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = oldItems[oldItemPosition] val newItem = newItems[newItemPosition] return if (oldItem is Diffable) oldItem.isContentTheSame(newItem) else oldItem == newItem } }
mit
9137f2b5de50cd9504e024532dd80e28
27.473684
90
0.670055
4.940639
false
false
false
false
TheCoinTosser/Kotlin-Koans---Solutions
src/i_introduction/_7_Nullable_Types/n07NullableTypes.kt
1
1136
package i_introduction._7_Nullable_Types import util.TODO import util.doc7 fun test() { val s: String = "this variable cannot store null references" val q: String? = null if (q != null) q.length // you have to check to dereference val i: Int? = q?.length // null val j: Int = q?.length ?: 0 // 0 } fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO( """ Task 7. Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression. Declarations of Client, PersonalInfo and Mailer are given below. """, documentation = doc7(), references = { JavaCode7().sendMessageToClient(client, message, mailer) } ) fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) { val email = client?.personalInfo?.email if(email != null && message != null){ mailer.sendMessage(email, message) } } class Client (val personalInfo: PersonalInfo?) class PersonalInfo (val email: String?) interface Mailer { fun sendMessage(email: String, message: String) }
mit
b405d60974fd5d6068f3ad7d5f329d24
26.707317
88
0.640845
4.071685
false
false
false
false
techprd/kotlin_node_js_seed
webapp/src/main/kotlin/services/Ajax.kt
1
988
package services import model.Task import org.w3c.xhr.* class Ajax { var xhttp: dynamic = XMLHttpRequest() fun get(url: String, callback: (XMLHttpRequest) -> Unit) { xhttp.open( method = "GET", url = url, async = true ) xhttp.onreadystatechange = { if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200) { callback(xhttp) } } xhttp.send() } fun post(url: String, task: Task, callback: (XMLHttpRequest) -> Unit) { xhttp.open( method = "POST", url = url, async = true ) xhttp.setRequestHeader("Content-type", "application/json"); xhttp.onreadystatechange = { if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200) { callback(xhttp) } } xhttp.send(JSON.stringify(task)) } }
mit
00cc3c189fec2ded55e08385673e98e1
23.121951
81
0.498988
4.277056
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/edit/EditQuestViewController.kt
1
16033
package io.ipoli.android.quest.edit import android.app.DatePickerDialog import android.app.Dialog import android.graphics.drawable.Drawable import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.text.TextWatcher import android.view.* import android.view.inputmethod.EditorInfo import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.material_design_iconic_typeface_library.MaterialDesignIconic import io.ipoli.android.R import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.datetime.minutes import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.text.DateFormatter import io.ipoli.android.common.text.DurationFormatter import io.ipoli.android.common.view.* import io.ipoli.android.quest.Color import io.ipoli.android.quest.Icon import io.ipoli.android.quest.edit.EditQuestViewState.StateType.* import io.ipoli.android.quest.reminder.formatter.ReminderTimeFormatter import io.ipoli.android.quest.reminder.picker.ReminderPickerDialogController import io.ipoli.android.quest.reminder.picker.ReminderViewModel import io.ipoli.android.quest.subquest.view.ReadOnlySubQuestAdapter import io.ipoli.android.tag.widget.EditItemAutocompleteTagAdapter import io.ipoli.android.tag.widget.EditItemTagAdapter import kotlinx.android.synthetic.main.controller_edit_quest.view.* import kotlinx.android.synthetic.main.item_edit_repeating_quest_sub_quest.view.* import kotlinx.android.synthetic.main.view_no_elevation_toolbar.view.* import org.threeten.bp.LocalDate import java.util.* /** * Created by Polina Zhelyazkova <[email protected]> * on 4/10/18. */ class EditQuestViewController(args: Bundle? = null) : ReduxViewController<EditQuestAction, EditQuestViewState, EditQuestReducer>(args) { override val reducer = EditQuestReducer private var questId: String? = null private var params: Params? = null private lateinit var newSubQuestWatcher: TextWatcher data class Params( val name: String?, val scheduleDate: LocalDate?, val startTime: Time?, val duration: Int?, val icon: Icon?, val color: Color?, val reminderViewModel: ReminderViewModel? ) constructor( questId: String?, params: Params? = null ) : this() { this.questId = questId this.params = params } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) applyStatusBarColors = false val view = inflater.inflate(R.layout.controller_edit_quest, container, false) setToolbar(view.toolbar) initSubQuests(view) view.questTagList.layoutManager = LinearLayoutManager(activity!!) view.questTagList.adapter = EditItemTagAdapter(removeTagCallback = { dispatch(EditQuestAction.RemoveTag(it)) }) return view } private fun initSubQuests(view: View) { val adapter = ReadOnlySubQuestAdapter(view.questSubQuestList, useLightTheme = true) view.questSubQuestList.layoutManager = LinearLayoutManager(activity!!) view.questSubQuestList.adapter = adapter newSubQuestWatcher = object : TextWatcher { override fun afterTextChanged(editable: Editable) { if (editable.isBlank()) { view.questAddSubQuest.invisible() } else { view.questAddSubQuest.visible() } } override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } } view.questSubQuestName.addTextChangedListener(newSubQuestWatcher) view.questAddSubQuest.onDebounceClick { addSubQuest(view) } view.questSubQuestName.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { addSubQuest(view) } true } } override fun onCreateLoadAction(): EditQuestAction? { return if (questId.isNullOrEmpty()) { EditQuestAction.StartAdd(params) } else { EditQuestAction.Load(questId!!, params) } } override fun onAttach(view: View) { super.onAttach(view) showBackButton() exitFullScreen() } private fun addSubQuest(view: View) { val name = view.questSubQuestName.text.toString() dispatch(EditQuestAction.AddSubQuest(name)) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.edit_quest_menu, menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> { router.handleBack() } R.id.actionSave -> { dispatch( EditQuestAction.Validate( view!!.questName.text.toString() ) ) true } else -> super.onOptionsItemSelected(item) } override fun render(state: EditQuestViewState, view: View) { when (state.type) { DATA_LOADED -> { toolbarTitle = state.toolbarTitle view.questName.setText(state.name) renderScheduledDate(view, state) renderStartTime(view, state) renderDuration(view, state) renderReminder(view, state) renderIcon(view, state) renderColor(view, state) renderSubQuests(view, state) renderChallenge(view, state) renderNote(view, state) renderTags(view, state) } TAGS_CHANGED -> { renderTags(view, state) } SCHEDULE_DATE_CHANGED -> { renderScheduledDate(view, state) } DURATION_CHANGED -> { renderDuration(view, state) } START_TIME_CHANGED -> { renderStartTime(view, state) } ICON_CHANGED -> { renderIcon(view, state) } COLOR_CHANGED -> { renderColor(view, state) } REMINDER_CHANGED -> { renderReminder(view, state) } CHALLENGE_CHANGED -> { renderChallenge(view, state) } NOTE_CHANGED -> { renderNote(view, state) } SUB_QUEST_ADDED -> { (view.questSubQuestList.adapter as ReadOnlySubQuestAdapter).add( ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel( UUID.randomUUID().toString(), state.newSubQuestName ) ) view.questSubQuestName.setText("") view.questSubQuestName.requestFocus() view.questAddSubQuest.invisible() } VALIDATION_ERROR_EMPTY_NAME -> { view.questName.error = stringRes(R.string.think_of_a_name) } VALIDATION_SUCCESSFUL -> { val newSubQuestNames = view.questSubQuestList.children.map { val v = it.editSubQuestName v.tag.toString() to v.text.toString() }.toMap() dispatch(EditQuestAction.Save(newSubQuestNames)) router.handleBack() } else -> { } } } private fun renderTags( view: View, state: EditQuestViewState ) { (view.questTagList.adapter as EditItemTagAdapter).updateAll(state.tagViewModels) val add = view.addQuestTag if (state.maxTagsReached) { add.gone() view.maxTagsMessage.visible() } else { add.visible() view.maxTagsMessage.gone() val adapter = EditItemAutocompleteTagAdapter(state.tags, activity!!) add.setAdapter(adapter) add.setOnItemClickListener { _, _, position, _ -> dispatch(EditQuestAction.AddTag(adapter.getItem(position).name)) add.setText("") } add.threshold = 0 add.setOnTouchListener { _, _ -> add.showDropDown() false } } } private fun renderSubQuests(view: View, state: EditQuestViewState) { (view.questSubQuestList.adapter as ReadOnlySubQuestAdapter).updateAll(state.subQuestViewModels) } override fun onDestroyView(view: View) { view.questSubQuestName.removeTextChangedListener(newSubQuestWatcher) super.onDestroyView(view) } private fun renderChallenge( view: View, state: EditQuestViewState ) { view.questChallenge.text = state.challengeText view.questChallenge.onDebounceClick { navigate().toChallengePicker(state.challenge) { challenge -> dispatch(EditQuestAction.ChangeChallenge(challenge)) } } } private fun renderScheduledDate( view: View, state: EditQuestViewState ) { view.questScheduleDate.text = state.scheduleDateText view.questScheduleDate.onDebounceClick { val date = state.scheduleDate ?: LocalDate.now() val datePickerDialog = DatePickerDialog( view.context, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> dispatch(EditQuestAction.ChangeDate(LocalDate.of(year, month + 1, dayOfMonth))) }, date.year, date.month.value - 1, date.dayOfMonth ) datePickerDialog.setButton( Dialog.BUTTON_NEUTRAL, view.context.getString(R.string.do_not_know) ) { _, _ -> dispatch(EditQuestAction.ChangeDate(null)) } datePickerDialog.show() } } private fun renderDuration( view: View, state: EditQuestViewState ) { view.questDuration.text = state.durationText view.questDuration.onDebounceClick { navigate() .toDurationPicker( state.duration.minutes ) { dispatch(EditQuestAction.ChangeDuration(it.intValue)) } } } private fun renderStartTime( view: View, state: EditQuestViewState ) { view.questStartTime.text = state.startTimeText view.questStartTime.onDebounceClick { val startTime = state.startTime ?: Time.now() createTimePickerDialog( startTime = startTime, onTimePicked = { dispatch(EditQuestAction.ChangeStartTime(it)) } ).show(router) } } private fun renderColor( view: View, state: EditQuestViewState ) { colorLayout(view, state) view.questColor.onDebounceClick { navigate().toColorPicker( { dispatch(EditQuestAction.ChangeColor(it)) }, state.color ) } } private fun renderIcon( view: View, state: EditQuestViewState ) { view.questSelectedIcon.setImageDrawable(state.iconDrawable) view.questIcon.onDebounceClick { navigate() .toIconPicker({ icon -> dispatch(EditQuestAction.ChangeIcon(icon)) }, state.icon) } } private fun colorLayout( view: View, state: EditQuestViewState ) { val color500 = colorRes(state.color500) val color700 = colorRes(state.color700) view.appbar.setBackgroundColor(color500) view.toolbar.setBackgroundColor(color500) view.rootContainer.setBackgroundColor(color500) activity?.window?.navigationBarColor = color500 activity?.window?.statusBarColor = color700 } private fun renderReminder( view: View, state: EditQuestViewState ) { view.questReminder.text = state.reminderText view.questReminder.onDebounceClick { navigate() .toReminderPicker( object : ReminderPickerDialogController.ReminderPickedListener { override fun onReminderPicked(reminder: ReminderViewModel?) { dispatch(EditQuestAction.ChangeReminder(reminder)) } }, state.reminder ) } } private fun renderNote(view: View, state: EditQuestViewState) { view.questNote.text = state.noteText view.questNote.onDebounceClick { navigate() .toNotePicker( note = state.note, resultListener = { note -> dispatch(EditQuestAction.ChangeNote(note)) } ) } } private val EditQuestViewState.scheduleDateText: String get() = DateFormatter.formatWithoutYear(view!!.context, scheduleDate) private val EditQuestViewState.color500: Int get() = color.androidColor.color500 private val EditQuestViewState.color700: Int get() = color.androidColor.color700 private val EditQuestViewState.iconDrawable: Drawable get() = if (icon == null) { ContextCompat.getDrawable(view!!.context, R.drawable.ic_icon_white_24dp)!! } else { val androidIcon = icon.androidIcon IconicsDrawable(view!!.context) .largeIcon(androidIcon.icon) } private val EditQuestViewState.noteText: String get() = if (note.isBlank()) stringRes(R.string.tap_to_add_note) else note private val EditQuestViewState.startTimeText: String get() = startTime?.let { "At ${it.toString(shouldUse24HourFormat)}" } ?: stringRes(R.string.unscheduled) private val EditQuestViewState.durationText: String get() = "For ${DurationFormatter.formatReadable(activity!!, duration)}" private val EditQuestViewState.reminderText: String get() = reminder?.let { ReminderTimeFormatter.format( it.minutesFromStart.toInt(), activity!! ) } ?: stringRes(R.string.do_not_remind) private val EditQuestViewState.challengeText: String get() = challenge?.name ?: stringRes(R.string.add_to_challenge) private val EditQuestViewState.subQuestViewModels: List<ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel> get() = subQuests.entries.map { ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel( id = it.key, name = it.value.name ) } private val EditQuestViewState.tagViewModels: List<EditItemTagAdapter.TagViewModel> get() = questTags.map { EditItemTagAdapter.TagViewModel( name = it.name, icon = it.icon?.androidIcon?.icon ?: MaterialDesignIconic.Icon.gmi_label, tag = it ) } private val EditQuestViewState.toolbarTitle: String get() = stringRes(if (id.isEmpty()) R.string.title_add_quest else R.string.title_edit_quest) }
gpl-3.0
2b75920c9aaa76ef088209583439a1f8
31.521298
110
0.590844
5.168601
false
false
false
false
GunoH/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/AddAccessorsFactories.kt
1
1915
// 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.quickfix.fixes import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.idea.codeinsight.api.applicable.KotlinApplicableQuickFix import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactories import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddAccessorUtils import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddAccessorUtils.addAccessors import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtProperty object AddAccessorsFactories { val addAccessorsToUninitializedProperty = diagnosticFixFactories( KtFirDiagnostic.MustBeInitialized::class, KtFirDiagnostic.MustBeInitializedOrBeAbstract::class ) { diagnostic -> val property: KtProperty = diagnostic.psi val addGetter = property.getter == null val addSetter = property.isVar && property.setter == null if (!addGetter && !addSetter) return@diagnosticFixFactories emptyList() listOf( AddAccessorsQuickFix(property, addGetter, addSetter) ) } private class AddAccessorsQuickFix( target: KtProperty, private val addGetter: Boolean, private val addSetter: Boolean, ) : KotlinApplicableQuickFix<KtProperty>(target) { override fun getFamilyName(): String = AddAccessorUtils.familyAndActionName(addGetter, addSetter) override fun apply(element: KtProperty, project: Project, editor: Editor?, file: KtFile) = addAccessors(element, addGetter, addSetter, editor) } }
apache-2.0
5286cf86276b1e1633062963d8f3f3f1
48.128205
158
0.743081
4.7875
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/todo/TodoPanelCoroutineHelper.kt
2
2056
// 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.ide.todo import com.intellij.openapi.Disposable import com.intellij.openapi.application.EDT import com.intellij.openapi.application.readAction import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiDocumentManager import com.intellij.usageView.UsageInfo import com.intellij.util.ui.tree.TreeUtil import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal private class TodoPanelCoroutineHelper(private val panel: TodoPanel) : Disposable { private val scope = CoroutineScope(SupervisorJob()) init { Disposer.register(panel, this) } override fun dispose() { scope.cancel() } fun schedulePreviewPanelLayoutUpdate() { scope.launch(Dispatchers.EDT) { if (!panel.usagePreviewPanel.isVisible) return@launch val lastUserObject = TreeUtil.getLastUserObject(panel.tree.selectionPath) val usageInfos = if (lastUserObject != null) { readAction { val pointer = panel.treeBuilder.getFirstPointerForElement(lastUserObject) if (pointer != null) { val value = pointer.value!! val psiFile = PsiDocumentManager.getInstance(panel.myProject).getPsiFile(value.document) if (psiFile != null) { val rangeMarker = value.rangeMarker val usageInfos = mutableListOf( UsageInfo(psiFile, rangeMarker.startOffset, rangeMarker.endOffset), ) value.additionalRangeMarkers .filter { it.isValid } .mapTo(usageInfos) { UsageInfo(psiFile, it.startOffset, it.endOffset) } } else { emptyList() } } else { emptyList() } } } else { emptyList() } panel.usagePreviewPanel.updateLayout(usageInfos.ifEmpty { null }) } } }
apache-2.0
91e598cff39d5809ab6cd287dbb2a4e3
29.25
120
0.647374
4.814988
false
false
false
false