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
GunoH/intellij-community
python/src/com/jetbrains/python/run/TargetedPythonPaths.kt
2
9427
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("TargetedPythonPaths") package com.jetbrains.python.run import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.execution.target.value.TargetEnvironmentFunction import com.intellij.execution.target.value.constant import com.intellij.execution.target.value.targetPath import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkAdditionalData import com.intellij.openapi.roots.CompilerModuleExtension import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.remote.RemoteSdkProperties import com.intellij.util.PlatformUtils import com.jetbrains.python.PythonHelpersLocator import com.jetbrains.python.facet.LibraryContributingFacet import com.jetbrains.python.library.PythonLibraryType import com.jetbrains.python.remote.PyRemotePathMapper import com.jetbrains.python.run.target.getTargetPathForPythonConsoleExecution import com.jetbrains.python.sdk.PythonEnvUtil import com.jetbrains.python.sdk.PythonSdkAdditionalData import com.jetbrains.python.sdk.PythonSdkUtil import com.jetbrains.python.sdk.flavors.JythonSdkFlavor import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import java.io.File import java.nio.file.Path fun initPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>, passParentEnvs: Boolean, pythonPathList: MutableCollection<TargetEnvironmentFunction<String>>, targetEnvironmentRequest: TargetEnvironmentRequest) { // TODO [Targets API] Passing parent envs logic should be moved somewhere else if (passParentEnvs && targetEnvironmentRequest is LocalTargetEnvironmentRequest && !envs.containsKey(PythonEnvUtil.PYTHONPATH)) { appendSystemPythonPath(pythonPathList) } appendToPythonPath(envs, pythonPathList, targetEnvironmentRequest.targetPlatform) } private fun appendSystemPythonPath(pythonPath: MutableCollection<TargetEnvironmentFunction<String>>) { val syspath = System.getenv(PythonEnvUtil.PYTHONPATH) if (syspath != null) { pythonPath.addAll(syspath.split(File.pathSeparator).dropLastWhile(String::isEmpty).map(::constant)) } } fun collectPythonPath(project: Project, module: Module?, sdkHome: String?, pathMapper: PyRemotePathMapper?, shouldAddContentRoots: Boolean, shouldAddSourceRoots: Boolean, isDebug: Boolean): Collection<TargetEnvironmentFunction<String>> { val sdk = PythonSdkUtil.findSdkByPath(sdkHome) return collectPythonPath( Context(project, sdk, pathMapper), module, sdkHome, shouldAddContentRoots, shouldAddSourceRoots, isDebug ) } private fun collectPythonPath(context: Context, module: Module?, sdkHome: String?, shouldAddContentRoots: Boolean, shouldAddSourceRoots: Boolean, isDebug: Boolean): Collection<TargetEnvironmentFunction<String>> { val pythonPath: MutableSet<TargetEnvironmentFunction<String>> = LinkedHashSet( collectPythonPath(context, module, shouldAddContentRoots, shouldAddSourceRoots) ) if (isDebug && PythonSdkFlavor.getFlavor(sdkHome) is JythonSdkFlavor) { //that fixes Jython problem changing sys.argv on execfile, see PY-8164 for (helpersResource in listOf("pycharm", "pydev")) { val helperPath = PythonHelpersLocator.getHelperPath(helpersResource) val targetHelperPath = targetPath(Path.of(helperPath)) pythonPath.add(targetHelperPath) } } return pythonPath } private fun collectPythonPath(context: Context, module: Module?, addContentRoots: Boolean, addSourceRoots: Boolean): Collection<TargetEnvironmentFunction<String>> { val pythonPathList: MutableCollection<TargetEnvironmentFunction<String>> = LinkedHashSet() if (module != null) { val dependencies: MutableSet<Module> = HashSet() ModuleUtilCore.getDependencies(module, dependencies) if (addContentRoots) { addRoots(context, pythonPathList, ModuleRootManager.getInstance(module).contentRoots) for (dependency in dependencies) { addRoots(context, pythonPathList, ModuleRootManager.getInstance(dependency).contentRoots) } } if (addSourceRoots) { addRoots(context, pythonPathList, ModuleRootManager.getInstance(module).sourceRoots) for (dependency in dependencies) { addRoots(context, pythonPathList, ModuleRootManager.getInstance(dependency).sourceRoots) } } addLibrariesFromModule(module, pythonPathList) addRootsFromModule(module, pythonPathList) for (dependency in dependencies) { addLibrariesFromModule(dependency, pythonPathList) addRootsFromModule(dependency, pythonPathList) } } return pythonPathList } /** * List of [target->targetPath] functions. TargetPaths are to be added to ``PYTHONPATH`` because user did so */ fun getAddedPaths(sdkAdditionalData: SdkAdditionalData): List<TargetEnvironmentFunction<String>> { val pathList: MutableList<TargetEnvironmentFunction<String>> = ArrayList() if (sdkAdditionalData is PythonSdkAdditionalData) { val addedPaths = if (sdkAdditionalData is RemoteSdkProperties) { sdkAdditionalData.addedPathFiles.map { sdkAdditionalData.pathMappings.convertToRemote(it.path) } } else { sdkAdditionalData.addedPathFiles.map { it.path } } for (file in addedPaths) { pathList.add(constant(file)) } } return pathList } private fun addToPythonPath(context: Context, file: VirtualFile, pathList: MutableCollection<TargetEnvironmentFunction<String>>) { if (file.fileSystem is JarFileSystem) { val realFile = JarFileSystem.getInstance().getVirtualFileForJar(file) if (realFile != null) { addIfNeeded(context, realFile, pathList) } } else { addIfNeeded(context, file, pathList) } } private fun addIfNeeded(context: Context, file: VirtualFile, pathList: MutableCollection<TargetEnvironmentFunction<String>>) { val filePath = Path.of(FileUtil.toSystemDependentName(file.path)) pathList.add(getTargetPathForPythonConsoleExecution(context.project, context.sdk, context.pathMapper, filePath)) } /** * Adds all libs from [module] to [pythonPathList] as [target,targetPath] func */ private fun addLibrariesFromModule(module: Module, pythonPathList: MutableCollection<TargetEnvironmentFunction<String>>) { val entries = ModuleRootManager.getInstance(module).orderEntries for (entry in entries) { if (entry is LibraryOrderEntry) { val name = entry.libraryName if (name != null && name.endsWith(LibraryContributingFacet.PYTHON_FACET_LIBRARY_NAME_SUFFIX)) { // skip libraries from Python facet continue } for (root in entry.getRootFiles(OrderRootType.CLASSES).mapNotNull { it.toNioPathOrNull() }) { val library = entry.library if (!PlatformUtils.isPyCharm()) { pythonPathList += targetPath(root) } else if (library is LibraryEx) { val kind = library.kind if (kind === PythonLibraryType.getInstance().kind) { pythonPathList += targetPath(root) } } } } } } /** * Returns a related [Path] for [this] virtual file where possible or `null` otherwise. * * Unlike [VirtualFile.toNioPath], this extension function does not throw [UnsupportedOperationException], but rather return `null` in the * same cases. */ private fun VirtualFile.toNioPathOrNull(): Path? = fileSystem.getNioPath(this) private fun addRootsFromModule(module: Module, pythonPathList: MutableCollection<TargetEnvironmentFunction<String>>) { // for Jython val extension = CompilerModuleExtension.getInstance(module) if (extension != null) { val path = extension.compilerOutputPath if (path != null) { pythonPathList.add(constant(path.path)) } val pathForTests = extension.compilerOutputPathForTests if (pathForTests != null) { pythonPathList.add(constant(pathForTests.path)) } } } private fun addRoots(context: Context, pythonPathList: MutableCollection<TargetEnvironmentFunction<String>>, roots: Array<VirtualFile>) { for (root in roots) { addToPythonPath(context, root, pythonPathList) } } private data class Context(val project: Project, val sdk: Sdk?, val pathMapper: PyRemotePathMapper?)
apache-2.0
03edf9a8bbb61c1210faee5b43217f47
40.350877
140
0.717938
5.019702
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClsStubBuilder.kt
2
6901
// 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.decompiler.classFile import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.compiled.ClsStubBuilder import com.intellij.psi.impl.compiled.ClassFileStubBuilder import com.intellij.psi.stubs.PsiFileStub import com.intellij.util.indexing.FileContent import org.jetbrains.kotlin.descriptors.SourceElement import org.jetbrains.kotlin.idea.caches.IDEKotlinBinaryClassCache import org.jetbrains.kotlin.idea.decompiler.stubBuilder.* import org.jetbrains.kotlin.load.kotlin.* import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.Flags import org.jetbrains.kotlin.metadata.deserialization.NameResolver import org.jetbrains.kotlin.metadata.deserialization.TypeTable import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.stubs.KotlinStubVersions import org.jetbrains.kotlin.serialization.deserialization.getClassId import org.jetbrains.kotlin.storage.LockBasedStorageManager open class KotlinClsStubBuilder : ClsStubBuilder() { override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + KotlinStubVersions.CLASSFILE_STUB_VERSION override fun buildFileStub(content: FileContent): PsiFileStub<*>? { val virtualFile = content.file if (isKotlinInternalCompiledFile(virtualFile, content.content)) { return null } if (isVersioned(virtualFile)) { // Kotlin can't build stubs for versioned class files, because list of versioned inner classes // might be incomplete return null } return doBuildFileStub(virtualFile, content.content) } private fun doBuildFileStub(file: VirtualFile, fileContent: ByteArray): PsiFileStub<KtFile>? { val kotlinClass = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClass(file, fileContent) ?: error("Can't find binary class for Kotlin file: $file") val header = kotlinClass.classHeader val classId = kotlinClass.classId val packageFqName = header.packageName?.let { FqName(it) } ?: classId.packageFqName if (!header.metadataVersion.isCompatible()) { return createIncompatibleAbiVersionFileStub() } val components = createStubBuilderComponents(file, packageFqName, fileContent) if (header.kind == KotlinClassHeader.Kind.MULTIFILE_CLASS) { val partFiles = findMultifileClassParts(file, classId, header.multifilePartNames) return createMultifileClassStub(header, partFiles, classId.asSingleFqName(), components) } val annotationData = header.data if (annotationData == null) { LOG.error("Corrupted kotlin header for file ${file.name}") return null } val strings = header.strings if (strings == null) { LOG.error("String table not found in file ${file.name}") return null } return when (header.kind) { KotlinClassHeader.Kind.CLASS -> { if (classId.isLocal) return null val (nameResolver, classProto) = JvmProtoBufUtil.readClassDataFrom(annotationData, strings) if (Flags.VISIBILITY.get(classProto.flags) == ProtoBuf.Visibility.LOCAL) { // Older Kotlin compiler versions didn't put 'INNERCLASS' attributes in some cases (e.g. for cross-inline lambdas), // so 'ClassFileViewProvider.isInnerClass()' pre-check won't find them (EA-105730). // Example: `Timer().schedule(1000) { foo () }`. return null } val context = components.createContext(nameResolver, packageFqName, TypeTable(classProto.typeTable)) createTopLevelClassStub(classId, classProto, KotlinJvmBinarySourceElement(kotlinClass), context, header.isScript) } KotlinClassHeader.Kind.FILE_FACADE -> { val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(annotationData, strings) val context = components.createContext(nameResolver, packageFqName, TypeTable(packageProto.typeTable)) val fqName = header.packageName?.let { ClassId(FqName(it), classId.relativeClassName, classId.isLocal).asSingleFqName() } ?: classId.asSingleFqName() createFileFacadeStub(packageProto, fqName, context) } else -> throw IllegalStateException("Should have processed " + file.path + " with header $header") } } private fun createStubBuilderComponents(file: VirtualFile, packageFqName: FqName, fileContent: ByteArray): ClsStubBuilderComponents { val classFinder = DirectoryBasedClassFinder(file.parent!!, packageFqName) val classDataFinder = DirectoryBasedDataFinder(classFinder, LOG) val annotationLoader = AnnotationLoaderForClassFileStubBuilder(classFinder, file, fileContent) return ClsStubBuilderComponents(classDataFinder, annotationLoader, file) } companion object { val LOG = Logger.getInstance(KotlinClsStubBuilder::class.java) // Archive separator + META-INF + versions private val VERSIONED_PATH_MARKER = "!/META-INF/versions/" fun isVersioned(virtualFile: VirtualFile): Boolean { return virtualFile.path.contains(VERSIONED_PATH_MARKER) } } } class AnnotationLoaderForClassFileStubBuilder( kotlinClassFinder: KotlinClassFinder, private val cachedFile: VirtualFile, private val cachedFileContent: ByteArray ) : AbstractBinaryClassAnnotationAndConstantLoader<ClassId, Unit>(LockBasedStorageManager.NO_LOCKS, kotlinClassFinder) { override fun getCachedFileContent(kotlinClass: KotlinJvmBinaryClass): ByteArray? { if ((kotlinClass as? VirtualFileKotlinClass)?.file == cachedFile) { return cachedFileContent } return null } override fun loadTypeAnnotation(proto: ProtoBuf.Annotation, nameResolver: NameResolver): ClassId = nameResolver.getClassId(proto.id) override fun loadConstant(desc: String, initializer: Any) = null override fun transformToUnsignedConstant(constant: Unit) = null override fun loadAnnotation( annotationClassId: ClassId, source: SourceElement, result: MutableList<ClassId> ): KotlinJvmBinaryClass.AnnotationArgumentVisitor? { result.add(annotationClassId) return null } }
apache-2.0
1d6c0107defc78426c4eb7005bb7d97e
47.258741
158
0.715693
4.986272
false
false
false
false
jwren/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRSearchQuery.kt
3
6104
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.request.search.GithubIssueSearchSort import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import java.text.ParseException import java.text.SimpleDateFormat internal class GHPRSearchQuery(private val terms: List<Term<*>>) { fun buildApiSearchQuery(searchQueryBuilder: GithubApiSearchQueryBuilder) { for (term in terms) { when (term) { is Term.QueryPart -> { searchQueryBuilder.query(term.apiValue) } is Term.Qualifier -> { searchQueryBuilder.qualifier(term.apiName, term.apiValue) } } } } fun isEmpty() = terms.isEmpty() override fun toString(): String = terms.joinToString(" ") override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is GHPRSearchQuery) return false if (terms != other.terms) return false return true } override fun hashCode(): Int = terms.hashCode() companion object { val DEFAULT = GHPRSearchQuery(listOf(Term.Qualifier.Enum(QualifierName.state, GithubIssueState.open))) val EMPTY = GHPRSearchQuery(listOf()) private val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd") fun parseFromString(string: String): GHPRSearchQuery { val result = mutableListOf<Term<*>>() val terms = string.trim().split(' ') for (term in terms) { if (term.isEmpty()) continue val colonIdx = term.indexOf(':') if (colonIdx < 0) { result.add(Term.QueryPart(term.replace("#", ""))) } else { try { result.add(QualifierName.valueOf(term.substring(0, colonIdx)).createTerm(term.substring(colonIdx + 1))) } catch (e: IllegalArgumentException) { result.add(Term.QueryPart(term)) } } } return GHPRSearchQuery(result) } } @Suppress("EnumEntryName") enum class QualifierName(val apiName: String) { state("state") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueState>(this, value) }, assignee("assignee") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, author("author") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, label("label") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, after("created") { override fun createTerm(value: String) = Term.Qualifier.Date.After.from(this, value) }, before("created") { override fun createTerm(value: String) = Term.Qualifier.Date.Before.from(this, value) }, reviewedBy("reviewed-by") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) override fun toString() = apiName }, reviewRequested("review-requested") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) override fun toString() = apiName }, sortBy("sort") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueSearchSort>(this, value) }; abstract fun createTerm(value: String): Term<*> } /** * Part of search query (search term) */ sealed class Term<T : Any>(protected val value: T) { abstract val apiValue: String? override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Term<*>) return false if (value != other.value) return false return true } override fun hashCode(): Int = value.hashCode() class QueryPart(value: String) : Term<String>(value) { override val apiValue = this.value override fun toString(): String = value } sealed class Qualifier<T : Any>(protected val name: QualifierName, value: T) : Term<T>(value) { val apiName: String = name.apiName override fun toString(): String = "$name:$value" class Simple(name: QualifierName, value: String) : Qualifier<String>(name, value) { override val apiValue = this.value } class Enum<T : kotlin.Enum<T>>(name: QualifierName, value: T) : Qualifier<kotlin.Enum<T>>(name, value) { override val apiValue = this.value.name companion object { inline fun <reified T : kotlin.Enum<T>> from(name: QualifierName, value: String): Term<*> { return try { Enum(name, enumValueOf<T>(value)) } catch (e: IllegalArgumentException) { Simple(name, value) } } } } sealed class Date(name: QualifierName, value: java.util.Date) : Qualifier<java.util.Date>(name, value) { protected fun formatDate(): String = DATE_FORMAT.format(this.value) override fun toString(): String = "$name:${formatDate()}" class Before(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = "<${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { val date = try { DATE_FORMAT.parse(value) } catch (e: ParseException) { return Simple(name, value) } return Before(name, date) } } } class After(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = ">${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { return try { After(name, DATE_FORMAT.parse(value)) } catch (e: ParseException) { Simple(name, value) } } } } } } } }
apache-2.0
d2c9802cc5e88ba3772959fe8d8a9fa8
30.963351
140
0.612549
4.363117
false
false
false
false
GunoH/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/auth/ui/AccountsPanelFactory.kt
2
7557
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.collaboration.auth.ui import com.intellij.collaboration.auth.Account import com.intellij.collaboration.auth.AccountManager import com.intellij.collaboration.auth.DefaultAccountHolder import com.intellij.collaboration.messages.CollaborationToolsBundle import com.intellij.collaboration.ui.findIndex import com.intellij.collaboration.ui.util.JListHoveredRowMaterialiser import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.ModalTaskOwner import com.intellij.openapi.progress.runBlockingModal import com.intellij.ui.LayeredIcon import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.ToolbarDecorator import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.JBList import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.Row import com.intellij.util.ui.StatusText import com.intellij.util.ui.UIUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.awt.event.MouseEvent import javax.swing.* class AccountsPanelFactory<A : Account, Cred> private constructor(private val accountManager: AccountManager<A, Cred>, private val defaultAccountHolder: DefaultAccountHolder<A>?, private val accountsModel: AccountsListModel<A, Cred>, private val scope: CoroutineScope) { constructor(scope: CoroutineScope, accountManager: AccountManager<A, Cred>, defaultAccountHolder: DefaultAccountHolder<A>, accountsModel: AccountsListModel.WithDefault<A, Cred>) : this(accountManager, defaultAccountHolder, accountsModel, scope) constructor(scope: CoroutineScope, accountManager: AccountManager<A, Cred>, accountsModel: AccountsListModel<A, Cred>) : this(accountManager, null, accountsModel, scope) fun accountsPanelCell(row: Row, detailsProvider: LoadingAccountsDetailsProvider<A, *>, actionsController: AccountsPanelActionsController<A>): Cell<JComponent> { val accountsList = createList(actionsController, detailsProvider) { SimpleAccountsListCellRenderer({ (accountManager is AccountsListModel.WithDefault<*, *>) && it == accountManager.defaultAccount }, detailsProvider, actionsController) } val component = wrapWithToolbar(accountsList, actionsController) return row.cell(component) .onIsModified(::isModified) .onReset(::reset) .onApply { apply(component) } } private fun isModified(): Boolean { val defaultModified = if (defaultAccountHolder != null && accountsModel is AccountsListModel.WithDefault) { accountsModel.defaultAccount != defaultAccountHolder.account } else false return accountsModel.newCredentials.isNotEmpty() || accountsModel.accounts != accountManager.accountsState.value || defaultModified } private fun reset() { accountsModel.accounts = accountManager.accountsState.value if (defaultAccountHolder != null && accountsModel is AccountsListModel.WithDefault) { accountsModel.defaultAccount = defaultAccountHolder.account } accountsModel.clearNewCredentials() } private fun apply(component: JComponent) { try { val newTokensMap = mutableMapOf<A, Cred?>() newTokensMap.putAll(accountsModel.newCredentials) for (account in accountsModel.accounts) { newTokensMap.putIfAbsent(account, null) } runBlockingModal(ModalTaskOwner.component(component), CollaborationToolsBundle.message("accounts.saving.credentials")) { accountManager.updateAccounts(newTokensMap) } accountsModel.clearNewCredentials() if (defaultAccountHolder != null && accountsModel is AccountsListModel.WithDefault) { val defaultAccount = accountsModel.defaultAccount defaultAccountHolder.account = defaultAccount } } catch (_: Exception) { } } private fun <R> createList(actionsController: AccountsPanelActionsController<A>, detailsLoadingVm: LoadingAccountsDetailsProvider<A, *>, listCellRendererFactory: () -> R) : JBList<A> where R : ListCellRenderer<A>, R : JComponent { val accountsList = JBList(accountsModel.accountsListModel).apply { val renderer = listCellRendererFactory() cellRenderer = renderer UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer)) selectionMode = ListSelectionModel.SINGLE_SELECTION } val rowMaterialiser = JListHoveredRowMaterialiser.install(accountsList, listCellRendererFactory()) scope.launch { detailsLoadingVm.loadingState.collect { accountsList.setPaintBusy(it) } } scope.launch { detailsLoadingVm.loadingCompletionFlow.collect { repaint(accountsList, it) rowMaterialiser.update() } } accountsList.addListSelectionListener { accountsModel.selectedAccount = accountsList.selectedValue } accountsList.emptyText.apply { appendText(CollaborationToolsBundle.message("accounts.none.added")) appendSecondaryText(CollaborationToolsBundle.message("accounts.add.link"), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES) { val event = it.source val relativePoint = if (event is MouseEvent) RelativePoint(event) else null actionsController.addAccount(accountsList, relativePoint) } appendSecondaryText(" (${KeymapUtil.getFirstKeyboardShortcutText(CommonShortcuts.getNew())})", StatusText.DEFAULT_ATTRIBUTES, null) } return accountsList } private fun repaint(list: JList<A>, account: A): Boolean { val idx = list.model.findIndex(account).takeIf { it >= 0 } ?: return true val cellBounds = list.getCellBounds(idx, idx) list.repaint(cellBounds) return false } private fun wrapWithToolbar(accountsList: JBList<A>, actionsController: AccountsPanelActionsController<A>): JPanel { val addIcon: Icon = if (actionsController.isAddActionWithPopup) LayeredIcon.ADD_WITH_DROPDOWN else AllIcons.General.Add val toolbar = ToolbarDecorator.createDecorator(accountsList) .disableUpDownActions() .setAddAction { actionsController.addAccount(accountsList, it.preferredPopupPoint) } .setAddIcon(addIcon) if (accountsModel is AccountsListModel.WithDefault) { toolbar.addExtraAction(object : ToolbarDecorator.ElementActionButton(CollaborationToolsBundle.message("accounts.set.default"), AllIcons.Actions.Checked) { override fun actionPerformed(e: AnActionEvent) { val selected = accountsList.selectedValue if (selected == accountsModel.defaultAccount) return if (selected != null) accountsModel.defaultAccount = selected } override fun updateButton(e: AnActionEvent) { isEnabled = isEnabled && accountsModel.defaultAccount != accountsList.selectedValue } override fun getActionUpdateThread() = ActionUpdateThread.EDT }) } return toolbar.createPanel() } }
apache-2.0
24f8af8d3a26f8cd7a286952df967e3a
41.455056
140
0.727008
5.051471
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/actions/GitSingleCommitActionGroup.kt
6
1700
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.actions import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsActions import com.intellij.vcs.log.CommitId import com.intellij.vcs.log.VcsLog import com.intellij.vcs.log.VcsLogDataKeys import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager internal abstract class GitSingleCommitActionGroup() : ActionGroup(), DumbAware { constructor(actionText: @NlsActions.ActionText String, isPopup: Boolean) : this() { templatePresentation.text = actionText setPopup(isPopup) } override fun hideIfNoVisibleChildren(): Boolean { return true } override fun getChildren(e: AnActionEvent?): Array<AnAction> { if (e == null) return AnAction.EMPTY_ARRAY val project = e.project val log = e.getData(VcsLogDataKeys.VCS_LOG) if (project == null || log == null) { return AnAction.EMPTY_ARRAY } val commits = log.selectedCommits if (commits.size != 1) return AnAction.EMPTY_ARRAY val commit = commits.first() val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(commit.root) ?: return AnAction.EMPTY_ARRAY return getChildren(e, project, log, repository, commit) } abstract fun getChildren(e: AnActionEvent, project: Project, log: VcsLog, repository: GitRepository, commit: CommitId): Array<AnAction> }
apache-2.0
fbd319f33523ccd1fc2374bcb6e9dd3d
36.8
140
0.770588
4.347826
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/rebase/GitRebaseCheckinHandlerFactory.kt
12
1956
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.rebase import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.checkin.VcsCheckinHandlerFactory import git4idea.GitVcs import git4idea.branch.GitRebaseParams import git4idea.i18n.GitBundle import git4idea.repo.GitRepository class GitRebaseCheckinHandlerFactory : VcsCheckinHandlerFactory(GitVcs.getKey()) { override fun createVcsHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { return object : CheckinHandler() { private var active: Boolean = false private lateinit var project: Project private lateinit var repository: GitRepository private lateinit var rebaseFrom: String override fun checkinSuccessful() { if (!active) return object : Task.Backgroundable(project, GitBundle.message("rebase.progress.indicator.title")) { override fun run(indicator: ProgressIndicator) { val params = GitRebaseParams.editCommits(repository.vcs.version, rebaseFrom, null, false) GitRebaseUtils.rebase(project, listOf(repository), params, indicator) } }.queue() } override fun acceptExecutor(executor: CommitExecutor?): Boolean { if (executor is GitAutoSquashCommitAction.GitRebaseAfterCommitExecutor) { active = true project = executor.project repository = executor.repository rebaseFrom = executor.hash return false } return true } } } }
apache-2.0
e14a50371b027ec5579e64dd664bb1da
38.14
140
0.74182
4.877805
false
false
false
false
angelolloqui/SwiftKotlin
Assets/Tests/KotlinTokenizer/control_flow.kt
1
1441
if (number == 3) {} if (number > 3 && number != 6) {} if (number > 3 || number == 0) {} if (number == null) {} if (item is Movie) {} if (!object.condition()) {} val number = number if (number != null) {} val number = this.method() if (number != null) {} val name = formatter.next(fromIndex = firstTokenIndex) if (name != null) {} val number = some.method() val param = object.itemAt(number) if (number != null && param != null) {} val obj = obj as? Movie if (obj != null) {} val movie = obj2 as? Movie if (movie != null) {} if (numbers.flatMap({ it % 2 }).size == 1) {} for (current in someObjects) {} for (i in 0 until count) {} for (i in 1 .. 3) {} while (a > 1 && b < 2) {} if (number != 3) { return } if (value() < 3) { return } if (!condition) { return } if (condition) { return } if (number != 3 || value() < 3) { return } if (number != 3 || disabled || !enabled || value() < 3 || (a != 1 && a != 2)) { return } if (number != 3 && value() < 3) { return } val number = number ?: return val value = some.method() ?: return val result = some.method() val param = result.number() if (result == null || param == null || param <= 1) { return } val value = some.method() if (value == null) { NSLog("Do other operations") return } val value = some.method() ?: throw Exception() val match = this.interactor.match if (match == null || !(interactor.userIsOwner || interactor.userIsPlayer)) { return }
mit
bd35a2231636f7ee29c0fe5da448201e
21.873016
79
0.579459
3.112311
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/execute/usecases/ShowResultDialogUseCase.kt
1
5769
package ch.rmy.android.http_shortcuts.activities.execute.usecases import android.content.Context import android.content.Intent import android.net.Uri import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.widget.ImageView import ch.rmy.android.framework.extensions.runIf import ch.rmy.android.framework.extensions.runIfNotNull import ch.rmy.android.framework.extensions.startActivity import ch.rmy.android.framework.utils.ClipboardUtil import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.ExecuteActivity import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId import ch.rmy.android.http_shortcuts.data.enums.ResponseDisplayAction import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.databinding.DialogTextBinding import ch.rmy.android.http_shortcuts.extensions.getSafeName import ch.rmy.android.http_shortcuts.extensions.loadImage import ch.rmy.android.http_shortcuts.extensions.reloadImageSpans import ch.rmy.android.http_shortcuts.extensions.showAndAwaitDismissal import ch.rmy.android.http_shortcuts.http.ShortcutResponse import ch.rmy.android.http_shortcuts.utils.ActivityProvider import ch.rmy.android.http_shortcuts.utils.DialogBuilder import ch.rmy.android.http_shortcuts.utils.FileTypeUtil import ch.rmy.android.http_shortcuts.utils.HTMLUtil import ch.rmy.android.http_shortcuts.utils.ShareUtil import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext import javax.inject.Inject class ShowResultDialogUseCase @Inject constructor( private val context: Context, private val activityProvider: ActivityProvider, private val clipboardUtil: ClipboardUtil, ) { suspend operator fun invoke(shortcut: ShortcutModel, response: ShortcutResponse?, output: String?) = coroutineScope { val shortcutName = shortcut.getSafeName(context) withContext(Dispatchers.Main) { val activity = activityProvider.getActivity() DialogBuilder(activity) .title(shortcutName) .let { builder -> if (output == null && FileTypeUtil.isImage(response?.contentType)) { val imageView = ImageView(activity) imageView.loadImage(response!!.contentFile!!, preventMemoryCache = true) builder.view(imageView) } else { val view = DialogTextBinding.inflate(LayoutInflater.from(activity)) val textView = view.text val finalOutput = (output ?: response?.getContentAsString(context) ?: "") .ifBlank { context.getString(R.string.message_blank_response) } .let { HTMLUtil.formatWithImageSupport(it, context, textView::reloadImageSpans, this) } textView.text = finalOutput textView.movementMethod = LinkMovementMethod.getInstance() builder.view(textView) } } .positive(R.string.dialog_ok) .runIfNotNull(shortcut.responseHandling?.displayActions?.firstOrNull()) { action -> val text = output ?: response?.getContentAsString(context) ?: "" when (action) { ResponseDisplayAction.RERUN -> { neutral(R.string.action_rerun_shortcut) { rerunShortcut(shortcut.id) } } ResponseDisplayAction.SHARE -> { runIf(text.isNotEmpty() && text.length < MAX_SHARE_LENGTH) { neutral(R.string.share_button) { shareResponse(shortcutName, text, response?.contentType ?: "", response?.contentFile) } } } ResponseDisplayAction.COPY -> { runIf(text.isNotEmpty() && text.length < MAX_COPY_LENGTH) { neutral(R.string.action_copy_response) { copyResponse(text) } } } ResponseDisplayAction.SAVE -> this } } .showAndAwaitDismissal() } } private fun rerunShortcut(shortcutId: ShortcutId) { ExecuteActivity.IntentBuilder(shortcutId) .startActivity(context) } private fun shareResponse(shortcutName: String, text: String, type: String, responseFileUri: Uri?) { if (shouldShareAsText(text, type)) { ShareUtil.shareText(context, text) } else { Intent(Intent.ACTION_SEND) .setType(type) .putExtra(Intent.EXTRA_STREAM, responseFileUri) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) .let { Intent.createChooser(it, shortcutName) } .startActivity(activityProvider.getActivity()) } } private fun shouldShareAsText(text: String, type: String) = !FileTypeUtil.isImage(type) && text.length < MAX_SHARE_LENGTH private fun copyResponse(text: String) { clipboardUtil.copyToClipboard(text) } companion object { private const val MAX_SHARE_LENGTH = 300000 private const val MAX_COPY_LENGTH = 300000 } }
mit
d65205288e14eb95cec61d5d89c58d9c
44.425197
121
0.606691
5.091792
false
false
false
false
MyCollab/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/ui/format/ProjectMemberHistoryFieldFormat.kt
3
3018
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.ui.format import com.hp.gagawa.java.elements.A import com.hp.gagawa.java.elements.Img import com.mycollab.core.utils.StringUtils import com.mycollab.html.DivLessFormatter import com.mycollab.module.file.service.AbstractStorageService import com.mycollab.module.user.domain.SimpleUser import com.mycollab.module.user.service.UserService import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.TooltipHelper import com.mycollab.vaadin.TooltipHelper.TOOLTIP_ID import com.mycollab.vaadin.UserUIContext import com.mycollab.vaadin.ui.formatter.HistoryFieldFormat import com.mycollab.vaadin.web.ui.WebThemes import org.slf4j.LoggerFactory /** * @author MyCollab Ltd. * @since 4.0 */ class ProjectMemberHistoryFieldFormat : HistoryFieldFormat { override fun toString(value: String): String = toString(UserUIContext.getUser(), value, true, "") override fun toString(currentViewUser:SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String { if (StringUtils.isBlank(value)) { return msgIfBlank } try { val userService = AppContextUtil.getSpringBean(UserService::class.java) val user = userService.findUserByUserNameInAccount(value, AppUI.accountId) if (user != null) { return if (displayAsHtml) { val userAvatar = Img("", AppContextUtil.getSpringBean(AbstractStorageService::class.java) .getAvatarPath(user.avatarid, 16)).setCSSClass(WebThemes.CIRCLE_BOX) val link = A().setId("tag" + TOOLTIP_ID).appendText(StringUtils.trim(user.displayName, 30, true)) link.setAttribute("onmouseover", TooltipHelper.userHoverJsFunction(user.username)) link.setAttribute("onmouseleave", TooltipHelper.itemMouseLeaveJsFunction()) DivLessFormatter().appendChild(userAvatar, DivLessFormatter.EMPTY_SPACE, link).write() } else user.displayName!! } } catch (e: Exception) { LOG.error("Error", e) } return value } companion object { private val LOG = LoggerFactory.getLogger(ProjectMemberHistoryFieldFormat::class.java) } }
agpl-3.0
ba7adaaade68196ab3a1fbb1a603e067
41.492958
122
0.71064
4.40438
false
false
false
false
saksmt/karaf-runner
src/main/java/run/smt/karafrunner/modules/impl/installation/BaseInstallationModule.kt
1
2493
package run.smt.karafrunner.modules.impl.installation import org.kohsuke.args4j.Option import run.smt.karafrunner.io.exception.UserErrorException import run.smt.karafrunner.io.output.hightlight import run.smt.karafrunner.io.output.info import run.smt.karafrunner.io.output.success import run.smt.karafrunner.io.output.warning import run.smt.karafrunner.logic.* import run.smt.karafrunner.logic.installation.base.AssemblyInstaller import run.smt.karafrunner.logic.installation.base.ImageInstaller import run.smt.karafrunner.logic.installation.instance.Installer import run.smt.karafrunner.logic.manager.ConfigurationManager import run.smt.karafrunner.logic.manager.ImageManager import run.smt.karafrunner.logic.manager.TemplateManager import run.smt.karafrunner.logic.provider.DeploymentFileProvider import run.smt.karafrunner.modules.impl.InstanceAwareModule import java.io.File abstract class BaseInstallationModule : InstanceAwareModule() { @Option(name = "--env", aliases = arrayOf("--environment", "-e"), required = false) protected var env: String? = null @Option(name = "--use-assembly", aliases = arrayOf("-A"), required = false) protected open var useAssembly = false @Option(name = "--project-name", aliases = arrayOf("-p"), required = false) protected var projectNames: Array<String>? = null @Option(name = "--no-project", aliases = arrayOf("-P"), forbids = arrayOf("-p")) protected var noProject = false protected val imageManager by lazy { if (useAssembly) { AssemblyInstaller(targetInstance) } else { ImageInstaller(targetInstance, ImageManager(imageName)) } } protected val templateManager by lazy { TemplateManager(File(templatesPath), env) } protected abstract val deploymentProvider: DeploymentFileProvider protected val installer by lazy { Installer(configurationManager, templateManager, imageManager, deploymentProvider) } protected val preparedProjectNames: Set<String>? by lazy { if (noProject) { emptySet() } else { projectNames?.toSet() } } override fun doRun() { info("Installing...") if (env == null) { warning("Environment is not set! (use -e to set it)") } info("Using ${imageName.hightlight()} as base image") installer .install(targetInstance, env, preparedProjectNames) success("Installed!") } }
mit
368fd682cba16056d6533d40b8af5799
37.369231
90
0.707581
4.428064
false
false
false
false
bixlabs/bkotlin
bkotlin/src/main/java/com/bixlabs/bkotlin/Color.kt
1
2080
package com.bixlabs.bkotlin import android.annotation.SuppressLint import android.content.Context import android.content.res.Resources import android.graphics.Color import android.os.Build import androidx.annotation.ColorRes /** * Return the color with 0xFF opacity. * E.g., `0xabcdef` will be translated to `0xFFabcdef`. */ val Int.opaque: Int get() = this or 0xff000000.toInt() /** * Return the color with the given alpha value. * Examples: * ``` * 0xabcdef.withAlpha(0xCF) == 0xCFabcdef * 0xFFabcdef.withAlpha(0xCF) == 0xCFabcdef * ``` * * @param alpha the alpha channel value: [0x0..0xFF]. * @return the color with the given alpha value applied. */ fun Int.withAlpha(alpha: Int): Int { require(alpha in 0..0xFF) return this and 0x00FFFFFF or (alpha shl 24) } /** * Returns a themed color integer associated with a particular resource ID. * If the resource holds a complex ColorStateList, then the default color from the set is returned. * @param [color] The color resource * @param [theme] Resources.Theme: The theme used to style the color attributes, may be null. The same * will not be used on Android versions lower than Marshmallow. * @return A single color value in the form 0xAARRGGBB */ @SuppressLint("NewApi") fun Context.getColorCompat(@ColorRes color: Int, theme: Resources.Theme? = null): Int { var c: Int = 0 doStartingFromSdk(Build.VERSION_CODES.M, { c = this.resources.getColor(color, theme) }, { c = this.resources.getColor(color) }) return c } /** * Get a brighter (luma) version of this [Color] */ fun Int.getLuma(): Double = 0.299 * Color.red(this) + 0.587 * Color.green(this) + 0.114 * Color.blue(this) /** * Get a darker version of this [Color] */ fun Int.getDarker(alpha: Float): Int = Color.rgb((Color.red(this) * alpha).toInt(), (Color.green(this) * alpha).toInt(), (Color.blue(this) * alpha).toInt()) /** * Convert this color to a HEX [String] */ fun Int.toHexString(): String = String.format("#%06X", 0xFFFFFF and this)
apache-2.0
5c46c17eaf42d8235613dc218086005e
28.309859
102
0.680769
3.460899
false
false
false
false
facebook/fresco
vito/options/src/main/java/com/facebook/fresco/vito/options/EncodedImageOptions.kt
2
2059
/* * 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.options import com.facebook.common.internal.Objects import com.facebook.imagepipeline.common.Priority import com.facebook.imagepipeline.request.ImageRequest.CacheChoice open class EncodedImageOptions(builder: Builder<*>) { val priority: Priority? = builder.priority val cacheChoice: CacheChoice? = builder.cacheChoice override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null || javaClass != other.javaClass) { return false } return equalEncodedOptions(other as EncodedImageOptions) } protected fun equalEncodedOptions(other: EncodedImageOptions): Boolean { return Objects.equal(priority, other.priority) && Objects.equal(cacheChoice, other.cacheChoice) } override fun hashCode(): Int { val result = priority?.hashCode() ?: 0 return 31 * result + (cacheChoice?.hashCode() ?: 0) } override fun toString(): String = toStringHelper().toString() protected open fun toStringHelper(): Objects.ToStringHelper = Objects.toStringHelper(this).add("priority", priority).add("cacheChoice", cacheChoice) open class Builder<T : Builder<T>> { internal var priority: Priority? = null internal var cacheChoice: CacheChoice? = null protected constructor() protected constructor(defaultOptions: EncodedImageOptions) { priority = defaultOptions.priority cacheChoice = defaultOptions.cacheChoice } fun priority(priority: Priority?): T = modify { this.priority = priority } fun cacheChoice(cacheChoice: CacheChoice?): T = modify { this.cacheChoice = cacheChoice } open fun build(): EncodedImageOptions = EncodedImageOptions(this) protected fun getThis(): T = this as T private inline fun modify(block: Builder<T>.() -> Unit): T { block() return getThis() } } }
mit
6c3eefe45a40839bc4eabc87c71b2fa9
30.676923
99
0.711025
4.447084
false
false
false
false
AsynkronIT/protoactor-kotlin
proto-actor/src/test/kotlin/actor/proto/tests/LocalContextTests.kt
1
1022
package actor.proto.tests import actor.proto.Actor import actor.proto.ActorContext import actor.proto.PID import actor.proto.fixture.DoNothingSupervisorStrategy import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Test import java.time.Duration class LocalContextTests { @Test fun `given context ctor should set required fields`() { val producer: () -> Actor = { NullActor } val supervisorStrategyMock = DoNothingSupervisorStrategy() val parent = PID("test", "test") val self = PID("abc", "def") val context = ActorContext(producer, self, supervisorStrategyMock, listOf(), listOf(), parent) assertEquals(parent, context.parent) assertNull(context.sender) assertNotNull(context.children) assertEquals(context.children, setOf<PID>()) assertEquals(Duration.ZERO, context.getReceiveTimeout()) } }
apache-2.0
eaa815351f6735183232d2b749ad51ec
35.5
102
0.73092
4.348936
false
true
false
false
j-selby/kotgb
lwjgl/src/net/jselby/kotgb/lwjgl/ui/NanoVGWindow.kt
1
1086
package net.jselby.kotgb.lwjgl.ui import org.lwjgl.nanovg.NanoVGGL3.* import org.lwjgl.system.MemoryUtil.NULL import org.lwjgl.system.NativeResource /** * The NanoVG handler is able to process events and render * GLFW windows via NanoVG. */ abstract class NanoVGWindow(flags : Int = NVG_STENCIL_STROKES or NVG_DEBUG or NVG_ANTIALIAS) : Window(), NativeResource { private var nvg = nvgCreate(flags) init { if (nvg == NULL) { error("Unable to create NanoVG instance!") } } /** * Draws a Window. * * A OpenGL context is already available and ready, * and NanoVG will be automatically handled for you. * * Events should not be handled here. * * @param window The active window which will be drawn to * @param nvg A instance of NanoVG, ready to be used for rendering. */ abstract fun draw(nvg : Long) final override fun draw() = draw(nvg) override fun close() { super<Window>.close() nvgDelete(nvg) } }
mit
ca2637e7227f8597b970f3e059b66590
24.880952
84
0.61326
3.963504
false
false
false
false
industrial-data-space/trusted-connector
ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/NodeData.kt
1
7560
/*- * ========================LICENSE_START================================= * ids-route-manager * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.rm.util import org.apache.camel.model.AggregateDefinition import org.apache.camel.model.BeanDefinition import org.apache.camel.model.ChoiceDefinition import org.apache.camel.model.FilterDefinition import org.apache.camel.model.FromDefinition import org.apache.camel.model.OtherwiseDefinition import org.apache.camel.model.ProcessorDefinition import org.apache.camel.model.RecipientListDefinition import org.apache.camel.model.ResequenceDefinition import org.apache.camel.model.RoutingSlipDefinition import org.apache.camel.model.SplitDefinition import org.apache.camel.model.ToDefinition import org.apache.camel.model.TransformDefinition import org.apache.camel.model.WhenDefinition import org.apache.camel.util.ObjectHelper import java.util.Locale /** Represents a node in Graphviz representation of a route. */ class NodeData(var id: String, node: Any?, imagePrefix: String) { var image: String? = null var label: String? = null var shape: String? = null var edgeLabel: String? = null var tooltip: String? = null var nodeType: String? = null var nodeWritten = false var url: String? = null var outputs: List<ProcessorDefinition<*>>? = null private fun removeQueryString(text: String?): String? { return text?.indexOf('?')?.let { idx -> if (idx <= 0) { text } else { text.substring(0, idx) } } } companion object { /** Inserts a space before each upper case letter after a lowercase */ fun insertSpacesBetweenCamelCase(name: String): String { var lastCharacterLowerCase = false val buffer = StringBuilder() var i = 0 val size = name.length while (i < size) { val ch = name[i] lastCharacterLowerCase = if (Character.isUpperCase(ch)) { if (lastCharacterLowerCase) { buffer.append(' ') } false } else { true } buffer.append(ch) i++ } return buffer.toString() } } init { if (node is ProcessorDefinition<*>) { edgeLabel = node.label } when (node) { is FromDefinition -> { tooltip = node.label label = removeQueryString(tooltip) url = "http://camel.apache.org/message-endpoint.html" } is ToDefinition -> { tooltip = node.label label = removeQueryString(tooltip) edgeLabel = "" url = "http://camel.apache.org/message-endpoint.html" } is FilterDefinition -> { image = imagePrefix + "MessageFilterIcon.png" label = "Filter" nodeType = "Message Filter" } is WhenDefinition -> { image = imagePrefix + "MessageFilterIcon.png" nodeType = "When Filter" label = "When" url = "http://camel.apache.org/content-based-router.html" } is OtherwiseDefinition -> { nodeType = "Otherwise" edgeLabel = "" url = "http://camel.apache.org/content-based-router.html" tooltip = "Otherwise" } is ChoiceDefinition -> { image = imagePrefix + "ContentBasedRouterIcon.png" nodeType = "Content Based Router" label = "Choice" edgeLabel = "" val choice = node val outputs: MutableList<ProcessorDefinition<*>> = ArrayList(choice.whenClauses) if (choice.otherwise != null) { outputs.add(choice.otherwise) } this.outputs = outputs } is RecipientListDefinition<*> -> { image = imagePrefix + "RecipientListIcon.png" nodeType = "Recipient List" } is RoutingSlipDefinition<*> -> { image = imagePrefix + "RoutingTableIcon.png" nodeType = "Routing Slip" url = "http://camel.apache.org/routing-slip.html" } is SplitDefinition -> { image = imagePrefix + "SplitterIcon.png" nodeType = "Splitter" } is AggregateDefinition -> { image = imagePrefix + "AggregatorIcon.png" nodeType = "Aggregator" } is ResequenceDefinition -> { image = imagePrefix + "ResequencerIcon.png" nodeType = "Resequencer" } is BeanDefinition -> { nodeType = "Bean Ref" label = node.label + " Bean" shape = "box" } is TransformDefinition -> { nodeType = "Transform" url = "http://camel.apache.org/message-translator.html" } } // lets auto-default as many values as we can if (ObjectHelper.isEmpty(nodeType) && node != null) { var name = node.javaClass.name val idx = name.lastIndexOf('.') if (idx > 0) { name = name.substring(idx + 1) } if (name.endsWith("Type")) { name = name.substring(0, name.length - 4) } nodeType = insertSpacesBetweenCamelCase(name) } if (label == null) { if (ObjectHelper.isEmpty(image)) { label = nodeType shape = "box" } else if (ObjectHelper.isNotEmpty(edgeLabel)) { label = "" } else { label = node.toString() } } if (ObjectHelper.isEmpty(tooltip)) { if (ObjectHelper.isNotEmpty(nodeType)) { val description = if (ObjectHelper.isNotEmpty(edgeLabel)) edgeLabel else label tooltip = nodeType + ": " + description } else { tooltip = label } } if (ObjectHelper.isEmpty(url) && ObjectHelper.isNotEmpty(nodeType)) { url = ( "http://camel.apache.org/" + nodeType!!.lowercase(Locale.ENGLISH).replace(' ', '-') + ".html" ) } if (node is ProcessorDefinition<*> && outputs == null) { outputs = node.outputs } } }
apache-2.0
f47590b037a179549d81d699cd63ec18
35.878049
96
0.520635
4.890039
false
false
false
false
cketti/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/messagelist/MessageListViewHolder.kt
1
1165
package com.fsck.k9.ui.messagelist import android.view.View import android.widget.CheckBox import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.fsck.k9.ui.R sealed class MessageListViewHolder(view: View) : ViewHolder(view) class MessageViewHolder(view: View) : MessageListViewHolder(view) { var uniqueId: Long = -1L val selected: View = view.findViewById(R.id.selected) val contactPicture: ImageView = view.findViewById(R.id.contact_picture) val subject: TextView = view.findViewById(R.id.subject) val preview: TextView = view.findViewById(R.id.preview) val date: TextView = view.findViewById(R.id.date) val chip: ImageView = view.findViewById(R.id.account_color_chip) val threadCount: TextView = view.findViewById(R.id.thread_count) val flagged: CheckBox = view.findViewById(R.id.star) val attachment: ImageView = view.findViewById(R.id.attachment) val status: ImageView = view.findViewById(R.id.status) } class FooterViewHolder(view: View) : MessageListViewHolder(view) { val text: TextView = view.findViewById(R.id.main_text) }
apache-2.0
8620252d86e0c5bec52f13b2c1fc3740
39.172414
75
0.764807
3.710191
false
false
false
false
signed/intellij-community
plugins/stats-collector/log-events/test/com/intellij/stats/events/completion/EventStreamValidatorTest.kt
1
3053
package com.intellij.stats.events.completion import org.assertj.core.api.Assertions.assertThat import org.junit.Test class EventStreamValidatorTest { @Test fun simple_sequence_of_actions() { val list = listOf(LogEventFixtures.completion_started_3_items_shown, LogEventFixtures.explicit_select_position_0) validate(list, list.join(), "") } @Test fun sample_error_sequence_of_actions() { val list = listOf(LogEventFixtures.completion_started_3_items_shown, LogEventFixtures.explicit_select_position_1) validate(list, expectedOut = "", expectedErr = list.join()) } @Test fun up_down_actions() { val list = listOf( LogEventFixtures.completion_started_3_items_shown, LogEventFixtures.down_event_new_pos_1, LogEventFixtures.up_pressed_new_pos_0, LogEventFixtures.up_pressed_new_pos_2, LogEventFixtures.up_pressed_new_pos_1, LogEventFixtures.explicit_select_position_1 ) validate(list, list.join(), expectedErr = "") } @Test fun up_down_actions_wrong() { val list = listOf( LogEventFixtures.completion_started_3_items_shown, LogEventFixtures.down_event_new_pos_1, LogEventFixtures.up_pressed_new_pos_0, LogEventFixtures.up_pressed_new_pos_2, LogEventFixtures.up_pressed_new_pos_1, LogEventFixtures.explicit_select_position_0 ) validate(list, expectedOut = "", expectedErr = list.join()) } @Test fun selected_by_typing() { val list = listOf( LogEventFixtures.completion_started_3_items_shown, LogEventFixtures.type_event_current_pos_0_left_ids_1_2, LogEventFixtures.type_event_current_pos_0_left_id_0, LogEventFixtures.selected_by_typing_0 ) validate(list, expectedOut = "", expectedErr = list.join()) } @Test fun selected_by_typing_error() { val list = listOf( LogEventFixtures.completion_started_3_items_shown, LogEventFixtures.type_event_current_pos_0_left_ids_0_1, LogEventFixtures.down_event_new_pos_1, LogEventFixtures.explicit_select_position_1 ) validate(list, expectedOut = list.join(), expectedErr = "") } private fun validate(list: List<com.intellij.stats.events.completion.LogEvent>, expectedOut: String, expectedErr: String) { val output = java.io.ByteArrayOutputStream() val err = java.io.ByteArrayOutputStream() val input = list.join().toByteArray() val separator = com.intellij.stats.events.completion.SessionsInputSeparator(java.io.ByteArrayInputStream(input), output, err) separator.processInput() assertThat(err.toString().trim()).isEqualTo(expectedErr) assertThat(output.toString().trim()).isEqualTo(expectedOut) } } private fun List<LogEvent>.join(): String { return this.map { LogEventSerializer.toString(it) }.joinToString(System.lineSeparator()) }
apache-2.0
9ddfee8bd88a25d785b732f5c6e9714c
34.929412
133
0.661644
3.996073
false
true
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/ical/ICalendarReader.kt
1
2865
package be.digitalia.fosdem.ical import be.digitalia.fosdem.ical.internal.CRLF import okio.Buffer import okio.BufferedSource import java.io.Closeable import java.io.IOException /** * Optimized streaming ICalendar reader. */ class ICalendarReader(private val source: BufferedSource) : Closeable { private var state = STATE_BEGIN_KEY class Options private constructor(internal val suffixedKey: okio.Options) { companion object { fun of(vararg keys: String): Options { val buffer = Buffer() val result = Array(keys.size) { buffer.writeUtf8(keys[it]) buffer.writeByte(':'.code) buffer.readByteString() } return Options(okio.Options.of(*result)) } } } fun hasNext(): Boolean = !source.exhausted() fun nextKey(): String { check(state == STATE_BEGIN_KEY) val endPosition = source.indexOf(':'.code.toByte()) endPosition >= 0L || throw IOException("Invalid key") val result = source.readUtf8(endPosition) source.skip(1L) state = STATE_BEGIN_VALUE return result } fun skipKey() { check(state == STATE_BEGIN_KEY) val endPosition = source.indexOf(':'.code.toByte()) endPosition >= 0L || throw IOException("Invalid key") source.skip(endPosition + 1L) state = STATE_BEGIN_VALUE } fun selectKey(options: Options): Int { check(state == STATE_BEGIN_KEY) val result = source.select(options.suffixedKey) if (result >= 0) { state = STATE_BEGIN_VALUE } return result } private inline fun BufferedSource.unfoldLines(lineLambda: BufferedSource.(endPosition: Long) -> Unit) { while (true) { val endPosition = indexOf(CRLF) if (endPosition < 0L) { // buffer now contains the rest of the file until the end lineLambda(buffer.size) break } lineLambda(endPosition) skip(2L) if (!request(1L) || buffer[0L] != ' '.code.toByte()) { break } skip(1L) } } fun nextValue(): String { check(state == STATE_BEGIN_VALUE) val resultBuffer = Buffer() source.unfoldLines { read(resultBuffer, it) } state = STATE_BEGIN_KEY return resultBuffer.readUtf8() } fun skipValue() { check(state == STATE_BEGIN_VALUE) source.unfoldLines { skip(it) } state = STATE_BEGIN_KEY } @Throws(IOException::class) override fun close() { source.close() } companion object { private const val STATE_BEGIN_KEY = 0 private const val STATE_BEGIN_VALUE = 1 } }
apache-2.0
c9b307ca88f1dd1ae1cd838568071ac9
28.244898
107
0.568586
4.462617
false
false
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/shared/resilience/TimedCountdownLatch.kt
2
816
package com.lasthopesoftware.bluewater.shared.resilience import org.joda.time.Duration class TimedCountdownLatch(private val maxTriggers: Int, disarmDuration: Duration) { private val disarmDuration = disarmDuration.millis @Volatile private var lastTriggered = System.currentTimeMillis() @Volatile private var triggers = 0 @Synchronized fun trigger(): Boolean { val triggerTime = System.currentTimeMillis() // Open latch if more than max number of triggers has occurred if (++triggers >= maxTriggers) { // and the last trigger time is less than the disarm duration if (triggerTime - lastTriggered <= disarmDuration) { return true } // reset the trigger count if enough time has elapsed to reset the error count triggers = 0 } lastTriggered = triggerTime return false } }
lgpl-3.0
6d30ba8b033adc047e132677fd73ee8e
25.322581
83
0.748775
4.019704
false
false
false
false
square/leakcanary
leakcanary-android-core/src/main/java/leakcanary/internal/activity/screen/HprofExplorerScreen.kt
2
11698
package leakcanary.internal.activity.screen import android.app.AlertDialog import android.view.View import android.view.View.OnAttachStateChangeListener import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.EditText import android.widget.ListView import android.widget.TextView import android.widget.Toast import com.squareup.leakcanary.core.R import leakcanary.internal.activity.db.Io import leakcanary.internal.activity.db.executeOnIo import leakcanary.internal.activity.ui.SimpleListAdapter import leakcanary.internal.navigation.Screen import leakcanary.internal.navigation.activity import leakcanary.internal.navigation.inflate import shark.HeapField import shark.HeapObject.HeapClass import shark.HeapObject.HeapInstance import shark.HeapObject.HeapObjectArray import shark.HeapObject.HeapPrimitiveArray import shark.HeapValue import shark.HprofHeapGraph.Companion.openHeapGraph import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.BooleanArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ByteArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.CharArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.DoubleArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.FloatArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.IntArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.LongArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ShortArrayDump import shark.ValueHolder.BooleanHolder import shark.ValueHolder.ByteHolder import shark.ValueHolder.CharHolder import shark.ValueHolder.DoubleHolder import shark.ValueHolder.FloatHolder import shark.ValueHolder.IntHolder import shark.ValueHolder.LongHolder import shark.ValueHolder.ReferenceHolder import shark.ValueHolder.ShortHolder import java.io.Closeable import java.io.File internal class HprofExplorerScreen( private val heapDumpFile: File ) : Screen() { override fun createView(container: ViewGroup) = container.inflate(R.layout.leak_canary_hprof_explorer).apply { container.activity.title = resources.getString(R.string.leak_canary_loading_title) var closeable: Closeable? = null addOnAttachStateChangeListener(object : OnAttachStateChangeListener { override fun onViewAttachedToWindow(view: View) { } override fun onViewDetachedFromWindow(view: View) { Io.execute { closeable?.close() } } }) executeOnIo { val graph = heapDumpFile.openHeapGraph() closeable = graph updateUi { container.activity.title = resources.getString(R.string.leak_canary_explore_heap_dump) val titleView = findViewById<TextView>(R.id.leak_canary_explorer_title) val searchView = findViewById<View>(R.id.leak_canary_search_button) val listView = findViewById<ListView>(R.id.leak_canary_explorer_list) titleView.visibility = VISIBLE searchView.visibility = VISIBLE listView.visibility = VISIBLE searchView.setOnClickListener { val input = EditText(context) AlertDialog.Builder(context) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Type a fully qualified class name") .setView(input) .setPositiveButton(android.R.string.ok) { _, _ -> executeOnIo { val partialClassName = input.text.toString() val matchingClasses = graph.classes .filter { partialClassName in it.name } .toList() if (matchingClasses.isEmpty()) { updateUi { Toast.makeText( context, "No class matching [$partialClassName]", Toast.LENGTH_LONG ) .show() } } else { updateUi { titleView.text = "${matchingClasses.size} classes matching [$partialClassName]" listView.adapter = SimpleListAdapter( R.layout.leak_canary_simple_row, matchingClasses ) { view, position -> val itemTitleView = view.findViewById<TextView>(R.id.leak_canary_row_text) itemTitleView.text = matchingClasses[position].name } listView.setOnItemClickListener { _, _, position, _ -> val selectedClass = matchingClasses[position] showClass(titleView, listView, selectedClass) } } } } } .setNegativeButton(android.R.string.cancel, null) .show() } } } } private fun View.showClass( titleView: TextView, listView: ListView, selectedClass: HeapClass ) { executeOnIo { val className = selectedClass.name val instances = selectedClass.directInstances.toList() val staticFields = selectedClass.readStaticFields() .fieldsAsString() updateUi { titleView.text = "Class $className (${instances.size} instances)" listView.adapter = SimpleListAdapter( R.layout.leak_canary_simple_row, staticFields + instances ) { view, position -> val itemTitleView = view.findViewById<TextView>(R.id.leak_canary_row_text) if (position < staticFields.size) { itemTitleView.text = staticFields[position].second } else { itemTitleView.text = "@${instances[position - staticFields.size].objectId}" } } listView.setOnItemClickListener { _, _, position, _ -> if (position < staticFields.size) { val staticField = staticFields[position].first onHeapValueClicked(titleView, listView, staticField.value) } else { val instance = instances[position - staticFields.size] showInstance(titleView, listView, instance) } } } } } private fun View.showInstance( titleView: TextView, listView: ListView, instance: HeapInstance ) { executeOnIo { val fields = instance.readFields() .fieldsAsString() val className = instance.instanceClassName updateUi { titleView.text = "Instance @${instance.objectId} of class $className" listView.adapter = SimpleListAdapter( R.layout.leak_canary_simple_row, fields ) { view, position -> val itemTitleView = view.findViewById<TextView>(R.id.leak_canary_row_text) itemTitleView.text = fields[position].second } listView.setOnItemClickListener { _, _, position, _ -> val field = fields[position].first onHeapValueClicked(titleView, listView, field.value) } } } } private fun View.showObjectArray( titleView: TextView, listView: ListView, instance: HeapObjectArray ) { executeOnIo { val elements = instance.readElements() .mapIndexed { index: Int, element: HeapValue -> element to "[$index] = ${element.heapValueAsString()}" } .toList() val arrayClassName = instance.arrayClassName val className = arrayClassName.substring(0, arrayClassName.length - 2) updateUi { titleView.text = "Array $className[${elements.size}]" listView.adapter = SimpleListAdapter( R.layout.leak_canary_simple_row, elements ) { view, position -> val itemTitleView = view.findViewById<TextView>(R.id.leak_canary_row_text) itemTitleView.text = elements[position].second } listView.setOnItemClickListener { _, _, position, _ -> val element = elements[position].first onHeapValueClicked(titleView, listView, element) } } } } private fun View.showPrimitiveArray( titleView: TextView, listView: ListView, instance: HeapPrimitiveArray ) { executeOnIo { val (type, values) = when (val record = instance.readRecord()) { is BooleanArrayDump -> "boolean" to record.array.map { it.toString() } is CharArrayDump -> "char" to record.array.map { "'$it'" } is FloatArrayDump -> "float" to record.array.map { it.toString() } is DoubleArrayDump -> "double" to record.array.map { it.toString() } is ByteArrayDump -> "byte" to record.array.map { it.toString() } is ShortArrayDump -> "short" to record.array.map { it.toString() } is IntArrayDump -> "int" to record.array.map { it.toString() } is LongArrayDump -> "long" to record.array.map { it.toString() } } updateUi { titleView.text = "Array $type[${values.size}]" listView.adapter = SimpleListAdapter( R.layout.leak_canary_simple_row, values ) { view, position -> val itemTitleView = view.findViewById<TextView>(R.id.leak_canary_row_text) itemTitleView.text = "$type ${values[position]}" } listView.setOnItemClickListener { _, _, _, _ -> } } } } private fun View.onHeapValueClicked( titleView: TextView, listView: ListView, heapValue: HeapValue ) { if (heapValue.isNonNullReference) { when (val objectRecord = heapValue.asObject!!) { is HeapInstance -> { showInstance(titleView, listView, objectRecord) } is HeapClass -> { showClass(titleView, listView, objectRecord) } is HeapObjectArray -> { showObjectArray(titleView, listView, objectRecord) } is HeapPrimitiveArray -> { showPrimitiveArray(titleView, listView, objectRecord) } } } } private fun Sequence<HeapField>.fieldsAsString(): List<Pair<HeapField, String>> { return map { field -> field to "${field.declaringClass.simpleName}.${field.name} = ${field.value.heapValueAsString()}" } .toList() } private fun HeapValue.heapValueAsString(): String { return when (val heapValue = holder) { is ReferenceHolder -> { if (isNullReference) { "null" } else { when (val objectRecord = asObject!!) { is HeapInstance -> { if (objectRecord instanceOf "java.lang.String") { "${objectRecord.instanceClassName}@${heapValue.value} \"${objectRecord.readAsJavaString()!!}\"" } else { "${objectRecord.instanceClassName}@${heapValue.value}" } } is HeapClass -> { "Class ${objectRecord.name}" } is HeapObjectArray -> { objectRecord.arrayClassName } is HeapPrimitiveArray -> objectRecord.arrayClassName } } } is BooleanHolder -> "boolean ${heapValue.value}" is CharHolder -> "char ${heapValue.value}" is FloatHolder -> "float ${heapValue.value}" is DoubleHolder -> "double ${heapValue.value}" is ByteHolder -> "byte ${heapValue.value}" is ShortHolder -> "short ${heapValue.value}" is IntHolder -> "int ${heapValue.value}" is LongHolder -> "long ${heapValue.value}" } } }
apache-2.0
5de20fdc9a7c58e450158aede0f292b9
36.614148
111
0.630877
4.841887
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/components/LoadingScreen.kt
1
1760
/* * Copyright 2021, Lawnchair * * 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 app.lawnchair.ui.preferences.components import androidx.compose.animation.Crossfade import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun LoadingScreen(isLoading: Boolean, content: @Composable () -> Unit) { Crossfade(targetState = isLoading) { if (it) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { CircularProgressIndicator() } } else { content() } } } @Composable fun <T> LoadingScreen(obj: T?, content: @Composable (T) -> Unit) { LoadingScreen(isLoading = obj == null) { content(obj!!) } }
gpl-3.0
db22531a6ae1c780cd8da3998722d8fc
32.846154
75
0.710795
4.643799
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/about/acknowledgements/loadNotice.kt
1
2729
/* * Copyright 2022, Lawnchair * * 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 app.lawnchair.ui.preferences.about.acknowledgements import android.text.SpannableString import android.text.style.URLSpan import android.text.util.Linkify import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.* import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextDecoration import app.lawnchair.ossnotices.OssLibrary import com.android.launcher3.R @Composable fun loadNotice(ossLibrary: OssLibrary): State<OssLibraryWithNotice?> { val context = LocalContext.current val noticeStringState = remember { mutableStateOf<OssLibraryWithNotice?>(null) } val accentColor = MaterialTheme.colorScheme.primary DisposableEffect(Unit) { val string = ossLibrary.getNotice(context = context, thirdPartyLicensesId = R.raw.third_party_licenses) val spannable = SpannableString(string) Linkify.addLinks(spannable, Linkify.WEB_URLS) val spans = spannable.getSpans(0, string.length, URLSpan::class.java) val annotatedString = buildAnnotatedString { append(string) spans.forEach { urlSpan -> val start = spannable.getSpanStart(urlSpan) val end = spannable.getSpanEnd(urlSpan) addStyle( style = SpanStyle( color = accentColor, textDecoration = TextDecoration.Underline ), start = start, end = end ) addStringAnnotation( tag = "URL", annotation = urlSpan.url, start = start, end = end ) } } noticeStringState.value = OssLibraryWithNotice(ossLibrary, annotatedString) onDispose { } } return noticeStringState } data class OssLibraryWithNotice( val ossLibrary: OssLibrary, val notice: AnnotatedString, )
gpl-3.0
b8d7b4835e2c1e0dda826864010297cd
36.902778
111
0.670575
4.787719
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/view/VerticalStepIconView.kt
1
3853
package info.papdt.express.helper.view import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import android.util.AttributeSet import android.view.View import info.papdt.express.helper.R import info.papdt.express.helper.support.ScreenUtils import moe.feng.kotlinyan.common.* class VerticalStepIconView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) { private var mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private var mCirclePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private var mBounds: RectF? = null private var mIconBounds: RectF? = null private var radius: Float = 0.toFloat() private val lineWidth: Float private var pointOffsetY = 0f private val iconSize: Float @ColorInt private var pointColor = Color.BLUE @ColorInt private val iconColor = Color.WHITE private var isMini = false private var centerIcon: Drawable? = null private var centerIconBitmap: Bitmap? = null init { lineWidth = ScreenUtils.dpToPx(context, 2f) iconSize = ScreenUtils.dpToPx(context, 16f) init() pointColor = ContextCompat.getColor(context, R.color.blue_500) } internal fun init() { mPaint.style = Paint.Style.FILL_AND_STROKE mPaint.strokeWidth = lineWidth mCirclePaint.style = Paint.Style.FILL_AND_STROKE mCirclePaint.strokeWidth = lineWidth mCirclePaint.color = pointColor } fun setPointColor(@ColorInt color: Int) { pointColor = color } fun setPointColorResource(@ColorRes resId: Int) { pointColor = ContextCompat.getColor(context, resId) } fun setIsMini(isMini: Boolean) { this.isMini = isMini } fun setCenterIcon(drawable: Drawable?) { this.centerIcon = drawable this.centerIconBitmap = applyBitmapFromDrawable(drawable) } fun setCenterIcon(@DrawableRes resId: Int) { setCenterIcon(ContextCompat.getDrawable(context, resId)) } fun setPointOffsetY(pointOffsetY: Float) { this.pointOffsetY = pointOffsetY } override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) { super.onSizeChanged(w, h, oldW, oldH) mBounds = RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat()) mIconBounds = RectF(mBounds!!.centerX() - iconSize / 2, mBounds!!.centerY() - iconSize / 2 + pointOffsetY, mBounds!!.centerX() + iconSize / 2, mBounds!!.centerY() + iconSize / 2 + pointOffsetY) radius = (Math.min(w, h) / 4).toFloat() } override fun onDraw(canvas: Canvas) { val r = if (isMini) radius / 5 * 3 else radius super.onDraw(canvas) mCirclePaint.color = pointColor canvas.drawCircle(mBounds!!.centerX(), mBounds!!.centerY() + pointOffsetY, r, mCirclePaint) if (centerIcon != null) { mPaint.color = iconColor mIconBounds!!.top = mBounds!!.centerY() - iconSize / 2 + pointOffsetY mIconBounds!!.bottom = mBounds!!.centerY() + iconSize / 2 + pointOffsetY canvas.drawBitmap(centerIconBitmap!!, null, mIconBounds!!, mPaint) } } private fun applyBitmapFromDrawable(d: Drawable?): Bitmap? { if (d == null) { return null } if (d is BitmapDrawable) { return d.bitmap } return try { val bitmap: Bitmap = if (d is ColorDrawable) { Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) } else { Bitmap.createBitmap( Math.max(24f.dpToPx(context).toInt(), d.intrinsicWidth), Math.max(24f.dpToPx(context).toInt(), d.intrinsicHeight), Bitmap.Config.ARGB_8888 ) } val canvas = Canvas(bitmap) d.setBounds(0, 0, canvas.width, canvas.height) d.draw(canvas) bitmap } catch (e: OutOfMemoryError) { null } } }
gpl-3.0
3186301ee4dfa3e038960d7ab5a77451
28.189394
120
0.7306
3.474301
false
false
false
false
Kotlin/dokka
core/src/main/kotlin/model/CompositeSourceSetID.kt
1
1441
package org.jetbrains.dokka.model import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.DokkaSourceSetID data class CompositeSourceSetID( private val children: Set<DokkaSourceSetID> ) { constructor(sourceSetIDs: Iterable<DokkaSourceSetID>) : this(sourceSetIDs.toSet()) constructor(sourceSetId: DokkaSourceSetID) : this(setOf(sourceSetId)) init { require(children.isNotEmpty()) { "Expected at least one source set id" } } val merged: DokkaSourceSetID get() = children.sortedBy { it.scopeId + it.sourceSetName }.let { sortedChildren -> DokkaSourceSetID( scopeId = sortedChildren.joinToString(separator = "+") { it.scopeId }, sourceSetName = sortedChildren.joinToString(separator = "+") { it.sourceSetName } ) } val all: Set<DokkaSourceSetID> get() = setOf(merged, *children.toTypedArray()) operator fun contains(sourceSetId: DokkaSourceSetID): Boolean { return sourceSetId in all } operator fun contains(sourceSet: DokkaConfiguration.DokkaSourceSet): Boolean { return sourceSet.sourceSetID in this } operator fun plus(other: DokkaSourceSetID): CompositeSourceSetID { return copy(children = children + other) } } operator fun DokkaSourceSetID.plus(other: DokkaSourceSetID): CompositeSourceSetID { return CompositeSourceSetID(listOf(this, other)) }
apache-2.0
ac9a209c822758a3da3e2e3c77e4ab58
33.309524
97
0.69882
4.884746
false
false
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckselect/LeaderItem.kt
1
2304
package com.bachhuberdesign.deckbuildergwent.features.deckselect import android.net.Uri import android.support.annotation.ColorRes import android.support.constraint.ConstraintLayout import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import android.widget.TextView import com.bachhuberdesign.deckbuildergwent.R import com.bumptech.glide.Glide import com.mikepenz.fastadapter.items.AbstractItem import kotlinx.android.synthetic.main.item_leader.view.* /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ class LeaderItem : AbstractItem<LeaderItem, LeaderItem.ViewHolder>() { companion object { @JvmStatic val TAG: String = LeaderItem::class.java.name } var leaderName: String = "" var backgroundUrl: String = "" var backgroundColor: Int = 0 fun withLeaderName(leaderName: String): LeaderItem { this.leaderName = leaderName return this } fun withBackgroundUrl(backgroundUrl: String): LeaderItem { this.backgroundUrl = backgroundUrl return this } fun withBackgroundColor(@ColorRes backgroundColor: Int): LeaderItem { this.backgroundColor = backgroundColor return this } override fun getLayoutRes(): Int { return R.layout.item_leader } override fun getType(): Int { return R.id.leader_item } override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } override fun bindView(holder: ViewHolder, payloads: MutableList<Any>) { super.bindView(holder, payloads) holder.nameText.text = leaderName if (backgroundColor > 0) { holder.constraintLayout.setBackgroundResource(backgroundColor) } if (backgroundUrl.isNotEmpty()) { Glide.with(holder.itemView.context) .load(Uri.parse(backgroundUrl)) .centerCrop() .dontAnimate() .into(holder.background) } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var nameText: TextView = view.card_name_text var background: ImageView = view.slim_card_background var constraintLayout: ConstraintLayout = view.constraint_layout } }
apache-2.0
6291e5c5823a89429e90a48e99e660cc
27.45679
75
0.676649
4.589641
false
false
false
false
wuan/rest-demo-jersey-kotlin
src/main/java/com/tngtech/demo/weather/resources/weather/WeatherController.kt
1
4751
package com.tngtech.demo.weather.resources.weather import com.mercateo.common.rest.schemagen.types.WithId import com.tngtech.demo.weather.domain.Station import com.tngtech.demo.weather.domain.gis.Point import com.tngtech.demo.weather.domain.measurement.AtmosphericData import com.tngtech.demo.weather.lib.EventCounter import com.tngtech.demo.weather.lib.GeoCalculations import com.tngtech.demo.weather.lib.TimestampFactory import com.tngtech.demo.weather.repositories.StationRepository import com.tngtech.demo.weather.repositories.WeatherDataRepository import org.springframework.stereotype.Component import java.util.* @Component class WeatherController( private val stationRepository: StationRepository, private val weatherDataRepository: WeatherDataRepository, private val timestampFactory: TimestampFactory, private val requestFrequency: EventCounter<UUID>, private val radiusFrequency: EventCounter<Double>, private val geoCalculations: GeoCalculations ) { val statistics: Map<String, Any> get() { val result = HashMap<String, Any>() result.put("datasize", countOfDataUpdatedSinceADayAgo) result.put("station_freq", stationFractions) result.put("radius_freq", radiusHistogram) return result } private val countOfDataUpdatedSinceADayAgo: Int get() { val oneDayAgo = timestampFactory.currentTimestamp - MILLISECONDS_PER_DAY return weatherDataRepository .weatherData .count { data -> data.lastUpdateTime > oneDayAgo } } private val stationFractions: Map<UUID, Double> get() { val freq = HashMap<UUID, Double>() stationRepository.stations.map { station -> station.id }.forEach { stationId -> freq.put(stationId, requestFrequency.fractionOf(stationId)) } return freq } private val radiusHistogram: Array<Int> get() { val maxRange = radiusFrequency.events.max() ?: 1000.0 val binSize = 10 val binCount = Math.ceil(maxRange / binSize + 1).toInt() val hist = (1..binCount).map { 0 }.toTypedArray() radiusFrequency .stream() .forEach { tuple -> val radius = tuple._1() val binIndex = radius!!.toInt() / 10 val radiusFrequency = tuple._2().get() hist[binIndex] += radiusFrequency } return hist } /** * Retrieve the most up to date atmospheric information from the given stationId and other airports in the given * radius. * * @param stationId the three letter stationId code * @param radius the radius, in km, from which to collect weather data * @return an HTTP Response and a list of [AtmosphericData] from the requested stationId and * airports in the given radius */ fun queryWeather(stationId: UUID, radius: Double?): List<AtmosphericData> { updateRequestFrequency(stationId, radius) return if (radius == 0.0 || radius == null) { weatherDataRepository .getWeatherDataFor(stationId)?.let { listOf(it) } ?: emptyList() } else { stationRepository .getStationById(stationId) ?.let { centerStation -> val map: List<UUID> = stationRepository .stations .filter { otherStation -> geoCalculations .calculateDistance(otherStation.`object`, centerStation.`object`) <= radius } .map { station -> station.id } map.flatMap { weatherDataRepository.getWeatherDataFor(it)?.let { listOf(it) } ?: emptyList() } } ?: emptyList() } } fun queryWeather(location: Point, radius: Double?): List<AtmosphericData> { return emptyList() } private fun updateRequestFrequency(stationId: UUID, radius: Double?) { val stationById: WithId<Station>? = stationRepository .getStationById(stationId) stationById ?.let { station -> requestFrequency.increment(station.id) if (radius != null) { radiusFrequency.increment(radius) } } } companion object { private val MILLISECONDS_PER_DAY = 86400000 } }
apache-2.0
66065234b9eb38dd5aa4284a72637e49
37.008
153
0.587666
5.001053
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/setIdentity/SetIdentityActivity.kt
1
10377
package com.garpr.android.features.setIdentity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.garpr.android.R import com.garpr.android.data.models.AbsPlayer import com.garpr.android.extensions.layoutInflater import com.garpr.android.features.common.activities.BaseActivity import com.garpr.android.features.common.views.NoResultsItemView import com.garpr.android.features.common.views.StringDividerView import com.garpr.android.misc.PlayerListBuilder.PlayerListItem import com.garpr.android.misc.Refreshable import com.garpr.android.misc.RegionHandleUtils import com.garpr.android.misc.Searchable import kotlinx.android.synthetic.main.activity_set_identity.* import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel class SetIdentityActivity : BaseActivity(), PlayerSelectionItemView.Listener, Refreshable, Searchable, SetIdentityToolbar.Listener, SwipeRefreshLayout.OnRefreshListener { private val adapter = Adapter(this) override val activityName = TAG private val viewModel: SetIdentityViewModel by viewModel() protected val regionHandleUtils: RegionHandleUtils by inject() private fun fetchPlayers() { viewModel.fetchPlayers(regionHandleUtils.getRegion(this)) } private fun initListeners() { viewModel.stateLiveData.observe(this, Observer { refreshState(it) }) } override fun navigateUp() { if (!viewModel.warnBeforeClose) { super.navigateUp() return } AlertDialog.Builder(this) .setMessage(R.string.youve_selected_an_identity_but_havent_saved) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.yes) { dialog, which -> [email protected]() } .show() } override fun onBackPressed() { if (toolbar.isSearchFieldExpanded) { toolbar.closeSearchField() return } if (!viewModel.warnBeforeClose) { super.onBackPressed() return } AlertDialog.Builder(this) .setMessage(R.string.youve_selected_an_identity_but_havent_saved) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.yes) { dialog, which -> [email protected]() } .show() } override fun onClick(v: PlayerSelectionItemView) { viewModel.selectedIdentity = v.player } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_set_identity) initListeners() fetchPlayers() } override fun onRefresh() { refresh() } override fun onSaveClick(v: SetIdentityToolbar) { viewModel.saveSelectedIdentity(regionHandleUtils.getRegion(this)) setResult(Activity.RESULT_OK) supportFinishAfterTransition() } override fun onViewsBound() { super.onViewsBound() val region = regionHandleUtils.getRegion(this) toolbar.subtitleText = getString(R.string.region_endpoint_format, region.displayName, getText(region.endpoint.title)) toolbar.searchable = this toolbar.listener = this refreshLayout.setOnRefreshListener(this) recyclerView.setHasFixedSize(true) recyclerView.adapter = adapter } override fun refresh() { fetchPlayers() } private fun refreshState(state: SetIdentityViewModel.State) { when (state.saveIconStatus) { SetIdentityViewModel.SaveIconStatus.DISABLED -> { toolbar.showSaveIcon = true toolbar.enableSaveIcon = false } SetIdentityViewModel.SaveIconStatus.ENABLED -> { toolbar.showSaveIcon = true toolbar.enableSaveIcon = true } SetIdentityViewModel.SaveIconStatus.GONE -> { toolbar.showSaveIcon = false toolbar.enableSaveIcon = false } } toolbar.showSearchIcon = if (toolbar.isSearchFieldExpanded) false else state.showSearchIcon if (state.hasError) { adapter.clear() recyclerView.visibility = View.GONE empty.visibility = View.GONE error.visibility = View.VISIBLE } else if (state.isEmpty) { adapter.clear() recyclerView.visibility = View.GONE error.visibility = View.GONE empty.visibility = View.VISIBLE } else { if (state.searchResults != null) { adapter.set(state.searchResults, state.selectedIdentity) } else { adapter.set(state.list, state.selectedIdentity) } error.visibility = View.GONE empty.visibility = View.GONE recyclerView.visibility = View.VISIBLE } if (state.isFetching) { refreshLayout.isEnabled = true refreshLayout.isRefreshing = true } else { refreshLayout.isRefreshing = false refreshLayout.isEnabled = state.isRefreshEnabled } } override fun search(query: String?) { viewModel.search(query) } companion object { private const val TAG = "SetIdentityActivity" fun getLaunchIntent(context: Context) = Intent(context, SetIdentityActivity::class.java) } private class Adapter( private val playerItemViewListener: PlayerSelectionItemView.Listener ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var selectedIdentity: AbsPlayer? = null private val list = mutableListOf<PlayerListItem>() init { setHasStableIds(true) } private fun bindDividerViewHolder(holder: DividerViewHolder, item: PlayerListItem.Divider) { val content: String = when (item) { is PlayerListItem.Divider.Digit -> holder.dividerItemView.resources.getString(R.string.number) is PlayerListItem.Divider.Letter -> item.letter is PlayerListItem.Divider.Other -> holder.dividerItemView.resources.getString(R.string.other) } holder.dividerItemView.setContent(content) } private fun bindNoResultsViewHolder(holder: NoResultsViewHolder, item: PlayerListItem.NoResults) { holder.noResultsViewHolder.setContent(item.query) } private fun bindPlayerViewHolder(holder: PlayerViewHolder, item: PlayerListItem.Player) { holder.playerSelectionItemView.setContent(item.player, item.player == selectedIdentity) } internal fun clear() { list.clear() selectedIdentity = null notifyDataSetChanged() } override fun getItemCount(): Int { return list.size } override fun getItemId(position: Int): Long { return list[position].listId } override fun getItemViewType(position: Int): Int { return when (list[position]) { is PlayerListItem.Divider -> VIEW_TYPE_DIVIDER is PlayerListItem.NoResults -> VIEW_TYPE_NO_RESULTS is PlayerListItem.Player -> VIEW_TYPE_PLAYER } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (val item = list[position]) { is PlayerListItem.Divider -> bindDividerViewHolder(holder as DividerViewHolder, item) is PlayerListItem.NoResults -> bindNoResultsViewHolder(holder as NoResultsViewHolder, item) is PlayerListItem.Player -> bindPlayerViewHolder(holder as PlayerViewHolder, item) else -> throw RuntimeException("unknown item: $item, position: $position") } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = parent.layoutInflater return when (viewType) { VIEW_TYPE_DIVIDER -> DividerViewHolder(inflater.inflate(R.layout.divider_string, parent, false)) VIEW_TYPE_NO_RESULTS -> NoResultsViewHolder(inflater.inflate( R.layout.item_no_results, parent, false)) VIEW_TYPE_PLAYER -> PlayerViewHolder(playerItemViewListener, inflater.inflate( R.layout.item_player_selection, parent, false)) else -> throw IllegalArgumentException("unknown viewType: $viewType") } } internal fun set(list: List<PlayerListItem>?, selectedIdentity: AbsPlayer?) { this.list.clear() if (!list.isNullOrEmpty()) { this.list.addAll(list) } this.selectedIdentity = selectedIdentity notifyDataSetChanged() } companion object { private const val VIEW_TYPE_DIVIDER = 0 private const val VIEW_TYPE_NO_RESULTS = 1 private const val VIEW_TYPE_PLAYER = 2 } } private class DividerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal val dividerItemView: StringDividerView = itemView as StringDividerView } private class NoResultsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal val noResultsViewHolder: NoResultsItemView = itemView as NoResultsItemView } private class PlayerViewHolder( listener: PlayerSelectionItemView.Listener, itemView: View ) : RecyclerView.ViewHolder(itemView) { internal val playerSelectionItemView: PlayerSelectionItemView = itemView as PlayerSelectionItemView init { playerSelectionItemView.listener = listener } } }
unlicense
6ef77297fb69aca0c75c11b050e73946
34.416382
110
0.642864
5.172981
false
false
false
false
italoag/qksms
data/src/main/java/com/moez/QKSMS/extensions/MmsPartExtensions.kt
3
1114
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.extensions import com.google.android.mms.ContentType import com.moez.QKSMS.model.MmsPart fun MmsPart.isSmil() = ContentType.APP_SMIL == type fun MmsPart.isImage() = ContentType.isImageType(type) fun MmsPart.isVideo() = ContentType.isVideoType(type) fun MmsPart.isText() = ContentType.TEXT_PLAIN == type fun MmsPart.isVCard() = ContentType.TEXT_VCARD == type
gpl-3.0
dc7d89b686a9f2930fddc01071efa45e
33.8125
71
0.745961
3.725753
false
false
false
false
http4k/http4k
src/docs/guide/reference/opentelemetry/example_tracing.kt
1
1844
package guide.reference.opentelemetry import io.opentelemetry.context.propagation.ContextPropagators.create import io.opentelemetry.extension.aws.AwsXrayPropagator import io.opentelemetry.sdk.OpenTelemetrySdk import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.ClientFilters import org.http4k.filter.OpenTelemetryTracing import org.http4k.filter.ServerFilters import org.http4k.routing.bind import org.http4k.routing.path import org.http4k.routing.routes fun main() { // configure OpenTelemetry using the Amazon XRAY tracing scheme val openTelemetry = OpenTelemetrySdk.builder() .setPropagators(create(AwsXrayPropagator.getInstance())) .buildAndRegisterGlobal() // this HttpHandler represents a 3rd party service, and will repeat the request body val repeater: HttpHandler = { println("REMOTE REQUEST WITH TRACING HEADERS: $it") Response(OK).body(it.bodyString() + it.bodyString()) } // we will propagate the tracing headers using the tracer instance val repeaterClient = ClientFilters.OpenTelemetryTracing(openTelemetry).then(repeater) // this is the server app which will add tracing spans to incoming requests val app = ServerFilters.OpenTelemetryTracing(openTelemetry) .then(routes("/echo/{name}" bind GET to { val remoteResponse = repeaterClient( Request(POST, "http://aRemoteServer/endpoint") .body(it.path("name")!!) ) Response(OK).body(remoteResponse.bodyString()) })) println("RETURNED TO CALLER: " + app(Request(GET, "http://localhost:8080/echo/david"))) }
apache-2.0
dad6fd870f2c022e1c49e10deebb987b
39.086957
91
0.738069
4.061674
false
false
false
false
lewinskimaciej/planner
app/src/main/java/com/atc/planner/commons/LocationProvider.kt
1
3816
package com.atc.planner.commons import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.location.Location import android.location.LocationManager import android.os.Bundle import android.support.v4.content.ContextCompat import com.atc.planner.App import com.atc.planner.data.service.SearchService import com.github.ajalt.timberkt.d import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import java.lang.Exception import javax.inject.Inject interface LocationProvider : android.location.LocationListener { fun getLastLocation(onSuccess: ((location: Location?) -> Unit)? = null, onFailure: ((exception: Exception) -> Unit)? = null) fun addListener(listener: com.google.android.gms.location.LocationListener) fun removeListener(listener: com.google.android.gms.location.LocationListener) fun startService() fun stopService() } class LocationProviderImpl @Inject constructor(var app: App) : LocationProvider { private var fusedLocationProviderClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(app) private var locationManager: LocationManager? = app.getSystemService(Context.LOCATION_SERVICE) as LocationManager private var listeners: ArrayList<com.google.android.gms.location.LocationListener> = arrayListOf() override fun getLastLocation(onSuccess: ((location: Location?) -> Unit)?, onFailure: ((exception: Exception) -> Unit)?) { d { "getting last location" } val checkSelfPermission = ContextCompat.checkSelfPermission(app, Manifest.permission.ACCESS_FINE_LOCATION) if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) { val task = fusedLocationProviderClient.lastLocation task.addOnCompleteListener { if (it.isSuccessful) { d { "successful, result: ${it.result}" } onSuccess?.invoke(it.result) } else { it.exception?.let { d { "failure, exception: ${it.message}" } onFailure?.invoke(it) } } } } else { onFailure?.invoke(SecurityException("Manifest.permission.ACCESS_FINE_LOCATION not available")) } } override fun addListener(listener: com.google.android.gms.location.LocationListener) { val permissionCheck = ContextCompat.checkSelfPermission(app, Manifest.permission.ACCESS_FINE_LOCATION) if (permissionCheck == PackageManager.PERMISSION_GRANTED) { if (listeners.isEmpty()) { locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10.toFloat(), this) } listeners.add(listener) } } override fun removeListener(listener: com.google.android.gms.location.LocationListener) { listeners.remove(listener) if (listeners.isEmpty()) { locationManager?.removeUpdates(this) } } override fun onLocationChanged(p0: Location?) { listeners.forEach { it.onLocationChanged(p0) } } override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) { // ignore } override fun onProviderEnabled(p0: String?) { // ignore } override fun onProviderDisabled(p0: String?) { // ignore } override fun startService() { val intent = Intent(app, SearchService::class.java) app.startService(intent) } override fun stopService() { val intent = Intent(app, SearchService::class.java) app.stopService(intent) } }
mit
7eb85ccf678a115e21450be27b566caa
36.058252
127
0.67217
4.96875
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/DrawingActivity.kt
1
3991
/**************************************************************************************** * Copyright (c) 2021 Akshay Jadhav <[email protected]> * * * * 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.ichi2.anki import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.widget.LinearLayout import com.ichi2.libanki.utils.TimeManager import timber.log.Timber import java.io.FileNotFoundException /** * Activity allowing the user to draw an image to be added the collection * * user can use all basic whiteboard functionally and can save image from this activity. * * To access this screen: Add/Edit Note - Attachment - Add Image - Drawing */ class DrawingActivity : AnkiActivity() { private lateinit var mColorPalette: LinearLayout private lateinit var mWhiteboard: Whiteboard override fun onCreate(savedInstanceState: Bundle?) { if (showedActivityFailedScreen(savedInstanceState)) { return } super.onCreate(savedInstanceState) setTitle(R.string.drawing) setContentView(R.layout.activity_drawing) enableToolbar() mColorPalette = findViewById(R.id.whiteboard_editor) mWhiteboard = Whiteboard.createInstance(this, true, null) mWhiteboard.setOnTouchListener { _: View?, event: MotionEvent? -> mWhiteboard.handleTouchEvent(event!!) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.drawing_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_save -> { Timber.i("Drawing:: Save button pressed") finishWithSuccess() } R.id.action_whiteboard_edit -> { Timber.i("Drawing:: Pen Color button pressed") if (mColorPalette.visibility == View.GONE) { mColorPalette.visibility = View.VISIBLE } else { mColorPalette.visibility = View.GONE } } } return super.onOptionsItemSelected(item) } private fun finishWithSuccess() { try { val savedWhiteboardFileName = mWhiteboard.saveWhiteboard(TimeManager.time) val resultData = Intent() resultData.putExtra(EXTRA_RESULT_WHITEBOARD, savedWhiteboardFileName) setResult(RESULT_OK, resultData) } catch (e: FileNotFoundException) { Timber.w(e) } finally { finishActivityWithFade(this) } } companion object { const val EXTRA_RESULT_WHITEBOARD = "drawing.editedImage" } }
gpl-3.0
805733bd8255468b26090a196771f08e
41.913978
113
0.566024
5.307181
false
false
false
false
Aunmag/a-zombie-shooter-game
src/main/java/aunmag/shooter/ux/Hud.kt
1
2348
package aunmag.shooter.ux import aunmag.nightingale.font.FontStyleDefault import aunmag.nightingale.font.Text import aunmag.nightingale.utilities.UtilsMath import aunmag.shooter.client.App import aunmag.shooter.data.player import aunmag.shooter.gui.Parameter class Hud { private val health = Parameter("Health", 0.0f, 30, 32) private val stamina = Parameter("Stamina", 0.0f, 30, 33) private val ammo = Parameter("Ammo", 0.0f, 30, 34) private val debug = Text(10f, 10f, "", FontStyleDefault.simple) fun update() { Parameter.update() health.value = player?.health ?: 0f stamina.value = player?.stamina?.current ?: 0f ammo.value = player?.weapon?.magazine?.calculateVolumeRatio() ?: 0f ammo.isPulsing = player?.weapon?.magazine?.isReloading ?: false } fun render() { health.render() stamina.render() ammo.render() if (App.main.isDebug) { renderDebug() } } private fun renderDebug() { val game = App.main.game ?: return val world = game.world var timeSpentUpdate = 0f // TODO: Invoke data var timeSpentRender = 0f // TODO: Invoke data var timeSpentTotal = timeSpentUpdate + timeSpentRender val round = 100f timeSpentUpdate = UtilsMath.calculateRoundValue(timeSpentUpdate, round) timeSpentRender = UtilsMath.calculateRoundValue(timeSpentRender, round) timeSpentTotal = UtilsMath.calculateRoundValue(timeSpentTotal, round) var message = "" message += String.format("Spent time on updating: %s ms\n", timeSpentUpdate) message += String.format("Spent time on rendering: %s ms\n", timeSpentRender) message += String.format("Spent time total: %s ms \n", timeSpentTotal) message += String.format("\nAIs: %s", world.ais.all.size) message += String.format("\nActors: %s", world.actors.all.size) message += String.format("\nBullets: %s", world.projectiles.all.size) message += String.format("\nGround: %s", world.ground.all.size) message += String.format("\nTrees: %s", world.trees.all.size) debug.load(message) debug.orderRendering() } fun remove() { health.remove() stamina.remove() ammo.remove() debug.remove() } }
apache-2.0
5c02d956026833832eaaf41c493f23d8
33.529412
85
0.643526
3.880992
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/viewModel/WebViewViewModel.kt
1
2431
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.viewModel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.graphics.Bitmap import com.toshi.R import com.toshi.model.local.network.Networks import com.toshi.util.SingleLiveEvent import com.toshi.view.BaseApplication import java.net.URI class WebViewViewModel(startUrl: String) : ViewModel() { val addressBarUrl by lazy { MutableLiveData<String>() } val favicon by lazy { SingleLiveEvent<Bitmap>() } val title by lazy { SingleLiveEvent<String>() } val toolbarUpdate by lazy { SingleLiveEvent<Unit>() } val url by lazy { MutableLiveData<String>() } val mainFrameProgress by lazy { MutableLiveData<Int>() } init { setAddressBarUrl(startUrl) // AddressBar should contain url before loading starts url.value = startUrl } fun setAddressBarUrl(url: String) { if (url.startsWith("data:")) return addressBarUrl.value = url } fun tryGetAddress(): String { return try { getAddress() } catch (e: IllegalArgumentException) { BaseApplication.get().getString(R.string.unknown_address) } } @Throws(IllegalArgumentException::class) private fun getAddress(): String { val value = url.value ?: throw IllegalArgumentException() val prefixedValue = prependScheme(value) val uri = URI.create(prefixedValue) return uri.toASCIIString() } private fun prependScheme(value: String): String { return if (value.startsWith("http")) value else "http://$value" } fun updateToolbar() = toolbarUpdate.postValue(Unit) fun getNetworks() = Networks.getInstance() }
gpl-3.0
da2b3a79c7dfac2d31df2ce2af8a6e16
33.253521
89
0.691074
4.411978
false
false
false
false
huhanpan/smart
app/src/main/java/com/etong/smart/Main/LeftDrawer/SystemSetting/ChangePhoneActivity.kt
1
6629
package com.etong.smart.Main.LeftDrawer.SystemSetting import android.content.Context import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.widget.Toolbar import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Button import android.widget.EditText import com.alibaba.fastjson.JSONException import com.alibaba.fastjson.JSONObject import com.etong.smart.Other.BaseActivity import com.etong.smart.Other.Service import com.etong.smart.Other.Storage import com.etong.smart.R import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class ChangePhoneActivity : BaseActivity(), TextWatcher { private var mSendCode: Button? = null private var mCommitBtn: Button? = null private var mPwdEditText: EditText? = null private var mPhoneEditText: EditText? = null private var mCodeEditText: EditText? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_change_phone) val toolbar = findViewById(R.id.toolbar) as Toolbar mSendCode = findViewById(R.id.button8) as Button mCommitBtn = findViewById(R.id.button9) as Button mPwdEditText = findViewById(R.id.et_pwd) as EditText mPhoneEditText = findViewById(R.id.et_phone) as EditText mCodeEditText = findViewById(R.id.et_code) as EditText mPwdEditText?.addTextChangedListener(this) mPhoneEditText?.addTextChangedListener(this) mCodeEditText?.addTextChangedListener(this) setSupportActionBar(toolbar) toolbar.setNavigationOnClickListener { v -> finish() } findViewById(R.id.back_view).setOnClickListener { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(mSendCode?.windowToken, 0) } //发送code mSendCode!!.setOnClickListener { v -> mSendCode!!.isEnabled = false val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(mSendCode?.windowToken, 0) if (mPhoneEditText!!.text.length < 11) { Snackbar.make(v, "手机号不正确,请重新输入", Snackbar.LENGTH_SHORT).show() } else if (mPwdEditText?.text.toString() != Storage.readPwd()) { Snackbar.make(v, "密码不正确,请重新输入", Snackbar.LENGTH_SHORT).show() } else { Service.sendCode(mPhoneEditText?.text.toString(), false) .enqueue(object : Callback<String> { override fun onFailure(call: Call<String>?, t: Throwable?) { t?.printStackTrace() } override fun onResponse(call: Call<String>?, response: Response<String>?) { try { val json = JSONObject.parseObject(response?.body()) if (json.getIntValue("status") == 1) setTiemr() else { Snackbar.make(v, json.getString("error"), Snackbar.LENGTH_SHORT).show() } } catch (e: JSONException) { Snackbar.make(v, "服务器出错,请稍后再试", Snackbar.LENGTH_SHORT).show() } } }) } } } //提交 fun commit(v: View) { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(mSendCode?.windowToken, 0) Service.binding_mobile(mPhoneEditText?.text.toString(), mCodeEditText?.text.toString()) .enqueue(object : Callback<String> { override fun onResponse(call: Call<String>?, response: Response<String>?) { try { val jsonObj = JSONObject.parseObject(response?.body()) val status = jsonObj.getInteger("status") if (status == 1) { Snackbar.make(v, "修改手机号成功", Snackbar.LENGTH_SHORT).setCallback(object :Snackbar.Callback(){ override fun onDismissed(snackbar: Snackbar?, event: Int) { finish() } }).show() } else if (status == 0) { Snackbar.make(v, jsonObj.getString("error"), Snackbar.LENGTH_SHORT).show() } } catch (e: JSONException) { Snackbar.make(v, "服务器出错,请稍后再试", Snackbar.LENGTH_SHORT).show() } } override fun onFailure(call: Call<String>?, t: Throwable?) { t?.printStackTrace() } }) } /////////////////////////////////////////////////////////////////////////// // textChangeWhater /////////////////////////////////////////////////////////////////////////// override fun afterTextChanged(s: Editable?) { mCommitBtn?.isEnabled = mPwdEditText?.text?.length!! >= 6 && mPhoneEditText?.text?.length!! == 11 && mCodeEditText?.length()!! == 4 } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } private var time = 60 //设置计时器 private fun setTiemr() { val timer = Timer() timer.schedule(object : TimerTask() { override fun run() { if (time > 0) { runOnUiThread { mSendCode!!.setText(time.toString() + "s") mSendCode!!.isEnabled = false } time-- } else { runOnUiThread { mSendCode!!.text = "重发验证码" mSendCode!!.isEnabled = true } time = 60 timer.cancel() } } }, 0, 1000) } }
gpl-2.0
b01bca6abafe4748eece856bcf3ffdfd
40.433121
139
0.532821
5.086005
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/util/RateLimiter.kt
1
1756
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.boardgamegeek.util import android.os.SystemClock import androidx.collection.ArrayMap import java.util.concurrent.TimeUnit /** * Utility class that decides whether we should fetch some data or not. */ class RateLimiter<in KEY>(timeout: Int, timeUnit: TimeUnit) { private val timestamps = ArrayMap<KEY, Long>() private val timeout = timeUnit.toMillis(timeout.toLong()) @Synchronized fun shouldProcess(key: KEY, now: Long = SystemClock.uptimeMillis()): Boolean { val lastFetched = timestamps[key] return if ((lastFetched == null) || (now - lastFetched > timeout)) { timestamps[key] = now true } else false } // @Synchronized // @Suppress("unused") // fun willProcessAt(key: KEY): Long { // val lastFetched = timestamps[key] // val now = SystemClock.uptimeMillis() // return if ((lastFetched == null) || (now - lastFetched > timeout)) { // now // } else lastFetched + timeout // } @Synchronized fun reset(key: KEY) { timestamps.remove(key) } }
gpl-3.0
96f752047b31f9b15587f59d3624a1e1
31.518519
82
0.655467
4.251816
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/store/ListStore.kt
2
19414
package org.wordpress.android.fluxc.store import androidx.lifecycle.Lifecycle import androidx.lifecycle.LiveData import androidx.paging.LivePagedListBuilder import androidx.paging.PagedList import androidx.paging.PagedList.BoundaryCallback import com.yarolegovich.wellsql.WellSql import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.Payload import org.wordpress.android.fluxc.action.ListAction import org.wordpress.android.fluxc.action.ListAction.FETCHED_LIST_ITEMS import org.wordpress.android.fluxc.action.ListAction.LIST_DATA_INVALIDATED import org.wordpress.android.fluxc.action.ListAction.LIST_ITEMS_REMOVED import org.wordpress.android.fluxc.action.ListAction.LIST_REQUIRES_REFRESH import org.wordpress.android.fluxc.action.ListAction.REMOVE_ALL_LISTS import org.wordpress.android.fluxc.action.ListAction.REMOVE_EXPIRED_LISTS import org.wordpress.android.fluxc.annotations.action.Action import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId import org.wordpress.android.fluxc.model.list.LIST_STATE_TIMEOUT import org.wordpress.android.fluxc.model.list.ListDescriptor import org.wordpress.android.fluxc.model.list.ListDescriptorTypeIdentifier import org.wordpress.android.fluxc.model.list.ListItemModel import org.wordpress.android.fluxc.model.list.ListModel import org.wordpress.android.fluxc.model.list.ListState import org.wordpress.android.fluxc.model.list.ListState.FETCHED import org.wordpress.android.fluxc.model.list.PagedListFactory import org.wordpress.android.fluxc.model.list.PagedListWrapper import org.wordpress.android.fluxc.model.list.datasource.InternalPagedListDataSource import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface import org.wordpress.android.fluxc.persistence.ListItemSqlUtils import org.wordpress.android.fluxc.persistence.ListSqlUtils import org.wordpress.android.fluxc.store.ListStore.OnListChanged.CauseOfListChange import org.wordpress.android.fluxc.tools.CoroutineEngine import org.wordpress.android.util.AppLog import org.wordpress.android.util.DateTimeUtils import java.util.Date import javax.inject.Inject import javax.inject.Singleton import kotlin.coroutines.CoroutineContext // How long a list should stay in DB if it hasn't been updated const val DEFAULT_EXPIRATION_DURATION = 1000L * 60 * 60 * 24 * 7 /** * This Store is responsible for managing lists and their metadata. One of the designs goals for this Store is expose * as little as possible to the consumers and make sure the exposed parts are immutable. This not only moves the * responsibility of mutation to the Store but also makes it much easier to use the exposed data. */ @Singleton class ListStore @Inject constructor( private val listSqlUtils: ListSqlUtils, private val listItemSqlUtils: ListItemSqlUtils, private val coroutineContext: CoroutineContext, private val coroutineEngine: CoroutineEngine, dispatcher: Dispatcher ) : Store(dispatcher) { @Subscribe(threadMode = ThreadMode.ASYNC) override fun onAction(action: Action<*>) { val actionType = action.type as? ListAction ?: return when (actionType) { FETCHED_LIST_ITEMS -> handleFetchedListItems(action.payload as FetchedListItemsPayload) LIST_ITEMS_REMOVED -> handleListItemsRemoved(action.payload as ListItemsRemovedPayload) LIST_REQUIRES_REFRESH -> handleListRequiresRefresh(action.payload as ListDescriptorTypeIdentifier) LIST_DATA_INVALIDATED -> handleListDataInvalidated(action.payload as ListDescriptorTypeIdentifier) REMOVE_EXPIRED_LISTS -> handleRemoveExpiredLists(action.payload as RemoveExpiredListsPayload) REMOVE_ALL_LISTS -> handleRemoveAllLists() } } override fun onRegister() { AppLog.d(AppLog.T.API, ListStore::class.java.simpleName + " onRegister") } /** * This is the function that'll be used to consume lists. * * @param listDescriptor Describes which list will be consumed * @param dataSource Describes how to take certain actions such as fetching a list for the item type [LIST_ITEM]. * @param lifecycle The lifecycle of the client that'll be consuming this list. It's used to make sure everything * is cleaned up properly once the client is destroyed. * * @return A [PagedListWrapper] that provides all the necessary information to consume a list such as its data, * whether the first page is being fetched, whether there are any errors etc. in `LiveData` format. */ fun <LIST_DESCRIPTOR : ListDescriptor, ITEM_IDENTIFIER, LIST_ITEM> getList( listDescriptor: LIST_DESCRIPTOR, dataSource: ListItemDataSourceInterface<LIST_DESCRIPTOR, ITEM_IDENTIFIER, LIST_ITEM>, lifecycle: Lifecycle ): PagedListWrapper<LIST_ITEM> { val factory = createPagedListFactory(listDescriptor, dataSource) val pagedListData = createPagedListLiveData( listDescriptor = listDescriptor, dataSource = dataSource, pagedListFactory = factory ) return PagedListWrapper( data = pagedListData, dispatcher = mDispatcher, listDescriptor = listDescriptor, lifecycle = lifecycle, refresh = { handleFetchList(listDescriptor, loadMore = false) { offset -> dataSource.fetchList(listDescriptor, offset) } }, invalidate = factory::invalidate, parentCoroutineContext = coroutineContext ) } /** * A helper function that creates a [PagedList] [LiveData] for the given [LIST_DESCRIPTOR], [dataSource] and the * [PagedListFactory]. */ private fun <LIST_DESCRIPTOR : ListDescriptor, ITEM_IDENTIFIER, LIST_ITEM> createPagedListLiveData( listDescriptor: LIST_DESCRIPTOR, dataSource: ListItemDataSourceInterface<LIST_DESCRIPTOR, ITEM_IDENTIFIER, LIST_ITEM>, pagedListFactory: PagedListFactory<LIST_DESCRIPTOR, ITEM_IDENTIFIER, LIST_ITEM> ): LiveData<PagedList<LIST_ITEM>> { val pagedListConfig = PagedList.Config.Builder() .setEnablePlaceholders(true) .setInitialLoadSizeHint(listDescriptor.config.initialLoadSize) .setPageSize(listDescriptor.config.dbPageSize) .build() val boundaryCallback = object : BoundaryCallback<LIST_ITEM>() { override fun onItemAtEndLoaded(itemAtEnd: LIST_ITEM) { // Load more items if we are near the end of list coroutineEngine.launch(AppLog.T.API, this, "ListStore: Loading next page") { handleFetchList(listDescriptor, loadMore = true) { offset -> dataSource.fetchList(listDescriptor, offset) } } super.onItemAtEndLoaded(itemAtEnd) } } return LivePagedListBuilder<Int, LIST_ITEM>(pagedListFactory, pagedListConfig) .setBoundaryCallback(boundaryCallback).build() } /** * A helper function that creates a [PagedListFactory] for the given [LIST_DESCRIPTOR] and [dataSource]. */ private fun <LIST_DESCRIPTOR : ListDescriptor, ITEM_IDENTIFIER, LIST_ITEM> createPagedListFactory( listDescriptor: LIST_DESCRIPTOR, dataSource: ListItemDataSourceInterface<LIST_DESCRIPTOR, ITEM_IDENTIFIER, LIST_ITEM> ): PagedListFactory<LIST_DESCRIPTOR, ITEM_IDENTIFIER, LIST_ITEM> { val getRemoteItemIds = { getListItems(listDescriptor).map { RemoteId(value = it) } } val getIsListFullyFetched = { getListState(listDescriptor) == FETCHED } return PagedListFactory( createDataSource = { InternalPagedListDataSource( listDescriptor = listDescriptor, remoteItemIds = getRemoteItemIds(), isListFullyFetched = getIsListFullyFetched(), itemDataSource = dataSource ) }) } /** * A helper function that returns the list items for the given [ListDescriptor]. */ private fun getListItems(listDescriptor: ListDescriptor): List<Long> { val listModel = listSqlUtils.getList(listDescriptor) return if (listModel != null) { listItemSqlUtils.getListItems(listModel.id).map { it.remoteItemId } } else emptyList() } /** * A helper function that initiates the fetch from remote for the given [ListDescriptor]. * * Before fetching the list, it'll first check if this is a valid fetch depending on the list's state. Then, it'll * update the list's state and emit that change. Finally, it'll calculate the offset and initiate the fetch with * the given [fetchList] function. */ private fun handleFetchList( listDescriptor: ListDescriptor, loadMore: Boolean, fetchList: (Long) -> Unit ) { val currentState = getListState(listDescriptor) if (!loadMore && currentState.isFetchingFirstPage()) { // already fetching the first page return } else if (loadMore && !currentState.canLoadMore()) { // we can only load more if there is more data to be loaded return } val newState = if (loadMore) ListState.LOADING_MORE else ListState.FETCHING_FIRST_PAGE listSqlUtils.insertOrUpdateList(listDescriptor, newState) handleListStateChange(listDescriptor, newState) val listModel = requireNotNull(listSqlUtils.getList(listDescriptor)) { "The `ListModel` can never be `null` here since either a new list is inserted or existing one updated" } val offset = if (loadMore) listItemSqlUtils.getListItemsCount(listModel.id) else 0L fetchList(offset) } /** * A helper function that emits the latest [ListState] for the given [ListDescriptor]. */ private fun handleListStateChange(listDescriptor: ListDescriptor, newState: ListState, error: ListError? = null) { emitChange(OnListStateChanged(listDescriptor, newState, error)) } /** * Handles the [ListAction.FETCHED_LIST_ITEMS] action. * * Here is how it works: * 1. If there was an error, update the list's state and emit the change. Otherwise: * 2. If the first page is fetched, delete the existing [ListItemModel]s. * 3. Update the [ListModel]'s state depending on whether there is more data to be fetched * 4. Insert the [ListItemModel]s and emit the change * * See [handleFetchList] to see how items are fetched. */ private fun handleFetchedListItems(payload: FetchedListItemsPayload) { val newState = when { payload.isError -> ListState.ERROR payload.canLoadMore -> ListState.CAN_LOAD_MORE else -> FETCHED } listSqlUtils.insertOrUpdateList(payload.listDescriptor, newState) if (!payload.isError) { val db = WellSql.giveMeWritableDb() db.beginTransaction() try { if (!payload.loadedMore) { deleteListItems(payload.listDescriptor) } val listModel = requireNotNull(listSqlUtils.getList(payload.listDescriptor)) { "The `ListModel` can never be `null` here since either a new list is inserted or existing one " + "updated" } listItemSqlUtils.insertItemList(payload.remoteItemIds.map { remoteItemId -> val listItemModel = ListItemModel() listItemModel.listId = listModel.id listItemModel.remoteItemId = remoteItemId return@map listItemModel }) db.setTransactionSuccessful() } finally { db.endTransaction() } } val causeOfChange = if (payload.isError) { CauseOfListChange.ERROR } else { if (payload.loadedMore) CauseOfListChange.LOADED_MORE else CauseOfListChange.FIRST_PAGE_FETCHED } emitChange(OnListChanged(listOf(payload.listDescriptor), causeOfChange, payload.error)) handleListStateChange(payload.listDescriptor, newState, payload.error) } /** * Handles the [ListAction.LIST_ITEMS_REMOVED] action. * * Items in [ListItemsRemovedPayload.remoteItemIds] will be removed from lists with * [ListDescriptorTypeIdentifier] after which [OnListDataInvalidated] event will be emitted. */ private fun handleListItemsRemoved(payload: ListItemsRemovedPayload) { val lists = listSqlUtils.getListsWithTypeIdentifier(payload.type) listItemSqlUtils.deleteItemsFromLists(lists.map { it.id }, payload.remoteItemIds) emitChange(OnListDataInvalidated(payload.type)) } /** * Handles the [ListAction.LIST_REQUIRES_REFRESH] action. * * Whenever a type of list needs to be refreshed, [OnListRequiresRefresh] event will be emitted so the listening * lists can refresh themselves. */ private fun handleListRequiresRefresh(typeIdentifier: ListDescriptorTypeIdentifier) { emitChange(OnListRequiresRefresh(type = typeIdentifier)) } /** * Handles the [ListAction.LIST_DATA_INVALIDATED] action. * * Whenever the data of a list is invalidated, [OnListDataInvalidated] event will be emitted so the listening * lists can invalidate their data. */ private fun handleListDataInvalidated(typeIdentifier: ListDescriptorTypeIdentifier) { emitChange(OnListDataInvalidated(type = typeIdentifier)) } /** * Handles the [ListAction.REMOVE_EXPIRED_LISTS] action. * * It deletes [ListModel]s that hasn't been updated for the given [RemoveExpiredListsPayload.expirationDuration]. */ private fun handleRemoveExpiredLists(payload: RemoveExpiredListsPayload) { listSqlUtils.deleteExpiredLists(payload.expirationDuration) } /** * Handles the [ListAction.REMOVE_ALL_LISTS] action. * * It simply deletes every [ListModel] in the DB. */ private fun handleRemoveAllLists() { listSqlUtils.deleteAllLists() } /** * Deletes all the items for the given [ListDescriptor]. */ private fun deleteListItems(listDescriptor: ListDescriptor) { listSqlUtils.getList(listDescriptor)?.let { listItemSqlUtils.deleteItems(it.id) } } /** * A helper function that returns the [ListState] for the given [ListDescriptor]. */ private fun getListState(listDescriptor: ListDescriptor): ListState { val listModel = listSqlUtils.getList(listDescriptor) return if (listModel != null && !isListStateOutdated(listModel)) { requireNotNull(ListState.values().firstOrNull { it.value == listModel.stateDbValue }) { "The stateDbValue of the ListModel didn't match any of the `ListState`s. This likely happened " + "because the ListState values were altered without a DB migration." } } else ListState.defaultState } /** * A helper function that returns whether it has been more than a certain time has passed since it's `lastModified`. * * Since we keep the state in the DB, in the case of application being closed during a fetch, it'll carry * over to the next session. To prevent such cases, we use a timeout approach. If it has been more than a * certain time since the list is last updated, we should ignore the state. */ private fun isListStateOutdated(listModel: ListModel): Boolean { listModel.lastModified?.let { val lastModified = DateTimeUtils.dateUTCFromIso8601(it) val timePassed = (Date().time - lastModified.time) return timePassed > LIST_STATE_TIMEOUT } // If a list is null, it means we have never fetched it before, so it can't be outdated return false } /** * The event to be emitted when there is a change to a [ListModel]. */ class OnListChanged( val listDescriptors: List<ListDescriptor>, val causeOfChange: CauseOfListChange, error: ListError? ) : Store.OnChanged<ListError>() { enum class CauseOfListChange { ERROR, FIRST_PAGE_FETCHED, LOADED_MORE } init { this.error = error } } /** * The event to be emitted whenever there is a change to the [ListState] */ class OnListStateChanged( val listDescriptor: ListDescriptor, val newState: ListState, error: ListError? ) : Store.OnChanged<ListError>() { init { this.error = error } } /** * The event to be emitted when a list needs to be refresh for a specific [ListDescriptorTypeIdentifier]. */ class OnListRequiresRefresh(val type: ListDescriptorTypeIdentifier) : Store.OnChanged<ListError>() /** * The event to be emitted when a list's data is invalidated for a specific [ListDescriptorTypeIdentifier]. */ class OnListDataInvalidated(val type: ListDescriptorTypeIdentifier) : Store.OnChanged<ListError>() /** * This is the payload for [ListAction.LIST_ITEMS_REMOVED]. * * @property type [ListDescriptorTypeIdentifier] which will tell [ListStore] and the clients which * [ListDescriptor]s are updated. * @property remoteItemIds Remote item ids to be removed from the lists matching the [ListDescriptorTypeIdentifier]. */ class ListItemsRemovedPayload(val type: ListDescriptorTypeIdentifier, val remoteItemIds: List<Long>) /** * This is the payload for [ListAction.FETCHED_LIST_ITEMS]. * * @property listDescriptor List descriptor will be provided when the action to fetch items will be dispatched * from other Stores. The same list descriptor will need to be used in this payload so [ListStore] can decide * which list to update. * @property remoteItemIds Fetched item ids * @property loadedMore Indicates whether the first page is fetched or we loaded more data * @property canLoadMore Indicates whether there is more data to be loaded from the server. */ class FetchedListItemsPayload( val listDescriptor: ListDescriptor, val remoteItemIds: List<Long>, val loadedMore: Boolean, val canLoadMore: Boolean, error: ListError? ) : Payload<ListError>() { init { this.error = error } } /** * This is the payload for [ListAction.REMOVE_EXPIRED_LISTS]. * * @property expirationDuration Tells how long a list should be kept in the DB if it hasn't been updated */ class RemoveExpiredListsPayload(val expirationDuration: Long = DEFAULT_EXPIRATION_DURATION) class ListError( val type: ListErrorType, val message: String? = null ) : OnChangedError enum class ListErrorType { GENERIC_ERROR, PERMISSION_ERROR } }
gpl-2.0
23e144fcd33c6f37185b75f898a2019f
43.223235
120
0.680591
4.908723
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/entity/EntityProtocolTypes.kt
1
3442
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.entity import org.lanternpowered.api.key.minecraftKey import org.lanternpowered.api.registry.CatalogRegistry import org.lanternpowered.api.registry.require import org.lanternpowered.server.entity.LanternEntity import org.lanternpowered.server.entity.player.LanternPlayer object EntityProtocolTypes { val ARMOR_STAND: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("armor_stand")) val BAT: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("bat")) val CHICKEN: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("chicken")) val ENDER_DRAGON: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("ender_dragon")) val ENDERMITE: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("endermite")) val EXPERIENCE_ORB: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("experience_orb")) val GIANT: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("giant")) val HUMAN: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("human")) val HUSK: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("husk")) val IRON_GOLEM: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("iron_golem")) val ITEM: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("item")) val LIGHTNING: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("lightning")) val MAGMA_CUBE: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("magma_cube")) val PAINTING: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("painting")) val PIG: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("pig")) val PLAYER: EntityProtocolType<LanternPlayer> = CatalogRegistry.require(minecraftKey("player")) val RABBIT: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("rabbit")) val SHEEP: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("sheep")) val SILVERFISH: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("silverfish")) val SLIME: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("slime")) val SNOWMAN: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("snowman")) val VILLAGER: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("villager")) val ZOMBIE: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("zombie")) val ZOMBIE_VILLAGER: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("zombie_villager")) val HORSE: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("horse")) val DONKEY: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("donkey")) val LLAMA: EntityProtocolType<LanternEntity> = CatalogRegistry.require(minecraftKey("llama")) }
mit
df2dff7ecbe07bd6baef0412d449793e
70.729167
117
0.798083
4.192448
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/inventory/container/layout/RootMerchantContainerLayout.kt
1
5570
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.inventory.container.layout import org.lanternpowered.api.entity.player.Player import org.lanternpowered.api.item.inventory.container.layout.ContainerLayout import org.lanternpowered.api.item.inventory.container.layout.ContainerSlot import org.lanternpowered.api.item.inventory.container.layout.MerchantContainerLayout import org.lanternpowered.api.item.inventory.stack.asStack import org.lanternpowered.api.item.inventory.stack.orEmptySnapshot import org.lanternpowered.api.text.translatableTextOf import org.lanternpowered.api.util.collections.toImmutableList import org.lanternpowered.server.inventory.container.ClientWindowTypes import org.lanternpowered.server.network.packet.Packet import org.lanternpowered.server.network.vanilla.packet.type.play.OpenWindowPacket import org.lanternpowered.server.network.vanilla.packet.type.play.SetWindowTradeOffersPacket import org.lanternpowered.server.network.vanilla.trade.NetworkTradeOffer import org.spongepowered.api.item.merchant.TradeOffer class RootMerchantContainerLayout : LanternTopBottomContainerLayout<MerchantContainerLayout>( title = TITLE, slotFlags = ALL_INVENTORY_FLAGS ) { companion object { private val TITLE = translatableTextOf("container.trading") private val TOP_INVENTORY_FLAGS = intArrayOf( Flags.DISABLE_SHIFT_INSERTION, // First input slot Flags.DISABLE_SHIFT_INSERTION, // Second input slot Flags.REVERSE_SHIFT_INSERTION + Flags.DISABLE_SHIFT_INSERTION or Flags.IGNORE_DOUBLE_CLICK // Result slot ) private val ALL_INVENTORY_FLAGS = TOP_INVENTORY_FLAGS + MAIN_INVENTORY_FLAGS private const val UPDATE_TRADE_OFFERS = 0x1 } private val onClickOffer = ArrayList<(Player, TradeOffer) -> Unit>() override fun createOpenPackets(data: ContainerData): List<Packet> = listOf(OpenWindowPacket(data.containerId, ClientWindowTypes.MERCHANT, this.title)) override val top: MerchantContainerLayout = SubMerchantContainerLayout(0, TOP_INVENTORY_FLAGS.size, this) override fun collectChangePackets(data: ContainerData, packets: MutableList<Packet>) { if (data.slotUpdateFlags[0] and UpdateFlags.NEEDS_UPDATE != 0 || data.slotUpdateFlags[1] and UpdateFlags.NEEDS_UPDATE != 0) { // Force update the result slot if one of the inputs is modified data.queueSilentSlotChangeSafely(this.slots[2]) } if (data.extraUpdateFlags and UPDATE_TRADE_OFFERS != 0) { val networkOffers = this.offers .map { offer -> val firstInput = offer.firstBuyingItem.asStack() val secondInput = offer.secondBuyingItem.orEmptySnapshot().asStack() val output = offer.sellingItem.asStack() val disabled = offer.hasExpired() val uses = offer.uses val maxUses = offer.maxUses val experience = offer.experienceGrantedToMerchant val specialPrice = offer.demandBonus // TODO: Check if this is correct val priceMultiplier = offer.priceGrowthMultiplier NetworkTradeOffer(firstInput, secondInput, output, disabled, uses, maxUses, experience, specialPrice, priceMultiplier) } // TODO: Check if we need to expose some of these options. packets += SetWindowTradeOffersPacket(data.containerId, villagerLevel = 1, experience = 0, regularVillager = true, canRestock = true, tradeOffers = networkOffers) data.extraUpdateFlags = 0 } super.collectChangePackets(data, packets) } var offers: List<TradeOffer> = emptyList() set(value) { field = value.toImmutableList() for (data in this.viewerData) data.extraUpdateFlags = data.extraUpdateFlags or UPDATE_TRADE_OFFERS } fun onClickOffer(fn: (player: Player, offer: TradeOffer) -> Unit) { this.onClickOffer += fn } /** * Handles a click offer packet for the given player. */ fun handleClickOffer(player: Player, index: Int) { this.getData(player) ?: return // TODO: Check if updates are needed val offer = if (index >= 0 && index < this.offers.size) this.offers[index] else return for (onClickOffer in this.onClickOffer) onClickOffer(player, offer) } } private class SubMerchantContainerLayout( offset: Int, size: Int, private val root: RootMerchantContainerLayout ) : SubContainerLayout(offset, size, root), MerchantContainerLayout { // 0..last - 1 = inputs // last = output override val inputs: ContainerLayout = SubContainerLayout(offset, this.size - 1, this.base) override val output: ContainerSlot get() = this[this.size - 1] override var offers: List<TradeOffer> get() = this.root.offers set(value) { this.root.offers = value } override fun onClickOffer(fn: (player: Player, offer: TradeOffer) -> Unit) { this.root.onClickOffer(fn) } }
mit
3733976efc42dcce6d3d540dc721e594
43.919355
121
0.680072
4.456
false
false
false
false
songzhw/CleanAlpha-Kotlin
app/src/main/kotlin/cn/song/kotlind/net/BaseRequest.kt
2
853
package cn.song.kotlind.net import java.io.BufferedInputStream import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL /** * @author hzsongzhengwang * @date 2015/7/14 * Copyright 2015 Six. All rights reserved. */ class BaseRequest(getUrl : String){ val url = getUrl; fun sendRequest() : String?{ var urlObj = URL(url) var http = urlObj.openConnection() as HttpURLConnection if(http.getResponseCode() == HttpURLConnection.HTTP_OK){ var stream = BufferedInputStream(http.getInputStream()) var reader = BufferedReader(InputStreamReader(stream)) val sb = StringBuilder() reader.forEachLine { sb.append(it) } return sb.toString(); } http.disconnect(); return null; } }
apache-2.0
dfa8d10ef4ca7ea9382cd76db563d7a8
25.6875
67
0.658851
4.352041
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/highlighting/BibtexSyntaxHighlighter.kt
1
2860
package nl.hannahsten.texifyidea.highlighting import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.DefaultLanguageHighlighterColors.* import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType import nl.hannahsten.texifyidea.BibtexLexerAdapter import nl.hannahsten.texifyidea.psi.BibtexTypes /** * @author Hannah Schellekens */ open class BibtexSyntaxHighlighter : SyntaxHighlighterBase() { companion object { val ASSIGNMENT = createTextAttributesKey("BIBTEX_ASSIGNMENT", OPERATION_SIGN) val BRACES = createTextAttributesKey("BIBTEX_BRACES", LatexSyntaxHighlighter.BRACES) val COMMENTS = createTextAttributesKey("BIBTEX_COMMENTS", LatexSyntaxHighlighter.COMMENT) val CONCATENATION = createTextAttributesKey("BIBTEX_CONCATENATION", OPERATION_SIGN) val IDENTIFIER = createTextAttributesKey("BIBTEX_IDENTIFIER", INSTANCE_FIELD) val KEY = createTextAttributesKey("BIBTEX_KEY", PARAMETER) val NUMBER = createTextAttributesKey("BIBTEX_NUMBER", DefaultLanguageHighlighterColors.NUMBER) val STRING = createTextAttributesKey("BIBTEX_STRING", DefaultLanguageHighlighterColors.STRING) val TYPE_TOKEN = createTextAttributesKey("BIBTEX_TYPE_TOKEN", KEYWORD) val VALUE = createTextAttributesKey("BIBTEX_VALUE", DefaultLanguageHighlighterColors.IDENTIFIER) val ASSIGNMENT_KEYS = arrayOf(ASSIGNMENT) val BRACES_KEYS = arrayOf(BRACES) val COMMENT_KEYS = arrayOf(COMMENTS) val CONCATENATION_KEYS = arrayOf(CONCATENATION) val IDENTIFIER_KEYS = arrayOf(IDENTIFIER) val KEY_KEYS = arrayOf(KEY) val NUMBER_KEYS = arrayOf(NUMBER) val STRING_KEYS = arrayOf(STRING) val TYPE_TOKEN_KEYS = arrayOf(TYPE_TOKEN) val VALUE_KEYS = arrayOf(VALUE) val EMPTY_KEYS = emptyArray<TextAttributesKey>() } override fun getHighlightingLexer() = BibtexLexerAdapter() override fun getTokenHighlights(tokenType: IElementType?) = when (tokenType) { BibtexTypes.ASSIGNMENT -> ASSIGNMENT_KEYS BibtexTypes.OPEN_BRACE, BibtexTypes.CLOSE_BRACE, BibtexTypes.OPEN_PARENTHESIS -> BRACES_KEYS BibtexTypes.COMMENT, BibtexTypes.COMMENT_TOKEN -> COMMENT_KEYS BibtexTypes.CONCATENATE -> CONCATENATION_KEYS BibtexTypes.IDENTIFIER -> IDENTIFIER_KEYS BibtexTypes.KEY -> KEY_KEYS BibtexTypes.NUMBER -> NUMBER_KEYS BibtexTypes.TYPE_TOKEN -> TYPE_TOKEN_KEYS BibtexTypes.STRING, BibtexTypes.QUOTED_STRING -> STRING_KEYS BibtexTypes.CONTENT, BibtexTypes.BRACED_STRING -> VALUE_KEYS else -> EMPTY_KEYS } }
mit
7069f1249125d7188c9958f5a7665905
48.327586
104
0.747902
4.914089
false
false
false
false
ykrank/S1-Next
library/src/main/java/com/github/ykrank/androidtools/widget/track/event/TrackEvent.kt
1
809
package com.github.ykrank.androidtools.widget.track.event import java.util.* /** * Created by ykrank on 2016/12/27. */ open class TrackEvent { var group: String? = null var name: String? = null private val data: MutableMap<String, String?> = hashMapOf() /** * use to verify handler */ val eventType: Class<*> get() = this.javaClass protected constructor() constructor(group: String?, name: String?, data: Map<String, String?>) { this.group = group this.name = name this.data.putAll(data) } fun getData(): Map<String, String?> { return data } fun addData(key: String, value: String?) { data[key] = value } fun addData(data: Map<String, String?>) { this.data.putAll(data) } }
apache-2.0
8fdec7d1190db4b4858104c686fa1cbe
18.731707
76
0.590853
3.870813
false
false
false
false
zyallday/kotlin-koans
src/iv_properties/n33LazyProperty.kt
1
696
package iv_properties import util.TODO class LazyProperty(val initializer: () -> Int) { var _lazy: Int? = null val lazy: Int get() { if (null == _lazy) { _lazy = initializer.invoke() } return _lazy ?: throw AssertionError("has not initialized yet") } } fun todoTask33(): Nothing = TODO( """ Task 33. Add a custom getter to make the 'lazy' val really lazy. It should be initialized by the invocation of 'initializer()' at the moment of the first access. You can add as many additional properties as you need. Do not use delegated properties yet! """, references = { LazyProperty({ 42 }).lazy } )
mit
75faf5a2346b75e97d3fcee7a1c9bcd9
25.769231
69
0.609195
4.243902
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/injection/ApplicationModule.kt
1
3808
package org.tasks.injection import android.app.NotificationManager import android.content.Context import androidx.appcompat.app.AppCompatDelegate import com.franmontiel.persistentcookiejar.persistence.CookiePersistor import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor import com.todoroo.astrid.dao.Database import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import org.tasks.analytics.Firebase import org.tasks.billing.BillingClient import org.tasks.billing.BillingClientImpl import org.tasks.billing.Inventory import org.tasks.data.* import org.tasks.jobs.WorkManager import org.tasks.notifications.NotificationDao import java.util.* import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class ApplicationModule { @Provides fun getLocale(): Locale { return AppCompatDelegate.getApplicationLocales() .toLanguageTags() .split(",") .firstOrNull { it.isNotBlank() } ?.let { Locale.forLanguageTag(it) } ?: Locale.getDefault() } @Provides @Singleton fun getNotificationDao(db: Database): NotificationDao = db.notificationDao() @Provides @Singleton fun getTagDataDao(db: Database): TagDataDao = db.tagDataDao @Provides @Singleton fun getUserActivityDao(db: Database): UserActivityDao = db.userActivityDao @Provides @Singleton fun getTaskAttachmentDao(db: Database): TaskAttachmentDao = db.taskAttachmentDao @Provides @Singleton fun getTaskListMetadataDao(db: Database): TaskListMetadataDao = db.taskListMetadataDao @Provides @Singleton fun getGoogleTaskDao(db: Database): GoogleTaskDao = db.googleTaskDao @Provides @Singleton fun getAlarmDao(db: Database): AlarmDao = db.alarmDao @Provides @Singleton fun getGeofenceDao(db: Database): LocationDao = db.locationDao @Provides @Singleton fun getTagDao(db: Database): TagDao = db.tagDao @Provides @Singleton fun getFilterDao(db: Database): FilterDao = db.filterDao @Provides @Singleton fun getGoogleTaskListDao(db: Database): GoogleTaskListDao = db.googleTaskListDao @Provides @Singleton fun getCaldavDao(db: Database): CaldavDao = db.caldavDao @Provides @Singleton fun getTaskDao(db: Database): TaskDao = db.taskDao @Provides @Singleton fun getDeletionDao(db: Database): DeletionDao = db.deletionDao @Provides @Singleton fun getContentProviderDao(db: Database): ContentProviderDao = db.contentProviderDao @Provides @Singleton fun getUpgraderDao(db: Database) = db.upgraderDao @Provides @Singleton fun getPrincipalDao(db: Database) = db.principalDao @Provides fun getBillingClient( @ApplicationContext context: Context, inventory: Inventory, firebase: Firebase, workManager: WorkManager, ): BillingClient = BillingClientImpl(context, inventory, firebase, workManager) @Singleton @ApplicationScope @Provides fun providesCoroutineScope( @DefaultDispatcher defaultDispatcher: CoroutineDispatcher ): CoroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher) @Provides fun providesNotificationManager(@ApplicationContext context: Context) = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager @Provides fun cookiePersistor(@ApplicationContext context: Context): CookiePersistor = SharedPrefsCookiePersistor(context) }
gpl-3.0
6c1f47a0aa00c7d3d52c2342ed5407cc
28.3
90
0.746324
4.814159
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/graph/GtkCanvas.kt
1
2114
package ch.bailu.aat_gtk.view.graph import ch.bailu.aat_lib.util.Point import ch.bailu.aat_lib.view.graph.GraphCanvas import ch.bailu.gtk.cairo.Context import ch.bailu.gtk.pango.Pango import ch.bailu.gtk.pangocairo.Pangocairo import ch.bailu.gtk.type.Str import org.mapsforge.map.gtk.util.color.ARGB import org.mapsforge.map.gtk.util.color.ColorInterface import org.mapsforge.map.gtk.util.color.Conv255 class GtkCanvas (private val context: Context) : GraphCanvas { private val fontDescription = Pango.fontDescriptionFromString(Str("Arial Thin 9")) override fun drawLine(x1: Int, y1: Int, x2: Int, y2: Int) { drawLine(x1, y1, x2, y2, ColorInterface.DKGRAY) } override fun drawLine(pa: Point, pb: Point, color: Int) { drawLine(pa.x, pa.y, pb.x, pb.y, color) } private fun drawLine(x1: Int, y1: Int, x2: Int, y2: Int, color: Int) { context.save() setColor(color) context.setLineWidth(1.0) context.moveTo(x1.toDouble(), y1.toDouble()) context.lineTo(x2.toDouble(), y2.toDouble()) context.stroke() context.restore() } override fun drawBitmap(pa: Point?, color: Int) { } override fun getTextSize(): Int { return 12 } private fun setColor(color: Int) { val argb = ARGB(color) context.setSourceRgba( Conv255.toDouble(argb.red()), Conv255.toDouble(argb.green()), Conv255.toDouble(argb.blue()), Conv255.toDouble(argb.alpha()) ) } override fun drawText(text: String, x: Int, y: Int) { val strText = Str(text) val layout = Pangocairo.createLayout(context) layout.setText(strText, strText.size - 1) layout.fontDescription = fontDescription context.save() context.setLineWidth(0.5) context.moveTo(x.toDouble(), y.toDouble()) Pangocairo.layoutPath(context, layout) setColor(ColorInterface.DKGRAY) context.fillPreserve() context.stroke() context.restore() layout.unref() strText.destroy() } }
gpl-3.0
1bbd05d0e1ce06d27f50deb01305ccab
28.788732
86
0.640492
3.476974
false
false
false
false
chimbori/crux
src/main/kotlin/com/chimbori/crux/Crux.kt
1
4058
package com.chimbori.crux import com.chimbori.crux.api.Extractor import com.chimbori.crux.api.Plugin import com.chimbori.crux.api.Resource import com.chimbori.crux.api.Rewriter import com.chimbori.crux.common.CHROME_USER_AGENT import com.chimbori.crux.plugins.AmpRedirector import com.chimbori.crux.plugins.ArticleExtractor import com.chimbori.crux.plugins.FacebookUrlRewriter import com.chimbori.crux.plugins.FaviconExtractor import com.chimbori.crux.plugins.GoogleUrlRewriter import com.chimbori.crux.plugins.HtmlMetadataExtractor import com.chimbori.crux.plugins.TrackingParameterRemover import com.chimbori.crux.plugins.WebAppManifestParser import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.HttpUrl import okhttp3.OkHttpClient import org.jsoup.nodes.Document /** * An ordered list of default plugins configured in Crux. Callers can override and provide their own list, or pick and * choose from the set of available default plugins to create their own configuration. */ public fun createDefaultPlugins(okHttpClient: OkHttpClient): List<Plugin> = listOf( // Static redirectors go first, to avoid getting stuck into CAPTCHAs. GoogleUrlRewriter(), FacebookUrlRewriter(), // Remove any tracking parameters remaining. TrackingParameterRemover(), // Prefer canonical URLs over AMP URLs. AmpRedirector(refetchContentFromCanonicalUrl = true, okHttpClient), // Fetches and parses the Web Manifest. May replace existing favicon URL with one from the manifest.json. WebAppManifestParser(okHttpClient), // Parses many standard HTML metadata attributes. HtmlMetadataExtractor(okHttpClient), // Extracts the best possible favicon from all the markup available on the page itself. FaviconExtractor(), // Parses the content of the page to remove ads, navigation, and all the other fluff. ArticleExtractor(okHttpClient), ) /** * Crux can be configured with a set of plugins, including custom ones, in sequence. Each plugin can optionally process * resource metadata, can make additional HTTP requests if necessary, and pass along updated metadata to the next plugin * in the chain. */ public class Crux( /** Select from available plugins, or provide custom plugins for Crux to use. */ private val plugins: List<Plugin>? = null, /** If the calling app has its own instance of [OkHttpClient], use it, otherwise Crux can create and use its own. */ okHttpClient: OkHttpClient = createCruxOkHttpClient(), ) { private val activePlugins: List<Plugin> = plugins ?: createDefaultPlugins(okHttpClient) /** * Processes the provided URL, and returns a metadata object containing custom fields. * @param originalUrl the URL to extract metadata and content from. * @param parsedDoc if the calling app already has access to a parsed DOM tree, Crux can reuse it instead of * re-parsing it. If a custom [Document] is provided, Crux will not make any HTTP requests itself, and may not follow * HTTP redirects (but plugins may still optionally make additional HTTP requests themselves.) */ public suspend fun extractFrom(originalUrl: HttpUrl, parsedDoc: Document? = null): Resource = withContext(Dispatchers.IO) { val rewrittenUrl = activePlugins .filterIsInstance<Rewriter>() .fold(originalUrl) { rewrittenUrl, rewriter -> rewriter.rewrite(rewrittenUrl) } activePlugins .filterIsInstance<Extractor>() .fold(Resource(url = rewrittenUrl, document = parsedDoc)) { resource, extractor -> if (extractor.canExtract(resource.url ?: rewrittenUrl)) { resource + extractor.extract(resource) } else { resource } }.removeNullValues() } } private fun createCruxOkHttpClient(): OkHttpClient = OkHttpClient.Builder() .followRedirects(true) .followSslRedirects(true) .retryOnConnectionFailure(true) .addNetworkInterceptor { chain -> chain.proceed( chain.request().newBuilder() .header("User-Agent", CHROME_USER_AGENT).build() ) } .build()
apache-2.0
7294f214466c599f73c9a696519a54f0
42.170213
120
0.757516
4.488938
false
false
false
false
yh-kim/gachi-android
Gachi/app/src/main/kotlin/com/pickth/gachi/view/festival/adapter/FestivalDetailAdapter.kt
1
3028
/* * Copyright 2017 Yonghoon Kim * * 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.pickth.gachi.view.festival.adapter import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.pickth.gachi.R import com.pickth.gachi.util.OnItemClickListener import com.pickth.gachi.view.gachi.Gachi import kotlinx.android.synthetic.main.item_festival_gachi.view.* class FestivalDetailAdapter(val listener: OnItemClickListener): RecyclerView.Adapter<FestivalDetailAdapter.FestivalDetailViewHolder>() { private var items = ArrayList<Gachi>() override fun onBindViewHolder(holder: FestivalDetailViewHolder?, position: Int) { holder?.onBInd(items[position], position) } override fun getItemCount(): Int = items.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): FestivalDetailViewHolder { val itemView = LayoutInflater.from(parent?.context) .inflate(R.layout.item_festival_gachi, parent, false) return FestivalDetailViewHolder(itemView, listener) } fun addItem(item: Gachi) { Log.d("Gachi__FestivalGachi", "addItem item: ${item}") items.add(item) notifyItemInserted(itemCount - 1) } fun getItem(position: Int) = items[position] class FestivalDetailViewHolder(val view: View, val listener: OnItemClickListener): RecyclerView.ViewHolder(view) { fun onBInd(item: Gachi, position: Int) { with(itemView) { setOnClickListener { listener.onItemClick(position) } if(item.title == "null") { tv_festival_gachi_title.text = "제목이 없습니다" } else { tv_festival_gachi_title.text = item.title } if(item.userImagePath == "") { Glide.with(view) .load(R.drawable.test) .apply(RequestOptions().circleCrop()) .into(iv_festival_gachi) } else { Glide.with(view) .load(item.userImagePath) .apply(RequestOptions().circleCrop()) .into(iv_festival_gachi) } } } } }
apache-2.0
9fff20d8d9fe727e8e20b7f47d780a26
34.470588
136
0.634373
4.505232
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/translations/reference/TranslationReference.kt
1
3417
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.reference import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.translations.TranslationConstants import com.demonwav.mcdev.translations.TranslationFiles import com.demonwav.mcdev.translations.identification.TranslationInstance import com.demonwav.mcdev.translations.index.TranslationIndex import com.demonwav.mcdev.translations.index.TranslationInverseIndex import com.demonwav.mcdev.translations.lang.gen.psi.LangEntry import com.demonwav.mcdev.util.mapToArray import com.demonwav.mcdev.util.toTypedArray import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.json.psi.JsonProperty import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult import com.intellij.psi.PsiPolyVariantReference import com.intellij.psi.PsiReferenceBase import com.intellij.psi.ResolveResult import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.IncorrectOperationException class TranslationReference( element: PsiElement, textRange: TextRange, val key: TranslationInstance.Key, private val renameHandler: (element: PsiElement, range: TextRange, newName: String) -> PsiElement = { elem, range, newName -> ElementManipulators.getManipulator(elem).handleContentChange(elem, range, newName)!! } ) : PsiReferenceBase.Poly<PsiElement>(element, textRange, false), PsiPolyVariantReference { override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { val project = myElement.project val entries = TranslationInverseIndex.findElements( key.full, GlobalSearchScope.allScope(project), TranslationConstants.DEFAULT_LOCALE ) return entries.mapToArray(::PsiElementResolveResult) } override fun getVariants(): Array<Any?> { val project = myElement.project val defaultTranslations = TranslationIndex.getAllDefaultTranslations(project) val pattern = Regex("${Regex.escape(key.prefix)}(.*?)${Regex.escape(key.suffix)}") return defaultTranslations .filter { it.key.isNotEmpty() } .mapNotNull { entry -> pattern.matchEntire(entry.key)?.let { entry to it } } .map { (entry, match) -> LookupElementBuilder .create(if (match.groups.size <= 1) entry.key else match.groupValues[1]) .withIcon(PlatformAssets.MINECRAFT_ICON) .withTypeText(TranslationConstants.DEFAULT_LOCALE) .withPresentableText(entry.key) } .toTypedArray() } @Throws(IncorrectOperationException::class) override fun handleElementRename(newElementName: String): PsiElement { return renameHandler(myElement, rangeInElement, newElementName) } override fun isReferenceTo(element: PsiElement): Boolean { if (TranslationFiles.getLocale(element.containingFile?.virtualFile) != TranslationConstants.DEFAULT_LOCALE) { return false } return (element is LangEntry && element.key == key.full) || (element is JsonProperty && element.name == key.full) } }
mit
5c4626e24efeafa5abd3b3e0fb3bf668
40.168675
117
0.722564
4.916547
false
false
false
false
mibac138/ArgParser
example/command-system/src/example/cmd/CommandRegistry.kt
1
819
package example.cmd /** * Created by mibac138 on 08-07-2017. */ interface CommandRegistry { fun getCommand(name: String): Command? fun addCommand(command: Command) fun removeCommand(command: Command) fun getCommands(): Collection<Command> // TODO operator functions ([i], +=) } class CommandRegistryImpl : CommandRegistry { private val commandMap = mutableMapOf<String, Command>() override fun getCommand(name: String): Command? = commandMap[name.toLowerCase()] override fun addCommand(command: Command) { commandMap[command.name.toLowerCase()] = command } override fun removeCommand(command: Command) { commandMap.remove(command.name.toLowerCase()) } override fun getCommands(): Collection<Command> = commandMap.values }
mit
ea77c18aad32a84010b0c2be4d38fb1c
24.625
60
0.683761
4.451087
false
false
false
false
AngrySoundTech/CouponCodes3
mods/canary/src/main/kotlin/tech/feldman/couponcodes/canary/entity/CanaryPlayer.kt
2
2308
/** * The MIT License * Copyright (c) 2015 Nicholas Feldman (AngrySoundTech) * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package tech.feldman.couponcodes.canary.entity import net.canarymod.Canary import net.canarymod.api.inventory.ItemType import tech.feldman.couponcodes.api.exceptions.UnknownMaterialException import tech.feldman.couponcodes.core.entity.SimplePlayer import java.util.* class CanaryPlayer(private val canaryPlayer: net.canarymod.api.entity.living.humanoid.Player) : SimplePlayer() { override fun hasPermission(node: String) = canaryPlayer.hasPermission(node) override fun getLocale() = Locale.forLanguageTag(canaryPlayer.locale) override fun getUUID() = canaryPlayer.uuidString override fun sendMessage(message: String) = canaryPlayer.message(message) override fun getLevel() = canaryPlayer.level override fun setLevel(level: Int) { canaryPlayer.level = level } @Throws(UnknownMaterialException::class) override fun giveItem(item: String, amount: Int) { if (ItemType.fromString(item) != null) { canaryPlayer.giveItem(Canary.factory().itemFactory.newItem(ItemType.fromString(item), 0, amount)) } else throw UnknownMaterialException(item) } }
mit
f68c8047d9df3e66ea0cb88fe2065fc4
41.740741
112
0.7513
4.242647
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/animation/RxPathAnimator.kt
1
2035
/* * Copyright (C) 2015 tyrantgit * * 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.tamsiree.rxui.animation import android.os.Handler import android.os.Looper import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.LinearInterpolator import java.util.concurrent.atomic.AtomicInteger /** * @author tamsiree */ class RxPathAnimator(config: Config?) : RxAbstractPathAnimator(config!!) { private val mCounter = AtomicInteger(0) private val mHandler: Handler override fun start(child: View, parent: ViewGroup?) { parent!!.addView(child, ViewGroup.LayoutParams(mConfig.heartWidth, mConfig.heartHeight)) val anim = FloatAnimation(createPath(mCounter, parent, 2), randomRotation(), parent, child) anim.duration = mConfig.animDuration.toLong() anim.interpolator = LinearInterpolator() anim.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { mHandler.post { parent.removeView(child) } mCounter.decrementAndGet() } override fun onAnimationRepeat(animation: Animation) {} override fun onAnimationStart(animation: Animation) { mCounter.incrementAndGet() } }) anim.interpolator = LinearInterpolator() child.startAnimation(anim) } init { mHandler = Handler(Looper.getMainLooper()) } }
apache-2.0
b45169018aa424d5fea89e50cbe1c50c
36.018182
99
0.703686
4.678161
false
true
false
false
Syex/Rode
sample/src/main/java/de/syex/sample/MainActivity.kt
1
2138
package de.syex.sample import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.design.widget.TextInputLayout import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.TextView import de.syex.rode.RodePresenterProvider import de.syex.rode.RodeViewModel class MainActivity : AppCompatActivity(), HelloWordView, RodePresenterProvider<HelloWorldPresenter, HelloWordView> { // The presenter is available after the [onCreate] method. private lateinit var presenter: HelloWorldPresenter private val helloWorldTextView by lazy { findViewById<TextView>(R.id.tv_helloWorld) } private val firstTextInputLayout by lazy { findViewById<TextInputLayout>(R.id.til_first_hint) } private val secondTextInputLayout by lazy { findViewById<TextInputLayout>(R.id.til_second_hint) } // Called one time to create a single surviving instance of HelloWorldPresenter override fun createPresenter(): HelloWorldPresenter { return HelloWorldPresenter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // This is the earliest point we can retrieve a ViewModel for this activity and therefore the earliest // point we can get our presenter presenter = ViewModelProviders.of(this) .get(RodeViewModel::class.java) .providePresenter(this) } fun onClickToggleFirst(v: View) { presenter.onClickToggleFirst() } fun onClickToggleSecond(v: View) { presenter.onClickToggleSecond() } override fun setHelloWorldText(text: String) { helloWorldTextView.text = text } override fun showFirstError() { firstTextInputLayout.error = "Random error" } override fun clearFirstError() { firstTextInputLayout.error = null } override fun showSecondError() { secondTextInputLayout.error = "Specific error" } override fun clearSecondError() { secondTextInputLayout.error = null } }
mit
e434f92141b722146b90a9bd0d02f887
31.393939
110
0.72217
4.678337
false
false
false
false
oldergod/red
app/src/test/java/com/benoitquenaudon/tvfoot/red/testutil/Dagger2Helper.kt
1
2158
package com.benoitquenaudon.tvfoot.red.testutil import java.lang.reflect.Method import java.util.HashMap object Dagger2Helper { private val methodsCache = HashMap<Class<*>, HashMap<Class<*>, Method>>() /** * This method is based on https://github.com/square/mortar/blob/ * master/dagger2support/src/main/java/mortar/dagger2support/Dagger2.java * file that has been released with Apache License Version 2.0, * January 2004 http://www.apache.org/licenses/ by Square, Inc. * * * Magic method that creates a component with its dependencies set, by reflection. Relies on * Dagger2 naming conventions. */ fun <T> buildComponent(componentClass: Class<T>, vararg dependencies: Any): T { buildMethodsCache(componentClass) val fqn = componentClass.name val packageName = componentClass.`package`.name // Accounts for inner classes, ie MyApplication$Component val simpleName = fqn.substring(packageName.length + 1) val generatedName = (packageName + ".Dagger" + simpleName).replace('$', '_') try { val generatedClass = Class.forName(generatedName) val builder = generatedClass.getMethod("builder").invoke(null) for (method in builder.javaClass.methods) { val params = method.parameterTypes if (params.size == 1) { val dependencyClass = params[0] for (dependency in dependencies) { if (dependencyClass.isAssignableFrom(dependency.javaClass)) { method.invoke(builder, dependency) break } } } } return builder.javaClass.getMethod("build").invoke(builder) as T } catch (e: Exception) { throw RuntimeException(e) } } private fun <T> buildMethodsCache(componentClass: Class<T>) { if (!Dagger2Helper.methodsCache.containsKey(componentClass)) { val methods = HashMap<Class<*>, Method>() for (method in componentClass.methods) { val params = method.parameterTypes if (params.size == 1) { methods.put(params[0], method) } } Dagger2Helper.methodsCache.put(componentClass, methods) } } }
apache-2.0
74f796b26bbcdfd6fe6619b4d65803a4
32.2
94
0.663114
4.386179
false
false
false
false
mayank408/susi_android
app/src/main/java/org/fossasia/susi/ai/settings/ChatSettingsFragment.kt
1
3301
package org.fossasia.susi.ai.settings import android.content.ComponentName import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.preference.ListPreference import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import org.fossasia.susi.ai.R import org.fossasia.susi.ai.data.UtilModel import org.fossasia.susi.ai.helper.Constant import org.fossasia.susi.ai.settings.contract.ISettingsPresenter /** * The Fragment for Settings Activity * * Created by mayanktripathi on 10/07/17. */ class ChatSettingsFragment : PreferenceFragmentCompat() { var settingsPresenter: ISettingsPresenter? = null var textToSpeech: Preference? = null var rate: Preference? = null var server: Preference? = null var micSettings: Preference? = null var theme: ListPreference? = null var hotwordSettings: Preference? = null var settingActivity: SettingsActivity? = null var utilModel: UtilModel?= null override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.pref_settings) settingsPresenter = SettingsPresenter(activity) utilModel = UtilModel(activity) (settingsPresenter as SettingsPresenter).onAttach(this) textToSpeech = preferenceManager.findPreference(Constant.LANG_SELECT) rate = preferenceManager.findPreference(Constant.RATE) server = preferenceManager.findPreference(Constant.SELECT_SERVER) theme = preferenceManager.findPreference(Constant.THEME_KEY) as ListPreference micSettings = preferenceManager.findPreference(Constant.MIC_INPUT) hotwordSettings = preferenceManager.findPreference(Constant.HOTWORD_DETECTION) settingActivity = SettingsActivity() if (theme?.value == null) theme?.setValueIndex(1) if (theme?.entry != null) theme?.summary = theme?.entry.toString() textToSpeech?.setOnPreferenceClickListener { val intent = Intent() intent.component = ComponentName("com.android.settings", "com.android.settings.Settings\$TextToSpeechSettingsActivity") startActivity(intent) true } rate?.setOnPreferenceClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))) true } if(utilModel?.getAnonymity()!!){ server?.isEnabled = true server?.setOnPreferenceClickListener { settingActivity?.showAlert(activity) true } } else { server?.isEnabled = false } theme?.setOnPreferenceChangeListener({ preference, newValue -> preference.summary = newValue.toString() settingsPresenter?.setTheme(newValue.toString()) activity.recreate() true }) micSettings?.isEnabled = settingsPresenter?.enableMic() as Boolean hotwordSettings?.isEnabled = settingsPresenter?.enableHotword() as Boolean } override fun onDestroyView() { super.onDestroyView() settingsPresenter?.onDetach() } }
apache-2.0
65472305824ca4b5c0a32c6ddfab849f
33.747368
135
0.690094
5.165884
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/TeamPermissionInteraction.kt
1
538
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Represents any interactions for a [TeamPermission]. * * @param edit an interaction denoting the ability to edit the [TeamPermission] * @param remove an interaction denoting the ability to remove the [TeamPermission] */ @JsonClass(generateAdapter = true) data class TeamPermissionInteraction( @Json(name = "edit") val edit: BasicInteraction? = null, @Json(name = "remove") val remove: BasicInteraction? = null )
mit
0bfcb2af97487ac3d79b4639b8db6f32
27.315789
83
0.743494
3.985185
false
false
false
false
arsich/messenger
app/src/main/kotlin/ru/arsich/messenger/mvp/presenters/ChatPresenter.kt
1
1430
package ru.arsich.messenger.mvp.presenters import com.vk.sdk.api.model.VKApiMessage import ru.arsich.messenger.mvp.models.ChatRepository import ru.arsich.messenger.mvp.models.RepositoryInjector import ru.arsich.messenger.mvp.views.ChatView import ru.arsich.messenger.vk.VKChat import java.lang.Exception class ChatPresenter(private val chatView: ChatView, private val dialog: VKChat): BasePresenter, ChatRepository.RequestMessagesListener { private lateinit var chatRepository: ChatRepository private var offset = 0 private var startMessageId = -1 override fun start() { chatRepository = RepositoryInjector.provideChatRepository() chatRepository.addMessagesSubscriber(this) requestMessages() } override fun close() { chatRepository.removeMessagesSubscriber(this) } fun loadNextMessages(offset: Int) { this.offset = offset chatView.showListProgress() requestMessages() } private fun requestMessages() { chatRepository.requestMessages(dialog.id, offset) } override fun onMessagesReceived(messages: List<VKApiMessage>) { if (startMessageId < 0 && messages.isNotEmpty()) { startMessageId = messages[0].id } chatView.hideListProgress() chatView.showMessages(messages) } override fun onMessagesError(error: Exception) { chatView.showError(error) } }
mit
712bc39a23e88c4723e85eb6785b4403
28.204082
136
0.715385
4.55414
false
false
false
false
android/identity-samples
Fido2/app/src/main/java/com/google/android/gms/identity/sample/fido2/repository/AuthRepository.kt
1
12321
/* * Copyright 2021 Google Inc. All Rights Reserved. * * 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.google.android.gms.identity.sample.fido2.repository import android.app.PendingIntent import android.util.Log import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import com.google.android.gms.identity.sample.fido2.api.ApiException import com.google.android.gms.identity.sample.fido2.api.ApiResult import com.google.android.gms.identity.sample.fido2.api.AuthApi import com.google.android.gms.identity.sample.fido2.api.Credential import com.google.android.gms.identity.sample.fido2.toBase64 import com.google.android.gms.fido.fido2.Fido2ApiClient import com.google.android.gms.fido.fido2.api.common.PublicKeyCredential import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import javax.inject.Inject import javax.inject.Singleton /** * Works with the API, the local data store, and FIDO2 API. */ @Singleton class AuthRepository @Inject constructor( private val api: AuthApi, private val dataStore: DataStore<Preferences>, scope: CoroutineScope ) { private companion object { const val TAG = "AuthRepository" // Keys for SharedPreferences val USERNAME = stringPreferencesKey("username") val SESSION_ID = stringPreferencesKey("session_id") val CREDENTIALS = stringSetPreferencesKey("credentials") val LOCAL_CREDENTIAL_ID = stringPreferencesKey("local_credential_id") suspend fun <T> DataStore<Preferences>.read(key: Preferences.Key<T>): T? { return data.map { it[key] }.first() } } private var fido2ApiClient: Fido2ApiClient? = null fun setFido2APiClient(client: Fido2ApiClient?) { fido2ApiClient = client } private val signInStateMutable = MutableSharedFlow<SignInState>( replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST ) /** The current [SignInState]. */ val signInState = signInStateMutable.asSharedFlow() /** * The list of credentials this user has registered on the server. This is only populated when * the sign-in state is [SignInState.SignedIn]. */ val credentials = dataStore.data.map { it[CREDENTIALS] ?: emptySet() }.map { parseCredentials(it) } init { scope.launch { val username = dataStore.read(USERNAME) val sessionId = dataStore.read(SESSION_ID) val initialState = when { username.isNullOrBlank() -> SignInState.SignedOut sessionId.isNullOrBlank() -> SignInState.SigningIn(username) else -> SignInState.SignedIn(username) } signInStateMutable.emit(initialState) if (initialState is SignInState.SignedIn) { refreshCredentials() } } } /** * Sends the username to the server. If it succeeds, the sign-in state will proceed to * [SignInState.SigningIn]. */ suspend fun username(username: String) { when (val result = api.username(username)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { dataStore.edit { prefs -> prefs[USERNAME] = username prefs[SESSION_ID] = result.sessionId!! } signInStateMutable.emit(SignInState.SigningIn(username)) } } } /** * Signs in with a password. This should be called only when the sign-in state is * [SignInState.SigningIn]. If it succeeds, the sign-in state will proceed to * [SignInState.SignedIn]. */ suspend fun password(password: String) { val username = dataStore.read(USERNAME)!! val sessionId = dataStore.read(SESSION_ID)!! try { when (val result = api.password(sessionId, password)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { if (result.sessionId != null) { dataStore.edit { prefs -> prefs[SESSION_ID] = result.sessionId } } signInStateMutable.emit(SignInState.SignedIn(username)) refreshCredentials() } } } catch (e: ApiException) { Log.e(TAG, "Invalid login credentials", e) // start login over again dataStore.edit { prefs -> prefs.remove(USERNAME) prefs.remove(SESSION_ID) prefs.remove(CREDENTIALS) } signInStateMutable.emit( SignInState.SignInError(e.message ?: "Invalid login credentials") ) } } private suspend fun refreshCredentials() { val sessionId = dataStore.read(SESSION_ID)!! when (val result = api.getKeys(sessionId)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { dataStore.edit { prefs -> result.sessionId?.let { prefs[SESSION_ID] = it } prefs[CREDENTIALS] = result.data.toStringSet() } } } } private fun List<Credential>.toStringSet(): Set<String> { return mapIndexed { index, credential -> "$index;${credential.id};${credential.publicKey}" }.toSet() } private fun parseCredentials(set: Set<String>): List<Credential> { return set.map { s -> val (index, id, publicKey) = s.split(";") index to Credential(id, publicKey) }.sortedBy { (index, _) -> index } .map { (_, credential) -> credential } } /** * Clears the credentials. The sign-in state will proceed to [SignInState.SigningIn]. */ suspend fun clearCredentials() { val username = dataStore.read(USERNAME)!! dataStore.edit { prefs -> prefs.remove(CREDENTIALS) } signInStateMutable.emit(SignInState.SigningIn(username)) } /** * Clears all the sign-in information. The sign-in state will proceed to * [SignInState.SignedOut]. */ suspend fun signOut() { dataStore.edit { prefs -> prefs.remove(USERNAME) prefs.remove(SESSION_ID) prefs.remove(CREDENTIALS) } signInStateMutable.emit(SignInState.SignedOut) } private suspend fun forceSignOut() { dataStore.edit { prefs -> prefs.remove(USERNAME) prefs.remove(SESSION_ID) prefs.remove(CREDENTIALS) } signInStateMutable.emit(SignInState.SignInError("Signed out by server")) } /** * Starts to register a new credential to the server. This should be called only when the * sign-in state is [SignInState.SignedIn]. */ suspend fun registerRequest(): PendingIntent? { fido2ApiClient?.let { client -> try { val sessionId = dataStore.read(SESSION_ID)!! when (val apiResult = api.registerRequest(sessionId)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { if (apiResult.sessionId != null) { dataStore.edit { prefs -> prefs[SESSION_ID] = apiResult.sessionId } } val task = client.getRegisterPendingIntent(apiResult.data) return task.await() } } } catch (e: Exception) { Log.e(TAG, "Cannot call registerRequest", e) } } return null } /** * Finishes registering a new credential to the server. This should only be called after * a call to [registerRequest] and a local FIDO2 API for public key generation. */ suspend fun registerResponse(credential: PublicKeyCredential) { try { val sessionId = dataStore.read(SESSION_ID)!! val credentialId = credential.rawId.toBase64() when (val result = api.registerResponse(sessionId, credential)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { dataStore.edit { prefs -> result.sessionId?.let { prefs[SESSION_ID] = it } prefs[CREDENTIALS] = result.data.toStringSet() prefs[LOCAL_CREDENTIAL_ID] = credentialId } } } } catch (e: ApiException) { Log.e(TAG, "Cannot call registerResponse", e) } } /** * Removes a credential registered on the server. */ suspend fun removeKey(credentialId: String) { try { val sessionId = dataStore.read(SESSION_ID)!! when (api.removeKey(sessionId, credentialId)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> refreshCredentials() } } catch (e: ApiException) { Log.e(TAG, "Cannot call removeKey", e) } } /** * Starts to sign in with a FIDO2 credential. This should only be called when the sign-in state * is [SignInState.SigningIn]. */ suspend fun signinRequest(): PendingIntent? { fido2ApiClient?.let { client -> val sessionId = dataStore.read(SESSION_ID)!! val credentialId = dataStore.read(LOCAL_CREDENTIAL_ID) if (credentialId != null) { when (val apiResult = api.signinRequest(sessionId, credentialId)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { val task = client.getSignPendingIntent(apiResult.data) return task.await() } } } } return null } /** * Finishes to signing in with a FIDO2 credential. This should only be called after a call to * [signinRequest] and a local FIDO2 API for key assertion. */ suspend fun signinResponse(credential: PublicKeyCredential) { try { val username = dataStore.read(USERNAME)!! val sessionId = dataStore.read(SESSION_ID)!! val credentialId = credential.rawId.toBase64() when (val result = api.signinResponse(sessionId, credential)) { ApiResult.SignedOutFromServer -> forceSignOut() is ApiResult.Success -> { dataStore.edit { prefs -> result.sessionId?.let { prefs[SESSION_ID] = it } prefs[CREDENTIALS] = result.data.toStringSet() prefs[LOCAL_CREDENTIAL_ID] = credentialId } signInStateMutable.emit(SignInState.SignedIn(username)) refreshCredentials() } } } catch (e: ApiException) { Log.e(TAG, "Cannot call registerResponse", e) } } }
apache-2.0
23bbbdbdc235c51506b0cbbe095fd4e3
36.449848
99
0.593377
4.811011
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/egl/templates/ExtensionFlags.kt
1
8874
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.egl.templates import org.lwjgl.egl.* import org.lwjgl.generator.* val EXT = "EXT" val KHR = "KHR" val ANDROID = "ANDROID" val ANGLE = "ANGLE" val ARM = "ARM" val HI = "HI" val IMG = "IMG" val MESA = "MESA" val NOK = "NOK" val NV = "NV" val OVR = "OVR" val TIZEN = "TIZEN" private val NativeClass.cap: String get() = "{@link #$capName $templateName}" val EXT_client_extensions = EXT_FLAG.nativeClassEGL("EXT_client_extensions", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension introduces the concept of *extension type*, requires that each EGL extension belong to exactly one type, and defines two types: display and client. It also provides a method to query, without initializing a display, the set of supported client extensions. A display extension adds functionality to an individual EGLDisplay. This type of extension has always existed but, until EGL_EXT_client_extensions, lacked an identifying name. A client extension adds functionality that is independent of any display. In other words, it adds functionality to the EGL client library itself. This is a new type of extension defined by EGL_EXT_client_extensions. EGL_EXT_client_extensions is itself a client extension. We suggest that each future extension clearly state its type by including the following toplevel section in its extension specification, preceding the Dependencies section. For client extensions, this suggestion is a requirement. ${codeBlock(""" Extension Type &lt;Either "EGL display extension" or "EGL client extension" or a future extension type.&gt;""")} By cleanly separating display extensions from client extensions, EGL_EXT_client_extensions solves a bootstrap problem for future EGL extensions that will modify display initialization. To query for such extensions without EGL_EXT_client_extensions, an EGL client would need to initialize a throw-away EGLDisplay solely to query its extension string. Initialization of the throw-away display may have undesired side-effects (discussed in the issues section below) for EGL clients that wish to use the new methods of display initialization. """ } val KHR_client_get_all_proc_addresses = EXT_FLAG.nativeClassEGL("KHR_client_get_all_proc_addresses", postfix = KHR) { documentation = """ When true, the ${registryLink("KHR", "EGL_KHR_get_all_proc_addresses")} extension is supported. eglGetProcAddress is currently defined to not support the querying of non-extension EGL or client API functions. Non-extension functions are expected to be exposed as library symbols that can be resolved statically at link time, or dynamically at run time using OS-specific runtime linking mechanisms. With the addition of OpenGL and OpenGL ES 3 support to EGL, the definition of a non-extension function becomes less clear. It is common for one OpenGL library to implement many versions of OpenGL. The suggested library name for OpenGL ES 3 is the same as that of OpenGL ES 2. If OpenGL ES 3 applications linked statically to OpenGL ES 3 functions are run on a system with only OpenGL ES 2 support, they may fail to load. Similar problems would be encountered by an application linking statically to various OpenGL functions. To avoid requiring applications to fall back to OS-specific dynamic linking mechanisms, this extension drops the requirement that eglGetProcAddress return only non-extension functions. If the extension string is present, applications can query all EGL and client API functions using eglGetProcAddress. To allow users to query this extension before initializing a display, and to also allow vendors to ship this extension without EGL_EXT_client_extensions, two names are assigned to this extension: one a display extension and the other a client extension. Identical functionality is exposed by each name, but users query each name using different methods. Users query EGL_KHR_get_all_proc_addresses in the usual way; that is, by calling eglQueryString(dpy, EGL_EXTENSIONS) on an initialized display. To query EGL_KHR_client_get_all_proc_addresses, users must use a different method which is described below in the section concerning EGL_EXT_client_extensions. Requires ${EGL12.core}. """ } val KHR_get_all_proc_addresses = EXT_FLAG.nativeClassEGL("KHR_get_all_proc_addresses", postfix = KHR) { documentation = """ When true, the $registryLink extension is supported. eglGetProcAddress is currently defined to not support the querying of non-extension EGL or client API functions. Non-extension functions are expected to be exposed as library symbols that can be resolved statically at link time, or dynamically at run time using OS-specific runtime linking mechanisms. With the addition of OpenGL and OpenGL ES 3 support to EGL, the definition of a non-extension function becomes less clear. It is common for one OpenGL library to implement many versions of OpenGL. The suggested library name for OpenGL ES 3 is the same as that of OpenGL ES 2. If OpenGL ES 3 applications linked statically to OpenGL ES 3 functions are run on a system with only OpenGL ES 2 support, they may fail to load. Similar problems would be encountered by an application linking statically to various OpenGL functions. To avoid requiring applications to fall back to OS-specific dynamic linking mechanisms, this extension drops the requirement that eglGetProcAddress return only non-extension functions. If the extension string is present, applications can query all EGL and client API functions using eglGetProcAddress. To allow users to query this extension before initializing a display, and to also allow vendors to ship this extension without EGL_EXT_client_extensions, two names are assigned to this extension: one a display extension and the other a client extension. Identical functionality is exposed by each name, but users query each name using different methods. Users query EGL_KHR_get_all_proc_addresses in the usual way; that is, by calling eglQueryString(dpy, EGL_EXTENSIONS) on an initialized display. To query EGL_KHR_client_get_all_proc_addresses, users must use a different method which is described below in the section concerning EGL_EXT_client_extensions. Requires ${EGL12.core}. """ } val KHR_stream_producer_aldatalocator = EXT_FLAG.nativeClassEGL("KHR_stream_producer_aldatalocator", postfix = KHR) { documentation = """ When true, the $registryLink extension is supported. This extension (in conjunction with the OpenMAX_AL_EGLStream_DataLocator extension to OpenMAX AL) allows an OpenMAX AL MediaPlayer object to be connected as the producer of an EGLStream. After the EGLStream is created and connected to a consumer, the OpenMAX AL MediaPlayer object is created by calling &lt;pEngine&gt;'s CreateMediaPlayer() method. The &lt;pImageVideoSnk&gt; argument points to an XADataLocator_EGLStream containing the EGLStreamKHR handle of the stream. The CreateMediaPlayer() method creates a MediaPlayer object and connects it as the producer of the EGLStream. (Note that the pFormat member of the XADataSink structure is ignored in this case and may be $NULL.) Once connected the MediaPlayer inserts image frames into the EGLStream. Requires ${EGL12.core} and ${KHR_stream.link}. Requires OpenMAX AL 1.1 and OpenMAX_AL_EGLStream_DataLocator. """ } val KHR_surfaceless_context = EXT_FLAG.nativeClassEGL("KHR_surfaceless_context", postfix = KHR) { documentation = """ When true, the $registryLink extension is supported. These extensions allows an application to make a context current by passing EGL_NO_SURFACE for the write and read surface in the call to eglMakeCurrent. The motivation is that applications that only want to render to client API targets (such as OpenGL framebuffer objects) should not need to create a throw-away EGL surface just to get a current context. The state of an OpenGL ES context with no default framebuffer provided by EGL is the same as a context with an incomplete framebuffer object bound. """ } val NV_post_convert_rounding = EXT_FLAG.nativeClassEGL("NV_post_convert_rounding", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension defines the conversions for posting operations when the destination's number of components or component sizes do not match the color buffer. This extension supports posting a 24 bit (888) color buffer to a 16 bit (565) destination buffer, posting a 16 bit (565) color buffer to a 24 bit (888) destination buffer, and posting a component that is present in the source buffer, but not present in the destination buffer. """ }
bsd-3-clause
d70c0864a94158c31d40791e1e0a72af
58.166667
153
0.779693
4.399603
false
false
false
false
jean79/yested
src/main/docsite/layout/scrollbarDemo.kt
2
2832
package layout import net.yested.* import net.yested.bootstrap.* import net.yested.layout.ScrollBar import net.yested.layout.ScrollBarOrientation fun createScrollBarSection(): Div { val positionTextVertical = Span() val positionTextHorizontal = Span() val scrollBarVetical = ScrollBar( orientation = ScrollBarOrientation.VERTICAL, size = 150.px(), numberOfItems = 100, visibleItems = 20, positionHandler = { positionTextVertical.setContent("Vertical: ${it}")} ) val scrollBarHorizontal = ScrollBar( orientation = ScrollBarOrientation.HORIZONTAL, size = 150.px(), numberOfItems = 100, visibleItems = 20, positionHandler = { positionTextHorizontal.setContent("Horizontal: ${it}")} ) val fieldTotalNumber = IntInputField() with { data = 100 } val fieldViewportSize = IntInputField() with { data = 20 } val fieldNewPosition = IntInputField() with { data = 30 } return div { row { col(Medium(12)) { pageHeader { h3 { +"ScrollBar" } } } } row { col(Medium(4)) { h4 { +"Demo" } btsForm(formStyle = FormStyle.HORIZONTAL) { item(label = { +"Total number:" }) { +fieldTotalNumber } item(label = { +"Viewport size:" }) { +fieldViewportSize } item(label = {}) { btsButton(size = ButtonSize.SMALL, label = { +"Set scrollbar"}) { scrollBarVetical.setup( numberOfItems = fieldTotalNumber.data?:100, visibleItems = fieldViewportSize.data?:20, newPosition = 10) } } item(label = {} ) { br() } item(label = { +"Set position:" }) { +fieldNewPosition } item(label = {}) { btsButton(size = ButtonSize.SMALL, label = { +"Set scrollbar"}) { scrollBarVetical.position = fieldNewPosition.data?:0 } } } +positionTextVertical br() +scrollBarVetical br() +scrollBarHorizontal +positionTextHorizontal } col(Medium(8)) { h4 { +"Code" } code(lang = "kotlin", content= """TODO:""") } } } }
mit
537756089d7b61e185517b1057fb0c19
33.975309
97
0.446681
5.363636
false
false
false
false
initrc/android-bootstrap
app/src/main/java/io/github/initrc/bootstrap/presenter/HomePresenter.kt
1
2050
package io.github.initrc.bootstrap.presenter import android.support.v7.widget.RecyclerView import android.view.View import io.github.initrc.bootstrap.adapter.FeedAdapter import io.github.initrc.bootstrap.repo.PhotoRepo import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import util.AnimationUtils import util.snack /** * Presenter for home view. */ class HomePresenter (_feedList: RecyclerView, gridColumnWidth: Int, _homeFab: View) : Presenter { private val feedList = _feedList private val homeFab = _homeFab private val feedAdapter = FeedAdapter() private val disposables = CompositeDisposable() private var nextPage = 1 val features = mutableListOf("popular", "editors", "upcoming", "fresh_today") var currentFeature = features[0] init { feedAdapter.gridColumnWidth = gridColumnWidth feedList.adapter = feedAdapter } override fun onBind() { disposables.add(loadPhotos()) } override fun onUnbind() { disposables.clear() } fun refreshPhotos(query: String) { feedAdapter.clear() nextPage = 1 loadPhotos(query) } fun loadPhotos(query: String = "", page: Int = nextPage) : Disposable { return PhotoRepo.getPhotos(query, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { feedAdapter.addPhotos(it.hits) nextPage = page + 1 if (page == 1) AnimationUtils.showFab(homeFab) }, { error -> feedList.snack(error.message) } ) } fun setGridColumnWidth(width: Int) { feedAdapter.gridColumnWidth = width } fun setImageOnly(imageOnly: Boolean) { feedAdapter.imageOnly = imageOnly } }
mit
e906fa01017eb1c9d36bb91f6c1aa2ab
30.060606
97
0.638049
4.74537
false
false
false
false
esofthead/mycollab
mycollab-web/src/main/java/com/mycollab/module/user/ui/format/UserHistoryFieldFormat.kt
3
2476
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.user.ui.format import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.core.utils.StringUtils.isBlank import com.mycollab.html.FormatUtils import com.mycollab.module.mail.MailUtils import com.mycollab.module.user.AccountLinkGenerator import com.mycollab.module.user.domain.SimpleUser import com.mycollab.module.user.service.UserService import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.UserUIContext import com.mycollab.vaadin.ui.formatter.HistoryFieldFormat /** * @author MyCollab Ltd. * @since 4.0 */ class UserHistoryFieldFormat : HistoryFieldFormat { override fun toString(value: String): String = toString(UserUIContext.getUser(), value, true, UserUIContext.getMessage(GenericI18Enum.FORM_EMPTY)) override fun toString(currentViewUser: SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String { if (isBlank(value)) { return msgIfBlank } val userService = AppContextUtil.getSpringBean(UserService::class.java) val user = userService.findUserByUserNameInAccount(value, currentViewUser.accountId!!) if (user != null) { return if (displayAsHtml) { val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16) val img = FormatUtils.newImg("avatar", userAvatarLink) val userLink = AccountLinkGenerator.generatePreviewFullUserLink( MailUtils.getSiteUrl(AppUI.accountId), user.username) val link = FormatUtils.newA(userLink, user.displayName!!) FormatUtils.newLink(img, link).write() } else user.displayName!! } return value } }
agpl-3.0
e381d65e4d88e364bd88dba6e1b9ccf7
38.919355
123
0.720404
4.419643
false
false
false
false
DeKoServidoni/OMFM
omfm/src/main/java/com/dekoservidoni/omfm/OneMoreFabMenu.kt
1
13726
package com.dekoservidoni.omfm import android.content.Context import android.content.res.ColorStateList import android.content.res.Resources import android.graphics.Typeface import android.graphics.drawable.ColorDrawable import android.os.Build import com.google.android.material.floatingactionbutton.FloatingActionButton import androidx.core.content.ContextCompat import android.util.AttributeSet import android.view.MenuItem import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.Animation.AnimationListener import android.widget.TextView import androidx.core.view.ViewCompat import com.dekoservidoni.omfm.utils.OneMoreFabUtils import com.dekoservidoni.omfm.utils.OneMoreFabValues class OneMoreFabMenu @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr), View.OnClickListener { interface OptionsClick { fun onOptionClick(optionId: Int?) } private var initialFab = FloatingActionButton(context) private var clickCallback: OneMoreFabMenu.OptionsClick? = null private var values = OneMoreFabValues(context) private var utils = OneMoreFabUtils(context) // click listener private val fabClickListener = OnClickListener { clickCallback?.onOptionClick(it.id) if(values.closeOnClick) { collapse() } } init { // initialize the values from attributes // and create them values.initializeValues(attrs) addButtons() utils.downChildAnimation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { // empty } override fun onAnimationEnd(animation: Animation) { requestLayout() } override fun onAnimationRepeat(animation: Animation) { // empty } }) } /// Override methods override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { // calculating the initial button sizes for use as reference val horizontalCenter = right - left - (values.maxButtonWidth / 2) val initialFabTop = bottom - top - initialFab.measuredHeight val initialFabLeft = horizontalCenter - (initialFab.measuredWidth / 2) val initialFabRight = initialFabLeft + initialFab.measuredWidth val initialFabBottom = initialFabTop + initialFab.measuredHeight // calculate the main button and it's label (if exists) calculateMainButton(initialFabTop, initialFabLeft, initialFabRight, initialFabBottom) // setup the main button as needed setupMainButton() // calculate the options buttons and it's respective labels calculateOptionsButton(initialFabTop, horizontalCenter) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { measureChildren(widthMeasureSpec, heightMeasureSpec) // initializing values var height = 0 var maxLabelWidth = 0 var width = Resources.getSystem().displayMetrics.widthPixels values.maxButtonWidth = 0 values.maxButtonHeight = 0 // calculating the size of every fab + label for(i in 0..(childCount-1)) { val view = getChildAt(i) if(view.id != utils.LABEL_ID && view.id != initialFab.id && view.visibility != View.GONE) { values.maxButtonWidth = Math.max(values.maxButtonWidth, view.measuredWidth) height += view.measuredHeight // calculating the width of the label val label = view.getTag(utils.TAG_ID) as? TextView if(label != null) { maxLabelWidth = Math.max(maxLabelWidth, label.measuredWidth) } } } if(isExpanded()) { // when the view is expanded, the height and width need to be // the entire screen height = Resources.getSystem().displayMetrics.heightPixels setBackgroundColor(values.expandedBackgroundColor) setOnClickListener({ collapse() }) } else { // calculating the total width and height of the component width = values.maxButtonWidth + values.initialFabSpacing height = initialFab.measuredHeight + values.initialFabSpacing setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent)) setOnClickListener(null) } setMeasuredDimension(width, height) } override fun onClick(view: View?) { if (isExpanded()) collapse() else expand() } /// Public methods fun isExpanded() = values.state == OneMoreFabUtils.Direction.EXPANDED fun collapse() { values.state = OneMoreFabUtils.Direction.COLLAPSED if(values.rotateMainButton) { initialFab.startAnimation(utils.collapseInitialFabAnimation) } animateChildren(utils.downChildAnimation) } fun expand() { values.state = OneMoreFabUtils.Direction.EXPANDED if(values.rotateMainButton) { initialFab.startAnimation(utils.expandInitialFabAnimation) } animateChildren(utils.upChildAnimation) requestLayout() } fun show() { visibility = View.VISIBLE initialFab.show() } fun hide() { if (isExpanded()) { utils.downChildAnimation.setAnimationListener(object : AnimationListener { override fun onAnimationRepeat(animation: Animation?) { } override fun onAnimationEnd(animation: Animation?) { hideMenu() utils.downChildAnimation?.setAnimationListener(null) } override fun onAnimationStart(animation: Animation?) { } }) collapse() } else { hideMenu() } } fun setOptionsClick(callback: OptionsClick) { clickCallback = callback } /// Private methods private fun hideMenu() { initialFab.hide(object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton?) { super.onShown(fab) fab?.visibility = View.INVISIBLE visibility = View.INVISIBLE } }) } /// Menu components setup private fun addButtons() { // add the other buttons from the options "menu" for (i in 0..(values.options.size() - 1)) { val item = values.options.getItem(i) // creating the floating action button val fab = buildFabButton(item, i == 0) if(i == 0) { // get the first position of the options array // to be the first fab button of the component initialFab = fab if(values.enableMainAsAction && !item.title.isEmpty() && item.title != null) { val mainLabel = buildTextLabel(item, true) initialFab.setTag(utils.TAG_ID, mainLabel) addView(mainLabel) } } else { // creating the label for the button val label = buildTextLabel(item, false) fab.setTag(utils.TAG_ID, label) addView(label) } // add the views addView(fab) } } private fun animateChildren(animation: Animation) { for(i in 0..(childCount-1)) { val child = getChildAt(i) if(child.id != initialFab.id){ child.startAnimation(animation) } } } private fun buildFabButton(item: MenuItem, isFirst: Boolean): FloatingActionButton { val fab = FloatingActionButton(context) fab.id = item.itemId fab.layoutParams = generateDefaultLayoutParams() fab.setImageDrawable(item.icon) val size = if(isFirst) values.mainFabSize else values.secondaryFabSize fab.size = size val buttonColor = if(isFirst) values.colorMainButton else values.colorSecondaryButtons fab.backgroundTintList = ColorStateList.valueOf(buttonColor) if (Build.VERSION.SDK_INT >= 21) { fab.elevation = values.childElevation } if(isFirst) { values.mainCollapsedDrawable = item.icon } return fab } private fun buildTextLabel(item: MenuItem, isFirst: Boolean): TextView { val label = TextView(context) label.text = item.title label.typeface = Typeface.DEFAULT_BOLD label.background = if(values.labelBackgroundColor != -1) ColorDrawable(values.labelBackgroundColor) else ContextCompat.getDrawable(context, values.labelBackgroundDrawable) label.layoutParams = generateDefaultLayoutParams() label.setPadding(values.labelPadding, values.labelPadding, values.labelPadding, values.labelPadding) label.setTextColor(ColorStateList.valueOf(values.labelTextColor)) if (ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL) { label.rotationX = 180F } if(isFirst) { label.id = utils.LABEL_ID label.alpha = 0f } if (Build.VERSION.SDK_INT >= 21) { label.elevation = values.childElevation } return label } /// Menu components calculations private fun setupMainButton() { // change the drawable of the main button // if it was set as action if(values.enableMainAsAction && values.mainExpandedDrawable != null) { initialFab.setImageDrawable(if(isExpanded()) values.mainExpandedDrawable else values.mainCollapsedDrawable) } // set the listener of the main button // if the main was enabled as action initialFab.setOnClickListener(if(!values.enableMainAsAction || !isExpanded()) this@OneMoreFabMenu else fabClickListener) // bring the initial fab to front so we can // call it onClick when the menu is collapsed bringChildToFront(initialFab) } private fun calculateMainButton(initialFabTop: Int, initialFabLeft: Int, initialFabRight: Int, initialFabBottom: Int) { initialFab.layout(initialFabLeft - values.initialFabRightMargin, initialFabTop - values.initialFabBottomMargin, initialFabRight - values.initialFabRightMargin, initialFabBottom - values.initialFabBottomMargin) // if this flag is true so we need to show the label of // the main button that are inside the content defined by user if(values.enableMainAsAction) { val label = initialFab.getTag(utils.TAG_ID) as? TextView if (label != null) { val labelRight = initialFab.left - values.labelSpacing val labelLeft = labelRight - label.measuredWidth val labelTop = initialFab.top + (initialFab.height / 4) label.layout(labelLeft, labelTop, labelRight, labelTop + label.measuredHeight) label.alpha = if (isExpanded()) 1f else 0f bringChildToFront(label) } } } private fun calculateOptionsButton(initialFabTop: Int, horizontalCenter: Int) { val labelsOffset = (values.maxButtonWidth / 2) var nextY = if(isExpanded()) initialFabTop - values.fabSpacing else initialFabTop + initialFab.measuredHeight + values.fabSpacing for(i in 0..(childCount-1)) { val view = getChildAt(i) // skipping gone views (because we don't need to calculate), the initial button and main label if exists if(view.id != initialFab.id && view.id != utils.LABEL_ID && view.visibility != View.GONE) { // positioning the fab button val childX = horizontalCenter - (view.measuredWidth / 2) val childY = if(values.state == OneMoreFabUtils.Direction.EXPANDED) nextY - view.measuredHeight else nextY view.layout(childX - values.initialFabRightMargin, childY, childX + view.measuredWidth - values.initialFabRightMargin, childY + view.measuredHeight) view.translationY = if(isExpanded()) 0f else (initialFabTop - childY).toFloat() view.alpha = if (isExpanded()) 1f else 0f view.setOnClickListener(if(isExpanded()) fabClickListener else null) // positioning the label on the left of fab val label = view.getTag(utils.TAG_ID) as? TextView if(label != null) { val labelRight = horizontalCenter - labelsOffset val labelLeft = labelRight - label.measuredWidth val labelTop = childY + (view.measuredHeight - label.measuredHeight) / 2 label.layout(labelLeft - values.labelSpacing, labelTop, labelRight - values.labelSpacing, labelTop + label.measuredHeight) label.translationY = if (isExpanded()) 0f else (initialFabTop - childY).toFloat() label.alpha = if (isExpanded()) 1f else 0f } nextY = if(isExpanded()) childY - values.fabSpacing else childY + view.measuredHeight + values.fabSpacing } } } }
apache-2.0
0341df8a5bf383c0d9a736571b769b7c
35.123684
128
0.626402
4.962401
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/data/dao/response/BookcaseWorksResponse.kt
2
1128
package ru.fantlab.android.data.dao.response import com.github.kittinunf.fuel.core.ResponseDeserializable import com.google.gson.JsonParser import ru.fantlab.android.data.dao.Pageable import ru.fantlab.android.data.dao.model.BookcaseWork import ru.fantlab.android.provider.rest.DataManager data class BookcaseWorksResponse( val works: Pageable<BookcaseWork> ) { class Deserializer(private val perPage: Int) : ResponseDeserializable<BookcaseWorksResponse> { override fun deserialize(content: String): BookcaseWorksResponse { val jsonObject = JsonParser().parse(content).asJsonObject val items: ArrayList<BookcaseWork> = arrayListOf() val array = jsonObject.getAsJsonArray("bookcase_items") array.map { items.add(DataManager.gson.fromJson(it, BookcaseWork::class.java)) } val totalCount = jsonObject.getAsJsonPrimitive("count").asInt val lastPage = (totalCount - 1) / perPage + 1 val works = Pageable(lastPage, totalCount, items) return BookcaseWorksResponse(works) } } }
gpl-3.0
c183101843af7476fd7dc4d92f4f969d
40.814815
98
0.699468
4.641975
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/commands/admin/RestartShardsCommand.kt
1
1768
package xyz.gnarbot.gnar.commands.admin import net.dv8tion.jda.api.JDA import xyz.gnarbot.gnar.commands.* @Command( aliases = ["revive", "restartShards"], description = "Restart all shard instances." ) @BotInfo( id = 37, admin = true, category = Category.NONE ) class RestartShardsCommand : CommandExecutor() { override fun execute(context: Context, label: String, args: Array<String>) { if (args.isEmpty()) { context.send().error("Try `all, dead, (#)`").queue() return } when (args[0]) { "all" -> { context.send().info("Bot is now restarting.").queue() context.bot.restart() } "dead" -> { val deadShards = context.bot.shardManager.shardCache.filter { it.status != JDA.Status.CONNECTED } if (deadShards.isEmpty()) { context.send().info("Every shard is connected.").queue() return } context.send().info("Shards `${deadShards.map { it.shardInfo.shardId }}` are now restarting.").queue() deadShards.map { it.shardInfo.shardId }.forEach { context.bot.shardManager.restart(it) } } else -> { val id = args[0].toLongOrNull()?.coerceIn(0, context.bot.shardManager.shardCache.size())?.toInt() ?: kotlin.run { context.send().error("You must enter a valid shard id.").queue() return } context.send().info("Shards `$id` are now restarting.").queue() context.bot.shardManager.restart(id) } } } }
mit
4662f95e941fbc0be07a91c93ab03f5a
34.38
118
0.515271
4.510204
false
false
false
false
inorichi/tachiyomi-extensions
src/en/tsumino/src/eu/kanade/tachiyomi/extension/en/tsumino/Tsumino.kt
1
10267
package eu.kanade.tachiyomi.extension.en.tsumino import com.github.salomonbrys.kotson.fromJson import com.github.salomonbrys.kotson.get import com.google.gson.Gson import com.google.gson.JsonObject import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.extension.en.tsumino.TsuminoUtils.Companion.getArtists import eu.kanade.tachiyomi.extension.en.tsumino.TsuminoUtils.Companion.getChapter import eu.kanade.tachiyomi.extension.en.tsumino.TsuminoUtils.Companion.getCollection import eu.kanade.tachiyomi.extension.en.tsumino.TsuminoUtils.Companion.getDesc import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable @Nsfw class Tsumino : ParsedHttpSource() { override val name = "Tsumino" override val baseUrl = "https://www.tsumino.com" override val lang = "en" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient private val gson = Gson() override fun latestUpdatesSelector() = "Not needed" override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/Search/Operate/?PageNumber=$page&Sort=Newest") override fun latestUpdatesParse(response: Response): MangasPage { val allManga = mutableListOf<SManga>() val body = response.body!!.string() val jsonManga = gson.fromJson<JsonObject>(body)["data"].asJsonArray for (i in 0 until jsonManga.size()) { val manga = SManga.create() manga.url = "/entry/" + jsonManga[i]["entry"]["id"].asString manga.title = jsonManga[i]["entry"]["title"].asString manga.thumbnail_url = jsonManga[i]["entry"]["thumbnailUrl"].asString allManga.add(manga) } val currentPage = gson.fromJson<JsonObject>(body)["pageNumber"].asString val totalPage = gson.fromJson<JsonObject>(body)["pageCount"].asString val hasNextPage = currentPage.toInt() != totalPage.toInt() return MangasPage(allManga, hasNextPage) } override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used") override fun latestUpdatesNextPageSelector() = "Not needed" override fun popularMangaRequest(page: Int) = GET("$baseUrl/Search/Operate/?PageNumber=$page&Sort=Popularity") override fun popularMangaParse(response: Response): MangasPage = latestUpdatesParse(response) override fun popularMangaFromElement(element: Element) = latestUpdatesFromElement(element) override fun popularMangaSelector() = latestUpdatesSelector() override fun popularMangaNextPageSelector() = latestUpdatesNextPageSelector() override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { // Taken from github.com/NerdNumber9/TachiyomiEH val f = filters + getFilterList() val advSearch = f.filterIsInstance<AdvSearchEntryFilter>().flatMap { filter -> val splitState = filter.state.split(",").map(String::trim).filterNot(String::isBlank) splitState.map { AdvSearchEntry(filter.type, it.removePrefix("-"), it.startsWith("-")) } } val body = FormBody.Builder() .add("PageNumber", page.toString()) .add("Text", query) .add("Sort", SortType.values()[f.filterIsInstance<SortFilter>().first().state].name) .add("List", "0") .add("Length", LengthType.values()[f.filterIsInstance<LengthFilter>().first().state].id.toString()) .add("MinimumRating", f.filterIsInstance<MinimumRatingFilter>().first().state.toString()) .apply { advSearch.forEachIndexed { index, entry -> add("Tags[$index][Type]", entry.type.toString()) add("Tags[$index][Text]", entry.text) add("Tags[$index][Exclude]", entry.exclude.toString()) } if (f.filterIsInstance<ExcludeParodiesFilter>().first().state) add("Exclude[]", "6") } .build() return POST("$baseUrl/Search/Operate/", headers, body) } private fun searchMangaByIdRequest(id: String) = GET("$baseUrl/entry/$id", headers) private fun searchMangaByIdParse(response: Response, id: String): MangasPage { val details = mangaDetailsParse(response) details.url = "/entry/$id" return MangasPage(listOf(details), false) } override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return if (query.startsWith(PREFIX_ID_SEARCH)) { val id = query.removePrefix(PREFIX_ID_SEARCH) client.newCall(searchMangaByIdRequest(id)) .asObservableSuccess() .map { response -> searchMangaByIdParse(response, id) } } else { super.fetchSearchManga(page, query, filters) } } override fun searchMangaParse(response: Response): MangasPage = latestUpdatesParse(response) override fun searchMangaSelector() = latestUpdatesSelector() override fun searchMangaFromElement(element: Element) = latestUpdatesFromElement(element) override fun searchMangaNextPageSelector() = latestUpdatesNextPageSelector() override fun mangaDetailsRequest(manga: SManga): Request { if (manga.url.startsWith("http")) { return GET(manga.url, headers) } return super.mangaDetailsRequest(manga) } override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.book-page-container") val manga = SManga.create() manga.title = infoElement.select("#Title").text() manga.artist = getArtists(document) manga.author = manga.artist manga.status = SManga.COMPLETED manga.thumbnail_url = infoElement.select("img").attr("src") manga.description = getDesc(document) manga.genre = document.select("#Tag a").joinToString { it.text() } return manga } override fun chapterListRequest(manga: SManga): Request { if (manga.url.startsWith("http")) { return GET(manga.url, headers) } return super.chapterListRequest(manga) } override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() val collection = document.select(chapterListSelector()) return if (collection.isNotEmpty()) { getCollection(document, chapterListSelector()) } else { getChapter(document, response) } } override fun chapterListSelector() = ".book-collection-table a" override fun chapterFromElement(element: Element) = throw UnsupportedOperationException("Not used") override fun pageListRequest(chapter: SChapter): Request { if (chapter.url.startsWith("http")) { return GET(chapter.url, headers) } return super.pageListRequest(chapter) } override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() val numPages = document.select("h1").text().split(" ").last() if (numPages.isNotEmpty()) { for (i in 1 until numPages.toInt() + 1) { val data = document.select("#image-container").attr("data-cdn") .replace("[PAGE]", i.toString()) pages.add(Page(i, "", data)) } } else { throw UnsupportedOperationException("Error: Open in WebView and solve the Captcha!") } return pages } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used") data class AdvSearchEntry(val type: Int, val text: String, val exclude: Boolean) override fun getFilterList() = FilterList( Filter.Header("Separate tags with commas (,)"), Filter.Header("Prepend with dash (-) to exclude"), TagFilter(), CategoryFilter(), CollectionFilter(), GroupFilter(), ArtistFilter(), ParodyFilter(), CharactersFilter(), UploaderFilter(), Filter.Separator(), SortFilter(), LengthFilter(), MinimumRatingFilter(), ExcludeParodiesFilter() ) class TagFilter : AdvSearchEntryFilter("Tags", 1) class CategoryFilter : AdvSearchEntryFilter("Categories", 2) class CollectionFilter : AdvSearchEntryFilter("Collections", 3) class GroupFilter : AdvSearchEntryFilter("Groups", 4) class ArtistFilter : AdvSearchEntryFilter("Artists", 5) class ParodyFilter : AdvSearchEntryFilter("Parodies", 6) class CharactersFilter : AdvSearchEntryFilter("Characters", 7) class UploaderFilter : AdvSearchEntryFilter("Uploaders", 8) open class AdvSearchEntryFilter(name: String, val type: Int) : Filter.Text(name) class SortFilter : Filter.Select<SortType>("Sort by", SortType.values()) class LengthFilter : Filter.Select<LengthType>("Length", LengthType.values()) class MinimumRatingFilter : Filter.Select<String>("Minimum rating", (0..5).map { "$it stars" }.toTypedArray()) class ExcludeParodiesFilter : Filter.CheckBox("Exclude parodies") enum class SortType { Popularity, Newest, Oldest, Alphabetical, Rating, Pages, Views, Random, Comments, } enum class LengthType(val id: Int) { Any(0), Short(1), Medium(2), Long(3) } companion object { const val PREFIX_ID_SEARCH = "id:" } }
apache-2.0
8462b7ac7b22abad35fbd5f51d8b5239
37.453184
117
0.666894
4.656236
false
true
false
false
GrogramCat/Bellezza
app/src/main/java/com/temoa/gankio/data/local/AppDatabase.kt
1
713
package com.temoa.gankio.data.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase /** * Created by lai * on 2020/8/13. */ @Database( entities = [FavEntity::class], version = 1, exportSchema = false ) abstract class AppDatabase : RoomDatabase() { abstract fun favDao(): FacDao companion object { private var instance: AppDatabase? = null @Synchronized fun init(context: Context): AppDatabase? { if (instance == null) { instance = Room .databaseBuilder( context, AppDatabase::class.java, "gank.db") .build() } return instance } } }
gpl-3.0
caaff3a8ec4718055df7897d6607d203
18.833333
60
0.638149
4.097701
false
false
false
false
fython/NHentai-android
app/src/main/kotlin/moe/feng/nhentai/ui/widget/SwipeBackCoordinatorLayout.kt
2
6525
package moe.feng.nhentai.ui.widget import android.content.Context import android.graphics.Color import android.support.annotation.ColorInt import android.support.annotation.IntDef import android.support.design.widget.CoordinatorLayout import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Animation import android.view.animation.Transformation /** * Swipe back coordinator layout. * * A [CoordinatorLayout] that has swipe back operation. * */ class SwipeBackCoordinatorLayout : CoordinatorLayout { private var swipeListener: OnSwipeListener? = null private var swipeDistance: Int = 0 private var swipeTrigger: Float = 0.toFloat() private var isVerticalDragged: Boolean = false @DirectionRule private var swipeDir = NULL_DIR private val resetAnimListener = object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { isEnabled = false } override fun onAnimationEnd(animation: Animation) { isEnabled = true } override fun onAnimationRepeat(animation: Animation) { // do nothing. } } @IntDef(NULL_DIR, UP_DIR, DOWN_DIR) annotation class DirectionRule private inner class ResetAnimation internal constructor(private val fromDistance: Int) : Animation() { public override fun applyTransformation(interpolatedTime: Float, t: Transformation) { swipeDistance = (fromDistance * (1 - interpolatedTime)).toInt() setSwipeTranslation() } } private class RecolorAnimation internal constructor(private val view: View, private val showing: Boolean) : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { super.applyTransformation(interpolatedTime, t) if (showing) { view.setBackgroundColor(Color.argb((255.0 * 0.5 * interpolatedTime.toDouble()).toInt(), 0, 0, 0)) } else { view.setBackgroundColor(Color.argb((255.0 * 0.5 * (1 - interpolatedTime).toDouble()).toInt(), 0, 0, 0)) } } } constructor(context: Context) : super(context) { this.initialize() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { this.initialize() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { this.initialize() } private fun initialize() { this.swipeDistance = 0 this.swipeTrigger = (resources.displayMetrics.heightPixels / 4.0).toFloat() } // nested scroll. override fun onStartNestedScroll(child: View, target: View, nestedScrollAxes: Int, type: Int): Boolean { super.onStartNestedScroll(child, target, nestedScrollAxes, type) isVerticalDragged = nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL != 0 return type == 0 } override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) { var dyConsumed = 0 if (isVerticalDragged && swipeDistance != 0) { dyConsumed = onVerticalPreScroll(dy) } val newConsumed = intArrayOf(0, 0) super.onNestedPreScroll(target, dx, dy - dyConsumed, newConsumed, type) consumed[0] = newConsumed[0] consumed[1] = newConsumed[1] + dyConsumed } override fun onNestedScroll(target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int) { var newDyConsumed = dyConsumed var newDyUnconsumed = dyUnconsumed if (isVerticalDragged && swipeDistance == 0) { val dir = if (dyUnconsumed < 0) DOWN_DIR else UP_DIR if (swipeListener != null && swipeListener!!.canSwipeBack(dir)) { onVerticalScroll(dyUnconsumed) newDyConsumed = dyConsumed + dyUnconsumed newDyUnconsumed = 0 } } super.onNestedScroll(target, dxConsumed, newDyConsumed, dxUnconsumed, newDyUnconsumed, type) } override fun onStopNestedScroll(child: View, type: Int) { super.onStopNestedScroll(child, type) if (isVerticalDragged) { if (Math.abs(swipeDistance) >= swipeTrigger) { swipeBack() } else { reset() } } } private fun onVerticalPreScroll(dy: Int): Int { val consumed: Int if (swipeDistance * (swipeDistance - dy) < 0) { swipeDir = NULL_DIR consumed = swipeDistance swipeDistance = 0 } else { consumed = dy swipeDistance -= dy } setSwipeTranslation() return consumed } private fun onVerticalScroll(dy: Int) { swipeDistance = -dy swipeDir = if (swipeDistance > 0) DOWN_DIR else UP_DIR setSwipeTranslation() } private fun swipeBack() { if (swipeListener != null) { swipeListener!!.onSwipeFinish(swipeDir) } } fun reset() { swipeDir = NULL_DIR if (swipeDistance != 0) { val a = ResetAnimation(swipeDistance) a.duration = (200.0 + 100.0 * Math.abs(swipeDistance) / swipeTrigger).toLong() a.interpolator = AccelerateDecelerateInterpolator() a.setAnimationListener(resetAnimListener) startAnimation(a) } } private fun setSwipeTranslation() { val dir = if (swipeDistance > 0) UP_DIR else DOWN_DIR translationY = (dir.toDouble() * SWIPE_RADIO.toDouble() * swipeTrigger.toDouble() * Math.log10(1 + 9.0 * Math.abs(swipeDistance) / swipeTrigger)).toFloat() if (swipeListener != null) { swipeListener!!.onSwipeProcess( Math.min( 1.0, Math.abs(1.0 * swipeDistance / swipeTrigger)).toFloat()) } } // interface. // on swipe listener. interface OnSwipeListener { fun canSwipeBack(dir: Int): Boolean fun onSwipeProcess(percent: Float) fun onSwipeFinish(dir: Int) } fun setOnSwipeListener(l: OnSwipeListener) { this.swipeListener = l } companion object { private val SWIPE_RADIO = 0.33f const val NULL_DIR = 0 const val UP_DIR = 1 const val DOWN_DIR = -1 /** * Whether the SwipeBackView can swipe back. * * @param v child view. * @param dir drag direction. */ fun canSwipeBack(v: View?, dir: Int): Boolean { return v?.canScrollVertically(dir) != true } /** * Compute shadow background color by drag percent. * * @param percent drag percent. * * @return Color. */ @ColorInt fun getBackgroundColor(percent: Float): Int { return Color.argb((255 * (0.9 - percent * (0.9 - 0.5))).toInt(), 0, 0, 0) } /** * Execute fade animation to hide shadow background. * * @param background The view to show shadow background. */ fun hideBackgroundShadow(background: View) { val a = RecolorAnimation(background, false) a.duration = 200 background.startAnimation(a) } } }
gpl-3.0
710b368ec050206d6fb77df0905540c5
25.855967
122
0.707586
3.651371
false
false
false
false
jeffgbutler/mybatis-dynamic-sql
src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/elements/SqlElements.kt
1
15318
/* * Copyright 2016-2022 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 * * 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. */ @file:Suppress("TooManyFunctions") package org.mybatis.dynamic.sql.util.kotlin.elements import org.mybatis.dynamic.sql.AndOrCriteriaGroup import org.mybatis.dynamic.sql.BasicColumn import org.mybatis.dynamic.sql.BindableColumn import org.mybatis.dynamic.sql.Constant import org.mybatis.dynamic.sql.SortSpecification import org.mybatis.dynamic.sql.SqlBuilder import org.mybatis.dynamic.sql.SqlColumn import org.mybatis.dynamic.sql.StringConstant import org.mybatis.dynamic.sql.select.aggregate.Avg import org.mybatis.dynamic.sql.select.aggregate.Count import org.mybatis.dynamic.sql.select.aggregate.CountAll import org.mybatis.dynamic.sql.select.aggregate.CountDistinct import org.mybatis.dynamic.sql.select.aggregate.Max import org.mybatis.dynamic.sql.select.aggregate.Min import org.mybatis.dynamic.sql.select.aggregate.Sum import org.mybatis.dynamic.sql.select.function.Add import org.mybatis.dynamic.sql.select.function.Concatenate import org.mybatis.dynamic.sql.select.function.Divide import org.mybatis.dynamic.sql.select.function.Lower import org.mybatis.dynamic.sql.select.function.Multiply import org.mybatis.dynamic.sql.select.function.OperatorFunction import org.mybatis.dynamic.sql.select.function.Substring import org.mybatis.dynamic.sql.select.function.Subtract import org.mybatis.dynamic.sql.select.function.Upper import org.mybatis.dynamic.sql.util.kotlin.GroupingCriteriaCollector import org.mybatis.dynamic.sql.util.kotlin.GroupingCriteriaReceiver import org.mybatis.dynamic.sql.util.kotlin.KotlinSubQueryBuilder import org.mybatis.dynamic.sql.where.condition.IsBetween import org.mybatis.dynamic.sql.where.condition.IsEqualTo import org.mybatis.dynamic.sql.where.condition.IsEqualToColumn import org.mybatis.dynamic.sql.where.condition.IsEqualToWithSubselect import org.mybatis.dynamic.sql.where.condition.IsGreaterThan import org.mybatis.dynamic.sql.where.condition.IsGreaterThanColumn import org.mybatis.dynamic.sql.where.condition.IsGreaterThanOrEqualTo import org.mybatis.dynamic.sql.where.condition.IsGreaterThanOrEqualToColumn import org.mybatis.dynamic.sql.where.condition.IsGreaterThanOrEqualToWithSubselect import org.mybatis.dynamic.sql.where.condition.IsGreaterThanWithSubselect import org.mybatis.dynamic.sql.where.condition.IsIn import org.mybatis.dynamic.sql.where.condition.IsInCaseInsensitive import org.mybatis.dynamic.sql.where.condition.IsInWithSubselect import org.mybatis.dynamic.sql.where.condition.IsLessThan import org.mybatis.dynamic.sql.where.condition.IsLessThanColumn import org.mybatis.dynamic.sql.where.condition.IsLessThanOrEqualTo import org.mybatis.dynamic.sql.where.condition.IsLessThanOrEqualToColumn import org.mybatis.dynamic.sql.where.condition.IsLessThanOrEqualToWithSubselect import org.mybatis.dynamic.sql.where.condition.IsLessThanWithSubselect import org.mybatis.dynamic.sql.where.condition.IsLike import org.mybatis.dynamic.sql.where.condition.IsLikeCaseInsensitive import org.mybatis.dynamic.sql.where.condition.IsNotBetween import org.mybatis.dynamic.sql.where.condition.IsNotEqualTo import org.mybatis.dynamic.sql.where.condition.IsNotEqualToColumn import org.mybatis.dynamic.sql.where.condition.IsNotEqualToWithSubselect import org.mybatis.dynamic.sql.where.condition.IsNotIn import org.mybatis.dynamic.sql.where.condition.IsNotInCaseInsensitive import org.mybatis.dynamic.sql.where.condition.IsNotInWithSubselect import org.mybatis.dynamic.sql.where.condition.IsNotLike import org.mybatis.dynamic.sql.where.condition.IsNotLikeCaseInsensitive import org.mybatis.dynamic.sql.where.condition.IsNotNull import org.mybatis.dynamic.sql.where.condition.IsNull // support for criteria without initial conditions fun and(receiver: GroupingCriteriaReceiver): AndOrCriteriaGroup = with(GroupingCriteriaCollector().apply(receiver)) { AndOrCriteriaGroup.Builder().withInitialCriterion(this.initialCriterion) .withSubCriteria(this.subCriteria) .withConnector("and") .build() } fun or(receiver: GroupingCriteriaReceiver): AndOrCriteriaGroup = with(GroupingCriteriaCollector().apply(receiver)) { AndOrCriteriaGroup.Builder().withInitialCriterion(this.initialCriterion) .withSubCriteria(this.subCriteria) .withConnector("or") .build() } // aggregate support fun count(): CountAll = SqlBuilder.count() fun count(column: BasicColumn): Count = SqlBuilder.count(column) fun countDistinct(column: BasicColumn): CountDistinct = SqlBuilder.countDistinct(column) fun <T> max(column: BindableColumn<T>): Max<T> = SqlBuilder.max(column) fun <T> min(column: BindableColumn<T>): Min<T> = SqlBuilder.min(column) fun <T> avg(column: BindableColumn<T>): Avg<T> = SqlBuilder.avg(column) fun <T> sum(column: BindableColumn<T>): Sum<T> = SqlBuilder.sum(column) // constants fun <T> constant(constant: String): Constant<T> = SqlBuilder.constant(constant) fun stringConstant(constant: String): StringConstant = SqlBuilder.stringConstant(constant) // functions fun <T> add( firstColumn: BindableColumn<T>, secondColumn: BasicColumn, vararg subsequentColumns: BasicColumn ): Add<T> = Add.of(firstColumn, secondColumn, subsequentColumns.asList()) fun <T> divide( firstColumn: BindableColumn<T>, secondColumn: BasicColumn, vararg subsequentColumns: BasicColumn ): Divide<T> = Divide.of(firstColumn, secondColumn, subsequentColumns.asList()) fun <T> multiply( firstColumn: BindableColumn<T>, secondColumn: BasicColumn, vararg subsequentColumns: BasicColumn ): Multiply<T> = Multiply.of(firstColumn, secondColumn, subsequentColumns.asList()) fun <T> subtract( firstColumn: BindableColumn<T>, secondColumn: BasicColumn, vararg subsequentColumns: BasicColumn ): Subtract<T> = Subtract.of(firstColumn, secondColumn, subsequentColumns.asList()) fun <T> concatenate( firstColumn: BindableColumn<T>, secondColumn: BasicColumn, vararg subsequentColumns: BasicColumn ): Concatenate<T> = Concatenate.of(firstColumn, secondColumn, subsequentColumns.asList()) fun <T> applyOperator( operator: String, firstColumn: BindableColumn<T>, secondColumn: BasicColumn, vararg subsequentColumns: BasicColumn ): OperatorFunction<T> = OperatorFunction.of(operator, firstColumn, secondColumn, subsequentColumns.asList()) fun <T> lower(column: BindableColumn<T>): Lower<T> = SqlBuilder.lower(column) fun <T> substring( column: BindableColumn<T>, offset: Int, length: Int ): Substring<T> = SqlBuilder.substring(column, offset, length) fun <T> upper(column: BindableColumn<T>): Upper<T> = SqlBuilder.upper(column) // conditions for all data types fun <T> isNull(): IsNull<T> = SqlBuilder.isNull() fun <T> isNotNull(): IsNotNull<T> = SqlBuilder.isNotNull() fun <T> isEqualTo(value: T & Any): IsEqualTo<T> = SqlBuilder.isEqualTo(value) fun <T> isEqualTo(subQuery: KotlinSubQueryBuilder.() -> Unit): IsEqualToWithSubselect<T> = SqlBuilder.isEqualTo(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isEqualTo(column: BasicColumn): IsEqualToColumn<T> = SqlBuilder.isEqualTo(column) fun <T> isEqualToWhenPresent(value: T?): IsEqualTo<T> = SqlBuilder.isEqualToWhenPresent(value) fun <T> isNotEqualTo(value: T & Any): IsNotEqualTo<T> = SqlBuilder.isNotEqualTo(value) fun <T> isNotEqualTo(subQuery: KotlinSubQueryBuilder.() -> Unit): IsNotEqualToWithSubselect<T> = SqlBuilder.isNotEqualTo(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isNotEqualTo(column: BasicColumn): IsNotEqualToColumn<T> = SqlBuilder.isNotEqualTo(column) fun <T> isNotEqualToWhenPresent(value: T?): IsNotEqualTo<T> = SqlBuilder.isNotEqualToWhenPresent(value) fun <T> isGreaterThan(value: T & Any): IsGreaterThan<T> = SqlBuilder.isGreaterThan(value) fun <T> isGreaterThan(subQuery: KotlinSubQueryBuilder.() -> Unit): IsGreaterThanWithSubselect<T> = SqlBuilder.isGreaterThan(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isGreaterThan(column: BasicColumn): IsGreaterThanColumn<T> = SqlBuilder.isGreaterThan(column) fun <T> isGreaterThanWhenPresent(value: T?): IsGreaterThan<T> = SqlBuilder.isGreaterThanWhenPresent(value) fun <T> isGreaterThanOrEqualTo(value: T & Any): IsGreaterThanOrEqualTo<T> = SqlBuilder.isGreaterThanOrEqualTo(value) fun <T> isGreaterThanOrEqualTo(subQuery: KotlinSubQueryBuilder.() -> Unit): IsGreaterThanOrEqualToWithSubselect<T> = SqlBuilder.isGreaterThanOrEqualTo(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isGreaterThanOrEqualTo(column: BasicColumn): IsGreaterThanOrEqualToColumn<T> = SqlBuilder.isGreaterThanOrEqualTo(column) fun <T> isGreaterThanOrEqualToWhenPresent(value: T?): IsGreaterThanOrEqualTo<T> = SqlBuilder.isGreaterThanOrEqualToWhenPresent(value) fun <T> isLessThan(value: T & Any): IsLessThan<T> = SqlBuilder.isLessThan(value) fun <T> isLessThan(subQuery: KotlinSubQueryBuilder.() -> Unit): IsLessThanWithSubselect<T> = SqlBuilder.isLessThan(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isLessThan(column: BasicColumn): IsLessThanColumn<T> = SqlBuilder.isLessThan(column) fun <T> isLessThanWhenPresent(value: T?): IsLessThan<T> = SqlBuilder.isLessThanWhenPresent(value) fun <T> isLessThanOrEqualTo(value: T & Any): IsLessThanOrEqualTo<T> = SqlBuilder.isLessThanOrEqualTo(value) fun <T> isLessThanOrEqualTo(subQuery: KotlinSubQueryBuilder.() -> Unit): IsLessThanOrEqualToWithSubselect<T> = SqlBuilder.isLessThanOrEqualTo(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isLessThanOrEqualTo(column: BasicColumn): IsLessThanOrEqualToColumn<T> = SqlBuilder.isLessThanOrEqualTo(column) fun <T> isLessThanOrEqualToWhenPresent(value: T?): IsLessThanOrEqualTo<T> = SqlBuilder.isLessThanOrEqualToWhenPresent(value) fun <T> isIn(vararg values: T & Any): IsIn<T> = isIn(values.asList()) fun <T> isIn(values: Collection<T & Any>): IsIn<T> = SqlBuilder.isIn(values) fun <T> isIn(subQuery: KotlinSubQueryBuilder.() -> Unit): IsInWithSubselect<T> = SqlBuilder.isIn(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isInWhenPresent(vararg values: T?): IsIn<T> = isInWhenPresent(values.asList()) fun <T> isInWhenPresent(values: Collection<T?>?): IsIn<T> = SqlBuilder.isInWhenPresent(values) fun <T> isNotIn(vararg values: T & Any): IsNotIn<T> = isNotIn(values.asList()) fun <T> isNotIn(values: Collection<T & Any>): IsNotIn<T> = SqlBuilder.isNotIn(values) fun <T> isNotIn(subQuery: KotlinSubQueryBuilder.() -> Unit): IsNotInWithSubselect<T> = SqlBuilder.isNotIn(KotlinSubQueryBuilder().apply(subQuery)) fun <T> isNotInWhenPresent(vararg values: T?): IsNotIn<T> = isNotInWhenPresent(values.asList()) fun <T> isNotInWhenPresent(values: Collection<T?>?): IsNotIn<T> = SqlBuilder.isNotInWhenPresent(values) fun <T> isBetween(value1: T & Any): BetweenBuilder<T & Any> = BetweenBuilder(value1) fun <T> isBetweenWhenPresent(value1: T?): BetweenWhenPresentBuilder<T> = BetweenWhenPresentBuilder(value1) fun <T> isNotBetween(value1: T & Any): NotBetweenBuilder<T & Any> = NotBetweenBuilder(value1) fun <T> isNotBetweenWhenPresent(value1: T?): NotBetweenWhenPresentBuilder<T> = NotBetweenWhenPresentBuilder(value1) // for string columns, but generic for columns with type handlers fun <T> isLike(value: T & Any): IsLike<T> = SqlBuilder.isLike(value) fun <T> isLikeWhenPresent(value: T?): IsLike<T> = SqlBuilder.isLikeWhenPresent(value) fun <T> isNotLike(value: T & Any): IsNotLike<T> = SqlBuilder.isNotLike(value) fun <T> isNotLikeWhenPresent(value: T?): IsNotLike<T> = SqlBuilder.isNotLikeWhenPresent(value) // shortcuts for booleans fun isTrue(): IsEqualTo<Boolean> = isEqualTo(true) fun isFalse(): IsEqualTo<Boolean> = isEqualTo(false) // conditions for strings only fun isLikeCaseInsensitive(value: String): IsLikeCaseInsensitive = SqlBuilder.isLikeCaseInsensitive(value) fun isLikeCaseInsensitiveWhenPresent(value: String?): IsLikeCaseInsensitive = SqlBuilder.isLikeCaseInsensitiveWhenPresent(value) fun isNotLikeCaseInsensitive(value: String): IsNotLikeCaseInsensitive = SqlBuilder.isNotLikeCaseInsensitive(value) fun isNotLikeCaseInsensitiveWhenPresent(value: String?): IsNotLikeCaseInsensitive = SqlBuilder.isNotLikeCaseInsensitiveWhenPresent(value) fun isInCaseInsensitive(vararg values: String): IsInCaseInsensitive = isInCaseInsensitive(values.asList()) fun isInCaseInsensitive(values: Collection<String>): IsInCaseInsensitive = SqlBuilder.isInCaseInsensitive(values) fun isInCaseInsensitiveWhenPresent(vararg values: String?): IsInCaseInsensitive = isInCaseInsensitiveWhenPresent(values.asList()) fun isInCaseInsensitiveWhenPresent(values: Collection<String?>?): IsInCaseInsensitive = SqlBuilder.isInCaseInsensitiveWhenPresent(values) fun isNotInCaseInsensitive(vararg values: String): IsNotInCaseInsensitive = isNotInCaseInsensitive(values.asList()) fun isNotInCaseInsensitive(values: Collection<String>): IsNotInCaseInsensitive = SqlBuilder.isNotInCaseInsensitive(values) fun isNotInCaseInsensitiveWhenPresent(vararg values: String?): IsNotInCaseInsensitive = isNotInCaseInsensitiveWhenPresent(values.asList()) fun isNotInCaseInsensitiveWhenPresent(values: Collection<String?>?): IsNotInCaseInsensitive = SqlBuilder.isNotInCaseInsensitiveWhenPresent(values) // order by support /** * Creates a sort specification based on a String. This is useful when a column has been * aliased in the select list. * * @param name the string to use as a sort specification * @return a sort specification */ fun sortColumn(name: String): SortSpecification = SqlBuilder.sortColumn(name) /** * Creates a sort specification based on a column and a table alias. This can be useful in a join * where the desired sort order is based on a column not in the select list. This will likely * fail in union queries depending on database support. * * @param tableAlias the table alias * @param column the column * @return a sort specification */ fun sortColumn(tableAlias: String, column: SqlColumn<*>): SortSpecification = SqlBuilder.sortColumn(tableAlias, column) // DSL Support Classes class BetweenBuilder<T>(private val value1: T) { fun and(value2: T): IsBetween<T> = SqlBuilder.isBetween(value1).and(value2) } class BetweenWhenPresentBuilder<T>(private val value1: T?) { fun and(value2: T?): IsBetween<T> { return SqlBuilder.isBetweenWhenPresent<T>(value1).and(value2) } } class NotBetweenBuilder<T>(private val value1: T) { fun and(value2: T): IsNotBetween<T> = SqlBuilder.isNotBetween(value1).and(value2) } class NotBetweenWhenPresentBuilder<T>(private val value1: T?) { fun and(value2: T?): IsNotBetween<T> { return SqlBuilder.isNotBetweenWhenPresent<T>(value1).and(value2) } }
apache-2.0
0cd2a51689328ef38659a19df513265b
43.658892
119
0.787505
3.773836
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_revenue/ui/adapter/delegate/CourseBenefitsMonthlyListAdapterDelegate.kt
1
4316
package org.stepik.android.view.course_revenue.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.error_no_connection_with_button_small.* import kotlinx.android.synthetic.main.item_course_benefits.* import org.stepic.droid.R import org.stepik.android.domain.course_revenue.model.CourseBenefitByMonthListItem import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature import org.stepik.android.view.course_revenue.mapper.RevenuePriceMapper import org.stepik.android.view.course_revenue.model.CourseBenefitOperationItem import ru.nobird.android.core.model.PaginationDirection import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import ru.nobird.android.view.base.ui.delegate.ViewStateDelegate import ru.nobird.android.view.base.ui.extension.setOnPaginationListener class CourseBenefitsMonthlyListAdapterDelegate( private val revenuePriceMapper: RevenuePriceMapper, private val onFetchNextPage: () -> Unit, private val reloadListAction: () -> Unit ) : AdapterDelegate<CourseBenefitOperationItem, DelegateViewHolder<CourseBenefitOperationItem>>() { private val sharedViewPool = RecyclerView.RecycledViewPool() override fun isForViewType(position: Int, data: CourseBenefitOperationItem): Boolean = data is CourseBenefitOperationItem.CourseBenefitsMonthly override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseBenefitOperationItem> = ViewHolder(createView(parent, R.layout.item_course_benefits)) private inner class ViewHolder( override val containerView: View ) : DelegateViewHolder<CourseBenefitOperationItem>(containerView), LayoutContainer { private val viewStateDelegate = ViewStateDelegate<CourseBenefitsMonthlyFeature.State>() private val adapter = DefaultDelegateAdapter<CourseBenefitByMonthListItem>() .also { it += CourseBenefitsMonthlyLoadingAdapterDelegate() it += CourseBenefitsMonthlyAdapterDelegate(revenuePriceMapper) } init { viewStateDelegate.addState<CourseBenefitsMonthlyFeature.State.Loading>(courseBenefitsRecycler) viewStateDelegate.addState<CourseBenefitsMonthlyFeature.State.Empty>(courseBenefitsEmpty) viewStateDelegate.addState<CourseBenefitsMonthlyFeature.State.Error>(courseBenefitsError) viewStateDelegate.addState<CourseBenefitsMonthlyFeature.State.Content>(courseBenefitsRecycler) courseBenefitsRecycler.adapter = adapter courseBenefitsRecycler.layoutManager = LinearLayoutManager(context) courseBenefitsRecycler.setRecycledViewPool(sharedViewPool) courseBenefitsRecycler.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply { AppCompatResources.getDrawable(context, R.drawable.bg_divider_vertical)?.let(::setDrawable) }) courseBenefitsRecycler.setOnPaginationListener { direction -> if (direction == PaginationDirection.NEXT) { onFetchNextPage() } } tryAgain.setOnClickListener { reloadListAction() } } override fun onBind(data: CourseBenefitOperationItem) { data as CourseBenefitOperationItem.CourseBenefitsMonthly render(data.state) } private fun render(state: CourseBenefitsMonthlyFeature.State) { viewStateDelegate.switchState(state) if (state is CourseBenefitsMonthlyFeature.State.Loading) { adapter.items = listOf(CourseBenefitByMonthListItem.Placeholder, CourseBenefitByMonthListItem.Placeholder) } if (state is CourseBenefitsMonthlyFeature.State.Content) { adapter.items = state.courseBenefitByMonthListItems } } } }
apache-2.0
f5a8c6644cb9c50c0550cd4256e1b7b6
50.392857
123
0.76089
5.484117
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/when/typeDisjunction.kt
2
259
fun foo(s: Any): String { val x = when (s) { is String -> s is Int -> "$s" else -> return "" } val y: String = x return y } fun box() = if (foo("OK") == "OK" && foo(42) == "42" && foo(true) == "") "OK" else "Fail"
apache-2.0
48290d9d9ade90fec3fdbe60202a249b
16.266667
89
0.413127
2.910112
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/settings/compose/RootSettingsScreen.kt
1
20597
package wangdaye.com.geometricweather.settings.compose import android.content.Context import android.content.Intent import android.os.Build import android.provider.Settings import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.res.stringResource import androidx.navigation.NavHostController import com.google.android.material.dialog.MaterialAlertDialogBuilder import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.background.polling.PollingManager import wangdaye.com.geometricweather.common.basic.models.options.DarkMode import wangdaye.com.geometricweather.common.basic.models.options.NotificationStyle import wangdaye.com.geometricweather.common.basic.models.options.UpdateInterval import wangdaye.com.geometricweather.common.basic.models.options.WidgetWeekIconMode import wangdaye.com.geometricweather.common.utils.helpers.AsyncHelper import wangdaye.com.geometricweather.common.utils.helpers.IntentHelper import wangdaye.com.geometricweather.remoteviews.config.* import wangdaye.com.geometricweather.remoteviews.presenters.* import wangdaye.com.geometricweather.remoteviews.presenters.notification.NormalNotificationIMP import wangdaye.com.geometricweather.settings.SettingsManager import wangdaye.com.geometricweather.settings.preference.* import wangdaye.com.geometricweather.settings.preference.composables.* import wangdaye.com.geometricweather.theme.ThemeManager @Composable fun RootSettingsView(context: Context, navController: NavHostController) { val todayForecastEnabledState = remember { mutableStateOf( SettingsManager .getInstance(context) .isTodayForecastEnabled ) } val tomorrowForecastEnabledState = remember { mutableStateOf( SettingsManager .getInstance(context) .isTomorrowForecastEnabled ) } val notificationEnabledState = remember { mutableStateOf( SettingsManager .getInstance(context) .isNotificationEnabled ) } val notificationTemperatureIconEnabledState = remember { mutableStateOf( SettingsManager .getInstance(context) .isNotificationTemperatureIconEnabled ) } PreferenceScreen { // basic. sectionHeaderItem(R.string.settings_category_basic) checkboxPreferenceItem(R.string.settings_title_background_free) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.settings_summary_background_free_on, summaryOffId = R.string.settings_summary_background_free_off, checked = SettingsManager.getInstance(context).isBackgroundFree, onValueChanged = { SettingsManager.getInstance(context).isBackgroundFree = it PollingManager.resetNormalBackgroundTask(context, false) if (!it) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { showBlockNotificationGroupDialog(context) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { showIgnoreBatteryOptimizationDialog(context) } } }, ) } checkboxPreferenceItem(R.string.settings_title_alert_notification_switch) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = SettingsManager.getInstance(context).isAlertPushEnabled, onValueChanged = { SettingsManager.getInstance(context).isAlertPushEnabled = it PollingManager.resetNormalBackgroundTask(context, false) }, ) } checkboxPreferenceItem(R.string.settings_title_precipitation_notification_switch) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = SettingsManager.getInstance(context).isPrecipitationPushEnabled, onValueChanged = { SettingsManager.getInstance(context).isPrecipitationPushEnabled = it PollingManager.resetNormalBackgroundTask(context, false) }, ) } listPreferenceItem(R.string.settings_title_refresh_rate) { id -> ListPreferenceView( titleId = id, selectedKey = SettingsManager.getInstance(context).updateInterval.id, valueArrayId = R.array.automatic_refresh_rate_values, nameArrayId = R.array.automatic_refresh_rates, onValueChanged = { SettingsManager .getInstance(context) .updateInterval = UpdateInterval.getInstance(it) }, ) } listPreferenceItem(R.string.settings_title_dark_mode) { id -> ListPreferenceView( titleId = id, selectedKey = SettingsManager.getInstance(context).darkMode.id, valueArrayId = R.array.dark_mode_values, nameArrayId = R.array.dark_modes, onValueChanged = { SettingsManager .getInstance(context) .darkMode = DarkMode.getInstance(it) AsyncHelper.delayRunOnUI({ ThemeManager .getInstance(context) .update(darkMode = SettingsManager.getInstance(context).darkMode) },300) }, ) } clickablePreferenceItem(R.string.settings_title_live_wallpaper) { id -> PreferenceView( titleId = id, summaryId = R.string.settings_summary_live_wallpaper ) { IntentHelper.startLiveWallpaperActivity(context) } } clickablePreferenceItem(R.string.settings_title_service_provider) { id -> PreferenceView( titleId = id, summaryId = R.string.settings_summary_service_provider ) { navController.navigate(SettingsScreenRouter.ServiceProvider.route) } } clickablePreferenceItem(R.string.settings_title_unit) { id -> PreferenceView( titleId = id, summaryId = R.string.settings_summary_unit ) { navController.navigate(SettingsScreenRouter.Unit.route) } } clickablePreferenceItem(R.string.settings_title_appearance) { id -> PreferenceView( titleId = id, summaryId = R.string.settings_summary_appearance ) { navController.navigate(SettingsScreenRouter.Appearance.route) } } sectionFooterItem(R.string.settings_category_basic) // forecast. sectionHeaderItem(R.string.settings_category_forecast) checkboxPreferenceItem(R.string.settings_title_forecast_today) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = todayForecastEnabledState.value, onValueChanged = { todayForecastEnabledState.value = it SettingsManager.getInstance(context).isTodayForecastEnabled = it PollingManager.resetNormalBackgroundTask(context, false) }, ) } timePickerPreferenceItem(R.string.settings_title_forecast_today_time) { id -> TimePickerPreferenceView( titleId = id, currentTime = SettingsManager.getInstance(context).todayForecastTime, enabled = todayForecastEnabledState.value, onValueChanged = { SettingsManager.getInstance(context).todayForecastTime = it PollingManager.resetTodayForecastBackgroundTask( context, false, false ) }, ) } checkboxPreferenceItem(R.string.settings_title_forecast_tomorrow) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = tomorrowForecastEnabledState.value, onValueChanged = { tomorrowForecastEnabledState.value = it SettingsManager.getInstance(context).isTomorrowForecastEnabled = it PollingManager.resetNormalBackgroundTask(context, false) }, ) } timePickerPreferenceItem(R.string.settings_title_forecast_tomorrow_time) { id -> TimePickerPreferenceView( titleId = id, currentTime = SettingsManager.getInstance(context).tomorrowForecastTime, enabled = tomorrowForecastEnabledState.value, onValueChanged = { SettingsManager.getInstance(context).tomorrowForecastTime = it PollingManager.resetTomorrowForecastBackgroundTask( context, false, false ) }, ) } sectionFooterItem(R.string.settings_category_forecast) // widget. sectionHeaderItem(R.string.settings_category_widget) listPreferenceItem(R.string.settings_title_week_icon_mode) { id -> ListPreferenceView( titleId = id, selectedKey = SettingsManager.getInstance(context).widgetWeekIconMode.id, valueArrayId = R.array.week_icon_mode_values, nameArrayId = R.array.week_icon_modes, onValueChanged = { SettingsManager .getInstance(context) .widgetWeekIconMode = WidgetWeekIconMode.getInstance(it) PollingManager.resetNormalBackgroundTask(context, true) }, ) } checkboxPreferenceItem(R.string.settings_title_minimal_icon) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = SettingsManager.getInstance(context).isWidgetMinimalIconEnabled, onValueChanged = { SettingsManager.getInstance(context).isWidgetMinimalIconEnabled = it PollingManager.resetNormalBackgroundTask(context, true) }, ) } if (DayWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_day) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, DayWidgetConfigActivity::class.java)) } } } if (WeekWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_week) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, WeekWidgetConfigActivity::class.java)) } } } if (DayWeekWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_day_week) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, DayWeekWidgetConfigActivity::class.java)) } } } if (ClockDayHorizontalWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_clock_day_horizontal) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, ClockDayHorizontalWidgetConfigActivity::class.java)) } } } if (ClockDayDetailsWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_clock_day_details) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, ClockDayDetailsWidgetConfigActivity::class.java)) } } } if (ClockDayVerticalWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_clock_day_vertical) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, ClockDayVerticalWidgetConfigActivity::class.java)) } } } if (ClockDayWeekWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_clock_day_week) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, ClockDayWeekWidgetConfigActivity::class.java)) } } } if (TextWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_text) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, TextWidgetConfigActivity::class.java)) } } } if (DailyTrendWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_trend_daily) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, DailyTrendWidgetConfigActivity::class.java)) } } } if (HourlyTrendWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_trend_hourly) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, HourlyTrendWidgetConfigActivity::class.java)) } } } if (MultiCityWidgetIMP.isEnable(context)) { clickablePreferenceItem(R.string.key_widget_multi_city) { PreferenceView(title = stringResource(it)) { context.startActivity(Intent(context, MultiCityWidgetConfigActivity::class.java)) } } } sectionFooterItem(R.string.settings_category_widget) // notification. sectionHeaderItem(R.string.settings_category_notification) checkboxPreferenceItem(R.string.settings_title_notification) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = notificationEnabledState.value, onValueChanged = { SettingsManager.getInstance(context).isNotificationEnabled = it notificationEnabledState.value = it if (it) { // open notification. PollingManager.resetNormalBackgroundTask(context, true) } else { // close notification. NormalNotificationIMP.cancelNotification(context) PollingManager.resetNormalBackgroundTask(context, false) } } ) } listPreferenceItem(R.string.settings_title_notification_style) { id -> ListPreferenceView( titleId = id, selectedKey = SettingsManager.getInstance(context).notificationStyle.id, valueArrayId = R.array.notification_style_values, nameArrayId = R.array.notification_styles, enabled = notificationEnabledState.value, onValueChanged = { SettingsManager .getInstance(context) .notificationStyle = NotificationStyle.getInstance(it) PollingManager.resetNormalBackgroundTask(context, true) }, ) } checkboxPreferenceItem(R.string.settings_title_notification_temp_icon) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = SettingsManager .getInstance(context) .isNotificationTemperatureIconEnabled, enabled = notificationEnabledState.value, onValueChanged = { SettingsManager .getInstance(context) .isNotificationTemperatureIconEnabled = it notificationTemperatureIconEnabledState.value = it PollingManager.resetNormalBackgroundTask(context, true) } ) } checkboxPreferenceItem(R.string.settings_title_notification_feels_like) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = SettingsManager .getInstance(context) .isNotificationFeelsLike, enabled = notificationEnabledState.value && notificationTemperatureIconEnabledState.value, onValueChanged = { SettingsManager .getInstance(context) .isNotificationFeelsLike = it PollingManager.resetNormalBackgroundTask(context, true) } ) } checkboxPreferenceItem(R.string.settings_title_notification_can_be_cleared) { id -> CheckboxPreferenceView( titleId = id, summaryOnId = R.string.on, summaryOffId = R.string.off, checked = SettingsManager .getInstance(context) .isNotificationCanBeClearedEnabled, enabled = notificationEnabledState.value, onValueChanged = { SettingsManager .getInstance(context) .isNotificationCanBeClearedEnabled = it PollingManager.resetNormalBackgroundTask(context, true) } ) } sectionFooterItem(R.string.settings_category_notification) bottomInsetItem() } } @RequiresApi(api = Build.VERSION_CODES.O) private fun showBlockNotificationGroupDialog(context: Context) { MaterialAlertDialogBuilder(context) .setTitle(R.string.feedback_interpret_notification_group_title) .setMessage(R.string.feedback_interpret_notification_group_content) .setPositiveButton(R.string.go_to_set) { _, _ -> val intent = Intent() intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS intent.putExtra( Settings.EXTRA_APP_PACKAGE, context.packageName ) context.startActivity(intent) showIgnoreBatteryOptimizationDialog(context) } .setNeutralButton( R.string.done ) { _, _ -> showIgnoreBatteryOptimizationDialog(context) } .setCancelable(false) .show() } @RequiresApi(api = Build.VERSION_CODES.M) private fun showIgnoreBatteryOptimizationDialog(context: Context) { MaterialAlertDialogBuilder(context) .setTitle(R.string.feedback_ignore_battery_optimizations_title) .setMessage(R.string.feedback_ignore_battery_optimizations_content) .setPositiveButton( R.string.go_to_set ) { _, _ -> IntentHelper.startBatteryOptimizationActivity(context) } .setNeutralButton(R.string.done) { _, _ -> } .setCancelable(false) .show() }
lgpl-3.0
034fe2810040b9a88e5e97fd75ec0199
42.453586
110
0.581007
5.517546
false
false
false
false
olivierperez/crapp
feature-timesheet/src/main/java/fr/o80/sample/timesheet/usecase/ProjectCrud.kt
1
1653
package fr.o80.sample.timesheet.usecase import fr.o80.crapp.data.ProjectRepository import fr.o80.crapp.data.entity.Project import fr.o80.sample.lib.dagger.FeatureScope import io.reactivex.Maybe import io.reactivex.Single import io.reactivex.schedulers.Schedulers import javax.inject.Inject /** * @author Olivier Perez */ @FeatureScope class ProjectCrud @Inject constructor(private val projectRepository: ProjectRepository) { fun create(label: String, code: String): Single<Boolean> = projectRepository .findByCode(code) .subscribeOn(Schedulers.io()) .map { it.copy(archived = 0) } .toSingle(Project(code = code, label = label)) .flatMap { it.save() } fun all(): Single<List<Project>> = projectRepository .all() .subscribeOn(Schedulers.io()) fun allActive(): Single<List<Project>> = projectRepository .allActive() .subscribeOn(Schedulers.io()) fun findByCode(code: String): Maybe<Project> = projectRepository .findByCode(code) .subscribeOn(Schedulers.io()) fun update(id: Long, label: String, code: String): Single<Boolean> = Project(id = id, code = code, label = label) .update() .subscribeOn(Schedulers.io()) fun archive(id: Long): Single<Boolean> = projectRepository.findById(id) .map { it.copy(archived = 1) } .flatMapSingle { it.update() } }
apache-2.0
0e55351678c497f9633a3ee40701548a
31.411765
72
0.574713
4.467568
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandReload.kt
1
1018
package nl.sugcube.dirtyarrows.command import nl.sugcube.dirtyarrows.Broadcast import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.util.sendError import org.bukkit.command.CommandSender /** * @author SugarCaney */ open class CommandReload : SubCommand<DirtyArrows>( name = "reload", usage = "/da reload", argumentCount = 0, description = "Reloads the configuration file." ) { init { addPermissions("dirtyarrows.admin") } override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) = with(plugin) { try { configurationManager.loadConfig() recipeManager.reloadConfig() bowManager.reload() sender.sendMessage(Broadcast.RELOADED_CONFIG) } catch (e: Exception) { e.printStackTrace() sender.sendError("Failed to load config.yml: ${e.message}") } } override fun assertSender(sender: CommandSender) = true }
gpl-3.0
9b4ef41312e3b7d61d72f3b6a4c21287
27.305556
115
0.660118
4.606335
false
true
false
false
mattvchandler/ProgressBars
app/src/main/java/db/DB.kt
1
2929
/* Copyright (C) 2020 Matthew Chandler 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 org.mattvchandler.progressbars.db import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper // helper functions for getting data from a cursor fun Cursor.get_nullable_string(column_name: String): String? { val column_index = this.getColumnIndexOrThrow(column_name) return if(this.isNull(column_index)) null else this.getString(column_index) } fun Cursor.get_nullable_long(column_name: String): Long? { val column_index = this.getColumnIndexOrThrow(column_name) return if(this.isNull(column_index)) null else this.getLong(column_index) } fun Cursor.get_nullable_int(column_name: String): Int? { val column_index = this.getColumnIndexOrThrow(column_name) return if(this.isNull(column_index)) null else this.getInt(column_index) } fun Cursor.get_nullable_bool(column_name: String): Boolean? { val column_index = this.getColumnIndexOrThrow(column_name) return if(this.isNull(column_index)) null else this.getInt(column_index) != 0 } // DB container class DB(private val context: Context): SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) { companion object { private const val DB_VERSION = 5 private const val DB_NAME = "progress_bar_db" } // build the tables / whatever else when new override fun onCreate(sqLiteDatabase: SQLiteDatabase) { sqLiteDatabase.execSQL(Progress_bars_table.CREATE_TABLE) } // if DB schema changes, put logic to migrate data here override fun onUpgrade(db: SQLiteDatabase, old_version: Int, new_version: Int) { check(new_version == DB_VERSION) { "DB version mismatch" } if(old_version < 4) db.execSQL("DROP TABLE IF EXISTS undo") Progress_bars_table.upgrade(context, db, old_version) } }
mit
8373a4ac5333f914b385c0c0a397966b
38.053333
92
0.751792
4.137006
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt
1
3475
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable import java.nio.ByteBuffer import java.util.* class StopDeliveryCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val deliveryType: DeliveryType, private val beepType: BeepType, nonce: Int ) : NonceEnabledCommand(CommandType.STOP_DELIVERY, uniqueId, sequenceNumber, multiCommandFlag, nonce) { override val encoded: ByteArray get() { return appendCrc( ByteBuffer.allocate(LENGTH + HEADER_LENGTH) .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) .put(commandType.value) .put(BODY_LENGTH) .putInt(nonce) .put((beepType.value.toInt() shl 4 or deliveryType.encoded[0].toInt()).toByte()) .array() ) } override fun toString(): String { return "StopDeliveryCommand{" + "deliveryType=" + deliveryType + ", beepType=" + beepType + ", nonce=" + nonce + ", commandType=" + commandType + ", uniqueId=" + uniqueId + ", sequenceNumber=" + sequenceNumber + ", multiCommandFlag=" + multiCommandFlag + '}' } enum class DeliveryType( private val basal: Boolean, private val tempBasal: Boolean, private val bolus: Boolean ) : Encodable { BASAL(true, false, false), TEMP_BASAL(false, true, false), BOLUS(false, false, true), ALL(true, true, true); override val encoded: ByteArray get() { val bitSet = BitSet(8) bitSet[0] = basal bitSet[1] = tempBasal bitSet[2] = bolus return bitSet.toByteArray() } } class Builder : NonceEnabledCommandBuilder<Builder, StopDeliveryCommand>() { private var deliveryType: DeliveryType? = null private var beepType: BeepType? = BeepType.LONG_SINGLE_BEEP fun setDeliveryType(deliveryType: DeliveryType): Builder { this.deliveryType = deliveryType return this } fun setBeepType(beepType: BeepType): Builder { this.beepType = beepType return this } override fun buildCommand(): StopDeliveryCommand { requireNotNull(deliveryType) { "deliveryType can not be null" } requireNotNull(beepType) { "beepType can not be null" } return StopDeliveryCommand( uniqueId!!, sequenceNumber!!, multiCommandFlag, deliveryType!!, beepType!!, nonce!! ) } } companion object { private const val LENGTH: Short = 7 private const val BODY_LENGTH: Byte = 5 } }
agpl-3.0
3e0469434a90ef9da143b77e206ec28a
34.459184
118
0.609784
4.734332
false
false
false
false
PolymerLabs/arcs
java/arcs/core/analysis/AccessPathLabels.kt
1
4464
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.analysis import arcs.core.data.AccessPath /** * An [AbstractValue] that keeps track of [InformationFlowLabels] for different [AccessPath] values. * * This abstract value uses a map from [AccessPath] to [InformationFlowLabels] to keep track of the * labels for each access path. We use a reduced bottom construction, i.e., whenever a value for an * access path is `BOTTOM`, the whole map is considered `BOTTOM`. */ data class AccessPathLabels private constructor( private val _accessPathLabels: BoundedAbstractElement<Map<AccessPath, InformationFlowLabels>> ) : AbstractValue<AccessPathLabels> { override val isBottom = _accessPathLabels.isBottom override val isTop = _accessPathLabels.isTop val accessPathLabels: Map<AccessPath, InformationFlowLabels>? get() = _accessPathLabels.value override infix fun isEquivalentTo(other: AccessPathLabels): Boolean { return _accessPathLabels.isEquivalentTo(other._accessPathLabels) { a, b -> a.size == b.size && a.all { (accessPath, aLabels) -> b[accessPath]?.isEquivalentTo(aLabels) ?: false } } } override infix fun join(other: AccessPathLabels): AccessPathLabels { return AccessPathLabels( _accessPathLabels.join(other._accessPathLabels) { thisMap, otherMap -> val result = thisMap.toMutableMap() otherMap.forEach { (accessPath, otherLabels) -> val thisLabels = thisMap[accessPath] result.put(accessPath, thisLabels?.join(otherLabels) ?: otherLabels) } result } ) } override infix fun meet(other: AccessPathLabels): AccessPathLabels { if (this.isBottom || other.isBottom) return AccessPathLabels.getBottom() if (this.isTop) return other if (other.isTop) return this val thisMap = requireNotNull(this.accessPathLabels) val otherMap = requireNotNull(other.accessPathLabels) val result = mutableMapOf<AccessPath, InformationFlowLabels>() thisMap.forEach { (accessPath, thisLabels) -> otherMap[accessPath]?.meet(thisLabels)?.let { result[accessPath] = it } } return AccessPathLabels.makeValue(result) } override fun toString() = toString(linePrefix = "", transform = null) /** * Returns the join of labels for the access paths for which the given [accessPath] is a prefix. * * For example, suppose that there is an entry for `root.foo` (say `fooValue`) and an entry for * `root.bar` (say `barValue`), then [getLabels] on `root` returns `fooValue join barValue`. */ fun getLabels(accessPath: AccessPath): InformationFlowLabels { val combinedLabels = accessPathLabels?.entries ?.fold(InformationFlowLabels.getBottom()) { acc, (curAccessPath, curLabels) -> if (accessPath.isPrefixOf(curAccessPath)) { acc join curLabels } else { acc } } return combinedLabels ?: InformationFlowLabels.getBottom() } fun toString(linePrefix: String = "", transform: ((Int) -> String)?): String { return when { _accessPathLabels.isTop -> "${linePrefix}TOP" _accessPathLabels.isBottom -> "${linePrefix}BOTTOM" else -> requireNotNull(_accessPathLabels.value).map { (accessPath, labels) -> "$accessPath -> ${labels.toString(transform)}" }.joinToString("\n$linePrefix", prefix = linePrefix) } } companion object { fun getBottom(): AccessPathLabels { return AccessPathLabels( BoundedAbstractElement.getBottom<Map<AccessPath, InformationFlowLabels>>() ) } fun getTop(): AccessPathLabels { return AccessPathLabels( BoundedAbstractElement.getTop<Map<AccessPath, InformationFlowLabels>>() ) } /** * Creates an [AccessPathLabels] with [map]. If any of the values in [map] is `bottom`, * returns `bottom`. */ fun makeValue(map: Map<AccessPath, InformationFlowLabels>): AccessPathLabels { val isBottom = map.any { (_, labels) -> labels.isBottom || (labels.labelSets?.isEmpty() == true) } if (isBottom) return getBottom() return AccessPathLabels(BoundedAbstractElement.makeValue(map)) } } }
bsd-3-clause
50491fcd06a994ce8183b776c4007358
35.292683
100
0.686828
4.12951
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/observe/Crc.kt
1
2622
/* * Copyright 2019 Poly Forest, 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.acornui.observe class Crc32 { /** * The crc checksum. */ private var crc = 0 /** * The fast CRC table. Computed once when the CRC32 class is loaded. */ private val crcTable = makeCrcTable() /** * Make the table for a fast CRC. */ private fun makeCrcTable(): IntArray { val table = IntArray(256) for (n in 0..255) { var c = n var k = 8 while (--k >= 0) { if ((c and 1) != 0) c = -306674912 xor (c.ushr(1)) else c = c.ushr(1) } table[n] = c } return table } /** * Returns the CRC32 data checksum computed so far. */ fun getValue(): Long { return crc.toLong() and 0xffffffffL } /** * Resets the CRC32 data checksum as if no update was ever called. */ fun reset() { crc = 0 } /** * Updates the checksum with given long. */ fun update(longVal: Long) { update((longVal shr 56).toByte()) update((longVal shr 48).toByte()) update((longVal shr 40).toByte()) update((longVal shr 32).toByte()) update((longVal shr 24).toByte()) update((longVal shr 16).toByte()) update((longVal shr 8).toByte()) update(longVal.toByte()) } /** * Updates the checksum with given integer. */ fun update(intVal: Int) { update((intVal shr 24).toByte()) update((intVal shr 16).toByte()) update((intVal shr 8).toByte()) update(intVal.toByte()) } /** * Updates the checksum with the given byte. */ fun update(byteVal: Byte) { var c = crc.inv() c = crcTable[(c xor byteVal.toInt()) and 255] xor (c.ushr(8)) crc = c.inv() } /** * Adds the byte array to the data checksum. * @param buf the buffer which contains the data * * @param off the offset in the buffer where the data starts * * @param len the length of the data */ fun update(buf: ByteArray, off: Int = 0, len: Int = buf.size) { var i = off var n = len var c = crc.inv() while (--n >= 0) { c = crcTable[(c xor buf[i++].toInt()) and 255] xor (c.ushr(8)) } crc = c.inv() } companion object { val CRC = Crc32() } }
apache-2.0
e70f49e2d1351977f74e9a1420460635
21.033613
75
0.632342
3.170496
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/util/crashlogging/WPCrashLoggingDataProvider.kt
1
4737
package org.wordpress.android.util.crashlogging import android.content.SharedPreferences import com.automattic.android.tracks.crashlogging.CrashLoggingDataProvider import com.automattic.android.tracks.crashlogging.CrashLoggingUser import com.automattic.android.tracks.crashlogging.EventLevel import com.automattic.android.tracks.crashlogging.ExtraKnownKey import org.wordpress.android.BuildConfig import org.wordpress.android.R import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.util.BuildConfigWrapper import org.wordpress.android.util.EncryptedLogging import org.wordpress.android.util.LocaleManagerWrapper import org.wordpress.android.util.LogFileProviderWrapper import org.wordpress.android.viewmodel.ResourceProvider import java.util.Locale import javax.inject.Inject class WPCrashLoggingDataProvider @Inject constructor( private val sharedPreferences: SharedPreferences, private val resourceProvider: ResourceProvider, private val accountStore: AccountStore, private val localeManager: LocaleManagerWrapper, private val encryptedLogging: EncryptedLogging, private val logFileProvider: LogFileProviderWrapper, private val buildConfig: BuildConfigWrapper ) : CrashLoggingDataProvider { override val buildType: String = BuildConfig.BUILD_TYPE override val enableCrashLoggingLogs: Boolean = BuildConfig.DEBUG override val locale: Locale get() = localeManager.getLocale() override val releaseName: String = BuildConfig.VERSION_NAME override val sentryDSN: String = BuildConfig.SENTRY_DSN override fun applicationContextProvider(): Map<String, String> { return emptyMap() } override fun crashLoggingEnabled(): Boolean { if (buildConfig.isDebug()) { return false } val hasUserAllowedReporting = sharedPreferences.getBoolean( resourceProvider.getString(R.string.pref_key_send_crash), true ) return hasUserAllowedReporting } override fun extraKnownKeys(): List<ExtraKnownKey> { return listOf(EXTRA_UUID) } /** * If Sentry is unable to upload the event in its first attempt, it'll call the `setBeforeSend` callback * before trying to send it again. This can be easily reproduced by turning off network connectivity * and re-launching the app over and over again which will hit this callback each time. * * The problem with that is it'll keep queuing more and more logs to be uploaded to MC and more * importantly, it'll set the `uuid` of the Sentry event to the log file at the time of the successful * Sentry request. Since we are interested in the logs for when the crash happened, this would not be * correct for us. * * We can simply fix this issue by checking if the [EXTRA_UUID] field is already set. */ override fun provideExtrasForEvent( currentExtras: Map<ExtraKnownKey, String>, eventLevel: EventLevel ): Map<ExtraKnownKey, String> { return currentExtras + if (currentExtras[EXTRA_UUID] == null) { appendEncryptedLogsUuid(eventLevel) } else { emptyMap() } } private fun appendEncryptedLogsUuid(eventLevel: EventLevel): Map<ExtraKnownKey, String> { val encryptedLogsUuid = mutableMapOf<ExtraKnownKey, String>() logFileProvider.getLogFiles().lastOrNull()?.let { logFile -> if (logFile.exists()) { encryptedLogging.encryptAndUploadLogFile( logFile = logFile, shouldStartUploadImmediately = eventLevel != EventLevel.FATAL )?.let { uuid -> encryptedLogsUuid.put(EXTRA_UUID, uuid) } } } return encryptedLogsUuid } override fun shouldDropWrappingException(module: String, type: String, value: String): Boolean { return module == EVENT_BUS_MODULE && type == EVENT_BUS_EXCEPTION && value == EVENT_BUS_INVOKING_SUBSCRIBER_FAILED_ERROR } override fun userProvider(): CrashLoggingUser? { return accountStore.account?.let { accountModel -> CrashLoggingUser( userID = accountModel.userId.toString(), email = accountModel.email, username = accountModel.userName ) } } companion object { const val EXTRA_UUID = "uuid" const val EVENT_BUS_MODULE = "org.greenrobot.eventbus" const val EVENT_BUS_EXCEPTION = "EventBusException" const val EVENT_BUS_INVOKING_SUBSCRIBER_FAILED_ERROR = "Invoking subscriber failed" } }
gpl-2.0
57615a1deb4f3374943ec6d9005da3e0
40.191304
108
0.691999
4.873457
false
true
false
false
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/PreviewStaticServer.kt
1
6350
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.preview import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.util.Urls.parseEncoded import io.netty.buffer.Unpooled import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import org.jetbrains.ide.BuiltInServerManager.Companion.getInstance import org.jetbrains.ide.HttpRequestHandler import org.jetbrains.io.FileResponses.checkCache import org.jetbrains.io.FileResponses.getContentType import org.jetbrains.io.send import java.net.URL import java.util.* /** * Will serve resources provided by registered resource providers. */ class PreviewStaticServer : HttpRequestHandler() { private val defaultResourceProvider = ResourceProvider.DefaultResourceProvider() private val resourceProviders = hashMapOf<Int, ResourceProvider>(defaultResourceProvider.hashCode() to defaultResourceProvider) /** * @return [Disposable] which will unregister [resourceProvider]. */ @Synchronized fun registerResourceProvider(resourceProvider: ResourceProvider): Disposable { resourceProviders[resourceProvider.hashCode()] = resourceProvider return Disposable { unregisterResourceProvider(resourceProvider) } } /** * Prefer unregistering providers by disposing [Disposable] returned by [registerResourceProvider]. */ @Synchronized fun unregisterResourceProvider(resourceProvider: ResourceProvider) { resourceProviders.remove(resourceProvider.hashCode()) } private fun getProviderHash(path: String): Int? { return path.split('/').getOrNull(2)?.toIntOrNull() } private fun getStaticPath(path: String): String { return path.split('/').drop(3).joinToString(separator = "/") } private fun obtainResourceProvider(path: String): ResourceProvider? { val providerHash = getProviderHash(path) ?: return null return synchronized(resourceProviders) { resourceProviders.getOrDefault(providerHash, null) } } override fun isSupported(request: FullHttpRequest): Boolean { if (!super.isSupported(request)) { return false } val path = request.uri() return path.startsWith(prefixPath) } override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean { val path = urlDecoder.path() check(path.startsWith(prefixPath)) { "prefix should have been checked by #isSupported" } val resourceProvider = obtainResourceProvider(path) ?: return false val resourceName = getStaticPath(path) if (resourceProvider.canProvide(resourceName)) { sendResource( request, context.channel(), resourceProvider.loadResource(resourceName), resourceName ) return true } return false } companion object { private const val endpointPrefix = "markdownPreview" private const val prefixPath = "/$endpointPrefix" @JvmStatic val instance: PreviewStaticServer get() = EP_NAME.findExtension(PreviewStaticServer::class.java) ?: error("Could not get server instance!") @JvmStatic fun createCSP(scripts: List<String>, styles: List<String>): String { // We need to remove any query parameters to stop annoying errors in the browser console fun stripQueryParameters(url: String) = url.replace("?${URL(url).query}", "") return """ default-src 'none'; script-src ${StringUtil.join(scripts.map(::stripQueryParameters), " ")}; style-src https: ${StringUtil.join(styles.map(::stripQueryParameters), " ")} 'unsafe-inline'; img-src file: *; connect-src 'none'; font-src * data: *; object-src 'none'; media-src 'none'; child-src 'none'; """ } /** * Expected to return same URL on each call for same [resourceProvider] and [staticPath], * if [resourceProvider] was not unregistered between those calls. */ @JvmStatic fun getStaticUrl(resourceProvider: ResourceProvider, staticPath: String): String { val providerHash = resourceProvider.hashCode() val port = getInstance().port val raw = "http://localhost:$port/$endpointPrefix/$providerHash/$staticPath" val url = parseEncoded(raw) requireNotNull(url) { "Could not parse url!" } return getInstance().addAuthToken(url).toExternalForm() } @Deprecated("Use PreviewStaticServer.getStaticUrl(ResourceProvider, String) instead") @JvmStatic fun getStaticUrl(staticPath: String): String { return getStaticUrl(instance.defaultResourceProvider, staticPath) } /** * The types for which `";charset=utf-8"` will be appended (only if guessed by [guessContentType]). */ private val typesForExplicitUtfCharset = arrayOf( "application/javascript", "text/html", "text/css", "image/svg+xml" ) private fun guessContentType(resourceName: String): String { val type = getContentType(resourceName) return if (type in typesForExplicitUtfCharset) { "$type; charset=utf-8" } else type } private fun sendResource( request: HttpRequest, channel: Channel, resource: ResourceProvider.Resource?, resourceName: String ) { val lastModified = ApplicationInfo.getInstance().buildDate.timeInMillis if (checkCache(request, channel, lastModified)) { return } if (resource == null) { HttpResponseStatus.NOT_FOUND.send(channel, request) return } val response: FullHttpResponse = DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(resource.content) ) with(response) { if (resource.type != null) { headers()[HttpHeaderNames.CONTENT_TYPE] = resource.type } else { headers()[HttpHeaderNames.CONTENT_TYPE] = guessContentType(resourceName) } headers()[HttpHeaderNames.CACHE_CONTROL] = "private, must-revalidate" headers()[HttpHeaderNames.LAST_MODIFIED] = Date(lastModified) send(channel, request) } } } }
apache-2.0
f00eee09bf34f857195993102b78e827
35.918605
140
0.706772
4.710682
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/players/PlayerStats.kt
4
422
package dev.mfazio.abl.players import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "stats") data class PlayerStats( val playerId: String, @Embedded(prefix = "batter") val batterStats: BatterStats = BatterStats(), @Embedded(prefix = "pitcher") val pitcherStats: PitcherStats = PitcherStats() ) { @PrimaryKey(autoGenerate = true) var id: Int = 0 }
apache-2.0
e61276b7cdcc861c131a005fb2fa7d47
27.2
81
0.739336
3.606838
false
false
false
false
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/hid/state/ButtonEdgeState.kt
1
952
package org.snakeskin.hid.state import org.snakeskin.hid.listener.ButtonEdgeListener import org.snakeskin.executor.ExceptionHandlingRunnable import org.snakeskin.utility.value.HistoryBoolean /** * @author Cameron Earle * @version 12/12/2018 * * Tracks the state of a button's edge */ class ButtonEdgeState(val listener: ButtonEdgeListener): IControlSurfaceState { private val history = HistoryBoolean() private val edgeValue = when (listener.edgeType) { ButtonEdgeListener.EdgeType.Pressed -> true ButtonEdgeListener.EdgeType.Released -> false } override fun update(timestamp: Double): Boolean { history.update(listener.surface.read()) if (history.current == edgeValue) { if (history.last == !edgeValue) { return true } } return false } override val action = ExceptionHandlingRunnable { listener.action(edgeValue) } }
gpl-3.0
65987433dabde2b25d8ebfe941acf07b
26.228571
79
0.681723
4.366972
false
false
false
false
akvo/akvo-rsr-up
android/AkvoRSR/app/src/main/java/org/akvo/rsr/up/worker/GetProjectDataWorker.kt
1
9815
package org.akvo.rsr.up.worker import android.content.Context import android.util.Log import androidx.work.Data import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import org.akvo.rsr.up.R import org.akvo.rsr.up.dao.RsrDbAdapter import org.akvo.rsr.up.domain.Project import org.akvo.rsr.up.util.ConstantUtil import org.akvo.rsr.up.util.Downloader import org.akvo.rsr.up.util.FileUtil import org.akvo.rsr.up.util.SettingsUtil import java.io.FileNotFoundException import java.net.MalformedURLException import java.net.URL import java.text.SimpleDateFormat import java.util.ArrayList import java.util.HashSet import java.util.Locale import java.util.TimeZone class GetProjectDataWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) { override fun doWork(): Result { val projectId = inputData.getString(ConstantUtil.PROJECT_ID_KEY) val appContext = applicationContext val ad = RsrDbAdapter(appContext) val dl = Downloader() var errMsg: String? = null val fetchImages = !SettingsUtil.ReadBoolean(appContext, "setting_delay_image_fetch", false) val fullSynch = SettingsUtil.ReadBoolean(appContext, "setting_fullsynch", false) val host = SettingsUtil.host(appContext) val start = System.currentTimeMillis() ad.open() val user = SettingsUtil.getAuthUser(appContext) try { try { // Make the list of projects to update val projectSet: MutableSet<String> if (projectId == null) { projectSet = user.publishedProjIds } else { projectSet = HashSet() projectSet.add(projectId) } val projects = projectSet.size // Iterate over projects instead of using a complex query URL, since it can take so long that the proxy times out projectSet.withIndex().forEach { (i, id) -> dl.fetchProject(appContext, ad, getProjectUpdateUrl(appContext, id)) // TODO: JSON if (FETCH_RESULTS) { dl.fetchProjectResultsPaged(appContext, ad, getResultsUrl(host, id)) } setProgressAsync( workDataOf( ConstantUtil.PHASE_KEY to 0, ConstantUtil.SOFAR_KEY to i + 1, ConstantUtil.TOTAL_KEY to projects ) ) } // country list rarely changes, so only fetch countries if we never did that if (FETCH_COUNTRIES && (fullSynch || ad.getCountryCount() == 0)) { dl.fetchCountryListRestApiPaged(appContext, ad, getCountriesUrl(appContext)) } setProgressAsync( workDataOf( ConstantUtil.PHASE_KEY to 0, ConstantUtil.SOFAR_KEY to 100, ConstantUtil.TOTAL_KEY to 100 ) ) if (FETCH_UPDATES) { val df1 = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US) df1.timeZone = TimeZone.getTimeZone("UTC") val fetchedIds = ArrayList<String>() projectSet.withIndex().forEach { (k, projId) -> val project = ad.findProject(projId) if (project != null) { // since last fetch or forever? val url = getProjectUpdateUrl(projId, df1, fullSynch, project, host) val date = dl.fetchUpdateListRestApiPaged(appContext, url, fetchedIds) // fetch completed; remember fetch date of this project - other users of the app may have different project set ad.updateProjectLastFetch(projId, date) if (fullSynch) { // now delete those that went away val removeIds = ad.getUpdatesForList(projId) removeIds.removeAll(fetchedIds) removeIds.forEach { id -> Log.i(TAG, "Deleting update $id") ad.deleteUpdate(id) } } } // show progress // TODO this is *very* uninformative for a user with one project and many updates! setProgressAsync( workDataOf( ConstantUtil.PHASE_KEY to 1, ConstantUtil.SOFAR_KEY to k + 1, ConstantUtil.TOTAL_KEY to projects ) ) } } } catch (e: FileNotFoundException) { Log.e(TAG, "Cannot find:", e) errMsg = appContext.resources.getString(R.string.errmsg_not_found_on_server) + e.message } catch (e: Exception) { Log.e(TAG, "Bad updates fetch:", e) errMsg = appContext.resources.getString(R.string.errmsg_update_fetch_failed) + e.message } if (FETCH_USERS) { val orgIds = ad.missingUsersList orgIds.forEach { id -> try { dl.fetchUser(appContext, ad, buildUserUrl(host, id), id) } catch (e: Exception) { // probably network reasons Log.e(TAG, "Bad user fetch:", e) errMsg = appContext.resources.getString(R.string.errmsg_user_fetch_failed) + e.message } } } if (FETCH_ORGS) { // Fetch user data for the organisations of users. val orgIds = ad.missingOrgsList var j = 0 orgIds.forEach { id -> try { dl.fetchOrg(appContext, ad, getOrgsUrl(host, id), id) j++ } catch (e: Exception) { // probably network reasons Log.e(TAG, "Bad org fetch:", e) errMsg = appContext.resources.getString(R.string.errmsg_org_fetch_failed) + e.message } } Log.i(TAG, "Fetched $j orgs") } setProgressAsync( workDataOf( ConstantUtil.PHASE_KEY to 1, ConstantUtil.SOFAR_KEY to 100, ConstantUtil.TOTAL_KEY to 100 ) ) if (fetchImages) { try { dl.fetchMissingThumbnails( appContext, host, FileUtil.getExternalCacheDir(appContext).toString() ) { sofar, total -> setProgressAsync( workDataOf( ConstantUtil.PHASE_KEY to 2, ConstantUtil.SOFAR_KEY to sofar, ConstantUtil.TOTAL_KEY to total ) ) } } catch (e: MalformedURLException) { Log.e(TAG, "Bad thumbnail URL:", e) errMsg = "Thumbnail url problem: $e" } } } finally { ad.close() } val end = System.currentTimeMillis() Log.i(TAG, "Fetch complete in: " + (end - start) / 1000.0) return if (errMsg != null) { Result.failure(createOutputDataWithError(appContext, errMsg)) } else { Result.success() } } private fun createOutputDataWithError(context: Context, message: String?): Data { return workDataOf(ConstantUtil.SERVICE_ERRMSG_KEY to context.resources.getString(R.string.errmsg_signin_failed) + message) } private fun getOrgsUrl(host: String, id: String?) = URL( host + String.format( Locale.US, ConstantUtil.FETCH_ORG_URL_PATTERN, id ) ) private fun getCountriesUrl(appContext: Context) = URL(SettingsUtil.host(appContext) + String.format(ConstantUtil.FETCH_COUNTRIES_URL)) private fun getResultsUrl(host: String, id: String) = URL(host + String.format(ConstantUtil.FETCH_RESULTS_URL_PATTERN, id)) private fun getProjectUpdateUrl( appContext: Context, id: String, ) = URL(SettingsUtil.host(appContext) + String.format(ConstantUtil.FETCH_PROJ_URL_PATTERN, id)) private fun getProjectUpdateUrl( projId: String, df1: SimpleDateFormat, fullSynch: Boolean, project: Project, host: String, ): URL { val u = String.format( ConstantUtil.FETCH_UPDATE_URL_PATTERN, projId, df1.format(if (fullSynch) 0 else project.lastFetch) ) return URL(host + u) } private fun buildUserUrl(host: String, id: String?) = URL(host + String.format(Locale.US, ConstantUtil.FETCH_USER_URL_PATTERN, id)) companion object { const val TAG = "GetProjectDataWorker" private const val FETCH_USERS = true private const val FETCH_COUNTRIES = true private const val FETCH_UPDATES = true private const val FETCH_ORGS = true private const val FETCH_RESULTS = false // TODO: why is this false? } }
agpl-3.0
a0d02492b1863db7efa757517f984eb6
41.306034
139
0.519511
4.962083
false
false
false
false
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/functions/LoadFunction.kt
2
2136
package com.eden.orchid.impl.themes.functions import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.options.annotations.BooleanDefault import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.resources.resourcesource.LocalResourceSource import com.eden.orchid.api.theme.pages.OrchidPage @Description(value = "Load content from a resource.", name = "Load") class LoadFunction : TemplateFunction("load", false) { @Option @Description("The resource to lookup.") lateinit var resource: String @Option @BooleanDefault(true) @Description("When true, only resources from local sources are considered, otherwise resources from all plugins " + "and from the current theme will also be considered." ) var local: Boolean = true @Option @BooleanDefault(false) @Description("When true, return the Front Matter data from the resource, instead of its content.") var frontMatter: Boolean = false @Option @BooleanDefault(true) @Description("When true, content will automatically be compiled according to its extension. If false, the raw " + "content will be returned directly as a String, minus any Front Matter." ) var compile: Boolean = true override fun parameters() = arrayOf(::resource.name, ::local.name, ::compile.name) override fun apply(context: OrchidContext, page: OrchidPage?): Any? { val foundResource = if (local) context.getDefaultResourceSource(LocalResourceSource, null).getResourceEntry(context, resource) else context.getDefaultResourceSource(null, null).getResourceEntry(context, resource) return if (foundResource != null) { if (frontMatter) { foundResource.embeddedData } else if (compile) { foundResource.compileContent(context, null) } else { foundResource.content } } else "" } }
mit
8fc267563fee6a57f2bf4acaf3942c17
35.827586
117
0.684925
4.633406
false
false
false
false
GunoH/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffActions.kt
3
13618
// 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.diff.tools.combined import com.intellij.diff.DiffContext import com.intellij.diff.actions.impl.* import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings import com.intellij.diff.tools.combined.CombinedDiffViewer.IterationState import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.tools.util.FoldingModelSupport import com.intellij.diff.tools.util.PrevNextDifferenceIterable import com.intellij.diff.tools.util.base.TextDiffSettingsHolder import com.intellij.diff.tools.util.base.TextDiffViewerUtil import com.intellij.diff.tools.util.text.SmartTextDiffProvider import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.ide.util.PsiNavigationSupport import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.ToolbarLabelAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.diff.DiffBundle.message import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.vcs.FilePath import com.intellij.pom.Navigatable import com.intellij.ui.HyperlinkAdapter import com.intellij.ui.ToggleActionButton import java.awt.Component import javax.swing.event.HyperlinkEvent import javax.swing.event.HyperlinkListener internal open class CombinedNextChangeAction(private val context: DiffContext) : NextChangeAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun update(e: AnActionEvent) { if (DiffUtil.isFromShortcut(e)) { e.presentation.isEnabledAndVisible = true return } val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) if (viewer == null || !viewer.isNavigationEnabled()) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = viewer.hasNextChange(true) } override fun actionPerformed(e: AnActionEvent) { val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?: return if (!viewer.isNavigationEnabled() || !viewer.hasNextChange(false)) return viewer.goToNextChange(false) } } internal open class CombinedPrevChangeAction(private val context: DiffContext) : PrevChangeAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun update(e: AnActionEvent) { if (DiffUtil.isFromShortcut(e)) { e.presentation.isEnabledAndVisible = true return } val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) if (viewer == null || !viewer.isNavigationEnabled()) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = viewer.hasPrevChange(true) } override fun actionPerformed(e: AnActionEvent) { val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?: return if (!viewer.isNavigationEnabled() || !viewer.hasPrevChange(false)) return viewer.goToPrevChange(false) } } internal open class CombinedNextDifferenceAction(private val settings: DiffSettings, private val context: DiffContext) : NextDifferenceAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } protected open fun getDifferenceIterable(e: AnActionEvent): PrevNextDifferenceIterable? { return e.getData(DiffDataKeys.PREV_NEXT_DIFFERENCE_ITERABLE) } override fun update(e: AnActionEvent) { if (DiffUtil.isFromShortcut(e)) { e.presentation.isEnabledAndVisible = true return } val iterable = getDifferenceIterable(e) if (iterable != null && iterable.canGoNext()) { e.presentation.isEnabled = true return } val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) if (viewer != null && settings.isGoToNextFileOnNextDifference && viewer.isNavigationEnabled() && viewer.hasNextChange(true)) { e.presentation.isEnabled = true return } e.presentation.isEnabled = false } override fun actionPerformed(e: AnActionEvent) { val iterable = getDifferenceIterable(e) val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?: return context.putUserData(DiffUserDataKeysEx.SCROLL_TO_CHANGE, DiffUserDataKeysEx.ScrollToPolicy.FIRST_CHANGE) if (iterable != null && iterable.canGoNext()) { iterable.goNext() viewer.iterationState = IterationState.NONE return } if (!viewer.isNavigationEnabled() || !viewer.hasNextChange(false) || !settings.isGoToNextFileOnNextDifference) return if (viewer.iterationState != IterationState.NEXT) { context.getUserData(COMBINED_DIFF_MAIN_UI)?.notifyMessage(e, true) viewer.iterationState = IterationState.NEXT return } viewer.goToNextChange(true) viewer.iterationState = IterationState.NONE } } internal open class CombinedPrevDifferenceAction(private val settings: DiffSettings, private val context: DiffContext) : PrevDifferenceAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } protected open fun getDifferenceIterable(e: AnActionEvent): PrevNextDifferenceIterable? { return e.getData(DiffDataKeys.PREV_NEXT_DIFFERENCE_ITERABLE) } override fun update(e: AnActionEvent) { if (DiffUtil.isFromShortcut(e)) { e.presentation.isEnabledAndVisible = true return } val iterable = getDifferenceIterable(e) if (iterable != null && iterable.canGoPrev()) { e.presentation.isEnabled = true return } val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) if (viewer != null && settings.isGoToNextFileOnNextDifference && viewer.isNavigationEnabled() && viewer.hasPrevChange(true)) { e.presentation.isEnabled = true return } e.presentation.isEnabled = false } override fun actionPerformed(e: AnActionEvent) { val iterable = getDifferenceIterable(e) val viewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?: return context.putUserData(DiffUserDataKeysEx.SCROLL_TO_CHANGE, DiffUserDataKeysEx.ScrollToPolicy.LAST_CHANGE) if (iterable != null && iterable.canGoPrev()) { iterable.goPrev() viewer.iterationState = IterationState.NONE return } if (!viewer.isNavigationEnabled() || !viewer.hasPrevChange(false) || !settings.isGoToNextFileOnNextDifference) return if (viewer.iterationState != IterationState.PREV) { context.getUserData(COMBINED_DIFF_MAIN_UI)?.notifyMessage(e, true) viewer.iterationState = IterationState.PREV return } viewer.goToPrevChange(true) viewer.iterationState = IterationState.NONE } } internal class CombinedToggleExpandByDefaultAction(private val textSettings: TextDiffSettingsHolder.TextDiffSettings, private val foldingModels: () -> List<FoldingModelSupport>) : ToggleActionButton(message("collapse.unchanged.fragments"), null), DumbAware { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun isVisible(): Boolean = textSettings.contextRange != -1 override fun isSelected(e: AnActionEvent): Boolean = !textSettings.isExpandByDefault override fun setSelected(e: AnActionEvent, state: Boolean) { val expand = !state if (textSettings.isExpandByDefault == expand) return textSettings.isExpandByDefault = expand expandAll(expand) } private fun expandAll(expand: Boolean) { foldingModels().forEach { it.expandAll(expand) } } } internal class CombinedIgnorePolicySettingAction(settings: TextDiffSettingsHolder.TextDiffSettings) : TextDiffViewerUtil.IgnorePolicySettingAction(settings, *SmartTextDiffProvider.IGNORE_POLICIES) internal class CombinedHighlightPolicySettingAction(settings: TextDiffSettingsHolder.TextDiffSettings) : TextDiffViewerUtil.HighlightPolicySettingAction(settings, *SmartTextDiffProvider.HIGHLIGHT_POLICIES) internal class CombinedEditorSettingsAction(private val settings: TextDiffSettingsHolder.TextDiffSettings, private val foldingModels: () -> List<FoldingModelSupport>, editors: () -> List<Editor>) : SetEditorSettingsAction(settings, editors) { init { templatePresentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true) } override fun getChildren(e: AnActionEvent?): Array<AnAction> { val editorSettingsGroup = ActionManager.getInstance().getAction(IdeActions.GROUP_DIFF_EDITOR_SETTINGS) val ignorePolicyGroup = CombinedIgnorePolicySettingAction(settings).actions.apply { add(Separator.create(message("option.ignore.policy.group.name")), Constraints.FIRST) } val highlightPolicyGroup = CombinedHighlightPolicySettingAction(settings).actions.apply { add(Separator.create(message("option.highlighting.policy.group.name")), Constraints.FIRST) } val actions = mutableListOf<AnAction>() actions.add(editorSettingsGroup) actions.add(CombinedToggleExpandByDefaultAction(settings, foldingModels)) actions.addAll(myActions) actions.add(Separator.getInstance()) actions.add(ignorePolicyGroup) actions.add(Separator.getInstance()) actions.add(highlightPolicyGroup) actions.add(Separator.getInstance()) actions.add(ActionManager.getInstance().getAction(IdeActions.ACTION_CONTEXT_HELP)) if (e != null && !e.place.endsWith(ActionPlaces.DIFF_RIGHT_TOOLBAR)) { val gutterGroup = ActionManager.getInstance().getAction(IdeActions.GROUP_DIFF_EDITOR_GUTTER_POPUP) as ActionGroup val result = arrayListOf(*gutterGroup.getChildren(e)) result.add(Separator.getInstance()) replaceOrAppend(result, editorSettingsGroup, DefaultActionGroup(actions)) return result.toTypedArray() } return actions.toTypedArray() } } internal class CombinedPrevNextFileAction(private val blockId: CombinedPathBlockId, private val toolbar: Component?, private val next: Boolean) : ToolbarLabelAction(), RightAlignedToolbarAction { private val text = message(if (next) "action.Combined.Diff.NextChange.text" else "action.Combined.Diff.PrevChange.text") init { ActionUtil.copyFrom(this, if (next) NextChangeAction.ID else PrevChangeAction.ID) templatePresentation.icon = null templatePresentation.text = HtmlBuilder().appendLink("", text).toString() templatePresentation.description = null //disable label tooltip } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun update(e: AnActionEvent) { val combinedDiffViewer = e.getData(COMBINED_DIFF_VIEWER) if (combinedDiffViewer == null) { e.presentation.isEnabledAndVisible = false return } val newPosition = if (next) combinedDiffViewer.nextBlockPosition() else combinedDiffViewer.prevBlockPosition() e.presentation.isVisible = newPosition != -1 } override fun actionPerformed(e: AnActionEvent) { val combinedDiffViewer = e.getData(COMBINED_DIFF_VIEWER) ?: return val newPosition = if (next) combinedDiffViewer.nextBlockPosition() else combinedDiffViewer.prevBlockPosition() if (newPosition != -1) { combinedDiffViewer.selectDiffBlock(newPosition, ScrollPolicy.DIFF_BLOCK) } } override fun createHyperlinkListener(): HyperlinkListener = object : HyperlinkAdapter() { override fun hyperlinkActivated(e: HyperlinkEvent) { val place = (toolbar as? ActionToolbarImpl)?.place ?: ActionPlaces.DIFF_TOOLBAR val event = AnActionEvent.createFromAnAction(this@CombinedPrevNextFileAction, e.inputEvent, place, ActionToolbar.getDataContextFor(toolbar)) actionPerformed(event) } } private fun CombinedDiffViewer.prevBlockPosition(): Int { val curPosition = curBlockPosition() return if (curPosition != -1 && curPosition >= 1) curPosition - 1 else -1 } private fun CombinedDiffViewer.nextBlockPosition(): Int { val curPosition = curBlockPosition() return if (curPosition != -1 && curPosition < diffBlocks.size - 1) curPosition + 1 else -1 } private fun CombinedDiffViewer.curBlockPosition(): Int = diffBlocksPositions[blockId] ?: -1 override fun isCopyable(): Boolean = true override fun getHyperlinkTooltip(): String = text } internal class CombinedOpenInEditorAction(private val path: FilePath) : OpenInEditorAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = DiffUtil.canNavigateToFile(e.project, path.virtualFile) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! findNavigatable(project)?.run { openEditor(project, this) } } private fun findNavigatable(project: Project?): Navigatable? { val file = path.virtualFile if (!DiffUtil.canNavigateToFile(project, file)) return null return PsiNavigationSupport.getInstance().createNavigatable(project!!, file!!, 0) } }
apache-2.0
7c68fc2a1b85f550dd18b6f6befa80a2
39.289941
122
0.738508
4.599122
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/model/YesNoModel.kt
1
1505
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.model import android.content.Context import org.jetbrains.anko.AnkoLogger import org.json.JSONArray import java.io.IOException import java.nio.charset.Charset /** * Created by abertschi on 01.09.17. */ @Deprecated("no longer needed") class YesNoModel(val context: Context) : AnkoLogger { var yes: List<String> = listOf() var no: List<String> = listOf() init { yes = loadJSONFromAsset("yes.json") no = loadJSONFromAsset("no.json") } fun getRandomYes(): String { return yes[(Math.random() * yes.size).toInt()] } fun getRandomNo(): String { return no[(Math.random() * no.size).toInt()] } fun loadJSONFromAsset(assetLocation: String): List<String> { var json: String? = null try { val stream = context.assets.open(assetLocation) val size = stream.available() val buffer = ByteArray(size) stream.read(buffer) stream.close() json = buffer.toString(Charset.defaultCharset()) val words = JSONArray(json) var result = ArrayList<String>() (0 until words.length()).mapTo(result) { words[it] as String } return result } catch (ex: IOException) { ex.printStackTrace() return listOf("") } } }
apache-2.0
efd9e5e68bce4d63d350f41426aa17c8
25.421053
74
0.606645
4.157459
false
false
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Float/MutableVec2.kt
1
20783
package glm data class MutableVec2(var x: Float, var y: Float) { // Initializes each element by evaluating init from 0 until 1 constructor(init: (Int) -> Float) : this(init(0), init(1)) operator fun get(idx: Int): Float = when (idx) { 0 -> x 1 -> y else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } operator fun set(idx: Int, value: Float) = when (idx) { 0 -> x = value 1 -> y = value else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun inc(): MutableVec2 = MutableVec2(x.inc(), y.inc()) operator fun dec(): MutableVec2 = MutableVec2(x.dec(), y.dec()) operator fun unaryPlus(): MutableVec2 = MutableVec2(+x, +y) operator fun unaryMinus(): MutableVec2 = MutableVec2(-x, -y) operator fun plus(rhs: MutableVec2): MutableVec2 = MutableVec2(x + rhs.x, y + rhs.y) operator fun minus(rhs: MutableVec2): MutableVec2 = MutableVec2(x - rhs.x, y - rhs.y) operator fun times(rhs: MutableVec2): MutableVec2 = MutableVec2(x * rhs.x, y * rhs.y) operator fun div(rhs: MutableVec2): MutableVec2 = MutableVec2(x / rhs.x, y / rhs.y) operator fun rem(rhs: MutableVec2): MutableVec2 = MutableVec2(x % rhs.x, y % rhs.y) operator fun plus(rhs: Float): MutableVec2 = MutableVec2(x + rhs, y + rhs) operator fun minus(rhs: Float): MutableVec2 = MutableVec2(x - rhs, y - rhs) operator fun times(rhs: Float): MutableVec2 = MutableVec2(x * rhs, y * rhs) operator fun div(rhs: Float): MutableVec2 = MutableVec2(x / rhs, y / rhs) operator fun rem(rhs: Float): MutableVec2 = MutableVec2(x % rhs, y % rhs) inline fun map(func: (Float) -> Float): MutableVec2 = MutableVec2(func(x), func(y)) fun toList(): List<Float> = listOf(x, y) // Predefined vector constants companion object Constants { val zero: MutableVec2 get() = MutableVec2(0f, 0f) val ones: MutableVec2 get() = MutableVec2(1f, 1f) val unitX: MutableVec2 get() = MutableVec2(1f, 0f) val unitY: MutableVec2 get() = MutableVec2(0f, 1f) } // Conversions to Float fun toVec(): Vec2 = Vec2(x, y) inline fun toVec(conv: (Float) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec2(): Vec2 = Vec2(x, y) inline fun toVec2(conv: (Float) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(z: Float = 0f): Vec3 = Vec3(x, y, z) inline fun toVec3(z: Float = 0f, conv: (Float) -> Float): Vec3 = Vec3(conv(x), conv(y), z) fun toVec4(z: Float = 0f, w: Float = 0f): Vec4 = Vec4(x, y, z, w) inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (Float) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w) // Conversions to Float fun toMutableVec(): MutableVec2 = MutableVec2(x, y) inline fun toMutableVec(conv: (Float) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec2(): MutableVec2 = MutableVec2(x, y) inline fun toMutableVec2(conv: (Float) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(z: Float = 0f): MutableVec3 = MutableVec3(x, y, z) inline fun toMutableVec3(z: Float = 0f, conv: (Float) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z) fun toMutableVec4(z: Float = 0f, w: Float = 0f): MutableVec4 = MutableVec4(x, y, z, w) inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (Float) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w) // Conversions to Double fun toDoubleVec(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble()) inline fun toDoubleVec(conv: (Float) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble()) inline fun toDoubleVec2(conv: (Float) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(z: Double = 0.0): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z) inline fun toDoubleVec3(z: Double = 0.0, conv: (Float) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z) fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z, w) inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Float) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble()) inline fun toMutableDoubleVec(conv: (Float) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble()) inline fun toMutableDoubleVec2(conv: (Float) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(z: Double = 0.0): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z) inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (Float) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z) fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z, w) inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (Float) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w) // Conversions to Int fun toIntVec(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec(conv: (Float) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec2(conv: (Float) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(z: Int = 0): IntVec3 = IntVec3(x.toInt(), y.toInt(), z) inline fun toIntVec3(z: Int = 0, conv: (Float) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z) fun toIntVec4(z: Int = 0, w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z, w) inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (Float) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w) // Conversions to Int fun toMutableIntVec(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec(conv: (Float) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec2(conv: (Float) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(z: Int = 0): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z) inline fun toMutableIntVec3(z: Int = 0, conv: (Float) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z) fun toMutableIntVec4(z: Int = 0, w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z, w) inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (Float) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w) // Conversions to Long fun toLongVec(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec(conv: (Float) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec2(conv: (Float) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(z: Long = 0L): LongVec3 = LongVec3(x.toLong(), y.toLong(), z) inline fun toLongVec3(z: Long = 0L, conv: (Float) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z) fun toLongVec4(z: Long = 0L, w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z, w) inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (Float) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w) // Conversions to Long fun toMutableLongVec(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec(conv: (Float) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec2(conv: (Float) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(z: Long = 0L): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z) inline fun toMutableLongVec3(z: Long = 0L, conv: (Float) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z) fun toMutableLongVec4(z: Long = 0L, w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z, w) inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (Float) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w) // Conversions to Short fun toShortVec(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec(conv: (Float) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec2(conv: (Float) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(z: Short = 0.toShort()): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z) inline fun toShortVec3(z: Short = 0.toShort(), conv: (Float) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z) fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z, w) inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Float) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w) // Conversions to Short fun toMutableShortVec(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec(conv: (Float) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec2(conv: (Float) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(z: Short = 0.toShort()): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z) inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (Float) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z) fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z, w) inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (Float) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w) // Conversions to Byte fun toByteVec(): ByteVec2 = ByteVec2(x.toByte(), y.toByte()) inline fun toByteVec(conv: (Float) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte()) inline fun toByteVec2(conv: (Float) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(z: Byte = 0.toByte()): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z) inline fun toByteVec3(z: Byte = 0.toByte(), conv: (Float) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z) fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z, w) inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Float) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w) // Conversions to Byte fun toMutableByteVec(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte()) inline fun toMutableByteVec(conv: (Float) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte()) inline fun toMutableByteVec2(conv: (Float) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(z: Byte = 0.toByte()): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z) inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (Float) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z) fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z, w) inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (Float) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w) // Conversions to Char fun toCharVec(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec(conv: (Float) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec2(conv: (Float) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec3(z: Char): CharVec3 = CharVec3(x.toChar(), y.toChar(), z) inline fun toCharVec3(z: Char, conv: (Float) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z) fun toCharVec4(z: Char, w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z, w) inline fun toCharVec4(z: Char, w: Char, conv: (Float) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w) // Conversions to Char fun toMutableCharVec(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec(conv: (Float) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec2(conv: (Float) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec3(z: Char): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z) inline fun toMutableCharVec3(z: Char, conv: (Float) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z) fun toMutableCharVec4(z: Char, w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z, w) inline fun toMutableCharVec4(z: Char, w: Char, conv: (Float) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w) // Conversions to Boolean fun toBoolVec(): BoolVec2 = BoolVec2(x != 0f, y != 0f) inline fun toBoolVec(conv: (Float) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0f, y != 0f) inline fun toBoolVec2(conv: (Float) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(z: Boolean = false): BoolVec3 = BoolVec3(x != 0f, y != 0f, z) inline fun toBoolVec3(z: Boolean = false, conv: (Float) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z) fun toBoolVec4(z: Boolean = false, w: Boolean = false): BoolVec4 = BoolVec4(x != 0f, y != 0f, z, w) inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Float) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec2 = MutableBoolVec2(x != 0f, y != 0f) inline fun toMutableBoolVec(conv: (Float) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0f, y != 0f) inline fun toMutableBoolVec2(conv: (Float) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(z: Boolean = false): MutableBoolVec3 = MutableBoolVec3(x != 0f, y != 0f, z) inline fun toMutableBoolVec3(z: Boolean = false, conv: (Float) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z) fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0f, y != 0f, z, w) inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (Float) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w) // Conversions to String fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec(conv: (Float) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Float) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z) inline fun toStringVec3(z: String = "", conv: (Float) -> String): StringVec3 = StringVec3(conv(x), conv(y), z) fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w) inline fun toStringVec4(z: String = "", w: String = "", conv: (Float) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w) // Conversions to String fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec(conv: (Float) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Float) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z) inline fun toMutableStringVec3(z: String = "", conv: (Float) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z) fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w) inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (Float) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w) // Conversions to T2 inline fun <T2> toTVec(conv: (Float) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec2(conv: (Float) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(z: T2, conv: (Float) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z) inline fun <T2> toTVec4(z: T2, w: T2, conv: (Float) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Float) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec2(conv: (Float) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(z: T2, conv: (Float) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z) inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (Float) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: MutableVec2 get() = MutableVec2(x, x) var xy: MutableVec2 get() = MutableVec2(x, y) set(value) { x = value.x y = value.y } var yx: MutableVec2 get() = MutableVec2(y, x) set(value) { y = value.x x = value.y } val yy: MutableVec2 get() = MutableVec2(y, y) val xxx: MutableVec3 get() = MutableVec3(x, x, x) val xxy: MutableVec3 get() = MutableVec3(x, x, y) val xyx: MutableVec3 get() = MutableVec3(x, y, x) val xyy: MutableVec3 get() = MutableVec3(x, y, y) val yxx: MutableVec3 get() = MutableVec3(y, x, x) val yxy: MutableVec3 get() = MutableVec3(y, x, y) val yyx: MutableVec3 get() = MutableVec3(y, y, x) val yyy: MutableVec3 get() = MutableVec3(y, y, y) val xxxx: MutableVec4 get() = MutableVec4(x, x, x, x) val xxxy: MutableVec4 get() = MutableVec4(x, x, x, y) val xxyx: MutableVec4 get() = MutableVec4(x, x, y, x) val xxyy: MutableVec4 get() = MutableVec4(x, x, y, y) val xyxx: MutableVec4 get() = MutableVec4(x, y, x, x) val xyxy: MutableVec4 get() = MutableVec4(x, y, x, y) val xyyx: MutableVec4 get() = MutableVec4(x, y, y, x) val xyyy: MutableVec4 get() = MutableVec4(x, y, y, y) val yxxx: MutableVec4 get() = MutableVec4(y, x, x, x) val yxxy: MutableVec4 get() = MutableVec4(y, x, x, y) val yxyx: MutableVec4 get() = MutableVec4(y, x, y, x) val yxyy: MutableVec4 get() = MutableVec4(y, x, y, y) val yyxx: MutableVec4 get() = MutableVec4(y, y, x, x) val yyxy: MutableVec4 get() = MutableVec4(y, y, x, y) val yyyx: MutableVec4 get() = MutableVec4(y, y, y, x) val yyyy: MutableVec4 get() = MutableVec4(y, y, y, y) } val swizzle: Swizzle get() = Swizzle() } fun mutableVecOf(x: Float, y: Float): MutableVec2 = MutableVec2(x, y) operator fun Float.plus(rhs: MutableVec2): MutableVec2 = MutableVec2(this + rhs.x, this + rhs.y) operator fun Float.minus(rhs: MutableVec2): MutableVec2 = MutableVec2(this - rhs.x, this - rhs.y) operator fun Float.times(rhs: MutableVec2): MutableVec2 = MutableVec2(this * rhs.x, this * rhs.y) operator fun Float.div(rhs: MutableVec2): MutableVec2 = MutableVec2(this / rhs.x, this / rhs.y) operator fun Float.rem(rhs: MutableVec2): MutableVec2 = MutableVec2(this % rhs.x, this % rhs.y)
mit
b290cd138281c4657173351946182645
69.690476
166
0.651398
3.407049
false
false
false
false
xamarin/XamarinComponents
Util/Xamarin.Kotlin.BindingSupport/native/src/main/kotlin/xamarin/binding/kotlin/bindingsupport/ProcessXmlCommand.kt
2
1660
@file:Suppress("RemoveCurlyBracesFromTemplate") package xamarin.binding.kotlin.bindingsupport import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.* import java.io.File class ProcessXmlCommand : CliktCommand(name = "KotlinBindingSupport") { val xmlFile: File by option("-x", "--xml", help = "path to the generated api.xml file") .file(exists = true) .required() val jarFiles: List<File> by option("-j", "--jar", help = "paths to the various .jar files being bound") .file(exists = true) .multiple(required = true) val outputFile: File? by option("-o", "--output", help = "path to the output transform file") .file(fileOkay = true, folderOkay = false) val ignoreFiles: List<File> by option("-i", "--ignore", help = "paths to the ignore files") .file(exists = true) .multiple() val companions: Processor.CompanionProcessing by option("--companions", help = "indicate how to handle companions") .choice( "default" to Processor.CompanionProcessing.Default, "rename" to Processor.CompanionProcessing.Rename, "remove" to Processor.CompanionProcessing.Remove ) .default(Processor.CompanionProcessing.Default) val verbose: Boolean by option("-v", "--verbose", help = "output verbose information") .flag(default = false) override fun run() { val proc = Processor(xmlFile, jarFiles, outputFile, ignoreFiles) proc.verbose = verbose proc.companions = companions proc.process() } }
mit
d4d6e79720cae532444ae5e3e29bcb60
36.727273
119
0.666265
4.18136
false
false
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/utils/extensions/MapExt.kt
1
932
package blue.aodev.animeultimetv.utils.extensions fun <K, V> mapOf(pairs: List<Pair<K, V>>): Map<K, V> { return if (pairs.isNotEmpty()) { linkedMapOf(*pairs.toTypedArray()) } else { emptyMap() } } fun <K, V> Map<K, V>.sliceIfPresent(keys: List<K>): List<V> { val result = ArrayList<V>(keys.size) keys.forEach { key -> val value = this[key] if (value != null) result.add(value) } return result } fun <K, V> Map<K, V>.sliceOrNull(keys: List<K>): List<V?> { val result = ArrayList<V>(keys.size) keys.forEach { key -> val value = this[key] if (value != null) result.add(value) } return result } fun <K, V> Map<K, V>.sliceOrDefault(keys: List<K>, default: V): List<V> { val result = ArrayList<V>(keys.size) keys.forEach { key -> val value = this.getOrDefault(key, default) result.add(value) } return result }
mit
1fa7167818bdd2fda964e1a434eaf3f6
24.888889
73
0.582618
3.191781
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/dataset/internal/DataSetCompleteRegistrationCall.kt
1
3892
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.dataset.internal import dagger.Reusable import io.reactivex.Observable import io.reactivex.Single import java.util.ArrayList import javax.inject.Inject import org.hisp.dhis.android.core.arch.call.factories.internal.QueryCall import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper.commaSeparatedCollectionValues import org.hisp.dhis.android.core.arch.helpers.internal.MultiDimensionalPartitioner import org.hisp.dhis.android.core.dataset.DataSetCompleteRegistration @Reusable internal class DataSetCompleteRegistrationCall @Inject constructor( private val service: DataSetCompleteRegistrationService, private val multiDimensionalPartitioner: MultiDimensionalPartitioner, private val processor: DataSetCompleteRegistrationCallProcessor ) : QueryCall<DataSetCompleteRegistration, DataSetCompleteRegistrationQuery> { companion object { private const val QUERY_WITHOUT_UIDS_LENGTH = ( "completeDataSetRegistrations?fields=period,dataSet,organisationUnit,attributeOptionCombo,date,storedBy" + "&dataSet=&period=&orgUnit&children=true&paging=false" ).length } override fun download(query: DataSetCompleteRegistrationQuery): Single<List<DataSetCompleteRegistration>> { return downloadInternal(query).doOnSuccess { registrations -> processor.process(registrations, query) } } private fun downloadInternal(query: DataSetCompleteRegistrationQuery): Single<List<DataSetCompleteRegistration>> { val partitions = multiDimensionalPartitioner.partitionForSize( QUERY_WITHOUT_UIDS_LENGTH, query.dataSetUids(), query.periodIds(), query.rootOrgUnitUids() ) return Observable.fromIterable(partitions).flatMapSingle { part -> service.getDataSetCompleteRegistrations( DataSetCompleteRegistrationFields.allFields, query.lastUpdatedStr(), commaSeparatedCollectionValues(part[0]), commaSeparatedCollectionValues(part[1]), commaSeparatedCollectionValues(part[2]), true, false ) }.map { it.dataSetCompleteRegistrations } .reduce(ArrayList(), { t1, t2 -> t1 + t2 }) } }
bsd-3-clause
aa01281613cb33c2463391b011f678e0
48.265823
118
0.743577
4.828784
false
false
false
false
mdanielwork/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/GradleLauncher.kt
7
2461
package com.intellij.testGuiFramework.launcher import com.intellij.testGuiFramework.impl.GuiTestStarter.Companion.COMMAND_NAME import com.intellij.testGuiFramework.launcher.system.SystemInfo import com.intellij.testGuiFramework.remote.IdeControl import org.apache.log4j.Logger import java.io.BufferedReader import java.io.InputStreamReader import kotlin.concurrent.thread object GradleLauncher { val LOG: Logger = Logger.getLogger(GradleLauncher::class.java) fun runIde(port: Int) { val composedArgs = composeCommandLineArgs(port) LOG.info("Composed command line to run IDE: $composedArgs") val process = ProcessBuilder().inheritIO().command(composedArgs).start() IdeControl.submitIdeProcess(process) val stdInput = BufferedReader(InputStreamReader(process.inputStream)) val stdError = BufferedReader(InputStreamReader(process.errorStream)) thread(start = true, name = "processStdIn") { processStdIn(stdInput) } thread(start = true, name = "processStdErr") { processStdErr(stdError) } } private val gradleWrapper: String by lazy { return@lazy if (SystemInfo.isWin()) "gradlew.bat" else "./gradlew" } private fun composeCommandLineArgs(port: Int): MutableList<String> { val result = mutableListOf<String>() return with(result) { add("$gradleWrapper") add("runIde") if (GuiTestOptions.isDebug) add("--debug-jvm") if (GuiTestOptions.isPassPrivacyPolicy) add("-Djb.privacy.policy.text=\"<!--999.999-->\"") if (GuiTestOptions.isPassDataSharing) add("-Djb.consents.confirmation.enabled=false") addIdeaAndJbProperties() add("-Dexec.args=$COMMAND_NAME,port=$port") this } } private fun MutableList<String>.addIdeaAndJbProperties() { System.getProperties().filter { val s = it.key as String s.startsWith("idea") || s.startsWith("jb") }.forEach{ this.add("-D${it.key}=${it.value}") } } private fun String.quoteValueIfHasSpaces(): String { return if (Regex("\\s").containsMatchIn(this)) return "\"$this\"" else this } private fun processStdIn(stdInput: BufferedReader) { var s: String? = stdInput.readLine() while (s != null) { LOG.info("[IDE output]: $s") s = stdInput.readLine() } } private fun processStdErr(stdInput: BufferedReader) { var s: String? = stdInput.readLine() while (s != null) { LOG.warn("[IDE warn]: $s") s = stdInput.readLine() } } }
apache-2.0
38c5c45f150f4602203da298c32dfed3
32.27027
96
0.697278
4.014682
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ConstructorConversion.kt
6
1720
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.tree.* class ConstructorConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKMethod) return recurse(element) val outerClass = element.parentOfType<JKClass>() ?: return recurse(element) if (element.name.value != outerClass.name.value) return recurse(element) element.invalidate() val delegationCall = lookupDelegationCall(element.block) ?: JKStubExpression() return JKConstructorImpl( element.name, element.parameters, element.block, delegationCall, element.annotationList, element.otherModifierElements, element.visibilityElement, element.modalityElement ).also { symbolProvider.transferSymbol(it, element) }.withFormattingFrom(element) } private fun lookupDelegationCall(block: JKBlock): JKDelegationConstructorCall? { val firstStatement = block.statements.firstOrNull() ?: return null val expressionStatement = firstStatement as? JKExpressionStatement ?: return null val expression = expressionStatement.expression as? JKDelegationConstructorCall ?: return null block.statements -= expressionStatement expressionStatement.invalidate() return expression } }
apache-2.0
24196ba3b3c65d7e30ca4e7e59c95156
42.025
158
0.711628
5.325077
false
false
false
false
kdwink/intellij-community
platform/configuration-store-impl/src/StoreAwareProjectManager.kt
1
10385
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.runBatchUpdate import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.* import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.ex.VirtualFileManagerAdapter import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent import com.intellij.util.SingleAlarm import com.intellij.util.containers.MultiMap import gnu.trove.THashSet import org.jetbrains.annotations.TestOnly import java.util.* import java.util.concurrent.atomic.AtomicInteger /** * Should be a separate service, not closely related to ProjectManager, but it requires some cleanup/investigation. */ class StoreAwareProjectManager(virtualFileManager: VirtualFileManager, progressManager: ProgressManager) : ProjectManagerImpl(progressManager) { companion object { private val CHANGED_FILES_KEY = Key.create<MultiMap<ComponentStoreImpl, StateStorage>>("CHANGED_FILES_KEY") } private val reloadBlockCount = AtomicInteger() private val changedApplicationFiles = LinkedHashSet<StateStorage>() private val restartApplicationOrReloadProjectTask = Runnable { if (isReloadUnblocked() && tryToReloadApplication()) { val projectsToReload = THashSet<Project>() for (project in openProjects) { if (project.isDisposed) { continue } val changes = CHANGED_FILES_KEY.get(project) ?: continue CHANGED_FILES_KEY.set(project, null) if (!changes.isEmpty) { runBatchUpdate(project.messageBus) { for ((store, storages) in changes.entrySet()) { if ((store.storageManager as? StateStorageManagerImpl)?.componentManager?.isDisposed ?: false) { continue } @Suppress("UNCHECKED_CAST") if (reloadStore(storages as Set<StateStorage>, store, false) == ReloadComponentStoreStatus.RESTART_AGREED) { projectsToReload.add(project) } } } } } for (project in projectsToReload) { ProjectManagerImpl.doReloadProject(project) } } } private val changedFilesAlarm = SingleAlarm(restartApplicationOrReloadProjectTask, 300, this) init { ApplicationManager.getApplication().messageBus.connect().subscribe(StateStorageManager.STORAGE_TOPIC, object : StorageManagerListener() { override fun storageFileChanged(event: VFileEvent, storage: StateStorage, componentManager: ComponentManager) { if (event is VFilePropertyChangeEvent) { // ignore because doesn't affect content return } if (event.requestor is StateStorage.SaveSession || event.requestor is StateStorage || event.requestor is ProjectManagerImpl) { return } registerChangedStorage(storage, componentManager) } }) virtualFileManager.addVirtualFileManagerListener(object : VirtualFileManagerAdapter() { override fun beforeRefreshStart(asynchronous: Boolean) { blockReloadingProjectOnExternalChanges() } override fun afterRefreshFinish(asynchronous: Boolean) { unblockReloadingProjectOnExternalChanges() } }) } private fun isReloadUnblocked(): Boolean { val count = reloadBlockCount.get() LOG.debug { "[RELOAD] myReloadBlockCount = $count" } return count == 0 } override fun saveChangedProjectFile(file: VirtualFile, project: Project) { val storageManager = (project.stateStore as ComponentStoreImpl).storageManager as? StateStorageManagerImpl ?: return storageManager.getCachedFileStorages(listOf(storageManager.collapseMacros(file.path))).firstOrNull()?.let { // if empty, so, storage is not yet loaded, so, we don't have to reload registerChangedStorage(it, project) } } override fun blockReloadingProjectOnExternalChanges() { reloadBlockCount.incrementAndGet() } override fun unblockReloadingProjectOnExternalChanges() { assert(reloadBlockCount.get() > 0) if (reloadBlockCount.decrementAndGet() == 0 && changedFilesAlarm.isEmpty) { if (ApplicationManager.getApplication().isUnitTestMode) { // todo fix test to handle invokeLater changedFilesAlarm.request(true) } else { ApplicationManager.getApplication().invokeLater(restartApplicationOrReloadProjectTask, ModalityState.NON_MODAL) } } } @TestOnly fun flushChangedAlarm() { changedFilesAlarm.flush() } override fun reloadProject(project: Project) { CHANGED_FILES_KEY.set(project, null) super.reloadProject(project) } private fun registerChangedStorage(storage: StateStorage, componentManager: ComponentManager) { if (LOG.isDebugEnabled) { LOG.debug("[RELOAD] Registering project to reload: $storage", Exception()) } val project: Project? = when (componentManager) { is Project -> componentManager is Module -> componentManager.project else -> null } if (project == null) { val changes = changedApplicationFiles synchronized (changes) { changes.add(storage) } } else { var changes = CHANGED_FILES_KEY.get(project) if (changes == null) { changes = MultiMap.createLinkedSet() CHANGED_FILES_KEY.set(project, changes) } synchronized (changes) { changes.putValue(componentManager.stateStore as ComponentStoreImpl, storage) } } if (storage is StateStorageBase<*>) { storage.disableSaving() } if (isReloadUnblocked()) { changedFilesAlarm.cancelAndRequest() } } private fun tryToReloadApplication(): Boolean { if (ApplicationManager.getApplication().isDisposed) { return false } if (changedApplicationFiles.isEmpty()) { return true } val changes = LinkedHashSet<StateStorage>(changedApplicationFiles) changedApplicationFiles.clear() val status = reloadStore(changes, ApplicationManager.getApplication().stateStore as ComponentStoreImpl, true) if (status == ReloadComponentStoreStatus.RESTART_AGREED) { ApplicationManagerEx.getApplicationEx().restart(true) return false } else { return status == ReloadComponentStoreStatus.SUCCESS || status == ReloadComponentStoreStatus.RESTART_CANCELLED } } } private fun reloadStore(changedStorages: Set<StateStorage>, store: ComponentStoreImpl, isApp: Boolean): ReloadComponentStoreStatus { val notReloadableComponents: Collection<String>? var willBeReloaded = false try { try { notReloadableComponents = store.reload(changedStorages) } catch (e: Throwable) { LOG.warn(e) Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.message), ProjectBundle.message("project.reload.failed.title")) return ReloadComponentStoreStatus.ERROR } if (notReloadableComponents == null || notReloadableComponents.isEmpty()) { return ReloadComponentStoreStatus.SUCCESS } willBeReloaded = askToRestart(store, notReloadableComponents, changedStorages, isApp) return if (willBeReloaded) ReloadComponentStoreStatus.RESTART_AGREED else ReloadComponentStoreStatus.RESTART_CANCELLED } finally { if (!willBeReloaded) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.enableSaving() } } } } } // used in settings repository plugin fun askToRestart(store: IComponentStore, notReloadableComponents: Collection<String>, changedStorages: Set<StateStorage>?, isApp: Boolean): Boolean { val message = StringBuilder() val storeName = if (store is IProjectStore) "Project '${store.projectName}'" else "Application" message.append(storeName).append(' ') message.append("components were changed externally and cannot be reloaded:\n\n") var count = 0 for (component in notReloadableComponents) { if (count == 10) { message.append('\n').append("and ").append(notReloadableComponents.size - count).append(" more").append('\n') } else { message.append(component).append('\n') count++ } } message.append("\nWould you like to ") if (isApp) { message.append(if (ApplicationManager.getApplication().isRestartCapable) "restart" else "shutdown").append(' ') message.append(ApplicationNamesInfo.getInstance().productName).append('?') } else { message.append("reload project?") } if (Messages.showYesNoDialog(message.toString(), "$storeName Files Changed", Messages.getQuestionIcon()) == Messages.YES) { if (changedStorages != null) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.disableSaving() } } } return true } return false } public enum class ReloadComponentStoreStatus { RESTART_AGREED, RESTART_CANCELLED, ERROR, SUCCESS }
apache-2.0
893bd97f19639ee3fc6214a8d9f82d68
34.20678
149
0.719403
5.004819
false
true
false
false
orauyeu/SimYukkuri
subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/event/action/actions/Poop.kt
1
2025
package simyukkuri.gameobject.yukkuri.event.action.actions import simyukkuri.Time import simyukkuri.gameobject.yukkuri.event.IndividualEvent import simyukkuri.gameobject.yukkuri.event.action.Action import simyukkuri.gameobject.yukkuri.event.action.MultipleAction import simyukkuri.gameobject.yukkuri.event.action.Posture import simyukkuri.gameobject.yukkuri.statistic.YukkuriStats import simyukkuri.gameobject.yukkuri.statistic.statistics.Emotion /** うんうんをするアクション. ゲスの場合うんうんをした後ふりふりする. */ class Poop(self: YukkuriStats) : MultipleAction() { override var currentAction: Action = PoopImpl(self) } /** うんうんをするアクション. ゲスの場合うんうんをした後ふりふりする. */ private class PoopImpl(val self: YukkuriStats) : Action { override var hasEnded: Boolean = false /** うんうん一回あたりにかかる時間 */ private val unitPoopTime = 2f private var elapsedPoopTime = 0f override var currentAction: Action = this private set override fun execute() { self.says(self.msgList.hasPooped, Time.UNIT) elapsedPoopTime += Time.UNIT if (elapsedPoopTime < unitPoopTime) return self.pooParam -= self.unitPoo elapsedPoopTime = 0f if (self.isBaby) { self.isDirty = true self.feels(Emotion.Happiness.SAD) } if (self.hasWrapper) { self.isDirty = true self.feels(Emotion.Happiness.SAD) } else { // TODO: うんうんをSceneに追加する処理. } if (self.pooParam < self.unitPoo) hasEnded = true if (self.willFurifuri()) currentAction = Furifuri() } override fun interrupt() = Unit override fun isTheSameAs(other: IndividualEvent): Boolean = other is Poop override val posture: Posture get() = Posture.SHOW_ANUS }
apache-2.0
4007f36924e633d9270fa093a228603d
29.338983
77
0.660531
3.538314
false
false
false
false
vladmm/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.kt
1
19876
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.editor.Document import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.util.Consumer import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.xdebugger.XSourcePositionWrapper import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation import com.intellij.xdebugger.frame.presentation.XStringValuePresentation import com.intellij.xdebugger.frame.presentation.XValuePresentation import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.values.* import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.regex.Pattern import javax.swing.Icon fun VariableView(variable: Variable, context: VariableContext) = VariableView(variable.name, variable, context) class VariableView(name: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(name), VariableContext { @Volatile private var value: Value? = null // lazy computed private var memberFilter: MemberFilter? = null @Volatile private var remainingChildren: List<Variable>? = null @Volatile private var remainingChildrenOffset: Int = 0 override fun watchableAsEvaluationExpression() = context.watchableAsEvaluationExpression() override fun getViewSupport() = context.viewSupport override fun getParent() = context override fun getMemberFilter(): Promise<MemberFilter> { return context.viewSupport.getMemberFilter(this) } override fun computePresentation(node: XValueNode, place: XValuePlace) { value = variable.value if (value != null) { computePresentation(value!!, node) return } if (variable !is ObjectProperty || variable.getter == null) { // it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables) evaluateContext.evaluate(variable.name) .done(node) { if (it.wasThrown) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(value, null), null, node) } else { value = it.value computePresentation(it.value, node) } } .rejected(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.getMessage()), it.getMessage(), node) } return } node.setPresentation(null, object : XValuePresentation() { override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderValue("\u2026") } }, false) node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { val valueModifier = variable.valueModifier assert(valueModifier != null) valueModifier!!.evaluateGet(variable, evaluateContext) .done(node) { callback.evaluated("") setEvaluatedValue(it, null, node) } } }.setShowValuePopup(false)) } private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) { if (value == null) { node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false) } else { this.value = value computePresentation(value, node) } } private fun computePresentation(value: Value, node: XValueNode) { when (value.type) { ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon) ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true) ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon) ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false) ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false) ValueType.STRING -> { node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false) // isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation), // so, even in case of StringValue, we check value string length if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) { node.setFullValueEvaluator(MyFullValueEvaluator(value)) } } else -> node.setPresentation(icon, null, value.valueString!!, true) } } override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) if (value !is ObjectValue) { node.addChildren(XValueChildrenList.EMPTY, true) return } val list = remainingChildren if (list != null) { val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size) val isLast = to == list.size node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, memberFilter), isLast) if (!isLast) { node.tooManyChildren(list.size - to) remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW } return } val objectValue = value as ObjectValue val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO val promises = SmartList<Promise<*>>() val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node) if (additionalProperties != null) { promises.add(additionalProperties) } // we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified if (hasIndexedProperties) { promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null)) } if (hasNamedProperties) { // named properties should be added after additional properties if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) { promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null)) } else { promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) }) } } if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) { Promise.all(promises).processed(object : ObsolescentConsumer<Any?>(node) { override fun consume(aVoid: Any?) = node.addChildren(XValueChildrenList.EMPTY, true) }) } } abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() { override fun isObsolete() = node.isObsolete } private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> { return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) { override fun consumeRanges(ranges: IntArray?) { if (ranges == null) { val groupList = XValueChildrenList() LazyVariablesGroup.addGroups(value, LazyVariablesGroup.GROUP_FACTORY, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView) node.addChildren(groupList, isLastChildren) } else { LazyVariablesGroup.addRanges(value, ranges, node, this@VariableView, isLastChildren) } } override fun consumeVariables(variables: List<Variable>) { node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren) } }, null) } private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables -> [email protected] = memberFilter if (value.type == ValueType.ARRAY && value !is ArrayValue) { computeArrayRanges(variables, node) return@processVariables } var functionValue = value as? FunctionValue if (functionValue != null && functionValue.hasScopes() == ThreeState.NO) { functionValue = null } remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null) if (remainingChildren != null) { remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW } if (functionValue != null) { // we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren) } } private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) { val variables = filterAndSort(properties, memberFilter!!) var count = variables.size val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW if (count <= bucketSize) { node.addChildren(createVariablesList(variables, this, null), true) return } while (count > 0) { if (Character.isDigit(variables.get(count - 1).name[0])) { break } count-- } val groupList = XValueChildrenList() if (count > 0) { LazyVariablesGroup.addGroups(variables, VariablesGroup.GROUP_FACTORY, groupList, 0, count, bucketSize, this) } var notGroupedVariablesOffset: Int if ((variables.size - count) > bucketSize) { notGroupedVariablesOffset = variables.size while (notGroupedVariablesOffset > 0) { if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) { break } notGroupedVariablesOffset-- } if (notGroupedVariablesOffset > 0) { LazyVariablesGroup.addGroups(variables, VariablesGroup.GROUP_FACTORY, groupList, count, notGroupedVariablesOffset, bucketSize, this) } } else { notGroupedVariablesOffset = count } for (i in notGroupedVariablesOffset..variables.size - 1) { val variable = variables.get(i) groupList.add(VariableView(memberFilter!!.rawNameToSource(variable), variable, this)) } node.addChildren(groupList, true) } private val icon: Icon get() = getIcon(value!!) override fun getModifier(): XValueModifier? { if (!variable.isMutable) { return null } return object : XValueModifier() { override fun getInitialValueEditorText(): String? { if (value!!.type == ValueType.STRING) { val string = value!!.valueString!! val builder = StringBuilder(string.length) builder.append('"') StringUtil.escapeStringCharacters(string.length, string, builder) builder.append('"') return builder.toString() } else { return if (value!!.type.isObjectType) null else value!!.valueString } } override fun setValue(expression: String, callback: XValueModifier.XModificationCallback) { variable.valueModifier!!.setValue(variable, expression, evaluateContext) .done(Consumer<Any?> { value = null callback.valueModified() }) .rejected(createErrorMessageConsumer(callback)) } } } override fun getEvaluateContext() = context.evaluateContext fun getValue() = variable.value override fun canNavigateToSource() = value is FunctionValue || viewSupport.canNavigateToSource(variable, context) override fun computeSourcePosition(navigatable: XNavigatable) { if (value is FunctionValue) { (value as FunctionValue).resolve() .done { function -> viewSupport.vm!!.scriptManager.getScript(function) .done { val position = if (it == null) null else viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) navigatable.setSourcePosition(if (position == null) null else object : XSourcePositionWrapper(position) { override fun createNavigatable(project: Project): Navigatable { val result = PsiVisitors.visit(myPosition, project, object : PsiVisitors.Visitor<Navigatable>() { override fun visit(element: PsiElement, positionOffset: Int, document: Document): Navigatable? { // element will be "open paren", but we should navigate to function name, // we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression) var referenceCandidate: PsiElement? = element var psiReference: PsiElement? = null while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } if (psiReference == null) { referenceCandidate = element.parent while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } } return (if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable } }, null) return result ?: super.createNavigatable(project) } }) } } } else { viewSupport.computeSourcePosition(name, value!!, variable, context, navigatable) } } override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback) = viewSupport.computeInlineDebuggerData(name, variable, context, callback) override fun getEvaluationExpression(): String? { if (!watchableAsEvaluationExpression()) { return null } val list = SmartList(variable.name) var parent: VariableContext? = context while (parent != null && parent.name != null) { list.add(parent.name!!) parent = parent.parent } return context.viewSupport.propertyNamesToString(list, false) } private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { if (value !is StringValue || !value.isTruncated) { callback.evaluated(value.valueString!!) return } val evaluated = AtomicBoolean() value.fullString .done { if (!callback.isObsolete && evaluated.compareAndSet(false, true)) { callback.evaluated(value.valueString!!) } } .rejected(createErrorMessageConsumer(callback)) } } override fun getScope() = context.scope companion object { fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) { node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO) } fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) { assert(value.type == ValueType.ARRAY) if (value is ArrayValue) { val length = value.length node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0) return } val valueString = value.valueString // only WIP reports normal description if (valueString != null && valueString.endsWith("]") && ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) { node.setPresentation(icon, null, valueString, true) } else { context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false) .done(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) } .rejected(node) { node.setPresentation(icon, null, "Internal error: $it", false) } } } fun getIcon(value: Value): Icon { val type = value.type return when (type) { ValueType.FUNCTION -> AllIcons.Nodes.Function ValueType.ARRAY -> AllIcons.Debugger.Db_array else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive } } } } fun getClassName(value: ObjectValue): String { val className = value.className return if (className.isNullOrEmpty()) "Object" else className!! } fun getObjectValueDescription(value: ObjectValue): String { val description = value.valueString return if (description.isNullOrEmpty()) getClassName(value) else description!! } internal fun trimFunctionDescription(value: Value): String { val presentableValue = value.valueString ?: return "" var endIndex = 0 while (endIndex < presentableValue.length && !StringUtil.isLineBreak(presentableValue[endIndex])) { endIndex++ } while (endIndex > 0 && Character.isWhitespace(presentableValue[endIndex - 1])) { endIndex-- } return presentableValue.substring(0, endIndex) } private fun createNumberPresentation(value: String): XValuePresentation { return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value) } private fun createErrorMessageConsumer(callback: XValueCallback): Consumer<Throwable> { return object : Consumer<Throwable> { override fun consume(error: Throwable) { callback.errorOccurred(error.getMessage()!!) } } } private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+\\[\\d+\\]$") private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() { private val length = Integer.toString(length) private val className = if (className.isNullOrEmpty()) "Array" else className!! override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderSpecialSymbol(className) renderer.renderSpecialSymbol("[") renderer.renderSpecialSymbol(length) renderer.renderSpecialSymbol("]") } }
apache-2.0
b5c002312c7eb2cf94f4a947452990d7
39.31643
181
0.685349
5.12929
false
false
false
false
vladmm/intellij-community
plugins/settings-repository/src/autoSync.kt
11
5935
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.configurationStore.ComponentStoreImpl import com.intellij.notification.Notification import com.intellij.notification.Notifications import com.intellij.notification.NotificationsAdapter import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationAdapter import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.stateStore import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.ShutDownTracker import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import java.util.concurrent.Future internal class AutoSyncManager(private val icsManager: IcsManager) { private @Volatile var autoSyncFuture: Future<*>? = null fun waitAutoSync(indicator: ProgressIndicator) { val autoFuture = autoSyncFuture if (autoFuture != null) { if (autoFuture.isDone) { autoSyncFuture = null } else if (autoSyncFuture != null) { LOG.info("Wait for auto sync future") indicator.text = "Wait for auto sync completion" while (!autoFuture.isDone) { if (indicator.isCanceled) { return } Thread.sleep(5) } } } } fun registerListeners(application: Application) { application.addApplicationListener(object : ApplicationAdapter() { override fun applicationExiting() { autoSync(true) } }) } fun registerListeners(project: Project) { project.messageBus.connect().subscribe(Notifications.TOPIC, object : NotificationsAdapter() { override fun notify(notification: Notification) { if (!icsManager.repositoryActive || project.isDisposed) { return } if (when { notification.groupId == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.displayId -> { val message = notification.content message.startsWith("VCS Update Finished") || message == VcsBundle.message("message.text.file.is.up.to.date") || message == VcsBundle.message("message.text.all.files.are.up.to.date") } notification.groupId == VcsNotifier.NOTIFICATION_GROUP_ID.displayId && notification.title == "Push successful" -> true else -> false }) { autoSync() } } }) } fun autoSync(onAppExit: Boolean = false, force: Boolean = false) { if (!icsManager.repositoryActive || (!force && !icsManager.settings.autoSync)) { return } var future = autoSyncFuture if (future != null && !future.isDone) { return } val app = ApplicationManagerEx.getApplicationEx() as ApplicationImpl if (onAppExit) { sync(app, onAppExit) return } else if (app.isDisposeInProgress) { // will be handled by applicationExiting listener return } future = app.executeOnPooledThread { if (autoSyncFuture == future) { // to ensure that repository will not be in uncompleted state and changes will be pushed ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread()) try { sync(app, onAppExit) } finally { autoSyncFuture = null ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread()) } } } autoSyncFuture = future } private fun sync(app: ApplicationImpl, onAppExit: Boolean) { catchAndLog { icsManager.runInAutoCommitDisabledMode { val repositoryManager = icsManager.repositoryManager if (!repositoryManager.canCommit()) { LOG.warn("Auto sync skipped: repository is not committable") return@runInAutoCommitDisabledMode } // on app exit fetch and push only if there are commits to push if (onAppExit && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0) { return@runInAutoCommitDisabledMode } val updater = repositoryManager.fetch() // we merge in EDT non-modal to ensure that new settings will be properly applied app.invokeAndWait({ catchAndLog { val updateResult = updater.merge() if (!onAppExit && !app.isDisposeInProgress && updateResult != null && updateStoragesFromStreamProvider(app.stateStore as ComponentStoreImpl, updateResult, app.messageBus)) { // force to avoid saveAll & confirmation app.exit(true, true, true, true) } } }, ModalityState.NON_MODAL) if (!updater.definitelySkipPush) { repositoryManager.push() } } } } } inline internal fun catchAndLog(runnable: () -> Unit) { try { runnable() } catch (e: ProcessCanceledException) { } catch (e: Throwable) { if (e is AuthenticationException || e is NoRemoteRepositoryException) { LOG.warn(e) } else { LOG.error(e) } } }
apache-2.0
05e08f348dc108bc5b5b64014d6da2e9
32.536723
185
0.677843
4.81737
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/domain/service/DiffService.kt
1
1039
package hamburg.remme.tinygit.domain.service import hamburg.remme.tinygit.Refreshable import hamburg.remme.tinygit.Service import hamburg.remme.tinygit.domain.Commit import hamburg.remme.tinygit.domain.File import hamburg.remme.tinygit.domain.Repository import hamburg.remme.tinygit.git.gitDiff @Service class DiffService : Refreshable { private val renderer = DiffRenderer() private lateinit var repository: Repository fun diff(file: File, contextLines: Int): String { val rawDiff = gitDiff(repository, file, contextLines) return renderer.render(rawDiff) } fun diff(file: File, commit: Commit, contextLines: Int): String { val rawDiff = gitDiff(repository, file, commit, contextLines) return renderer.render(rawDiff) } override fun onRefresh(repository: Repository) { this.repository = repository } override fun onRepositoryChanged(repository: Repository) { this.repository = repository } override fun onRepositoryDeselected() { } }
bsd-3-clause
866438a15f44be86f9a42518d45404f7
27.081081
69
0.729548
4.311203
false
false
false
false
google/intellij-community
jvm/jvm-analysis-api/src/com/intellij/codeInspection/analysisUastUtil.kt
5
1656
// 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.codeInspection import com.intellij.psi.LambdaUtil import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil import org.jetbrains.uast.* fun ULambdaExpression.getReturnType(): PsiType? { val lambdaType = functionalInterfaceType ?: getExpressionType() ?: uastParent?.let { when (it) { is UVariable -> it.type // in Kotlin local functions looks like lambda stored in variable is UCallExpression -> it.getParameterForArgument(this)?.type else -> null } } return LambdaUtil.getFunctionalInterfaceReturnType(lambdaType) } fun UAnnotated.findAnnotations(vararg fqNames: String) = uAnnotations.filter { ann -> fqNames.contains(ann.qualifiedName) } /** * Gets all classes in this file, including inner classes. */ fun UFile.allClasses() = classes.toTypedArray() + classes.flatMap { it.allInnerClasses().toList() } fun UClass.allInnerClasses(): Array<UClass> = innerClasses + innerClasses.flatMap { it.allInnerClasses().toList() } fun UClass.isAnonymousOrLocal(): Boolean = this is UAnonymousClass || isLocal() fun UClass.isLocal(): Boolean { val parent = uastParent if (parent is UDeclarationsExpression && parent.uastParent is UBlockExpression) return true return if (parent is UClass) parent.isLocal() else false } fun PsiType.isInheritorOf(baseClassName: String) = InheritanceUtil.isInheritor(this, baseClassName)
apache-2.0
46cabca3015637031e88d2174fdea791
41.487179
123
0.699275
4.813953
false
false
false
false
google/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUClass.kt
1
6262
// 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.uast.java import com.intellij.psi.* import com.intellij.psi.impl.light.LightMethodBuilder import com.intellij.psi.javadoc.PsiDocComment import com.intellij.util.SmartList import com.intellij.util.castSafelyTo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* import org.jetbrains.uast.java.internal.JavaUElementWithComments @ApiStatus.Internal abstract class AbstractJavaUClass( givenParent: UElement? ) : JavaAbstractUElement(givenParent), UClass, JavaUElementWithComments, UAnchorOwner, UDeclarationEx { abstract override val javaPsi: PsiClass @Suppress("OverridingDeprecatedMember") override val psi get() = javaPsi override val uastDeclarations: List<UDeclaration> by lz { mutableListOf<UDeclaration>().apply { addAll(fields) addAll(initializers) addAll(methods) addAll(innerClasses) } } protected fun createJavaUTypeReferenceExpression(referenceElement: PsiJavaCodeReferenceElement): LazyJavaUTypeReferenceExpression = LazyJavaUTypeReferenceExpression(referenceElement, this) { JavaPsiFacade.getElementFactory(referenceElement.project).createType(referenceElement) } internal var cachedSuperTypes: List<UTypeReferenceExpression>? = null override val uastSuperTypes: List<UTypeReferenceExpression> get() { var types = cachedSuperTypes if (types == null) { types = javaPsi.extendsList?.referenceElements?.map { createJavaUTypeReferenceExpression(it) }.orEmpty() + javaPsi.implementsList?.referenceElements?.map { createJavaUTypeReferenceExpression(it) }.orEmpty() cachedSuperTypes = types } return types } override val uastAnchor: UIdentifier? get() = UIdentifier(javaPsi.nameIdentifier, this) override val uAnnotations: List<UAnnotation> get() = javaPsi.annotations.map { JavaUAnnotation(it, this) } override fun equals(other: Any?): Boolean = other is AbstractJavaUClass && javaPsi == other.javaPsi override fun hashCode(): Int = javaPsi.hashCode() } @ApiStatus.Internal class JavaUClass( override val sourcePsi: PsiClass, givenParent: UElement? ) : AbstractJavaUClass(givenParent), UAnchorOwner, PsiClass by sourcePsi { override val javaPsi: PsiClass = unwrap<UClass, PsiClass>(sourcePsi) override fun getSuperClass(): UClass? = super.getSuperClass() override fun getFields(): Array<UField> = super.getFields() override fun getInitializers(): Array<UClassInitializer> = super.getInitializers() override fun getMethods(): Array<UMethod> = super.getMethods() override fun getInnerClasses(): Array<UClass> = super.getInnerClasses() companion object { fun create(psi: PsiClass, containingElement: UElement?): UClass { return if (psi is PsiAnonymousClass) JavaUAnonymousClass(psi, containingElement) else JavaUClass(psi, containingElement) } } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } @ApiStatus.Internal class JavaUAnonymousClass( override val sourcePsi: PsiAnonymousClass, uastParent: UElement? ) : AbstractJavaUClass(uastParent), UAnonymousClass, UAnchorOwner, PsiAnonymousClass by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiAnonymousClass get() = sourcePsi override val javaPsi: PsiAnonymousClass = sourcePsi override val uastSuperTypes: List<UTypeReferenceExpression> get() { var types = cachedSuperTypes if (types == null) { types = listOf(createJavaUTypeReferenceExpression(sourcePsi.baseClassReference)) + javaPsi.extendsList?.referenceElements?.map { createJavaUTypeReferenceExpression(it) }.orEmpty() + javaPsi.implementsList?.referenceElements?.map { createJavaUTypeReferenceExpression(it) }.orEmpty() cachedSuperTypes = types } return types } override fun convertParent(): UElement? = sourcePsi.parent.toUElementOfType<UObjectLiteralExpression>() ?: super.convertParent() override val uastAnchor: UIdentifier? by lazy { when (javaPsi) { is PsiEnumConstantInitializer -> (javaPsi.parent as? PsiEnumConstant)?.let { UIdentifier(it.nameIdentifier, this) } else -> UIdentifier(sourcePsi.baseClassReference.referenceNameElement, this) } } override fun getSuperClass(): UClass? = super<AbstractJavaUClass>.getSuperClass() override fun getFields(): Array<UField> = super<AbstractJavaUClass>.getFields() override fun getInitializers(): Array<UClassInitializer> = super<AbstractJavaUClass>.getInitializers() private val fakeConstructor: JavaUMethod? by lz { val psiClass = this.javaPsi val physicalNewExpression = psiClass.parent.castSafelyTo<PsiNewExpression>() ?: return@lz null val superConstructor = physicalNewExpression.resolveMethod() val lightMethodBuilder = object : LightMethodBuilder(psiClass.manager, psiClass.language, "<anon-init>") { init { containingClass = psiClass isConstructor = true } override fun getNavigationElement(): PsiElement = superConstructor?.navigationElement ?: psiClass.superClass?.navigationElement ?: super.getNavigationElement() override fun getParent(): PsiElement = psiClass override fun getModifierList(): PsiModifierList = superConstructor?.modifierList ?: super.getModifierList() override fun getParameterList(): PsiParameterList = superConstructor?.parameterList ?: super.getParameterList() override fun getDocComment(): PsiDocComment? = superConstructor?.docComment ?: super.getDocComment() } JavaUMethod(lightMethodBuilder, this@JavaUAnonymousClass) } override fun getMethods(): Array<UMethod> { val constructor = fakeConstructor ?: return super<AbstractJavaUClass>.getMethods() val uMethods = SmartList<UMethod>() uMethods.add(constructor) uMethods.addAll(super<AbstractJavaUClass>.getMethods()) return uMethods.toTypedArray() } override fun getInnerClasses(): Array<UClass> = super<AbstractJavaUClass>.getInnerClasses() override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement }
apache-2.0
fd64c6403f7192c3bec3f78b359693b5
39.928105
133
0.752316
5.248952
false
false
false
false
google/intellij-community
uast/uast-common/src/org/jetbrains/uast/declarations/UMethod.kt
6
3711
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * A method visitor to be used in [UastVisitor]. */ interface UMethod : UDeclaration, PsiMethod { @get:ApiStatus.ScheduledForRemoval @get:Deprecated("see the base property description") @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiMethod override val javaPsi: PsiMethod /** * Returns the body expression (which can be also a [UBlockExpression]). */ val uastBody: UExpression? /** * Returns the method parameters. */ val uastParameters: List<UParameter> override fun getName(): String override fun getReturnType(): PsiType? override fun isConstructor(): Boolean @Deprecated("Use uastBody instead.", ReplaceWith("uastBody")) override fun getBody(): PsiCodeBlock? = javaPsi.body override fun accept(visitor: UastVisitor) { if (visitor.visitMethod(this)) return uAnnotations.acceptList(visitor) uastParameters.acceptList(visitor) uastBody?.accept(visitor) visitor.afterVisitMethod(this) } override fun asRenderString(): String = buildString { if (uAnnotations.isNotEmpty()) { uAnnotations.joinTo(buffer = this, separator = "\n", postfix = "\n", transform = UAnnotation::asRenderString) } append(javaPsi.renderModifiers()) append("fun ").append(name) uastParameters.joinTo(this, prefix = "(", postfix = ")") { parameter -> val annotationsText = if (parameter.uAnnotations.isNotEmpty()) parameter.uAnnotations.joinToString(separator = " ", postfix = " ") { it.asRenderString() } else "" annotationsText + parameter.name + ": " + parameter.type.canonicalText } javaPsi.returnType?.let { append(" : " + it.canonicalText) } val body = uastBody append(when (body) { is UBlockExpression -> " " + body.asRenderString() else -> " = " + ((body ?: UastEmptyExpression(this@UMethod)).asRenderString()) }) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitMethod(this, data) override fun asLogString(): String = log("name = $name") @JvmDefault val returnTypeReference: UTypeReferenceExpression? get() { val sourcePsi = sourcePsi ?: return null for (child in sourcePsi.children) { val expression = child.toUElement(UTypeReferenceExpression::class.java) if (expression != null) { return expression } } return null } } interface UAnnotationMethod : UMethod, PsiAnnotationMethod { @get:ApiStatus.ScheduledForRemoval @get:Deprecated("see the base property description") @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiAnnotationMethod /** * Returns the default value of this annotation method. */ val uastDefaultValue: UExpression? override fun getDefaultValue(): PsiAnnotationMemberValue? = (javaPsi as? PsiAnnotationMethod)?.defaultValue override fun accept(visitor: UastVisitor) { if (visitor.visitMethod(this)) return uAnnotations.acceptList(visitor) uastParameters.acceptList(visitor) uastBody?.accept(visitor) uastDefaultValue?.accept(visitor) visitor.afterVisitMethod(this) } override fun asLogString(): String = log("name = $name") }
apache-2.0
3457aa7e4ef4eef19853dda41e5da8d1
30.717949
140
0.702237
4.703422
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/RiderTestEntities.kt
1
1979
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type interface ProjectModelTestEntity : WorkspaceEntity { val info: String val descriptor: Descriptor //region generated code @GeneratedCodeApiVersion(1) interface Builder : ProjectModelTestEntity, WorkspaceEntity.Builder<ProjectModelTestEntity>, ObjBuilder<ProjectModelTestEntity> { override var entitySource: EntitySource override var info: String override var descriptor: Descriptor } companion object : Type<ProjectModelTestEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(info: String, descriptor: Descriptor, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ProjectModelTestEntity { val builder = builder() builder.info = info builder.descriptor = descriptor builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ProjectModelTestEntity, modification: ProjectModelTestEntity.Builder.() -> Unit) = modifyEntity( ProjectModelTestEntity.Builder::class.java, entity, modification) //endregion open class Descriptor(val data: String) class DescriptorInstance(data: String) : Descriptor(data)
apache-2.0
4230f062e7d39837c4ce689271dc9f76
34.357143
131
0.742799
5.167102
false
true
false
false
vvv1559/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/TerminalFixture.kt
1
1871
/* * 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.testGuiFramework.fixtures import com.intellij.openapi.project.Project import com.intellij.terminal.JBTerminalPanel import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntil import com.jediterm.terminal.model.TerminalTextBuffer import org.fest.swing.core.Robot class TerminalFixture(project: Project, robot: Robot): ToolWindowFixture("Terminal", project, robot) { private val myJBTerminalPanel: JBTerminalPanel private val terminalTextBuffer: TerminalTextBuffer init { val content = this.getContent("") ?: throw Exception("Unable to get content of terminal tool window") myJBTerminalPanel = myRobot.finder().find(content.component) { component -> component is JBTerminalPanel } as JBTerminalPanel terminalTextBuffer = myJBTerminalPanel.terminalTextBuffer } fun getScreenLines(): String { return terminalTextBuffer.screenLines } fun getLastLine(): String { val lastLineIndex = terminalTextBuffer.height - 1 return terminalTextBuffer.getLine(lastLineIndex).text } fun waitUntilTextAppeared(text: String, timeoutInSeconds: Int = 60) { waitUntil(condition = "'$text' appeared in terminal", timeoutInSeconds = timeoutInSeconds) { terminalTextBuffer.screenLines.contains(text) } } }
apache-2.0
e24aec7b9c076e03c24858de3af1904c
36.44
129
0.768573
4.631188
false
true
false
false