repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
smmribeiro/intellij-community
platform/object-serializer/src/xml/xmlSerializer.kt
9
6709
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("PackageDirectoryMismatch", "ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.configurationStore import com.intellij.openapi.components.BaseState import com.intellij.openapi.util.JDOMUtil import com.intellij.reference.SoftReference import com.intellij.serialization.SerializationException import com.intellij.serialization.xml.KotlinAwareBeanBinding import com.intellij.serialization.xml.KotlinxSerializationBinding import com.intellij.util.io.URLUtil import com.intellij.util.xmlb.* import kotlinx.serialization.Serializable import org.jdom.Element import org.jdom.JDOMException import org.jetbrains.annotations.TestOnly import java.io.IOException import java.lang.reflect.Type import java.net.URL import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write private val skipDefaultsSerializationFilter = ThreadLocal<SoftReference<SkipDefaultsSerializationFilter>>() private fun doGetDefaultSerializationFilter(): SkipDefaultsSerializationFilter { var result = SoftReference.dereference(skipDefaultsSerializationFilter.get()) if (result == null) { result = object : SkipDefaultsSerializationFilter() { override fun accepts(accessor: Accessor, bean: Any): Boolean { return when (bean) { is BaseState -> bean.accepts(accessor, bean) else -> super.accepts(accessor, bean) } } } skipDefaultsSerializationFilter.set(SoftReference(result)) } return result } @Suppress("unused") private class JdomSerializerImpl : JdomSerializer { override fun getDefaultSerializationFilter() = doGetDefaultSerializationFilter() override fun <T : Any> serialize(obj: T, filter: SerializationFilter?, createElementIfEmpty: Boolean): Element? { try { val binding = serializer.getRootBinding(obj.javaClass) return if (binding is BeanBinding) { // top level expects not null (null indicates error, empty element will be omitted) binding.serialize(obj, createElementIfEmpty, filter) } else { binding.serialize(obj, null, filter) as Element } } catch (e: SerializationException) { throw e } catch (e: Exception) { throw XmlSerializationException("Can't serialize instance of ${obj.javaClass}", e) } } override fun serializeObjectInto(obj: Any, target: Element, filter: SerializationFilter?) { if (obj is Element) { val iterator = obj.children.iterator() for (child in iterator) { iterator.remove() target.addContent(child) } val attributeIterator = obj.attributes.iterator() for (attribute in attributeIterator) { attributeIterator.remove() target.setAttribute(attribute) } return } val beanBinding = serializer.getRootBinding(obj.javaClass) as KotlinAwareBeanBinding beanBinding.serializeInto(obj, target, filter ?: getDefaultSerializationFilter()) } override fun <T> deserialize(element: Element, clazz: Class<T>): T { if (clazz == Element::class.java) { @Suppress("UNCHECKED_CAST") return element as T } @Suppress("UNCHECKED_CAST") try { return (serializer.getRootBinding(clazz, clazz) as NotNullDeserializeBinding).deserialize(null, element) as T } catch (e: SerializationException) { throw e } catch (e: Exception) { throw XmlSerializationException("Cannot deserialize class ${clazz.name}", e) } } override fun clearSerializationCaches() { clearBindingCache() } override fun deserializeInto(obj: Any, element: Element) { try { (serializer.getRootBinding(obj.javaClass) as BeanBinding).deserializeInto(obj, element) } catch (e: SerializationException) { throw e } catch (e: Exception) { throw XmlSerializationException(e) } } override fun <T> deserialize(url: URL, aClass: Class<T>): T { try { return deserialize(JDOMUtil.load(URLUtil.openStream(url)), aClass) } catch (e: IOException) { throw XmlSerializationException(e) } catch (e: JDOMException) { throw XmlSerializationException(e) } } } fun deserializeBaseStateWithCustomNameFilter(state: BaseState, excludedPropertyNames: Collection<String>): Element? { val binding = serializer.getRootBinding(state.javaClass) as KotlinAwareBeanBinding return binding.serializeBaseStateInto(state, null, doGetDefaultSerializationFilter(), excludedPropertyNames) } private val serializer = MyXmlSerializer() private abstract class OldBindingProducer<ROOT_BINDING> { private val cache: MutableMap<Type, ROOT_BINDING> = HashMap() private val cacheLock = ReentrantReadWriteLock() @get:TestOnly val bindingCount: Int get() = cacheLock.read { cache.size } fun getRootBinding(aClass: Class<*>, originalType: Type = aClass): ROOT_BINDING { val cacheKey = createCacheKey(aClass, originalType) return cacheLock.read { // create cache only under write lock cache.get(cacheKey) } ?: cacheLock.write { cache.get(cacheKey)?.let { return it } createRootBinding(aClass, originalType, cacheKey, cache) } } protected open fun createCacheKey(aClass: Class<*>, originalType: Type) = originalType protected abstract fun createRootBinding(aClass: Class<*>, type: Type, cacheKey: Type, map: MutableMap<Type, ROOT_BINDING>): ROOT_BINDING fun clearBindingCache() { cacheLock.write { cache.clear() } } } private class MyXmlSerializer : XmlSerializerImpl.XmlSerializerBase() { val bindingProducer = object : OldBindingProducer<Binding>() { override fun createRootBinding(aClass: Class<*>, type: Type, cacheKey: Type, map: MutableMap<Type, Binding>): Binding { var binding = createClassBinding(aClass, null, type) if (binding == null) { if (aClass.isAnnotationPresent(Serializable::class.java)) { binding = KotlinxSerializationBinding(aClass) } else { binding = KotlinAwareBeanBinding(aClass) } } map.put(cacheKey, binding) try { binding.init(type, this@MyXmlSerializer) } catch (e: Throwable) { map.remove(type) throw e } return binding } } override fun getRootBinding(aClass: Class<*>, originalType: Type): Binding { return bindingProducer.getRootBinding(aClass, originalType) } } /** * used by MPS. Do not use if not approved. */ fun clearBindingCache() { serializer.bindingProducer.clearBindingCache() }
apache-2.0
4f1b18a2e6eaccd59146ffaa43941449
31.572816
139
0.71024
4.557745
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/binaryExpression/stringConcatenation.kt
1
1676
// ERROR: The character literal does not conform to the expected type Int internal object Foo { private val s: String? = null private val i: Int? = null private val c: Char? = null @JvmStatic fun main(args: Array<String>) { println("5" + 1) println(1.toString() + "5") println((1 + 3).toString() + "5") println((1 + 3).toString() + "5") println("5" + "5" + (1 + 3)) println("5" + "5" + 1 + 3) println("5" + "5" + 1) println("5" + ("5" + 1) + 3) println("5" + ("5" + 1) + 3 + 4) println(1.toString() + "3" + 4 + "5") println((1 + 3 + 4).toString() + "5") println("5" + 1 + 3 + 4) println('c'.toString() + "5") println(('c' + 'd').toString() + "5") // TODO: fix KTIJ-8532 println("5" + 'c') println("5" + 'c' + 'd') println(c.toString() + "s") println(c.toString() + "s" + c) println("s" + c + c) println(s + 'c') println(s + 'c' + 'd') println('c'.toString() + s) println(s + null) println(null.toString() + s) println(i.toString() + "s") println(i.toString() + "s" + i) println("s" + i + i) println(null.toString() + "s") println("s" + null) println("s" + null + null) val o = Any() println(o.toString() + "") println("" + o) println(o.hashCode().toString() + "") println("" + o.hashCode()) val bar = arrayOf("hi") println(1.toString() + bar[0]) println((1 + 2).toString() + bar[0]) println(bar[0] + 1) println(bar[0] + 1 + 2) } }
apache-2.0
4416ac09212cfc958268848b135f477f
32.52
73
0.451671
3.186312
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/environment/LocalesDescription.kt
1
1106
package ftl.environment import com.google.testing.model.Locale import ftl.run.exception.FlankGeneralError fun List<Locale>.getLocaleDescription(localeId: String) = findLocales(localeId)?.prepareDescription().orErrorMessage(localeId).plus("\n") private fun List<Locale>.findLocales(localeId: String) = find { it.id == localeId } private fun Locale.prepareDescription() = """ id: $id name: $name """.trimIndent().addRegionIfExist(region).addTagsIfExists(this) private fun String.addRegionIfExist(region: String?) = if (!region.isNullOrEmpty()) StringBuilder(this).appendLine("\nregion: $region").trim().toString() else this private fun String.addTagsIfExists(locale: Locale) = if (!locale.tags.isNullOrEmpty()) StringBuilder(this).appendLine("\ntags:").appendTagsToList(locale) else this private fun StringBuilder.appendTagsToList(locale: Locale) = apply { locale.tags.filterNotNull().forEach { tag -> appendLine("- $tag") } }.trim().toString() private fun String?.orErrorMessage(locale: String) = this ?: throw FlankGeneralError("ERROR: '$locale' is not a valid locale")
apache-2.0
e082ef172f5b8bbeb9833a1229074ed1
39.962963
137
0.746835
4.021818
false
false
false
false
mdaniel/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/buildtool/MavenSyncConsole.kt
3
23737
// 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.idea.maven.buildtool import com.intellij.build.BuildProgressListener import com.intellij.build.DefaultBuildDescriptor import com.intellij.build.FilePosition import com.intellij.build.SyncViewManager import com.intellij.build.events.BuildEvent import com.intellij.build.events.EventResult import com.intellij.build.events.MessageEvent import com.intellij.build.events.MessageEventResult import com.intellij.build.events.impl.* import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.execution.ExecutionException import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.util.ExceptionUtil import com.intellij.util.ThreeState import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.idea.maven.buildtool.quickfix.OffMavenOfflineModeQuickFix import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenSettingsQuickFix import org.jetbrains.idea.maven.buildtool.quickfix.UseBundledMavenQuickFix import org.jetbrains.idea.maven.execution.SyncBundle import org.jetbrains.idea.maven.externalSystemIntegration.output.importproject.quickfixes.DownloadArtifactBuildIssue import org.jetbrains.idea.maven.model.MavenProjectProblem import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.server.CannotStartServerException import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.server.MavenServerProgressIndicator import org.jetbrains.idea.maven.utils.MavenLog import org.jetbrains.idea.maven.utils.MavenUtil import java.io.File class MavenSyncConsole(private val myProject: Project) { @Volatile private var mySyncView: BuildProgressListener = BuildProgressListener { _, _ -> } private var mySyncId = createTaskId() private var finished = false private var started = false private var syncTransactionStarted = false private var hasErrors = false private var hasUnresolved = false private val JAVADOC_AND_SOURCE_CLASSIFIERS = setOf("javadoc", "sources", "test-javadoc", "test-sources") private val shownIssues = HashSet<String>() private val myPostponed = ArrayList<() -> Unit>() private var myStartedSet = LinkedHashSet<Pair<Any, String>>() @Synchronized fun startImport(syncView: BuildProgressListener, spec: MavenImportSpec) { if (started) { return } val restartAction: AnAction = object : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = !started || finished e.presentation.icon = AllIcons.Actions.Refresh } override fun actionPerformed(e: AnActionEvent) { e.project?.let { MavenProjectsManager.getInstance(it).forceUpdateAllProjectsOrFindAllAvailablePomFiles() } } } started = true finished = false hasErrors = false hasUnresolved = false mySyncView = syncView shownIssues.clear() mySyncId = createTaskId() val descriptor = DefaultBuildDescriptor(mySyncId, SyncBundle.message("maven.sync.title"), myProject.basePath!!, System.currentTimeMillis()) .withRestartAction(restartAction) descriptor.isActivateToolWindowWhenFailed = spec.isExplicitImport descriptor.isActivateToolWindowWhenAdded = ExternalSystemUtil.isNewProject(myProject) descriptor.isNavigateToError = if (spec.isExplicitImport) ThreeState.YES else ThreeState.UNSURE mySyncView.onEvent(mySyncId, StartBuildEventImpl(descriptor, SyncBundle.message("maven.sync.project.title", myProject.name))) debugLog("maven sync: started importing $myProject") myPostponed.forEach(this::doIfImportInProcess) myPostponed.clear() } private fun createTaskId() = ExternalSystemTaskId.create(MavenUtil.SYSTEM_ID, ExternalSystemTaskType.RESOLVE_PROJECT, myProject) fun getTaskId() = mySyncId fun addText(@Nls text: String) = addText(text, true) @Synchronized fun addText(@Nls text: String, stdout: Boolean) = doIfImportInProcess { addText(mySyncId, text, true) } @Synchronized fun addWrapperProgressText(@Nls text: String) = doIfImportInProcess { addText(SyncBundle.message("maven.sync.wrapper"), text, true) } @Synchronized private fun addText(parentId: Any, @Nls text: String, stdout: Boolean) = doIfImportInProcess { if (StringUtil.isEmpty(text)) { return } val toPrint = if (text.endsWith('\n')) text else "$text\n" mySyncView.onEvent(mySyncId, OutputBuildEventImpl(parentId, toPrint, stdout)) } @Synchronized fun addBuildEvent(buildEvent: BuildEvent) = doIfImportInProcess { mySyncView.onEvent(mySyncId, buildEvent) } @Synchronized fun addWarning(@Nls text: String, @Nls description: String) = addWarning(text, description, null) fun addBuildIssue(issue: BuildIssue, kind: MessageEvent.Kind) = doIfImportInProcessOrPostpone { if (!newIssue(issue.title + issue.description)) return@doIfImportInProcessOrPostpone mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, issue, kind)) hasErrors = hasErrors || kind == MessageEvent.Kind.ERROR } @Synchronized fun addWarning(@Nls text: String, @Nls description: String, filePosition: FilePosition?) = doIfImportInProcess { if (!newIssue(text + description + filePosition)) return if (filePosition == null) { mySyncView.onEvent(mySyncId, MessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text, description)) } else { mySyncView.onEvent(mySyncId, FileMessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text, description, filePosition)) } } private fun newIssue(s: String): Boolean { return shownIssues.add(s) } @Synchronized fun finishImport() { debugLog("Maven sync: finishImport") doFinish() } fun terminated(exitCode: Int) = doIfImportInProcess { if (EXIT_CODE_OK == exitCode || EXIT_CODE_SIGTERM == exitCode) doFinish() else doTerminate(exitCode) } private fun doTerminate(exitCode: Int) { if (syncTransactionStarted) { debugLog("Maven sync: sync transaction is still not finished, postpone build finish event") return } val tasks = myStartedSet.toList().asReversed() debugLog("Tasks $tasks are not completed! Force complete") tasks.forEach { completeTask(it.first, it.second, FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode))) } mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "", FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode)))) finished = true started = false } @Synchronized fun startWrapperResolving() { if (!started || finished) { startImport(myProject.getService(SyncViewManager::class.java), MavenImportSpec.EXPLICIT_IMPORT) } startTask(mySyncId, SyncBundle.message("maven.sync.wrapper")) } @Synchronized fun finishWrapperResolving(e: Throwable? = null) { if (e != null) { addBuildIssue(object : BuildIssue { override val title: String = SyncBundle.message("maven.sync.wrapper.failure") override val description: String = SyncBundle.message("maven.sync.wrapper.failure.description", e.localizedMessage, OpenMavenSettingsQuickFix.ID) override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.WARNING) } completeTask(mySyncId, SyncBundle.message("maven.sync.wrapper"), SuccessResultImpl()) } @Synchronized fun notifyReadingProblems(file: VirtualFile) = doIfImportInProcess { debugLog("reading problems in $file") hasErrors = true val desc = SyncBundle.message("maven.sync.failure.error.reading.file", file.path) mySyncView.onEvent(mySyncId, FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), desc, desc, FilePosition(File(file.path), -1, -1))) } @Synchronized fun showProblem(problem: MavenProjectProblem) = doIfImportInProcess { hasErrors = true val group = SyncBundle.message("maven.sync.group.error") val position = problem.getFilePosition() val message = problem.description ?: SyncBundle.message("maven.sync.failure.error.undefined.message") val detailedMessage = problem.description ?: SyncBundle.message("maven.sync.failure.error.undefined.detailed.message", problem.path) val eventImpl = FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, group, message, detailedMessage, position) mySyncView.onEvent(mySyncId, eventImpl) } private fun MavenProjectProblem.getFilePosition(): FilePosition { val (line, columns) = getPosition() ?: (-1 to -1) return FilePosition(File(path), line, columns) } private fun MavenProjectProblem.getPosition(): Pair<Int, Int>? { val description = description ?: return null if (type == MavenProjectProblem.ProblemType.STRUCTURE) { val pattern = Regex("@(\\d+):(\\d+)") val matchResults = pattern.findAll(description) val matchResult = matchResults.lastOrNull() ?: return null val (_, line, offset) = matchResult.groupValues return line.toInt() - 1 to offset.toInt() } return null } @Synchronized @ApiStatus.Internal fun addException(e: Throwable, progressListener: BuildProgressListener) { if (started && !finished) { MavenLog.LOG.warn(e) hasErrors = true mySyncView.onEvent(mySyncId, createMessageEvent(e)) } else { this.startImport(progressListener, MavenImportSpec.EXPLICIT_IMPORT) this.addException(e, progressListener) this.finishImport() } } private fun createMessageEvent(e: Throwable): MessageEventImpl { val csse = ExceptionUtil.findCause(e, CannotStartServerException::class.java) if (csse != null) { val cause = ExceptionUtil.findCause(csse, ExecutionException::class.java) if (cause != null) { return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"), getExceptionText(cause), getExceptionText(cause)) } else { return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"), getExceptionText(csse), getExceptionText(csse)) } } return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.error"), getExceptionText(e), getExceptionText(e)) } private fun getExceptionText(e: Throwable): @NlsSafe String { if (MavenWorkspaceSettingsComponent.getInstance(myProject).settings.getGeneralSettings().isPrintErrorStackTraces) { return ExceptionUtil.getThrowableText(e) } if(!e.localizedMessage.isNullOrEmpty()) return e.localizedMessage return if (StringUtil.isEmpty(e.message)) SyncBundle.message("build.event.title.error") else e.message!! } fun getListener(type: MavenServerProgressIndicator.ResolveType): ArtifactSyncListener { return when (type) { MavenServerProgressIndicator.ResolveType.PLUGIN -> ArtifactSyncListenerImpl("maven.sync.plugins") MavenServerProgressIndicator.ResolveType.DEPENDENCY -> ArtifactSyncListenerImpl("maven.sync.dependencies") } } @Synchronized private fun doFinish() { if (syncTransactionStarted) { debugLog("Maven sync: sync transaction is still not finished, postpone build finish event") return } val tasks = myStartedSet.toList().asReversed() debugLog("Tasks $tasks are not completed! Force complete") tasks.forEach { completeTask(it.first, it.second, DerivedResultImpl()) } mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "", if (hasErrors) FailureResultImpl() else DerivedResultImpl())) attachOfflineQuickFix() finished = true started = false } private fun attachOfflineQuickFix() { try { val generalSettings = MavenWorkspaceSettingsComponent.getInstance(myProject).settings.generalSettings if (hasUnresolved && generalSettings.isWorkOffline) { mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title: String = "Dependency Resolution Failed" override val description: String = "<a href=\"${OffMavenOfflineModeQuickFix.ID}\">Switch Off Offline Mode</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OffMavenOfflineModeQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.ERROR)) } } catch (ignore: Exception){} } @Synchronized private fun showError(keyPrefix: String, dependency: String) = doIfImportInProcess { hasErrors = true hasUnresolved = true val umbrellaString = SyncBundle.message("${keyPrefix}.resolve") val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency) startTask(mySyncId, umbrellaString) mySyncView.onEvent(mySyncId, MessageEventImpl(umbrellaString, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), errorString, errorString)) addText(mySyncId, errorString, false) } @Synchronized private fun showBuildIssue(keyPrefix: String, dependency: String, errorMessage: String?) = doIfImportInProcess { hasErrors = true hasUnresolved = true val umbrellaString = SyncBundle.message("${keyPrefix}.resolve") val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency) startTask(mySyncId, umbrellaString) val buildIssue = DownloadArtifactBuildIssue.getIssue(errorString, errorMessage ?: errorString) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(umbrellaString, buildIssue, MessageEvent.Kind.ERROR)) addText(mySyncId, errorString, false) } @Synchronized private fun showBuildIssueNode(key: String, buildIssue: BuildIssue) = doIfImportInProcess { hasErrors = true hasUnresolved = true startTask(mySyncId, key) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(key, buildIssue, MessageEvent.Kind.ERROR)) } @Synchronized private fun startTask(parentId: Any, @NlsSafe taskName: String) = doIfImportInProcess { debugLog("Maven sync: start $taskName") if (myStartedSet.add(parentId to taskName)) { mySyncView.onEvent(mySyncId, StartEventImpl(taskName, parentId, System.currentTimeMillis(), taskName)) } } @Synchronized private fun completeTask(parentId: Any, @NlsSafe taskName: String, result: EventResult) = doIfImportInProcess { hasErrors = hasErrors || result is FailureResultImpl debugLog("Maven sync: complete $taskName with $result") if (myStartedSet.remove(parentId to taskName)) { mySyncView.onEvent(mySyncId, FinishEventImpl(taskName, parentId, System.currentTimeMillis(), taskName, result)) } } @Synchronized private fun completeUmbrellaEvents(keyPrefix: String) = doIfImportInProcess { val taskName = SyncBundle.message("${keyPrefix}.resolve") completeTask(mySyncId, taskName, DerivedResultImpl()) } @Synchronized private fun downloadEventStarted(keyPrefix: String, dependency: String) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) startTask(mySyncId, downloadString) startTask(downloadString, downloadArtifactString) } @Synchronized private fun downloadEventCompleted(keyPrefix: String, dependency: String) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) addText(downloadArtifactString, downloadArtifactString, true) completeTask(downloadString, downloadArtifactString, SuccessResultImpl(false)) } @Synchronized private fun downloadEventFailed(keyPrefix: String, @NlsSafe dependency: String, @NlsSafe error: String, @NlsSafe stackTrace: String?) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) if (isJavadocOrSource(dependency)) { addText(downloadArtifactString, SyncBundle.message("maven.sync.failure.dependency.not.found", dependency), true) completeTask(downloadString, downloadArtifactString, object : MessageEventResult { override fun getKind(): MessageEvent.Kind { return MessageEvent.Kind.WARNING } override fun getDetails(): String? { return SyncBundle.message("maven.sync.failure.dependency.not.found", dependency) } }) } else { if (stackTrace != null && Registry.`is`("maven.spy.events.debug")) { addText(downloadArtifactString, stackTrace, false) } else { addText(downloadArtifactString, error, true) } completeTask(downloadString, downloadArtifactString, FailureResultImpl(error)) } } @Synchronized fun showQuickFixBadMaven(message: String, kind: MessageEvent.Kind) { val bundledVersion = MavenServerManager.getMavenVersion(MavenServerManager.BUNDLED_MAVEN_3) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title = SyncBundle.message("maven.sync.version.issue.title") override val description: String = "${message}\n" + "- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" + SyncBundle.message("maven.sync.version.open.settings") + "</a>\n" + "- <a href=\"${UseBundledMavenQuickFix.ID}\">" + SyncBundle.message("maven.sync.version.use.bundled", bundledVersion) + "</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix(), UseBundledMavenQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, kind)) } fun <Result> runTask(@NlsSafe taskName: String, task: () -> Result): Result { startTask(mySyncId, taskName) val startTime = System.currentTimeMillis() try { return task().also { completeTask(mySyncId, taskName, SuccessResultImpl()) } } catch (e: Exception) { completeTask(mySyncId, taskName, FailureResultImpl(e)) throw e } finally { MavenLog.LOG.info("[maven import] $taskName took ${System.currentTimeMillis() - startTime}ms") } } @Synchronized fun showQuickFixJDK(version: String) { mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title = SyncBundle.message("maven.sync.quickfixes.maven.jdk.version.title") override val description: String = SyncBundle.message("maven.sync.quickfixes.upgrade.to.jdk7", version) + "\n" + "- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" + SyncBundle.message("maven.sync.quickfixes.open.settings") + "</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.ERROR)) } private fun isJavadocOrSource(dependency: String): Boolean { val split = dependency.split(':') if (split.size < 4) { return false } val classifier = split.get(2) return JAVADOC_AND_SOURCE_CLASSIFIERS.contains(classifier) } private inline fun doIfImportInProcess(action: () -> Unit) { if (!started || finished) return action.invoke() } private fun doIfImportInProcessOrPostpone(action: () -> Unit) { if (!started || finished) { myPostponed.add(action) } else { action.invoke() } } private inner class ArtifactSyncListenerImpl(val keyPrefix: String) : ArtifactSyncListener { override fun downloadStarted(dependency: String) { downloadEventStarted(keyPrefix, dependency) } override fun downloadCompleted(dependency: String) { downloadEventCompleted(keyPrefix, dependency) } override fun downloadFailed(dependency: String, error: String, stackTrace: String?) { downloadEventFailed(keyPrefix, dependency, error, stackTrace) } override fun finish() { completeUmbrellaEvents(keyPrefix) } override fun showError(dependency: String) { showError(keyPrefix, dependency) } override fun showArtifactBuildIssue(dependency: String, errorMessage: String?) { showBuildIssue(keyPrefix, dependency, errorMessage) } override fun showBuildIssue(dependency: String, buildIssue: BuildIssue) { showBuildIssueNode(keyPrefix, buildIssue) } } companion object { val EXIT_CODE_OK = 0 val EXIT_CODE_SIGTERM = 143 @ApiStatus.Experimental @JvmStatic fun startTransaction(project: Project) { debugLog("Maven sync: start sync transaction") val syncConsole = MavenProjectsManager.getInstance(project).syncConsole synchronized(syncConsole) { syncConsole.syncTransactionStarted = true } } @ApiStatus.Experimental @JvmStatic fun finishTransaction(project: Project) { debugLog("Maven sync: finish sync transaction") val syncConsole = MavenProjectsManager.getInstance(project).syncConsole synchronized(syncConsole) { syncConsole.syncTransactionStarted = false syncConsole.finishImport() } } private fun debugLog(s: String, exception: Throwable? = null) { MavenLog.LOG.debug(s, exception) } } } interface ArtifactSyncListener { fun showError(dependency: String) fun showArtifactBuildIssue(dependency: String, errorMessage: String?) fun showBuildIssue(dependency: String, buildIssue: BuildIssue) fun downloadStarted(dependency: String) fun downloadCompleted(dependency: String) fun downloadFailed(dependency: String, error: String, stackTrace: String?) fun finish() }
apache-2.0
9175439a87ae5ffa1ae0ca8b0ead7478
40.067474
137
0.712095
4.94212
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/ui/components/components.kt
1
14425
// 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. @file:Suppress("FunctionName") package com.intellij.ui.components import com.intellij.BundleBase import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.* import com.intellij.openapi.ui.ComponentWithBrowseButton.BrowseFolderActionListener import com.intellij.openapi.ui.DialogWrapper.IdeModalityType import com.intellij.openapi.ui.ex.MultiLineLabel import com.intellij.openapi.util.NlsContexts.* import com.intellij.openapi.util.NlsContexts.Checkbox import com.intellij.openapi.util.NlsContexts.Label import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.* import com.intellij.util.FontUtil import com.intellij.util.SmartList import com.intellij.util.io.URLUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.SwingHelper import com.intellij.util.ui.SwingHelper.addHistoryOnExpansion import com.intellij.util.ui.UIUtil import java.awt.* import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.HyperlinkListener import javax.swing.text.BadLocationException import javax.swing.text.JTextComponent import javax.swing.text.Segment fun Label(@Label text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false) = Label(text, style, fontColor, bold, null) fun Label(@Label text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false, font: Font? = null): JLabel { val finalText = BundleBase.replaceMnemonicAmpersand(text) val label: JLabel if (fontColor == null) { label = if (finalText.contains('\n')) MultiLineLabel(finalText) else JLabel(finalText) } else { label = JBLabel(finalText, UIUtil.ComponentStyle.REGULAR, fontColor) } if (font != null) { label.font = font } else { style?.let { UIUtil.applyStyle(it, label) } if (bold) { label.font = label.font.deriveFont(Font.BOLD) } } // surrounded by space to avoid false match if (text.contains(" -> ")) { label.text = text.replace(" -> ", " ${FontUtil.rightArrow(label.font)} ") } return label } fun Link(@Label text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit): JComponent { val result = ActionLink(text) { action() } style?.let { UIUtil.applyStyle(it, result) } return result } @JvmOverloads fun noteComponent(@Label note: String, linkHandler: ((url: String) -> Unit)? = null): JComponent { val matcher = URLUtil.HREF_PATTERN.matcher(note) if (!matcher.find()) { return Label(note) } val noteComponent = SimpleColoredComponent() var prev = 0 do { if (matcher.start() != prev) { noteComponent.append(note.substring(prev, matcher.start())) } val linkUrl = matcher.group(1) val tag = if (linkHandler == null) SimpleColoredComponent.BrowserLauncherTag(linkUrl) else Runnable { linkHandler(linkUrl) } noteComponent.append(matcher.group(2), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, tag) prev = matcher.end() } while (matcher.find()) LinkMouseListenerBase.installSingleTagOn(noteComponent) if (prev < note.length) { noteComponent.append(note.substring(prev)) } return noteComponent } @JvmOverloads fun htmlComponent(@DetailedDescription text: String = "", font: Font? = null, background: Color? = null, foreground: Color? = null, lineWrap: Boolean = false, hyperlinkListener: HyperlinkListener? = BrowserHyperlinkListener.INSTANCE): JEditorPane { val pane = SwingHelper.createHtmlViewer(lineWrap, font, background, foreground) pane.text = text pane.border = null pane.disabledTextColor = UIUtil.getLabelDisabledForeground() if (hyperlinkListener != null) { pane.addHyperlinkListener(hyperlinkListener) } return pane } fun RadioButton(@RadioButton text: String): JRadioButton = JRadioButton(BundleBase.replaceMnemonicAmpersand(text)) fun CheckBox(@Checkbox text: String, selected: Boolean = false, toolTip: String? = null): JCheckBox { val component = JCheckBox(BundleBase.replaceMnemonicAmpersand(text), selected) toolTip?.let { component.toolTipText = it } return component } @JvmOverloads fun Panel(@BorderTitle title: String? = null, layout: LayoutManager2? = BorderLayout()): JPanel { return Panel(title, false, layout) } fun Panel(@BorderTitle title: String? = null, hasSeparator: Boolean = true, layout: LayoutManager2? = BorderLayout()): JPanel { val panel = JPanel(layout) title?.let { setTitledBorder(it, panel, hasSeparator) } return panel } fun DialogPanel(@BorderTitle title: String? = null, layout: LayoutManager2? = BorderLayout()): DialogPanel { val panel = DialogPanel(layout) title?.let { setTitledBorder(it, panel, hasSeparator = true) } return panel } private fun setTitledBorder(@BorderTitle title: String, panel: JPanel, hasSeparator: Boolean) { val border = when { hasSeparator -> IdeBorderFactory.createTitledBorder(title, false) else -> IdeBorderFactory.createTitledBorder(title, false, JBUI.insetsTop(8)).setShowLine(false) } panel.border = border border.acceptMinimumSize(panel) } /** * Consider using [UI DSL](http://www.jetbrains.org/intellij/sdk/docs/user_interface_components/kotlin_ui_dsl.html). */ @JvmOverloads fun dialog(@DialogTitle title: String, panel: JComponent, resizable: Boolean = false, focusedComponent: JComponent? = null, okActionEnabled: Boolean = true, project: Project? = null, parent: Component? = null, @DialogMessage errorText: String? = null, modality: IdeModalityType = IdeModalityType.IDE, createActions: ((DialogManager) -> List<Action>)? = null, ok: (() -> List<ValidationInfo>?)? = null): DialogWrapper { return object : MyDialogWrapper(project, parent, modality) { init { setTitle(title) setResizable(resizable) if (!okActionEnabled) { this.okAction.isEnabled = false } setErrorText(errorText) init() } override fun createCenterPanel() = panel override fun createActions(): Array<out Action> { return if (createActions == null) super.createActions() else createActions(this).toTypedArray() } override fun getPreferredFocusedComponent() = focusedComponent ?: super.getPreferredFocusedComponent() override fun doOKAction() { if (okAction.isEnabled) { performAction(ok) } } } } interface DialogManager { fun performAction(action: (() -> List<ValidationInfo>?)? = null) } private abstract class MyDialogWrapper(project: Project?, parent: Component?, modality: IdeModalityType) : DialogWrapper(project, parent, true, modality), DialogManager { override fun performAction(action: (() -> List<ValidationInfo>?)?) { val validationInfoList = action?.invoke() if (validationInfoList == null || validationInfoList.isEmpty()) { super.doOKAction() } else { setErrorInfoAll(validationInfoList) clearErrorInfoOnFirstChange(validationInfoList) } } private fun getTextField(info: ValidationInfo): JTextComponent? { val component = info.component ?: return null return when (component) { is JTextComponent -> component is TextFieldWithBrowseButton -> component.textField else -> null } } private fun clearErrorInfoOnFirstChange(validationInfoList: List<ValidationInfo>) { val unchangedFields = SmartList<Component>() for (info in validationInfoList) { val textField = getTextField(info) ?: continue unchangedFields.add(textField) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { textField.document.removeDocumentListener(this) if (unchangedFields.remove(textField) && unchangedFields.isEmpty()) { setErrorInfoAll(emptyList()) } } }) } } } @JvmOverloads fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?, component: ComponentWithBrowseButton<T>, textField: JTextField, @DialogTitle browseDialogTitle: String?, fileChooserDescriptor: FileChooserDescriptor, textComponentAccessor: TextComponentAccessor<T>, fileChosen: ((chosenFile: VirtualFile) -> String)? = null) { installFileCompletionAndBrowseDialog( project, component, textField, browseDialogTitle, null, fileChooserDescriptor, textComponentAccessor, fileChosen) } @JvmOverloads fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?, component: ComponentWithBrowseButton<T>, textField: JTextField, @DialogTitle browseDialogTitle: String?, @Label browseDialogDescription: String?, fileChooserDescriptor: FileChooserDescriptor, textComponentAccessor: TextComponentAccessor<T>, fileChosen: ((chosenFile: VirtualFile) -> String)? = null) { if (ApplicationManager.getApplication() == null) { // tests return } component.addActionListener( object : BrowseFolderActionListener<T>( browseDialogTitle, browseDialogDescription, component, project, fileChooserDescriptor, textComponentAccessor ) { override fun onFileChosen(chosenFile: VirtualFile) { if (fileChosen == null) { super.onFileChosen(chosenFile) } else { textComponentAccessor.setText(myTextComponent, fileChosen(chosenFile)) } } }) FileChooserFactory.getInstance().installFileCompletion(textField, fileChooserDescriptor, true, null /* infer disposable from UI context */) } @JvmOverloads fun textFieldWithHistoryWithBrowseButton(project: Project?, @DialogTitle browseDialogTitle: String, fileChooserDescriptor: FileChooserDescriptor, historyProvider: (() -> List<String>)? = null, fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithHistoryWithBrowseButton { val component = TextFieldWithHistoryWithBrowseButton() val textFieldWithHistory = component.childComponent textFieldWithHistory.setHistorySize(-1) textFieldWithHistory.setMinimumAndPreferredWidth(0) if (historyProvider != null) { addHistoryOnExpansion(textFieldWithHistory, historyProvider) } installFileCompletionAndBrowseDialog( project = project, component = component, textField = component.childComponent.textEditor, browseDialogTitle = browseDialogTitle, fileChooserDescriptor = fileChooserDescriptor, textComponentAccessor = TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT, fileChosen = fileChosen ) return component } @JvmOverloads fun textFieldWithBrowseButton(project: Project?, @DialogTitle browseDialogTitle: String?, fileChooserDescriptor: FileChooserDescriptor, fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithBrowseButton { val component = TextFieldWithBrowseButton() installFileCompletionAndBrowseDialog( project = project, component = component, textField = component.textField, browseDialogTitle = browseDialogTitle, fileChooserDescriptor = fileChooserDescriptor, textComponentAccessor = TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, fileChosen = fileChosen ) return component } @JvmOverloads fun textFieldWithBrowseButton(project: Project?, @DialogTitle browseDialogTitle: String?, textField: JTextField, fileChooserDescriptor: FileChooserDescriptor, fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithBrowseButton { return textFieldWithBrowseButton(project, browseDialogTitle, null, textField, fileChooserDescriptor, fileChosen) } @JvmOverloads fun textFieldWithBrowseButton(project: Project?, @DialogTitle browseDialogTitle: String?, @Label browseDialogDescription: String?, textField: JTextField, fileChooserDescriptor: FileChooserDescriptor, fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithBrowseButton { val component = TextFieldWithBrowseButton(textField) installFileCompletionAndBrowseDialog( project = project, component = component, textField = component.textField, browseDialogTitle = browseDialogTitle, browseDialogDescription = browseDialogDescription, fileChooserDescriptor = fileChooserDescriptor, textComponentAccessor = TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, fileChosen = fileChosen ) return component } val JPasswordField.chars: CharSequence? get() { val doc = document if (doc.length == 0) { return "" } else try { return Segment().also { doc.getText(0, doc.length, it) } } catch (e: BadLocationException) { return null } }
apache-2.0
989fea5bb2a6a7af15905dffe856ba41
38.092141
158
0.664263
5.177674
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/InlayHintsPass.kt
1
9932
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeHighlighting.EditorBoundHighlightingPass import com.intellij.codeInsight.daemon.impl.analysis.HighlightingLevelManager import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.concurrency.JobLauncher import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.InlayModel import com.intellij.openapi.editor.ex.util.EditorScrollingPositionKeeper import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.SyntaxTraverser import com.intellij.util.Processor import com.intellij.util.SlowOperations import it.unimi.dsi.fastutil.ints.Int2ObjectMap import it.unimi.dsi.fastutil.ints.Int2ObjectMaps import it.unimi.dsi.fastutil.ints.IntOpenHashSet import java.util.concurrent.ConcurrentLinkedQueue import java.util.stream.IntStream class InlayHintsPass( private val rootElement: PsiElement, private val enabledCollectors: List<CollectorWithSettings<out Any>>, private val editor: Editor ) : EditorBoundHighlightingPass(editor, rootElement.containingFile, true) { private var allHints: HintsBuffer? = null override fun doCollectInformation(progress: ProgressIndicator) { if (!HighlightingLevelManager.getInstance(myFile.project).shouldHighlight(myFile)) return if (enabledCollectors.isEmpty()) return val buffers = ConcurrentLinkedQueue<HintsBuffer>() JobLauncher.getInstance().invokeConcurrentlyUnderProgress( enabledCollectors, progress, true, false, Processor { collector -> // TODO [roman.ivanov] it is not good to create separate traverser here as there may be many hints providers val traverser = SyntaxTraverser.psiTraverser(rootElement) for (element in traverser.preOrderDfsTraversal()) { if (!collector.collectHints(element, myEditor)) break } val hints = collector.sink.complete() buffers.add(hints) true } ) val iterator = buffers.iterator() if (!iterator.hasNext()) return val allHintsAccumulator = iterator.next() for (hintsBuffer in iterator) { allHintsAccumulator.mergeIntoThis(hintsBuffer) } allHints = allHintsAccumulator } override fun doApplyInformationToEditor() { val positionKeeper = EditorScrollingPositionKeeper(editor) positionKeeper.savePosition() applyCollected(allHints, rootElement, editor) positionKeeper.restorePosition(false) if (rootElement === myFile) { InlayHintsPassFactory.putCurrentModificationStamp(myEditor, myFile) } } companion object { private const val BULK_CHANGE_THRESHOLD = 1000 private val MANAGED_KEY = Key.create<Boolean>("managed.inlay") internal fun applyCollected(hints: HintsBuffer?, element: PsiElement, editor: Editor) { val startOffset = element.textOffset val endOffset = element.textRange.endOffset val inlayModel = editor.inlayModel val existingInlineInlays = inlayModel.getInlineElementsInRange(startOffset, endOffset, InlineInlayRenderer::class.java) val existingAfterLineEndInlays = inlayModel.getAfterLineEndElementsInRange(startOffset, endOffset, InlineInlayRenderer::class.java) val existingBlockInlays: List<Inlay<out BlockInlayRenderer>> = inlayModel.getBlockElementsInRange(startOffset, endOffset, BlockInlayRenderer::class.java) val existingBlockAboveInlays = mutableListOf<Inlay<out PresentationContainerRenderer<*>>>() val existingBlockBelowInlays = mutableListOf<Inlay<out PresentationContainerRenderer<*>>>() for (inlay in existingBlockInlays) { when (inlay.placement) { Inlay.Placement.ABOVE_LINE -> existingBlockAboveInlays Inlay.Placement.BELOW_LINE -> existingBlockBelowInlays else -> throw IllegalStateException() }.add(inlay) } val isBulk = shouldBeBulk(hints, existingInlineInlays, existingBlockAboveInlays, existingBlockBelowInlays) val factory = PresentationFactory(editor as EditorImpl) inlayModel.execute(isBulk) { updateOrDispose(existingInlineInlays, hints, Inlay.Placement.INLINE, factory, editor) updateOrDispose(existingAfterLineEndInlays, hints, Inlay.Placement.INLINE /* 'hints' consider them as INLINE*/, factory, editor) updateOrDispose(existingBlockAboveInlays, hints, Inlay.Placement.ABOVE_LINE, factory, editor) updateOrDispose(existingBlockBelowInlays, hints, Inlay.Placement.BELOW_LINE, factory, editor) if (hints != null) { addInlineHints(hints, inlayModel) addBlockHints(inlayModel, hints.blockAboveHints, true) addBlockHints(inlayModel, hints.blockBelowHints, false) } } } private fun postprocessInlay(inlay: Inlay<out PresentationContainerRenderer<*>>) { inlay.renderer.setListener(InlayContentListener(inlay)) inlay.putUserData(MANAGED_KEY, true) } private fun addInlineHints(hints: HintsBuffer, inlayModel: InlayModel) { for (entry in Int2ObjectMaps.fastIterable(hints.inlineHints)) { val renderer = InlineInlayRenderer(entry.value) val toBePlacedAtTheEndOfLine = entry.value.any { it.constraints?.placedAtTheEndOfLine ?: false } val isRelatedToPrecedingText = entry.value.all { it.constraints?.relatesToPrecedingText ?: false } val inlay = if (toBePlacedAtTheEndOfLine) { inlayModel.addAfterLineEndElement(entry.intKey, true, renderer) } else { inlayModel.addInlineElement(entry.intKey, isRelatedToPrecedingText, renderer) ?: break } inlay?.let { postprocessInlay(it) } } } private fun addBlockHints(inlayModel: InlayModel, map: Int2ObjectMap<MutableList<ConstrainedPresentation<*, BlockConstraints>>>, showAbove: Boolean ) { for (entry in Int2ObjectMaps.fastIterable(map)) { val presentations = entry.value val constraints = presentations.first().constraints val inlay = inlayModel.addBlockElement( entry.intKey, constraints?.relatesToPrecedingText ?: true, showAbove, constraints?.priority ?: 0, BlockInlayRenderer(presentations) ) ?: break postprocessInlay(inlay) if (!showAbove) { break } } } private fun shouldBeBulk(hints: HintsBuffer?, existingInlineInlays: MutableList<Inlay<out InlineInlayRenderer>>, existingBlockAboveInlays: MutableList<Inlay<out PresentationContainerRenderer<*>>>, existingBlockBelowInlays: MutableList<Inlay<out PresentationContainerRenderer<*>>>): Boolean { val totalChangesCount = when { hints != null -> estimateChangesCountForPlacement(existingInlineInlays.offsets(), hints, Inlay.Placement.INLINE) + estimateChangesCountForPlacement(existingBlockAboveInlays.offsets(), hints, Inlay.Placement.ABOVE_LINE) + estimateChangesCountForPlacement(existingBlockBelowInlays.offsets(), hints, Inlay.Placement.BELOW_LINE) else -> existingInlineInlays.size + existingBlockAboveInlays.size + existingBlockBelowInlays.size } return totalChangesCount > BULK_CHANGE_THRESHOLD } private fun List<Inlay<*>>.offsets(): IntStream = stream().mapToInt { it.offset } private fun updateOrDispose(existing: List<Inlay<out PresentationContainerRenderer<*>>>, hints: HintsBuffer?, placement: Inlay.Placement, factory: InlayPresentationFactory, editor: Editor ) { for (inlay in existing) { val managed = inlay.getUserData(MANAGED_KEY) ?: continue if (!managed) continue val offset = inlay.offset val elements = hints?.remove(offset, placement) if (elements == null) { Disposer.dispose(inlay) continue } else { inlay.renderer.addOrUpdate(elements, factory, placement, editor) } } } /** * Estimates count of changes (removal, addition) for inlays */ fun estimateChangesCountForPlacement(existingInlayOffsets: IntStream, collected: HintsBuffer, placement: Inlay.Placement): Int { var count = 0 val offsetsWithExistingHints = IntOpenHashSet() for (offset in existingInlayOffsets) { if (!collected.contains(offset, placement)) { count++ } else { offsetsWithExistingHints.add(offset) } } val elementsToCreate = collected.countDisjointElements(offsetsWithExistingHints, placement) count += elementsToCreate return count } private fun <Constraints : Any> PresentationContainerRenderer<Constraints>.addOrUpdate( new: List<ConstrainedPresentation<*, *>>, factory: InlayPresentationFactory, placement: Inlay.Placement, editor: Editor ) { if (!isAcceptablePlacement(placement)) { throw IllegalArgumentException() } SlowOperations.allowSlowOperations<Exception> { @Suppress("UNCHECKED_CAST") addOrUpdate(new as List<ConstrainedPresentation<*, Constraints>>, editor, factory) } } } }
apache-2.0
1b5d3879a2f5596f0272d7fe4e15e5dc
42.757709
158
0.692006
4.958562
false
false
false
false
sewerk/Bill-Calculator
app/src/main/java/pl/srw/billcalculator/bill/calculation/CalculatedEnergyBill.kt
1
1697
package pl.srw.billcalculator.bill.calculation import org.threeten.bp.LocalDate import pl.srw.billcalculator.db.Prices import pl.srw.billcalculator.util.Dates import java.math.BigDecimal abstract class CalculatedEnergyBill( dateFrom: LocalDate, dateTo: LocalDate, oplataAbonamentowa: String, oplataPrzejsciowa: String, oplataStalaZaPrzesyl: String, prices: Prices ) : CalculatedBill(false, dateFrom, dateTo, prices) { companion object { private val EXCISE = BigDecimal("0.02") } val oplataAbonamentowaNetCharge = countNetAndAddToSum(oplataAbonamentowa, monthCount) val oplataPrzejsciowaNetCharge = countNetAndAddToSum(oplataPrzejsciowa, monthCount) val oplataDystrybucyjnaStalaNetCharge = countNetAndAddToSum(oplataStalaZaPrzesyl, monthCount) val oplataAbonamentowaVatCharge = countVatAndAddToSum(oplataAbonamentowaNetCharge) val oplataPrzejsciowaVatCharge = countVatAndAddToSum(oplataPrzejsciowaNetCharge) val oplataDystrybucyjnaStalaVatCharge = countVatAndAddToSum(oplataDystrybucyjnaStalaNetCharge) protected fun countConsumptionPartFromJuly16(dateFrom: LocalDate, dateTo: LocalDate, consumption: Int): Int { val daysFromJuly16 = Dates.countDaysFromJuly16(dateFrom, dateTo) val periodInDays = Dates.countDays(dateFrom, dateTo) if (daysFromJuly16 == periodInDays) { return consumption } return BigDecimal(consumption) .multiply(BigDecimal.valueOf(daysFromJuly16 / periodInDays.toDouble())) .toInt() } val excise: BigDecimal get() = EXCISE.multiply(BigDecimal(totalConsumption)) abstract val totalConsumption: Int }
mit
37ade3311fe04546a1157d99ab12af3b
37.568182
113
0.757219
4.489418
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddThrowsAnnotationIntention.kt
1
7979
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.idea.util.module import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.annotations.JVM_THROWS_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.annotations.KOTLIN_THROWS_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.getAbbreviatedType class AddThrowsAnnotationIntention : SelfTargetingIntention<KtThrowExpression>( KtThrowExpression::class.java, KotlinBundle.lazyMessage("add.throws.annotation") ) { override fun isApplicableTo(element: KtThrowExpression, caretOffset: Int): Boolean { if (element.platform.isJs()) return false val containingDeclaration = element.getContainingDeclaration() ?: return false val type = element.thrownExpression?.resolveToCall()?.resultingDescriptor?.returnType ?: return false if ((type.constructor.declarationDescriptor as? DeclarationDescriptorWithVisibility)?.visibility == DescriptorVisibilities.LOCAL) return false val module = element.module ?: return false if (!KOTLIN_THROWS_ANNOTATION_FQ_NAME.fqNameIsExists(module) && !(element.platform.isJvm() && JVM_THROWS_ANNOTATION_FQ_NAME.fqNameIsExists(module)) ) return false val context = element.analyze(BodyResolveMode.PARTIAL) val annotationEntry = containingDeclaration.findThrowsAnnotation(context) ?: return true val valueArguments = annotationEntry.valueArguments if (valueArguments.isEmpty()) return true val argumentExpression = valueArguments.firstOrNull()?.getArgumentExpression() if (argumentExpression is KtCallExpression && argumentExpression.calleeExpression?.getCallableDescriptor()?.fqNameSafe != FqName("kotlin.arrayOf") ) return false return valueArguments.none { it.hasType(type, context) } } override fun applyTo(element: KtThrowExpression, editor: Editor?) { val containingDeclaration = element.getContainingDeclaration() ?: return val type = element.thrownExpression?.resolveToCall()?.resultingDescriptor?.returnType ?: return val annotationArgumentText = if (type.getAbbreviatedType() != null) "$type::class" else type.constructor.declarationDescriptor?.fqNameSafe?.let { "$it::class" } ?: return val context = element.analyze(BodyResolveMode.PARTIAL) val annotationEntry = containingDeclaration.findThrowsAnnotation(context) if (annotationEntry == null || annotationEntry.valueArguments.isEmpty()) { annotationEntry?.delete() val whiteSpaceText = if (containingDeclaration is KtPropertyAccessor) " " else "\n" val annotationFqName = KOTLIN_THROWS_ANNOTATION_FQ_NAME.takeIf { element.languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 } ?: JVM_THROWS_ANNOTATION_FQ_NAME containingDeclaration.addAnnotation(annotationFqName, annotationArgumentText, whiteSpaceText) } else { val factory = KtPsiFactory(element) val argument = annotationEntry.valueArguments.firstOrNull() val expression = argument?.getArgumentExpression() val added = when { argument?.getArgumentName() == null -> annotationEntry.valueArgumentList?.addArgument(factory.createArgument(annotationArgumentText)) expression is KtCallExpression -> expression.valueArgumentList?.addArgument(factory.createArgument(annotationArgumentText)) expression is KtClassLiteralExpression -> { expression.replaced( factory.createCollectionLiteral(listOf(expression), annotationArgumentText) ).getInnerExpressions().lastOrNull() } expression is KtCollectionLiteralExpression -> { expression.replaced( factory.createCollectionLiteral(expression.getInnerExpressions(), annotationArgumentText) ).getInnerExpressions().lastOrNull() } else -> null } if (added != null) ShortenReferences.DEFAULT.process(added) } } } private fun KtThrowExpression.getContainingDeclaration(): KtDeclaration? { val parent = getParentOfTypesAndPredicate( true, KtNamedFunction::class.java, KtSecondaryConstructor::class.java, KtPropertyAccessor::class.java, KtClassInitializer::class.java, KtLambdaExpression::class.java ) { true } if (parent is KtClassInitializer || parent is KtLambdaExpression) return null return parent as? KtDeclaration } private fun KtDeclaration.findThrowsAnnotation(context: BindingContext): KtAnnotationEntry? { val annotationEntries = this.annotationEntries + (parent as? KtProperty)?.annotationEntries.orEmpty() return annotationEntries.find { val typeReference = it.typeReference ?: return@find false val fqName = context[BindingContext.TYPE, typeReference]?.fqName ?: return@find false fqName == KOTLIN_THROWS_ANNOTATION_FQ_NAME || fqName == JVM_THROWS_ANNOTATION_FQ_NAME } } private fun ValueArgument.hasType(type: KotlinType, context: BindingContext): Boolean = when (val argumentExpression = getArgumentExpression()) { is KtClassLiteralExpression -> listOf(argumentExpression) is KtCollectionLiteralExpression -> argumentExpression.getInnerExpressions().filterIsInstance(KtClassLiteralExpression::class.java) is KtCallExpression -> argumentExpression.valueArguments.mapNotNull { it.getArgumentExpression() as? KtClassLiteralExpression } else -> emptyList() }.any { it.getType(context)?.arguments?.firstOrNull()?.type == type } private fun KtPsiFactory.createCollectionLiteral(expressions: List<KtExpression>, lastExpression: String): KtCollectionLiteralExpression = buildExpression { appendFixedText("[") expressions.forEach { appendExpression(it) appendFixedText(", ") } appendFixedText(lastExpression) appendFixedText("]") } as KtCollectionLiteralExpression private fun FqName.fqNameIsExists(module: Module): Boolean = KotlinFullClassNameIndex.getInstance()[ asString(), module.project, GlobalSearchScope.moduleWithLibrariesScope(module) ].isNotEmpty()
apache-2.0
e225d992648c14979a9acdf4fcd4afc7
50.811688
158
0.732673
5.468814
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/data/ispn/JsonMarshallerIT.kt
2
2056
package com.github.kerubistan.kerub.data.ispn import com.fasterxml.jackson.databind.ObjectMapper import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualMachine import com.github.kerubistan.kerub.utils.createObjectMapper import org.hamcrest.CoreMatchers import org.junit.Assert.assertThat import org.junit.Test import java.util.UUID class JsonMarshallerIT { val mapper: ObjectMapper = createObjectMapper() val vm = VirtualMachine( id = UUID.randomUUID(), name = "foo" ) @Test fun objectToBuffer() { val buffer = JsonMarshaller(mapper).objectToBuffer(vm) assertThat("Buffer must be non-empty", buffer!!.length, CoreMatchers.not(0)) } @Test fun vmFromByteBuffer() { val vm = JsonMarshaller(mapper).objectFromByteBuffer( (""" { "@type":"vm", "id":"49c4364b-75c5-4c16-9d6d-984d20a7356e", "name":"foo", "nrOfCpus":1, "memory":{ "min":1024, "max":2048 }, "expectations":[], "virtualStorageLinks":[] } """).toByteArray(charset("UTF-8")) ) as VirtualMachine assertThat("Person must be non-null", vm, CoreMatchers.notNullValue()) assertThat("First name must match", vm.name, CoreMatchers.`is`("foo")) } @Test fun hostFromByteBuffer() { val host = JsonMarshaller(mapper).objectFromByteBuffer( (""" { "@type":"host", "id":"49c4364b-75c5-4c16-9d6d-984d20a7356e", "address":"127.0.0.1", "dedicated":false, "publicKey":"abcdef" } """).toByteArray(charset("UTF-8")) ) as Host assertThat("host must be non-null", host, CoreMatchers.notNullValue()) assertThat("Host address must match", host.address, CoreMatchers.`is`("127.0.0.1")) assertThat("Host public key must match", host.publicKey, CoreMatchers.`is`("abcdef")) assertThat("Host id must match", host.id, CoreMatchers.`is`(UUID.fromString("49c4364b-75c5-4c16-9d6d-984d20a7356e"))) } }
apache-2.0
4f87d8db5ba98eb33622eaa65ce1d120
28.385714
119
0.64251
3.398347
false
true
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/settings/CodeVisionGroupDefaultSettingModel.kt
1
4746
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.codeVision.settings import com.intellij.codeInsight.codeVision.* import com.intellij.codeInsight.hints.codeVision.CodeVisionPass import com.intellij.codeInsight.hints.codeVision.CodeVisionProviderAdapter import com.intellij.lang.IdeLanguageCustomization import com.intellij.lang.Language import com.intellij.openapi.editor.Editor import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.util.Key import com.intellij.psi.PsiFile import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.dsl.builder.panel import com.intellij.util.ResourceUtil import javax.swing.JComponent import javax.swing.JPanel open class CodeVisionGroupDefaultSettingModel(override val name: String, groupId: String, override val description: String?, isEnabled: Boolean, val providers: List<CodeVisionProvider<*>>) : CodeVisionGroupSettingModel(isEnabled, id = groupId) { companion object { private val CODE_VISION_PREVIEW_ENABLED = Key<Boolean>("code.vision.preview.data") internal fun isEnabledInPreview(editor: Editor) : Boolean? { return editor.getUserData(CODE_VISION_PREVIEW_ENABLED) } internal val anchorRenderer: SimpleListCellRenderer<CodeVisionAnchorKind> = SimpleListCellRenderer.create( SimpleListCellRenderer.Customizer { label, value, _ -> label.text = CodeVisionBundle.message(value.key) }) } private val settings = CodeVisionSettings.instance() private val uiData by lazy { var positionComboBox: ComboBox<CodeVisionAnchorKind>? = null val panel = panel { row { label(CodeVisionBundle.message("CodeVisionConfigurable.column.name.position")) val comboBox = comboBox(CodeVisionGlobalSettingsProvider.supportedAnchors, anchorRenderer).component comboBox.item = settings.getPositionForGroup(id) positionComboBox = comboBox } } UIData(panel, positionComboBox!!) } override fun collectData(editor: Editor, file: PsiFile): Runnable { for (provider in providers) { provider.preparePreview(editor, file) } val daemonBoundProviders = providers.filterIsInstance<CodeVisionProviderAdapter>().map { it.delegate } val codeVisionData = CodeVisionPass.collectData(editor, file, daemonBoundProviders) return Runnable { editor.putUserData(CODE_VISION_PREVIEW_ENABLED, isEnabled) val project = editor.project ?: return@Runnable codeVisionData.applyTo(editor, project) CodeVisionInitializer.getInstance(project).getCodeVisionHost().invalidateProviderSignal .fire(CodeVisionHost.LensInvalidateSignal(editor)) } } override val component: JComponent get() = uiData.component override val previewText: String? get() = getCasePreview() override val previewLanguage: Language? get() { val primaryIdeLanguages = IdeLanguageCustomization.getInstance().primaryIdeLanguages return CodeVisionSettingsPreviewLanguage.EP_NAME.extensionList.asSequence() .filter { it.modelId == id } .map { Language.findLanguageByID(it.language) } .sortedBy { primaryIdeLanguages.indexOf(it).takeIf { it != -1 } ?: Integer.MAX_VALUE } .firstOrNull() ?: Language.findLanguageByID("JAVA") } override fun isModified(): Boolean { return (isEnabled != (settings.isProviderEnabled(id) && settings.codeVisionEnabled) || (uiData.positionComboBox.item != null && uiData.positionComboBox.item != getPositionForGroup())) } private fun getPositionForGroup() = settings.getPositionForGroup(id) ?: CodeVisionAnchorKind.Default override fun apply() { settings.setProviderEnabled(id, isEnabled) settings.setPositionForGroup(id, uiData.positionComboBox.item) } override fun reset() { isEnabled = settings.isProviderEnabled(id) && settings.codeVisionEnabled uiData.positionComboBox.item = settings.getPositionForGroup(id) ?: CodeVisionAnchorKind.Default } private fun getCasePreview(): String? { val associatedFileType = previewLanguage?.associatedFileType ?: return null val path = "codeVisionProviders/" + id + "/preview." + associatedFileType.defaultExtension val stream = associatedFileType.javaClass.classLoader.getResourceAsStream(path) return if (stream != null) ResourceUtil.loadText(stream) else null } private class UIData(val component: JPanel, val positionComboBox: ComboBox<CodeVisionAnchorKind>) }
apache-2.0
d829c508a71e5e3dce9b9ad46a0501f3
42.944444
146
0.724189
4.907963
false
false
false
false
Yusspy/Jolt-Sphere
core/src/org/joltsphere/mechanics/MountainClimbingPlayer.kt
1
3118
package org.joltsphere.mechanics import org.joltsphere.main.JoltSphereMain import org.joltsphere.misc.ObjectData import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.BodyDef import com.badlogic.gdx.physics.box2d.BodyDef.BodyType import com.badlogic.gdx.physics.box2d.CircleShape import com.badlogic.gdx.physics.box2d.FixtureDef import com.badlogic.gdx.physics.box2d.World class MountainClimbingPlayer(private val world: World, x: Float, y: Float, private val color: Color) { var body: Body private val bdef: BodyDef private val fdef: FixtureDef private val circle: CircleShape private var isGrounded = false private var canDouble = false private val ppm = JoltSphereMain.ppm private var dt = 0.01666f init { bdef = BodyDef() bdef.type = BodyType.DynamicBody bdef.position.set(x / ppm, y / ppm) bdef.fixedRotation = false bdef.bullet = true bdef.linearDamping = 0.2f bdef.angularDamping = 0.5f body = world.createBody(bdef) body.userData = ObjectData("mountainClimber") fdef = FixtureDef() circle = CircleShape() circle.radius = 50 / ppm fdef.shape = circle fdef.friction = 0.1f fdef.density = 10f fdef.restitution = 0f body.createFixture(fdef) } fun shapeRender(shapeRender: ShapeRenderer) { shapeRender.color = color shapeRender.circle(body.position.x * ppm, body.position.y * ppm, 50f) shapeRender.color = Color.GOLD } fun update(dt: Float, groundContacts: Int) { this.dt = dt if (groundContacts > 0) isGrounded = true else isGrounded = false if (isGrounded) { canDouble = true } } fun moveLeft() { moveHorizontal(-1) } fun moveRight() { moveHorizontal(1) } private fun moveHorizontal(dir: Int) { body.applyForceToCenter((30 * dir).toFloat(), 0f, true) body.applyTorque((-5 * dir).toFloat(), true) } fun jump() { if (isGrounded) { body.setLinearVelocity(body.linearVelocity.x * 0.3f, body.linearVelocity.y * 0.3f) body.applyLinearImpulse(Vector2(0f, 16f), body.position, true) } if (canDouble) { canDouble = false body.setLinearVelocity(0f, 0f) body.applyLinearImpulse(Vector2(0f, 12f), body.position, true) } //body.applyForceToCenter(0, 40, true); } fun fly() { body.applyForceToCenter(Vector2(0f, 60f), true) } fun input(up: Int, down: Int, left: Int, right: Int, modifier: Int, fly: Boolean) { if (Gdx.input.isKeyPressed(left)) moveLeft() if (Gdx.input.isKeyPressed(right)) moveRight() if (Gdx.input.isKeyPressed(up) && fly) fly() else if (Gdx.input.isKeyJustPressed(up)) jump() } }
agpl-3.0
2c2c31ecb9bad37be1756010e25a273a
28.140187
102
0.633098
3.567506
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinLanguageCodeStyleSettingsProvider.kt
4
20632
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.formatter import com.intellij.application.options.CodeStyleAbstractConfigurable import com.intellij.application.options.CodeStyleAbstractPanel import com.intellij.application.options.IndentOptionsEditor import com.intellij.application.options.SmartIndentOptionsEditor import com.intellij.application.options.codeStyle.properties.CodeStyleFieldAccessor import com.intellij.application.options.codeStyle.properties.CodeStylePropertyAccessor import com.intellij.lang.Language import com.intellij.openapi.application.ApplicationBundle import com.intellij.psi.codeStyle.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntryTable import java.lang.reflect.Field import kotlin.reflect.KProperty class KotlinLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() { override fun getLanguage(): Language = KotlinLanguage.INSTANCE override fun getConfigurableDisplayName(): String = KotlinBundle.message("codestyle.name.kotlin") override fun createConfigurable(settings: CodeStyleSettings, modelSettings: CodeStyleSettings): CodeStyleConfigurable = object : CodeStyleAbstractConfigurable(settings, modelSettings, KotlinLanguage.INSTANCE.displayName) { override fun createPanel(settings: CodeStyleSettings): CodeStyleAbstractPanel = KotlinCodeStylePanel(currentSettings, settings) override fun getHelpTopic(): String = "reference.settingsdialog.codestyle.kotlin" } override fun getIndentOptionsEditor(): IndentOptionsEditor = SmartIndentOptionsEditor() override fun getDefaultCommonSettings(): CommonCodeStyleSettings = KotlinCommonCodeStyleSettings().apply { initIndentOptions() } override fun createCustomSettings(settings: CodeStyleSettings): CustomCodeStyleSettings = KotlinCodeStyleSettings(settings) override fun getAccessor(codeStyleObject: Any, field: Field): CodeStyleFieldAccessor<*, *>? { if (codeStyleObject is KotlinCodeStyleSettings && KotlinPackageEntryTable::class.java.isAssignableFrom(field.type)) { return KotlinPackageEntryTableAccessor(codeStyleObject, field) } return super.getAccessor(codeStyleObject, field) } override fun getAdditionalAccessors(codeStyleObject: Any): List<CodeStylePropertyAccessor<*>> { if (codeStyleObject is KotlinCodeStyleSettings) { return listOf(KotlinCodeStylePropertyAccessor(codeStyleObject)) } return super.getAdditionalAccessors(codeStyleObject) } override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) { fun showCustomOption(field: KProperty<*>, title: String, groupName: String? = null, vararg options: Any) { consumer.showCustomOption(KotlinCodeStyleSettings::class.java, field.name, title, groupName, *options) } val codeStyleSettingsCustomizableOptions = CodeStyleSettingsCustomizableOptions.getInstance() when (settingsType) { SettingsType.SPACING_SETTINGS -> { consumer.showStandardOptions( "SPACE_AROUND_ASSIGNMENT_OPERATORS", "SPACE_AROUND_LOGICAL_OPERATORS", "SPACE_AROUND_EQUALITY_OPERATORS", "SPACE_AROUND_RELATIONAL_OPERATORS", "SPACE_AROUND_ADDITIVE_OPERATORS", "SPACE_AROUND_MULTIPLICATIVE_OPERATORS", "SPACE_AROUND_UNARY_OPERATOR", "SPACE_AFTER_COMMA", "SPACE_BEFORE_COMMA", "SPACE_BEFORE_IF_PARENTHESES", "SPACE_BEFORE_WHILE_PARENTHESES", "SPACE_BEFORE_FOR_PARENTHESES", "SPACE_BEFORE_CATCH_PARENTHESES" ) showCustomOption( KotlinCodeStyleSettings::SPACE_AROUND_RANGE, KotlinBundle.message("formatter.title.range.operator"), codeStyleSettingsCustomizableOptions.SPACES_AROUND_OPERATORS ) showCustomOption( KotlinCodeStyleSettings::SPACE_BEFORE_TYPE_COLON, KotlinBundle.message("formatter.title.before.colon.after.declaration.name"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_AFTER_TYPE_COLON, KotlinBundle.message("formatter.title.after.colon.before.declaration.type"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_BEFORE_EXTEND_COLON, KotlinBundle.message("formatter.title.before.colon.in.new.type.definition"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_AFTER_EXTEND_COLON, KotlinBundle.message("formatter.title.after.colon.in.new.type.definition"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD, KotlinBundle.message("formatter.title.in.simple.one.line.methods"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_AROUND_FUNCTION_TYPE_ARROW, KotlinBundle.message("formatter.title.around.arrow.in.function.types"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_AROUND_WHEN_ARROW, KotlinBundle.message("formatter.title.around.arrow.in"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_BEFORE_LAMBDA_ARROW, KotlinBundle.message("formatter.title.before.lambda.arrow"), codeStyleSettingsCustomizableOptions.SPACES_OTHER ) showCustomOption( KotlinCodeStyleSettings::SPACE_BEFORE_WHEN_PARENTHESES, KotlinBundle.message("formatter.title.when.parentheses"), codeStyleSettingsCustomizableOptions.SPACES_BEFORE_PARENTHESES ) } SettingsType.WRAPPING_AND_BRACES_SETTINGS -> { consumer.showStandardOptions( // "ALIGN_MULTILINE_CHAINED_METHODS", "RIGHT_MARGIN", "WRAP_ON_TYPING", "KEEP_FIRST_COLUMN_COMMENT", "KEEP_LINE_BREAKS", "ALIGN_MULTILINE_EXTENDS_LIST", "ALIGN_MULTILINE_PARAMETERS", "ALIGN_MULTILINE_PARAMETERS_IN_CALLS", "ALIGN_MULTILINE_METHOD_BRACKETS", "ALIGN_MULTILINE_BINARY_OPERATION", "ELSE_ON_NEW_LINE", "WHILE_ON_NEW_LINE", "CATCH_ON_NEW_LINE", "FINALLY_ON_NEW_LINE", "CALL_PARAMETERS_WRAP", "METHOD_PARAMETERS_WRAP", "EXTENDS_LIST_WRAP", "METHOD_ANNOTATION_WRAP", "CLASS_ANNOTATION_WRAP", "PARAMETER_ANNOTATION_WRAP", "VARIABLE_ANNOTATION_WRAP", "FIELD_ANNOTATION_WRAP", "METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE", "METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE", "CALL_PARAMETERS_LPAREN_ON_NEXT_LINE", "CALL_PARAMETERS_RPAREN_ON_NEXT_LINE", "ENUM_CONSTANTS_WRAP", "METHOD_CALL_CHAIN_WRAP", "WRAP_FIRST_METHOD_IN_CALL_CHAIN", "ASSIGNMENT_WRAP", ) consumer.renameStandardOption( codeStyleSettingsCustomizableOptions.WRAPPING_SWITCH_STATEMENT, KotlinBundle.message("formatter.title.when.statements") ) consumer.renameStandardOption("FIELD_ANNOTATION_WRAP", KotlinBundle.message("formatter.title.property.annotations")) consumer.renameStandardOption( "METHOD_PARAMETERS_WRAP", KotlinBundle.message("formatter.title.function.declaration.parameters") ) consumer.renameStandardOption("CALL_PARAMETERS_WRAP", KotlinBundle.message("formatter.title.function.call.arguments")) consumer.renameStandardOption("METHOD_CALL_CHAIN_WRAP", KotlinBundle.message("formatter.title.chained.function.calls")) consumer.renameStandardOption("METHOD_ANNOTATION_WRAP", KotlinBundle.message("formatter.title.function.annotations")) consumer.renameStandardOption( codeStyleSettingsCustomizableOptions.WRAPPING_METHOD_PARENTHESES, KotlinBundle.message("formatter.title.function.parentheses") ) showCustomOption( KotlinCodeStyleSettings::ALIGN_IN_COLUMNS_CASE_BRANCH, KotlinBundle.message("formatter.title.align.when.branches.in.columns"), codeStyleSettingsCustomizableOptions.WRAPPING_SWITCH_STATEMENT ) showCustomOption( KotlinCodeStyleSettings::LINE_BREAK_AFTER_MULTILINE_WHEN_ENTRY, KotlinBundle.message("formatter.title.line.break.after.multiline.when.entry"), codeStyleSettingsCustomizableOptions.WRAPPING_SWITCH_STATEMENT ) showCustomOption( KotlinCodeStyleSettings::LBRACE_ON_NEXT_LINE, KotlinBundle.message("formatter.title.put.left.brace.on.new.line"), codeStyleSettingsCustomizableOptions.WRAPPING_BRACES ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_IN_PARAMETER_LISTS, KotlinBundle.message("formatter.title.use.continuation.indent"), codeStyleSettingsCustomizableOptions.WRAPPING_METHOD_PARAMETERS ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_IN_ARGUMENT_LISTS, KotlinBundle.message("formatter.title.use.continuation.indent"), codeStyleSettingsCustomizableOptions.WRAPPING_METHOD_ARGUMENTS_WRAPPING ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_FOR_CHAINED_CALLS, KotlinBundle.message("formatter.title.use.continuation.indent"), codeStyleSettingsCustomizableOptions.WRAPPING_CALL_CHAIN ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_IN_SUPERTYPE_LISTS, KotlinBundle.message("formatter.title.use.continuation.indent"), codeStyleSettingsCustomizableOptions.WRAPPING_EXTENDS_LIST ) showCustomOption( KotlinCodeStyleSettings::WRAP_EXPRESSION_BODY_FUNCTIONS, KotlinBundle.message("formatter.title.expression.body.functions"), options = *arrayOf( codeStyleSettingsCustomizableOptions.WRAP_OPTIONS_FOR_SINGLETON, CodeStyleSettingsCustomizable.WRAP_VALUES_FOR_SINGLETON ) ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_FOR_EXPRESSION_BODIES, KotlinBundle.message("formatter.title.use.continuation.indent"), KotlinBundle.message("formatter.title.expression.body.functions") ) showCustomOption( KotlinCodeStyleSettings::WRAP_ELVIS_EXPRESSIONS, KotlinBundle.message("formatter.title.elvis.expressions"), options = *arrayOf( codeStyleSettingsCustomizableOptions.WRAP_OPTIONS_FOR_SINGLETON, CodeStyleSettingsCustomizable.WRAP_VALUES_FOR_SINGLETON ) ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_IN_ELVIS, title = KotlinBundle.message("formatter.title.use.continuation.indent"), groupName = KotlinBundle.message("formatter.title.elvis.expressions") ) showCustomOption( KotlinCodeStyleSettings::IF_RPAREN_ON_NEW_LINE, ApplicationBundle.message("wrapping.rpar.on.new.line"), codeStyleSettingsCustomizableOptions.WRAPPING_IF_STATEMENT ) showCustomOption( KotlinCodeStyleSettings::CONTINUATION_INDENT_IN_IF_CONDITIONS, KotlinBundle.message("formatter.title.use.continuation.indent.in.conditions"), codeStyleSettingsCustomizableOptions.WRAPPING_IF_STATEMENT ) } SettingsType.BLANK_LINES_SETTINGS -> { consumer.showStandardOptions( "KEEP_BLANK_LINES_IN_CODE", "KEEP_BLANK_LINES_IN_DECLARATIONS", "KEEP_BLANK_LINES_BEFORE_RBRACE", "BLANK_LINES_AFTER_CLASS_HEADER" ) showCustomOption( KotlinCodeStyleSettings::BLANK_LINES_AROUND_BLOCK_WHEN_BRANCHES, KotlinBundle.message("formatter.title.around.when.branches.with"), codeStyleSettingsCustomizableOptions.BLANK_LINES ) showCustomOption( KotlinCodeStyleSettings::BLANK_LINES_BEFORE_DECLARATION_WITH_COMMENT_OR_ANNOTATION_ON_SEPARATE_LINE, KotlinBundle.message("formatter.title.before.declaration.with.comment.or.annotation"), codeStyleSettingsCustomizableOptions.BLANK_LINES ) } SettingsType.COMMENTER_SETTINGS -> { consumer.showAllStandardOptions() } else -> consumer.showStandardOptions() } } override fun usesCommonKeepLineBreaks(): Boolean { return true } override fun getCodeSample(settingsType: SettingsType): String = when (settingsType) { SettingsType.WRAPPING_AND_BRACES_SETTINGS -> """ @Deprecated("Foo") public class ThisIsASampleClass : Comparable<*>, Appendable { val test = 12 @Deprecated("Foo") fun foo1(i1: Int, i2: Int, i3: Int) : Int { when (i1) { is Number -> 0 else -> 1 } if (i2 > 0 && i3 < 0) { return 2 } return 0 } private fun foo2():Int { // todo: something try { return foo1(12, 13, 14) } catch (e: Exception) { return 0 } finally { if (true) { return 1 } else { return 2 } } } private val f = {a: Int->a*2} fun longMethod(@Named("param1") param1: Int, param2: String) { @Deprecated val foo = 1 } fun multilineMethod( foo: String, bar: String?, x: Int? ) { foo.toUpperCase().trim() .length val barLen = bar?.length() ?: x ?: -1 if (foo.length > 0 && barLen > 0) { println("> 0") } } } @Deprecated val bar = 1 enum class Enumeration { A, B } fun veryLongExpressionBodyMethod() = "abc" """.trimIndent() SettingsType.BLANK_LINES_SETTINGS -> """ class Foo { private var field1: Int = 1 private val field2: String? = null init { field1 = 2; } fun foo1() { run { field1 } when(field1) { 1 -> println("1") 2 -> println("2") 3 -> println("3" + "4") } when(field2) { 1 -> { println("1") } 2 -> { println("2") } } } class InnerClass { } } class AnotherClass { } interface TestInterface { } fun run(f: () -> Unit) { f() } class Bar { @Annotation val a = 42 @Annotation val b = 43 fun c() { a + b } fun d() = Unit // smth fun e() { d() } fun f() = d() } """.trimIndent() else -> """open class Some { private val f: (Int)->Int = { a: Int -> a * 2 } fun foo(): Int { val test: Int = 12 for (i in 10..<42) { println (when { i < test -> -1 i > test -> 1 else -> 0 }) } if (true) { } while (true) { break } try { when (test) { 12 -> println("foo") in 10..42 -> println("baz") else -> println("bar") } } catch (e: Exception) { } finally { } return test } private fun <T>foo2(): Int where T : List<T> { return 0 } fun multilineMethod( foo: String, bar: String ) { foo .length } fun expressionBodyMethod() = "abc" } class AnotherClass<T : Any> : Some() """.trimIndent() } }
apache-2.0
f90b499b67270dcf66764589aa7bebca
42.711864
223
0.516043
6.008154
false
false
false
false
lnr0626/cfn-templates
aws/src/main/kotlin/com/lloydramey/cfn/model/aws/autoscaling/EbsBlockDevice.kt
1
905
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lloydramey.cfn.model.aws.autoscaling data class EbsBlockDevice( val deleteOnTermination: Boolean? = null, val encrypted: Boolean? = null, val iops: Int? = null, val snapshotId: String? = null, val volumeSize: Int? = null, val volumeType: String? = null )
apache-2.0
cec038da4d69d500716621338496a4f2
35.24
75
0.723757
3.951965
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/DestructuringDeclarationReferenceSearcher.kt
4
2318
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.references.KtDestructuringDeclarationReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class DestructuringDeclarationReferenceSearcher( targetDeclaration: PsiElement, private val componentIndex: Int, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtDestructuringDeclaration>( targetDeclaration, searchScope, consumer, optimizer, options, wordsToSearch = listOf("(") ) { override fun extractReference(element: KtElement): PsiReference? { val destructuringDeclaration = element as? KtDestructuringDeclaration ?: return null val entries = destructuringDeclaration.entries if (entries.size < componentIndex) return null return entries[componentIndex - 1].references.firstIsInstance<KtDestructuringDeclarationReference>() } override fun isReferenceToCheck(ref: PsiReference) = ref is KtDestructuringDeclarationReference override fun processPossibleReceiverExpression(expression: KtExpression) { val destructuringDeclaration = when (val parent = expression.parent) { is KtDestructuringDeclaration -> parent is KtContainerNode -> { if (parent.node.elementType == KtNodeTypes.LOOP_RANGE) { (parent.parent as KtForExpression).destructuringDeclaration } else { null } } else -> null } if (destructuringDeclaration != null) { processReferenceElement(destructuringDeclaration) } } }
apache-2.0
9b56bd2563f42265788b9b34cdddf0d5
39.684211
158
0.735116
5.681373
false
false
false
false
GunoH/intellij-community
java/compiler/impl/src/com/intellij/packaging/impl/artifacts/workspacemodel/ArtifactManagerBridge.kt
1
13867
// 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.packaging.impl.artifacts.workspacemodel import com.intellij.compiler.server.BuildManager import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.trace import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.* import com.intellij.packaging.artifacts.* import com.intellij.packaging.elements.CompositePackagingElement import com.intellij.packaging.elements.PackagingElement import com.intellij.packaging.elements.PackagingElementFactory import com.intellij.packaging.elements.PackagingElementResolvingContext import com.intellij.packaging.impl.artifacts.ArtifactPointerManagerImpl import com.intellij.packaging.impl.artifacts.DefaultPackagingElementResolvingContext import com.intellij.packaging.impl.artifacts.InvalidArtifact import com.intellij.util.concurrency.annotations.RequiresReadLock import com.intellij.util.concurrency.annotations.RequiresWriteLock import com.intellij.util.containers.BidirectionalMap import com.intellij.util.xmlb.XmlSerializer import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.ArtifactEntity import com.intellij.workspaceModel.storage.bridgeEntities.ArtifactId import com.intellij.workspaceModel.storage.bridgeEntities.CustomPackagingElementEntity import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity class ArtifactManagerBridge(private val project: Project) : ArtifactManager(), Disposable { private val modificationTracker = SimpleModificationTracker() private val resolvingContext = DefaultPackagingElementResolvingContext(project) internal val artifactWithDiffs: MutableList<ArtifactBridge> = mutableListOf() init { (ArtifactPointerManager.getInstance(project) as ArtifactPointerManagerImpl).setArtifactManager(this) DynamicArtifactExtensionsLoaderBridge(this).installListeners(this) } @RequiresReadLock override fun getArtifacts(): Array<ArtifactBridge> { initBridges() val workspaceModel = WorkspaceModel.getInstance(project) val entityStorage = workspaceModel.entityStorage val store = entityStorage.current return store .entities(ArtifactEntity::class.java) .map { store.artifactsMap.getDataByEntity(it) ?: error("All artifact bridges should be already created at this moment") } .filter { VALID_ARTIFACT_CONDITION.value(it) } .toList().toTypedArray() } @RequiresReadLock override fun findArtifact(name: String): Artifact? { initBridges() val workspaceModel = WorkspaceModel.getInstance(project) val entityStorage = workspaceModel.entityStorage val store = entityStorage.current val artifactEntity = store.resolve(ArtifactId(name)) ?: return null return store.artifactsMap.getDataByEntity(artifactEntity) ?: error("All artifact bridges should be already created at this moment") } override fun getArtifactByOriginal(artifact: Artifact): Artifact = artifact override fun getOriginalArtifact(artifact: Artifact): Artifact = artifact @RequiresReadLock override fun getArtifactsByType(type: ArtifactType): List<ArtifactBridge> { // XXX @RequiresReadLock annotation doesn't work for kt now ApplicationManager.getApplication().assertReadAccessAllowed() initBridges() val workspaceModel = WorkspaceModel.getInstance(project) val entityStorage = workspaceModel.entityStorage val store = entityStorage.current val typeId = type.id return store .entities(ArtifactEntity::class.java) .filter { it.artifactType == typeId } .map { store.artifactsMap.getDataByEntity(it) ?: error("All artifact bridges should be already created at this moment") } .toList() } @RequiresReadLock override fun getAllArtifactsIncludingInvalid(): MutableList<out Artifact> { // XXX @RequiresReadLock annotation doesn't work for kt now ApplicationManager.getApplication().assertReadAccessAllowed() initBridges() val entityStorage = WorkspaceModel.getInstance(project).entityStorage val storage = entityStorage.current return storage .entities(ArtifactEntity::class.java) .map { storage.artifactsMap.getDataByEntity(it) ?: error("All artifact bridges should be already created at this moment") } .toMutableList() } @RequiresReadLock override fun getSortedArtifacts(): Array<ArtifactBridge> { val artifacts = this.artifacts // TODO: 02.02.2021 Do not sort them each time artifacts.sortWith(ARTIFACT_COMPARATOR) return artifacts } override fun createModifiableModel(): ModifiableArtifactModel { val storage = WorkspaceModel.getInstance(project).entityStorage.current return ArtifactModifiableModelBridge(project, MutableEntityStorage.from(storage), this) } override fun getResolvingContext(): PackagingElementResolvingContext = resolvingContext override fun addArtifact(name: String, type: ArtifactType, root: CompositePackagingElement<*>?): Artifact { return WriteAction.compute(ThrowableComputable<ModifiableArtifact, RuntimeException> { val model = createModifiableModel() val artifact = model.addArtifact(name, type) if (root != null) { artifact.rootElement = root } model.commit() artifact }) } override fun addElementsToDirectory(artifact: Artifact, relativePath: String, elements: Collection<PackagingElement<*>>) { val model = createModifiableModel() val root = model.getOrCreateModifiableArtifact(artifact).rootElement PackagingElementFactory.getInstance().getOrCreateDirectory(root, relativePath).addOrFindChildren(elements) WriteAction.run<RuntimeException> { model.commit() } } override fun addElementsToDirectory(artifact: Artifact, relativePath: String, element: PackagingElement<*>) { addElementsToDirectory(artifact, relativePath, listOf(element)) } override fun getModificationTracker(): ModificationTracker { return modificationTracker } @RequiresWriteLock fun commit(artifactModel: ArtifactModifiableModelBridge) { // XXX @RequiresReadLock annotation doesn't work for kt now ApplicationManager.getApplication().assertWriteAccessAllowed() LOG.trace { "Committing artifact manager bridge. diff: ${artifactModel.diff}" } updateCustomElements(artifactModel.diff) val current = WorkspaceModel.getInstance(project).entityStorage.current val changes = artifactModel.diff.collectChanges(current)[ArtifactEntity::class.java] ?: emptyList() val removed = mutableSetOf<ArtifactBridge>() val added = mutableListOf<ArtifactBridge>() val changed = mutableListOf<Triple<ArtifactBridge, String, ArtifactBridge>>() val changedArtifacts: MutableList<ArtifactBridge> = mutableListOf() val modifiableToOriginal = BidirectionalMap<ArtifactBridge, ArtifactBridge>() artifactModel.modifiableToOriginal.forEach { key, value -> modifiableToOriginal[key] = value } changes.forEach { when (it) { is EntityChange.Removed<*> -> current.artifactsMap.getDataByEntity(it.entity)?.let { it1 -> removed.add(it1) } is EntityChange.Added -> Unit is EntityChange.Replaced -> { // Collect changes and transfer info from the modifiable bridge artifact to the original artifact val originalArtifact = artifactModel.diff.artifactsMap.getDataByEntity(it.newEntity)!! val modifiableArtifact = modifiableToOriginal.getKeysByValue(originalArtifact)!!.single() if (modifiableArtifact !== originalArtifact) { changedArtifacts.add(modifiableArtifact) } originalArtifact.copyFrom(modifiableArtifact) changed.add(Triple(originalArtifact, (it.oldEntity as ArtifactEntity).name, modifiableArtifact)) originalArtifact.setActualStorage() modifiableToOriginal.remove(modifiableArtifact, originalArtifact) } } } modifiableToOriginal.entries.forEach { (modifiable, original) -> if (modifiable !== original) { changedArtifacts.add(modifiable) val oldName = original.name original.copyFrom(modifiable) changed.add(Triple(original, oldName, modifiable)) } } (ArtifactPointerManager.getInstance(project) as ArtifactPointerManagerImpl).disposePointers(changedArtifacts) WorkspaceModel.getInstance(project).updateProjectModel("Commit artifact manager") { it.addDiff(artifactModel.diff) } modificationTracker.incModificationCount() // Collect changes changes.forEach { when (it) { is EntityChange.Added<*> -> { val artifactBridge = artifactModel.diff.artifactsMap.getDataByEntity(it.entity)!! added.add(artifactBridge) artifactBridge.setActualStorage() } is EntityChange.Removed<*> -> Unit is EntityChange.Replaced<*> -> Unit } } // Set actual storages artifactWithDiffs.forEach { it.setActualStorage() } artifactWithDiffs.clear() val entityStorage = WorkspaceModel.getInstance(project).entityStorage added.forEach { bridge -> bridge.elementsWithDiff.forEach { it.setStorage(entityStorage, project, HashSet(), PackagingElementInitializer) } bridge.elementsWithDiff.clear() } changed.forEach { changedItem -> changedItem.third.elementsWithDiff.forEach { it.setStorage(entityStorage, project, HashSet(), PackagingElementInitializer) } changedItem.third.elementsWithDiff.clear() changedItem.first.elementsWithDiff.forEach { it.setStorage(entityStorage, project, HashSet(), PackagingElementInitializer) } changedItem.first.elementsWithDiff.clear() } artifactModel.elementsWithDiff.forEach { it.setStorage(entityStorage, project, HashSet(), PackagingElementInitializer) } artifactModel.elementsWithDiff.clear() val publisher: ArtifactListener = project.messageBus.syncPublisher(TOPIC) ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring { //it's important to send 'removed' events before 'added'. Otherwise when artifacts are reloaded from xml artifact pointers will be damaged removed.forEach { publisher.artifactRemoved(it) } added.forEach { publisher.artifactAdded(it) } changed.forEach { (artifact, oldName) -> publisher.artifactChanged(artifact, oldName) } } if (changes.isNotEmpty()) { BuildManager.getInstance().clearState(project) } } private fun updateCustomElements(diff: MutableEntityStorage) { val customEntities = diff.entities(CustomPackagingElementEntity::class.java).toList() for (customEntity in customEntities) { val packagingElement = diff.elements.getDataByEntity(customEntity) ?: continue val state = packagingElement.state ?: continue val newState = JDOMUtil.write(XmlSerializer.serialize(state)) if (newState != customEntity.propertiesXmlTag) { diff.modifyEntity(customEntity) { this.propertiesXmlTag = newState } } } } // Initialize all artifact bridges @RequiresReadLock private fun initBridges() { // XXX @RequiresReadLock annotation doesn't work for kt now ApplicationManager.getApplication().assertReadAccessAllowed() val workspaceModel = WorkspaceModel.getInstance(project) val current = workspaceModel.entityStorage.current if (current.entitiesAmount(ArtifactEntity::class.java) != current.artifactsMap.size()) { synchronized(lock) { val currentInSync = workspaceModel.entityStorage.current val artifactsMap = currentInSync.artifactsMap // Double check if (currentInSync.entitiesAmount(ArtifactEntity::class.java) != artifactsMap.size()) { val newBridges = currentInSync .entities(ArtifactEntity::class.java) .mapNotNull { if (artifactsMap.getDataByEntity(it) == null) { createArtifactBridge(it, workspaceModel.entityStorage, project) } else null } .toList() (workspaceModel as WorkspaceModelImpl).updateProjectModelSilent("Initialize artifact bridges") { addBridgesToDiff(newBridges, it) } } } } } companion object { private val lock = Any() private const val ARTIFACT_BRIDGE_MAPPING_ID = "intellij.artifacts.bridge" val EntityStorage.artifactsMap: ExternalEntityMapping<ArtifactBridge> get() = getExternalMapping(ARTIFACT_BRIDGE_MAPPING_ID) internal val MutableEntityStorage.mutableArtifactsMap: MutableExternalEntityMapping<ArtifactBridge> get() = getMutableExternalMapping(ARTIFACT_BRIDGE_MAPPING_ID) private val LOG = logger<ArtifactManagerBridge>() val VALID_ARTIFACT_CONDITION: Condition<Artifact> = Condition { it !is InvalidArtifact } } override fun dispose() { // Anything here? } @RequiresWriteLock fun dropMappings(selector: (ArtifactEntity) -> Boolean) { // XXX @RequiresReadLock annotation doesn't work for kt now ApplicationManager.getApplication().assertWriteAccessAllowed() (WorkspaceModel.getInstance(project) as WorkspaceModelImpl).updateProjectModelSilent("Drop artifact mappings") { val map = it.mutableArtifactsMap it.entities(ArtifactEntity::class.java).filter(selector).forEach { artifact -> map.removeMapping(artifact) } } } }
apache-2.0
cd52a8b9196c4b33617c7c9f882adc36
40.642643
144
0.74854
5.107551
false
false
false
false
kivensolo/UiUsingListView
library/player/src/main/java/com/kingz/library/player/internal/AndroidPlayer.kt
1
10890
package com.kingz.library.player.internal import android.content.Context import android.graphics.SurfaceTexture import android.media.MediaPlayer import android.media.TimedText import android.net.Uri import android.util.Log import android.view.Surface import android.view.SurfaceHolder import com.kingz.library.player.BasePlayer import com.kingz.library.player.IPlayer import com.kingz.library.player.IPlayer.Companion.MEDIA_INFO_VIDEO_RENDERING_START import com.kingz.library.player.TrackInfo import com.kingz.utils.runSafely /** * author:KingZ * date:2019/7/30 * description:Android原生播放器 */ class AndroidPlayer(context: Context?) : BasePlayer(){ private var mInternalMediaPlayer: MediaPlayer? private var bufferPercent = 0 private val isSeeking = false private val mIsBuffering = false private var isAutoPlayWhenRedy = false init { mContext = context mInternalMediaPlayer = MediaPlayer() mInternalMediaPlayer?.setScreenOnWhilePlaying(true) attachListener() } companion object { private val TAG = AndroidPlayer::class.java.simpleName // Protect time of seek. private const val SEEK_PROTECT_TIME_MS = 10 * 1000 } override fun selectAudioTrack(audioTrackIndex: Int) {} override fun setDisplayHolder(holder: SurfaceHolder?) { //TODO } override fun setSpeed(speed: Float) {} // Internal mediaPlayer is unsupport speed. override fun setPlayerOptions( playerOptionCategory: Int, optionName: String, optionValue: String ) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setPlayerOptions( playerOptionCategory: Int, optionName: String, optionValue: Long ) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setMirrorPlay() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setBufferSize(bufferSize: Int) {} override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} override fun play() { super.play() runSafely({ mInternalMediaPlayer?.start() }, { Log.e(TAG, "play error:" + it.message) playerListener?.onError(this,IPlayer.MEDIA_ERROR_PLAY_STATUS, -1) }) } override fun getAudioTrack(): IntArray { return mInternalMediaPlayer?.run { val arrayList = ArrayList<Int>() for (index in trackInfo.indices) { if (trackInfo[index].trackType == MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_AUDIO) { arrayList.add(index) } } arrayList.toIntArray() } ?: IntArray(0) } override fun pause() { super.pause() runSafely({ mInternalMediaPlayer?.pause() }, { Log.e(TAG, "pause error:" + it.message) playerListener?.onError(this,IPlayer.MEDIA_ERROR_PLAY_STATUS, -1) }) } override fun stop() { super.stop() } override fun destory() { super.destory() if (mInternalMediaPlayer == null) { return } // if (正在播放) { // mInternalMediaPlayer.stop(); // } mInternalMediaPlayer!!.reset() // ———> [IDLE] State mInternalMediaPlayer!!.release() // ———> [END] State reset() } public override fun reset() { super.reset() bufferPercent = 0 mInternalMediaPlayer = null } override fun setAudioTrack(stcTrackInfo: TrackInfo?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } private fun onBufferingUpdate(mp: MediaPlayer, percent: Int) { bufferPercent = percent // 后续可以做预加载更新 onPreLoadPosition } private fun onCompletion(mp: MediaPlayer) { if (isMediaStopped()) { return } changeState(STATE_COMPLETED) playerListener?.onCompletion(this) playerHandler.removeCallbacksAndMessages(null) } private fun onError(mp: MediaPlayer?, what: Int, extra: Int):Boolean { changeState(STATE_BUFFERING, 0) changeState(STATE_ERROR) when (what) { MediaPlayer.MEDIA_ERROR_SERVER_DIED -> Log.e(TAG, "play error: MEDIA_ERROR_SERVER_DIED , extra:$extra") MediaPlayer.MEDIA_ERROR_UNKNOWN -> Log.e(TAG, "play error: MEDIA_ERROR_UNKNOWN , extra:$extra") else -> Log.e(TAG, "play error: what is$what, extra is $extra") } playerHandler.removeCallbacksAndMessages(null) //mInternalMediaPlayer.reset();//重用Error状态的MediaPlayer对象 return playerListener?.onError(this, what, extra)?:true } private fun onInfo(mp: MediaPlayer, what: Int, extra: Int): Boolean { if (isMediaStopped()) { return false } when (what) { IPlayer.MEDIA_INFO_BUFFERING_START -> { if (!hasState(STATE_BUFFERING)) { changeState(STATE_BUFFERING) } playerListener?.onBuffering(this,true,100f) } IPlayer.MEDIA_INFO_BUFFERING_END -> { if (hasState(STATE_BUFFERING)) { changeState(STATE_BUFFERING, 0) } playerListener?.onBuffering(this,false,0f) } MEDIA_INFO_VIDEO_RENDERING_START ->{ playerListener?.onVideoFirstFrameShow(this) } } return false } private fun onPrepared(mp: MediaPlayer) { // handleTrackInfo() changeState(STATE_PREPARED) if (isAutoPlayWhenRedy) { isAutoPlayWhenRedy = false mInternalMediaPlayer?.start() changeState(STATE_PLAYING) } // mSurface?.requestLayout() playerListener?.onPrepared(this) } private fun onSeekComplete(mp: MediaPlayer?) { playerListener?.onSeekComplete(this) } private fun onTimedText(mp: MediaPlayer?, text: TimedText) { playerListener?.onTimedText(text) } override fun setSurface(surface: Surface?) { playerListener?.onSeekComplete(this) } override fun attachListener() { val playerListners = PlayerCallBack() mInternalMediaPlayer?.apply { setOnPreparedListener(playerListners) setOnErrorListener(playerListners) setOnBufferingUpdateListener(playerListners) setOnSeekCompleteListener(playerListners) setOnCompletionListener(playerListners) setOnInfoListener(playerListners) } } override fun detachListener() { mInternalMediaPlayer?.apply { setOnPreparedListener(null) setOnErrorListener(null) setOnBufferingUpdateListener(null) setOnSeekCompleteListener(null) setOnCompletionListener(null) setOnInfoListener(null) } } override fun seekTo(msec: Long) { runSafely({ var seekTo = msec if (msec >= duration) { seekTo = duration - SEEK_PROTECT_TIME_MS } mInternalMediaPlayer?.seekTo(seekTo.toInt()) }, { Log.e(TAG, "seek error:" + it.message) onError(null,IPlayer.MEDIA_ERROR_SEEK_STATUS, -1) }) } override fun setSoundTrack(soundTrack: String?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override val duration: Long get() = mInternalMediaPlayer!!.duration.toLong() override val currentPosition: Long get() = mInternalMediaPlayer!!.currentPosition.toLong() override val bufferedPosition: Long get() = (bufferPercent / 100.0 * duration).toLong() override fun setDataSource(uri: Uri?) { if (uri == null) { Log.e(TAG, "video uri can't null.") return } if (mInternalMediaPlayer == null) { mInternalMediaPlayer = MediaPlayer() mInternalMediaPlayer?.setSurface(mSurface) attachListener() } try { mUri = uri mInternalMediaPlayer?.setDataSource(mContext, uri) //异步准备 onPrepared回调至Prepared状态 ————> start() 至Started状态 mInternalMediaPlayer?.prepareAsync() } catch (e: Exception) { Log.e(TAG, "set play uri error:" + e.message) playerListener?.onError(this, IPlayer.MEDIA_ERROR_CUSTOM_ERROR, -1) } } override fun setDataSource(url: String) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getCurrentLoadSpeed(): Float { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setBufferTimeOutThreshold(threshold: Long) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } // <editor-fold defaultstate="collapsed" desc="播放器状态判断"> private fun isMediaStopped(): Boolean { return hasAnyState( STATE_IDLE, STATE_INITIALIZED, STATE_STOPPED, STATE_RELEASE, STATE_UNINITIALIZED, STATE_COMPLETED, STATE_ERROR ) } // </editor-fold> inner class PlayerCallBack : AndroidMediaPlayerListeners { override fun onSeekComplete(mp: MediaPlayer) { [email protected](mp) } override fun onInfo(mp: MediaPlayer, what: Int, extra: Int): Boolean { Log.d(TAG, "onInfo: what is$what, extra is $extra") return [email protected](mp, what, extra) } override fun onTimedText(mp: MediaPlayer, text: TimedText) { [email protected](mp, text) } override fun onPrepared(mp: MediaPlayer) { [email protected](mp) } override fun onBufferingUpdate(mp: MediaPlayer, percent: Int) { [email protected](mp, percent) } override fun onCompletion(mp: MediaPlayer) { [email protected](mp) } override fun onError(mp: MediaPlayer, what: Int, extra: Int): Boolean { return [email protected](mp, what, extra) } } }
gpl-2.0
fceaf08848d09904023f3e782402f8c8
30.505848
107
0.608873
4.594456
false
false
false
false
siosio/intellij-community
plugins/git-features-trainer/src/git4idea/ift/lesson/GitFeatureBranchWorkflowLesson.kt
1
12535
// 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 git4idea.ift.lesson import com.intellij.CommonBundle import com.intellij.configurationStore.StoreReloadManager import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.push.ui.PushLog import com.intellij.dvcs.ui.DvcsBundle import com.intellij.notification.NotificationType import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.status.TextPanel import com.intellij.ui.EngravedLabel import com.intellij.ui.components.BasicOptionButtonUI import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.i18n.GitBundle import git4idea.ift.GitLessonsBundle import git4idea.ift.GitLessonsUtil.checkoutBranch import git4idea.ift.GitLessonsUtil.highlightLatestCommitsFromBranch import git4idea.ift.GitLessonsUtil.openPushDialogText import git4idea.ift.GitLessonsUtil.openUpdateDialogText import git4idea.ift.GitLessonsUtil.resetGitLogWindow import git4idea.ift.GitLessonsUtil.triggerOnNotification import git4idea.ift.GitProjectUtil import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.branch.GitBranchPopupActions import training.dsl.* import java.io.File import javax.swing.JButton import javax.swing.JDialog import javax.swing.JList class GitFeatureBranchWorkflowLesson : GitLesson("Git.BasicWorkflow", GitLessonsBundle.message("git.feature.branch.lesson.name")) { override val existedFile = "git/simple_cat.yml" private val remoteName = "origin" private val branchName = "feature" private val main = "main" private val firstFileName = "sphinx_cat.yml" private val secondFileName = "puss_in_boots.yml" private val committerName = "Johnny Catsville" private val committerEmail = "[email protected]" private val firstCommitMessage = "Add new fact about sphinx's behaviour" private val secondCommitMessage = "Add fact about Puss in boots" private val firstFileAddition = """ | | - steal: | condition: food was left unattended | action: | - steal a piece of food and hide""".trimMargin() private val secondFileAddition = """ | | - care_for_weapon: | condition: favourite sword become blunt | actions: | - sharpen the sword using the stone""".trimMargin() private lateinit var repository: GitRepository override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) override val lessonContent: LessonContext.() -> Unit = { prepareRuntimeTask { repository = GitRepositoryManager.getInstance(project).repositories.first() } checkoutBranch(branchName) task("ActivateVersionControlToolWindow") { text(GitLessonsBundle.message("git.feature.branch.introduction.1", strong(branchName), strong(main), action(it))) stateCheck { val toolWindowManager = ToolWindowManager.getInstance(project) toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true } } resetGitLogWindow() task { text(GitLessonsBundle.message("git.feature.branch.introduction.2", strong(main))) highlightLatestCommitsFromBranch(branchName, sequenceLength = 2) proceedLink() } task { triggerByUiComponentAndHighlight(usePulsation = true) { ui: TextPanel.WithIconAndArrows -> ui.text == branchName } } lateinit var firstShowBranchesTaskId: TaskContext.TaskId task("Git.Branches") { firstShowBranchesTaskId = taskId text(GitLessonsBundle.message("git.feature.branch.open.branches.popup.1", strong(main), action(it))) text(GitLessonsBundle.message("git.feature.branch.open.branches.popup.balloon"), LearningBalloonConfig(Balloon.Position.above, 0)) triggerOnBranchesPopupShown() } task { triggerByListItemAndHighlight { item -> item.toString() == main } } task { lateinit var curBranchName: String before { curBranchName = repository.currentBranchName ?: error("Not found information about active branch") } val checkoutItemText = GitBundle.message("branches.checkout") text(GitLessonsBundle.message("git.feature.branch.checkout.branch", strong(main), strong(checkoutItemText))) highlightListItemAndRehighlight { item -> item.toString() == checkoutItemText } stateCheck { repository.currentBranchName == main } restoreState(firstShowBranchesTaskId, delayMillis = defaultRestoreDelay) { val newBranchName = repository.currentBranchName previous.ui?.isShowing != true || (newBranchName != curBranchName && newBranchName != main) } } prepareRuntimeTask { val showSettingsOption = ProjectLevelVcsManagerEx.getInstanceEx(project).getOptions(VcsConfiguration.StandardOption.UPDATE) showSettingsOption.value = true // needed to show update project dialog } task("Vcs.UpdateProject") { val updateProjectDialogTitle = VcsBundle.message("action.display.name.update.scope", VcsBundle.message("update.project.scope.name")) openUpdateDialogText(GitLessonsBundle.message("git.feature.branch.open.update.dialog", strong(main))) triggerByUiComponentAndHighlight(false, false) { ui: JDialog -> ui.title?.contains(updateProjectDialogTitle) == true } } task { text(GitLessonsBundle.message("git.feature.branch.confirm.update", strong(CommonBundle.getOkButtonText()))) triggerByUiComponentAndHighlight { ui: JButton -> ui.text == CommonBundle.getOkButtonText() } triggerOnNotification { notification -> notification.groupId == "Vcs Notifications" && notification.type == NotificationType.INFORMATION } restoreState(delayMillis = defaultRestoreDelay) { previous.ui?.isShowing != true && !ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning } } task("Git.Branches") { text(GitLessonsBundle.message("git.feature.branch.new.commits.explanation", strong(main))) highlightLatestCommitsFromBranch("$remoteName/$main", sequenceLength = 2) proceedLink() } task { triggerByUiComponentAndHighlight(usePulsation = true) { ui: TextPanel.WithIconAndArrows -> ui.text == main } } lateinit var secondShowBranchesTaskId: TaskContext.TaskId task("Git.Branches") { secondShowBranchesTaskId = taskId text(GitLessonsBundle.message("git.feature.branch.open.branches.popup.2", strong(branchName), strong(main), action(it))) text(GitLessonsBundle.message("git.feature.branch.open.branches.popup.balloon"), LearningBalloonConfig(Balloon.Position.above, 200)) triggerOnBranchesPopupShown() } task { triggerByListItemAndHighlight { item -> item.toString() == branchName } } task { val repositories = GitRepositoryManager.getInstance(project).repositories val checkoutAndRebaseText = GitBundle.message("branches.checkout.and.rebase.onto.branch", GitBranchPopupActions.getCurrentBranchTruncatedPresentation(project, repositories)) text(GitLessonsBundle.message("git.feature.branch.checkout.and.rebase", strong(branchName), strong(checkoutAndRebaseText))) highlightListItemAndRehighlight { item -> item.toString().contains(checkoutAndRebaseText) } triggerOnNotification { notification -> notification.title == GitBundle.message("rebase.notification.successful.title") } restoreState(secondShowBranchesTaskId, delayMillis = 3 * defaultRestoreDelay) { previous.ui?.isShowing != true && !StoreReloadManager.getInstance().isReloadBlocked() // reload is blocked when rebase is running } } task("Vcs.Push") { openPushDialogText(GitLessonsBundle.message("git.feature.branch.open.push.dialog", strong(branchName))) triggerByUiComponentAndHighlight(false, false) { _: PushLog -> true } } val forcePushText = DvcsBundle.message("action.force.push").dropMnemonic() task { text(GitLessonsBundle.message("git.feature.branch.choose.force.push", strong(branchName), strong(forcePushText), strong(DvcsBundle.message("action.push").dropMnemonic()))) triggerByUiComponentAndHighlight(usePulsation = true) { _: BasicOptionButtonUI.ArrowButton -> true } val forcePushDialogTitle = DvcsBundle.message("force.push.dialog.title") triggerByUiComponentAndHighlight(false, false) { ui: JDialog -> ui.title?.contains(forcePushDialogTitle) == true } restoreByUi() } task { text(GitLessonsBundle.message("git.feature.branch.confirm.force.push", strong(forcePushText))) text(GitLessonsBundle.message("git.feature.branch.force.push.tip", strong(forcePushText))) triggerOnNotification { notification -> notification.groupId == "Vcs Notifications" && notification.type == NotificationType.INFORMATION } restoreByUi(delayMillis = defaultRestoreDelay) } } override fun prepare(project: Project) { super.prepare(project) val remoteProjectRoot = GitProjectUtil.createRemoteProject(remoteName, project) modifyRemoteProject(remoteProjectRoot) } private fun TaskContext.triggerOnBranchesPopupShown() { triggerByUiComponentAndHighlight(false, false) { ui: EngravedLabel -> val branchesInRepoText = DvcsBundle.message("branch.popup.vcs.name.branches.in.repo", GitBundle.message("git4idea.vcs.name"), DvcsUtil.getShortRepositoryName(repository)) ui.text?.contains(branchesInRepoText) == true } } private fun TaskContext.highlightListItemAndRehighlight(checkList: TaskRuntimeContext.(item: Any) -> Boolean) { var showedList: JList<*>? = null triggerByPartOfComponent l@{ ui: JList<*> -> val ind = (0 until ui.model.size).find { checkList(ui.model.getElementAt(it)) } ?: return@l null showedList = ui ui.getCellBounds(ind, ind) } // it is a hack: restart current task to highlight list item when it will be shown again // rehighlightPreviousUi property can not be used in this case, because I can't highlight this list item in the previous task restoreState(restoreId = taskId) { showedList != null && !showedList!!.isShowing } } private fun modifyRemoteProject(remoteProjectRoot: File) { val files = mutableListOf<File>() FileUtil.processFilesRecursively(remoteProjectRoot, files::add) val firstFile = files.find { it.name == firstFileName } val secondFile = files.find { it.name == secondFileName } if (firstFile != null && secondFile != null) { gitChange(remoteProjectRoot, "user.name", committerName) gitChange(remoteProjectRoot, "user.email", committerEmail) createOneFileCommit(remoteProjectRoot, firstFile, firstCommitMessage) { it.appendText(firstFileAddition) } createOneFileCommit(remoteProjectRoot, secondFile, secondCommitMessage) { it.appendText(secondFileAddition) } } else error("Failed to find files to modify in $remoteProjectRoot") } private fun gitChange(root: File, param: String, value: String) { val handler = GitLineHandler(null, root, GitCommand.CONFIG) handler.addParameters(param, value) runGitCommandSynchronously(handler) } private fun createOneFileCommit(root: File, editingFile: File, commitMessage: String, editFileContent: (File) -> Unit) { editFileContent(editingFile) val handler = GitLineHandler(null, root, GitCommand.COMMIT) handler.addParameters("-a") handler.addParameters("-m", commitMessage) handler.endOptions() runGitCommandSynchronously(handler) } private fun runGitCommandSynchronously(handler: GitLineHandler) { val task = { Git.getInstance().runCommand(handler).throwOnError() } ProgressManager.getInstance().runProcessWithProgressSynchronously(task, "", false, null) } }
apache-2.0
45e00e812e61d8a724c28ad60f8d7c56
43.6121
140
0.735062
4.753508
false
false
false
false
JetBrains/kotlin-native
tools/benchmarks/shared/src/main/kotlin/analyzer/Statistics.kt
1
6798
/* * Copyright 2010-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.analyzer import org.jetbrains.report.BenchmarkResult import org.jetbrains.report.MeanVariance import org.jetbrains.report.MeanVarianceBenchmark import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.pow import kotlin.math.sqrt val MeanVariance.description: String get() { val format = { number: Double -> number.format(2) } return "${format(mean)} ± ${format(variance)}" } val MeanVarianceBenchmark.description: String get() = "${score.format()} ± ${variance.format()}" // Calculate difference in percentage compare to another. fun MeanVarianceBenchmark.calcPercentageDiff(other: MeanVarianceBenchmark): MeanVariance { if (score == 0.0 && variance == 0.0 && other.score == 0.0 && other.variance == 0.0) return MeanVariance(score, variance) assert(other.score >= 0 && other.variance >= 0 && (other.score - other.variance != 0.0 || other.score == 0.0), { "Mean and variance should be positive and not equal!" }) // Analyze intervals. Calculate difference between border points. val (bigValue, smallValue) = if (score > other.score) Pair(this, other) else Pair(other, this) val bigValueIntervalStart = bigValue.score - bigValue.variance val bigValueIntervalEnd = bigValue.score + bigValue.variance val smallValueIntervalStart = smallValue.score - smallValue.variance val smallValueIntervalEnd = smallValue.score + smallValue.variance if (smallValueIntervalEnd > bigValueIntervalStart) { // Interval intersect. return MeanVariance(0.0, 0.0) } val mean = ((smallValueIntervalEnd - bigValueIntervalStart) / bigValueIntervalStart) * (if (score > other.score) -1 else 1) val maxValueChange = ((bigValueIntervalEnd - smallValueIntervalEnd) / bigValueIntervalEnd) val minValueChange = ((bigValueIntervalStart - smallValueIntervalStart) / bigValueIntervalStart) val variance = abs(abs(mean) - max(minValueChange, maxValueChange)) return MeanVariance(mean * 100, variance * 100) } // Calculate ratio value compare to another. fun MeanVarianceBenchmark.calcRatio(other: MeanVarianceBenchmark): MeanVariance { if (other.score == 0.0 && other.variance == 0.0) return MeanVariance(1.0, 0.0) assert(other.score >= 0 && other.variance >= 0 && (other.score - other.variance != 0.0 || other.score == 0.0), { "Mean and variance should be positive and not equal!" }) val mean = if (other.score != 0.0) (score / other.score) else 0.0 val minRatio = (score - variance) / (other.score + other.variance) val maxRatio = (score + variance) / (other.score - other.variance) val ratioConfInt = min(abs(minRatio - mean), abs(maxRatio - mean)) return MeanVariance(mean, ratioConfInt) } fun geometricMean(values: Collection<Double>, totalNumber: Int = values.size) = with(values.asSequence().filter { it != 0.0 }) { if (count() == 0 || totalNumber == 0) { 0.0 } else { map { it.pow(1.0 / totalNumber) }.reduce { a, b -> a * b } } } fun computeMeanVariance(samples: List<Double>): MeanVariance { val removedBroadSamples = 0.2 val zStar = 1.67 // Critical point for 90% confidence of normal distribution. // Skip several minimal and maximum values. val filteredSamples = if (samples.size >= 1/removedBroadSamples) { samples.sorted().subList((samples.size * removedBroadSamples).toInt(), samples.size - (samples.size * removedBroadSamples).toInt()) } else { samples } val mean = filteredSamples.sum() / filteredSamples.size val variance = samples.indices.sumByDouble { (samples[it] - mean) * (samples[it] - mean) } / samples.size val confidenceInterval = sqrt(variance / samples.size) * zStar return MeanVariance(mean, confidenceInterval) } // Calculate average results for benchmarks (each benchmark can be run several times). fun collectMeanResults(benchmarks: Map<String, List<BenchmarkResult>>): BenchmarksTable { return benchmarks.map { (name, resultsSet) -> val repeatedSequence = IntArray(resultsSet.size) var metric = BenchmarkResult.Metric.EXECUTION_TIME var currentStatus = BenchmarkResult.Status.PASSED var currentWarmup = -1 // Results can be already processed. if (resultsSet[0] is MeanVarianceBenchmark) { assert(resultsSet.size == 1) { "Several MeanVarianceBenchmark instances." } name to resultsSet[0] as MeanVarianceBenchmark } else { // Collect common benchmark values and check them. resultsSet.forEachIndexed { index, result -> // If there was at least one failure, summary is marked as failure. if (result.status == BenchmarkResult.Status.FAILED) { currentStatus = result.status } repeatedSequence[index] = result.repeat if (currentWarmup != -1) if (result.warmup != currentWarmup) println("Check data consistency. Warmup value for benchmark '${result.name}' differs.") currentWarmup = result.warmup metric = result.metric } repeatedSequence.sort() // Check if there are missed loop during running benchmarks. repeatedSequence.forEachIndexed { index, element -> if (index != 0) if ((element - repeatedSequence[index - 1]) != 1) println("Check data consistency. For benchmark '$name' there is no run" + " between ${repeatedSequence[index - 1]} and $element.") } // Create mean and variance benchmarks result. val scoreMeanVariance = computeMeanVariance(resultsSet.map { it.score }) val runtimeInUsMeanVariance = computeMeanVariance(resultsSet.map { it.runtimeInUs }) val meanBenchmark = MeanVarianceBenchmark(name, currentStatus, scoreMeanVariance.mean, metric, runtimeInUsMeanVariance.mean, repeatedSequence[resultsSet.size - 1], currentWarmup, scoreMeanVariance.variance) name to meanBenchmark } }.toMap() } fun collectBenchmarksDurations(benchmarks: Map<String, List<BenchmarkResult>>): Map<String, Double> = benchmarks.map { (name, resultsSet) -> name to resultsSet.sumByDouble { it.runtimeInUs } }.toMap()
apache-2.0
8d52049e1bea00f5904e076369902428
45.238095
111
0.647145
4.263488
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/checkin/GitAmendCommitService.kt
7
1537
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.checkin import com.intellij.dvcs.commit.AmendCommitService import com.intellij.openapi.components.Service import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.config.GitVersionSpecialty import org.jetbrains.annotations.NonNls @Service internal class GitAmendCommitService(project: Project) : AmendCommitService(project) { override fun isAmendCommitSupported(): Boolean = true @Throws(VcsException::class) override fun getLastCommitMessage(root: VirtualFile): String { val h = GitLineHandler(project, root, GitCommand.LOG) h.addParameters("--max-count=1") h.addParameters("--encoding=UTF-8") h.addParameters("--pretty=format:${getCommitMessageFormatPattern()}") return Git.getInstance().runCommand(h).getOutputOrThrow() } private fun getCommitMessageFormatPattern(): @NonNls String = if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project)) { "%B" } else { // only message: subject + body; "%-b" means that preceding line-feeds will be deleted if the body is empty // %s strips newlines from subject; there is no way to work around it before 1.7.2 with %B (unless parsing some fixed format) "%s%n%n%-b" } }
apache-2.0
6f3c1e60092a76cc8f8068b34f7d3b90
40.567568
131
0.761874
4.076923
false
false
false
false
smmribeiro/intellij-community
plugins/toml/core/src/test/kotlin/org/toml/ide/json/TomlJsonSchemaKeyCompletionTest.kt
1
2207
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide.json class TomlJsonSchemaKeyCompletionTest : TomlJsonSchemaCompletionTestBase() { fun `test top level completion`() = checkContainsCompletion(listOf("package", "dependencies"), """ <caret> """) fun `test completion inside table`() = checkContainsCompletion(listOf("name", "version", "authors", "edition"), """ [package] <caret> """) fun `test completion inside array table`() = checkContainsCompletion(listOf("name", "path"), """ [[bin]] <caret> """) fun `test completion in key segments`() = checkContainsCompletion(listOf("name", "version", "authors", "edition"), """ package.<caret> """) fun `test completion in table header`() = checkContainsCompletion(listOf("name", "version", "authors", "edition"), """ [package.<caret>] """) fun `test completion in table key`() = checkContainsCompletion(listOf("dependencies", "package"), """ [<caret>] """) fun `test completion in array key`() = checkContainsCompletion(listOf("bin"), """ [[<caret>]] """) fun `test completion inside inline tables`() = checkContainsCompletion(listOf("name", "version", "authors", "edition"), """ package = { <caret> } """) fun `test completion inside inline array`() = checkContainsCompletion(listOf("name", "path"), """ bin = [{<caret>}] """) fun `test completion in variable path`() = checkContainsCompletion(listOf("version", "features"), """ [dependencies] foo = { <caret> } """) fun `test key segment completion`() = checkContainsCompletion(listOf("version", "features"), """ target.'cfg(unix)'.dependencies.rocket.<caret> """) fun `test mixed nested tables completion`() = checkContainsCompletion(listOf("d"), """ [foo] a = 0 [[foo.bar]] c = 0 [[foo.baz]] b = 0 [[foo.bar.qux]] d = 0 [[foo.baz]] b = 1 [[foo.bar.qux]] <caret> """) }
apache-2.0
dce0001b2ea23b87b0ff179e57a70a4b
28.426667
127
0.565927
4.597917
false
true
false
false
android/compose-samples
JetNews/app/src/main/java/com/example/jetnews/ui/JetnewsNavGraph.kt
1
2495
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.jetnews.data.AppContainer import com.example.jetnews.ui.home.HomeRoute import com.example.jetnews.ui.home.HomeViewModel import com.example.jetnews.ui.interests.InterestsRoute import com.example.jetnews.ui.interests.InterestsViewModel @Composable fun JetnewsNavGraph( appContainer: AppContainer, isExpandedScreen: Boolean, modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), openDrawer: () -> Unit = {}, startDestination: String = JetnewsDestinations.HOME_ROUTE ) { NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { composable(JetnewsDestinations.HOME_ROUTE) { val homeViewModel: HomeViewModel = viewModel( factory = HomeViewModel.provideFactory(appContainer.postsRepository) ) HomeRoute( homeViewModel = homeViewModel, isExpandedScreen = isExpandedScreen, openDrawer = openDrawer ) } composable(JetnewsDestinations.INTERESTS_ROUTE) { val interestsViewModel: InterestsViewModel = viewModel( factory = InterestsViewModel.provideFactory(appContainer.interestsRepository) ) InterestsRoute( interestsViewModel = interestsViewModel, isExpandedScreen = isExpandedScreen, openDrawer = openDrawer ) } } }
apache-2.0
e56b682ed23077ed03f5f007c3011afe
36.238806
93
0.710621
5.050607
false
false
false
false
simonnorberg/dmach
app/src/main/java/net/simno/dmach/patch/PatchProcessor.kt
1
2995
package net.simno.dmach.patch import androidx.paging.PagingSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import net.simno.dmach.db.PatchEntity import net.simno.dmach.db.PatchRepository class PatchProcessor( private val patchRepository: PatchRepository ) : (Flow<Action>) -> Flow<Result> { override fun invoke(actions: Flow<Action>): Flow<Result> = merge( actions.filterIsInstance<LoadAction>().let(load), actions.filterIsInstance<DismissAction>().let(dismiss), actions.filterIsInstance<ConfirmOverwriteAction>().let(confirmOverwrite), actions.filterIsInstance<ConfirmDeleteAction>().let(confirmDelete), actions.filterIsInstance<SavePatchAction>().let(savePatch), actions.filterIsInstance<DeletePatchAction>().let(deletePatch), actions.filterIsInstance<SelectPatchAction>().let(selectPatch) ) fun patches(): PagingSource<Int, PatchEntity> = patchRepository.getAllPatches() private val load: (Flow<LoadAction>) -> Flow<LoadResult> = { actions -> actions .computeResult { val patch = patchRepository.unsavedPatch() LoadResult( title = patch.title ) } } private val dismiss: (Flow<DismissAction>) -> Flow<DismissResult> = { actions -> actions .computeResult { DismissResult } } private val confirmOverwrite: (Flow<ConfirmOverwriteAction>) -> Flow<ConfirmOverwriteResult> = { actions -> actions .computeResult { patchRepository.replacePatch() ConfirmOverwriteResult } } private val confirmDelete: (Flow<ConfirmDeleteAction>) -> Flow<ConfirmDeleteResult> = { actions -> actions .computeResult { patchRepository.deletePatch() ConfirmDeleteResult } } private val savePatch: (Flow<SavePatchAction>) -> Flow<SavePatchResult> = { actions -> actions .computeResult { action -> val saved = patchRepository.insertPatch(action.title) SavePatchResult(!saved, action.title) } } private val deletePatch: (Flow<DeletePatchAction>) -> Flow<DeletePatchResult> = { actions -> actions .computeResult { action -> patchRepository.acceptDeleteTitle(action.title) DeletePatchResult(action.title) } } private val selectPatch: (Flow<SelectPatchAction>) -> Flow<SelectPatchResult> = { actions -> actions .computeResult { action -> patchRepository.selectPatch(action.title) SelectPatchResult } } private fun <T, R : Result> Flow<T>.computeResult(mapper: suspend (T) -> R): Flow<R> = map(mapper) }
gpl-3.0
ee6f2c9edcd1d0ae14a885ae30db7015
34.235294
111
0.628381
4.846278
false
false
false
false
7449/Album
scan/src/main/java/com/gallery/scan/Types.kt
1
667
package com.gallery.scan /** * 类型Type */ object Types { /*** 扫描类型*/ object Scan { /*** 扫描全部*/ const val ALL = (-111111111).toLong() /*** 不扫描*/ const val NONE = (-11111112).toLong() } /*** 排序方式*/ object Sort { /*** 降序*/ const val DESC = "DESC" /*** 升序*/ const val ASC = "ASC" } /*** 用作区分是扫描还是单个文件*/ object Result { /*** 扫描多文件*/ const val MULTIPLE = "MULTIPLE" /*** 扫描单文件*/ const val SINGLE = "SINGLE" } }
mpl-2.0
0b1e2c32360c3793a0a45a94c4008339
14.6
45
0.411054
3.61875
false
false
false
false
wn1/LNotes
app/src/main/java/ru/qdev/lnotes/mvp/QDVNotesListPresenter.kt
1
5933
package ru.qdev.lnotes.mvp import android.os.AsyncTask import android.os.Handler import android.os.Looper import android.support.annotation.AnyThread import android.support.annotation.MainThread import android.support.annotation.UiThread import com.arellomobile.mvp.InjectViewState import com.j256.ormlite.dao.CloseableIterator import com.j256.ormlite.stmt.Where import ru.qdev.lnotes.* import ru.qdev.lnotes.db.entity.QDVDbFolderOrMenuItem import ru.qdev.lnotes.db.entity.QDVDbNote import java.util.* /** * Created by Vladimir Kudashov on 29.09.18. */ @InjectViewState class QDVNotesListPresenter : QDVMvpDbPresenter <QDVNotesListView> () { private var state: QDVNotesListState = QDVNotesListState() @AnyThread override fun beforeDatabaseClose() { } @UiThread override fun afterDatabaseReload() { } @AnyThread fun dbIteratotorFoldersQuery(): CloseableIterator<QDVDbFolderOrMenuItem> { val noteDao = database.getDaoWithIdLong(QDVDbFolderOrMenuItem::class.java) val queryBuilder = noteDao.queryBuilder() queryBuilder.orderByRaw("label") return queryBuilder.iterator() } @AnyThread fun dbIteratorNotesQuery(): CloseableIterator<QDVDbNote> { val noteDao = database.getDaoWithIdLong(QDVDbNote::class.java) val queryBuilder = noteDao.queryBuilder() val filter = state.filterByFolderState var where: Where<QDVDbNote, Long>? = null if (filter.filterType == QDVFilterByFolderState.FilterType.FOLDER_NOT_SELECTED) { val columnName = "folder_id" where = queryBuilder.where().isNull(columnName).or().le(columnName, 0) } else { val columnName = "folder_id" if (filter.filterType == QDVFilterByFolderState.FilterType.FOLDER_ID && state.filterByFolderState.folderId != null) { where = queryBuilder.where().eq(columnName, state.filterByFolderState.folderId) } else if (filter.filterType == QDVFilterByFolderState.FilterType.FOLDER && state.filterByFolderState.folder != null) { where = queryBuilder.where().eq(columnName, state.filterByFolderState.folder?.id ?: 0) } } if (state.searchState.isSearchActive && !state.searchState.searchText.isNullOrEmpty()) { val columnName = "content" where = if (where != null) { where.and() } else { queryBuilder.where() } where.like(columnName, "%${state.searchState.searchText}%") } val oderString = "(isready > 0), complete_time_u DESC, update_time_u DESC" queryBuilder.orderByRaw(oderString) return queryBuilder.iterator() } @AnyThread fun getFolderNameForFilter(): String { val context = ThisApp.getContext() return when (state.filterByFolderState.filterType) { QDVFilterByFolderState.FilterType.ALL_FOLDER -> { context.getString(R.string.category_all) } QDVFilterByFolderState.FilterType.FOLDER_NOT_SELECTED -> { context.getString(R.string.category_unknown) } else -> { state.filterByFolderState.folder?.label ?: "" } } } private var isReloadState: Boolean = false @MainThread fun loadNotesListAsync() { if (isReloadState) { return } isReloadState = true AsyncTask.execute { try { val iteratorNotes = dbIteratorNotesQuery() Handler(Looper.getMainLooper()).post { isReloadState = false viewState.loadNotesList(iteratorNotes) } } catch (e: Exception) { Handler(Looper.getMainLooper()).postDelayed({ loadNotesListAsync() }, 1000) e.printStackTrace() return@execute } } } @UiThread fun initWithState(state: QDVNotesListState) { this.state = state if (state.filterByFolderState.filterType == QDVFilterByFolderState.FilterType.FOLDER_ID) { val noteDao = database.getDaoWithIdLong(QDVDbFolderOrMenuItem::class.java) state.filterByFolderState.folder = noteDao.queryForId(state.filterByFolderState.folderId ?: 0) } loadNotesListAsync() viewState.setSearchState(state.searchState) viewState.setFolderName(getFolderNameForFilter()) } @UiThread fun onSearchText(text: String) { state.searchState.isSearchActive = true state.searchState.searchText = text loadNotesListAsync() viewState.setSearchState(state.searchState) } @UiThread fun onUndoSearch() { state.searchState.isSearchActive = false loadNotesListAsync() viewState.setSearchState(state.searchState) } @UiThread fun doUpdateNote(note: QDVDbNote) { database.getDaoWithIdLong(QDVDbNote::class.java).update(note) loadNotesListAsync() } @UiThread fun doDeleteNote(note: QDVDbNote) { database.getDaoWithIdLong(QDVDbNote::class.java).delete(note) loadNotesListAsync() } @UiThread fun doSetStatusOfExecution(note: QDVDbNote, status: QDVDbNote.StatusOfExecution) { note.statusOfExecution = status if (status!=QDVDbNote.StatusOfExecution.CREATED){ note.completeTime = Date() } else { note.completeTime = null } database.getDaoWithIdLong(QDVDbNote::class.java).update(note) loadNotesListAsync() } @UiThread fun doFabVisible(visible: Boolean) { viewState.setFabVisible(visible) } }
mit
befae862487dac14b02663de787749f9
31.966667
98
0.626496
4.588554
false
false
false
false
mikepenz/MaterialDrawer
materialdrawer/src/main/java/com/mikepenz/materialdrawer/util/MenuDrawerUtils.kt
1
2689
package com.mikepenz.materialdrawer.util import android.annotation.SuppressLint import android.view.Menu import androidx.annotation.MenuRes import androidx.appcompat.view.SupportMenuInflater import androidx.appcompat.view.menu.MenuBuilder import com.mikepenz.materialdrawer.R import com.mikepenz.materialdrawer.model.DividerDrawerItem import com.mikepenz.materialdrawer.model.PrimaryDrawerItem import com.mikepenz.materialdrawer.model.SecondaryDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import com.mikepenz.materialdrawer.model.interfaces.iconDrawable import com.mikepenz.materialdrawer.model.interfaces.nameText import com.mikepenz.materialdrawer.widget.MaterialDrawerSliderView /** * Inflates the DrawerItems from a menu.xml */ @SuppressLint("RestrictedApi") fun MaterialDrawerSliderView.inflateMenu(@MenuRes menuRes: Int) { val menuInflater = SupportMenuInflater(context) val mMenu = MenuBuilder(context) menuInflater.inflate(menuRes, mMenu) addMenuItems(mMenu, false) } /** * helper method to init the drawerItems from a menu */ private fun MaterialDrawerSliderView.addMenuItems(mMenu: Menu, subMenu: Boolean) { var groupId = R.id.material_drawer_menu_default_group for (i in 0 until mMenu.size()) { val mMenuItem = mMenu.getItem(i) var iDrawerItem: IDrawerItem<*> if (!subMenu && mMenuItem.groupId != groupId && mMenuItem.groupId != 0) { groupId = mMenuItem.groupId iDrawerItem = DividerDrawerItem() itemAdapter.add(iDrawerItem) } if (mMenuItem.hasSubMenu()) { iDrawerItem = PrimaryDrawerItem().apply { nameText = mMenuItem.title iconDrawable = mMenuItem.icon identifier = mMenuItem.itemId.toLong() isEnabled = mMenuItem.isEnabled isSelectable = false } itemAdapter.add(iDrawerItem) addMenuItems(mMenuItem.subMenu, true) } else if (mMenuItem.groupId != 0 || subMenu) { iDrawerItem = SecondaryDrawerItem().apply { nameText = mMenuItem.title iconDrawable = mMenuItem.icon identifier = mMenuItem.itemId.toLong() isEnabled = mMenuItem.isEnabled } itemAdapter.add(iDrawerItem) } else { iDrawerItem = PrimaryDrawerItem().apply { nameText = mMenuItem.title iconDrawable = mMenuItem.icon identifier = mMenuItem.itemId.toLong() isEnabled = mMenuItem.isEnabled } itemAdapter.add(iDrawerItem) } } }
apache-2.0
7c715dbed5e04a370902cf86b152b9bc
36.887324
82
0.673856
4.853791
false
false
false
false
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/serialize/fast/FastSerializer.kt
1
12942
package ch.softappeal.yass.serialize.fast import ch.softappeal.yass.* import ch.softappeal.yass.serialize.* import ch.softappeal.yass.serialize.fast.ObjectType.* import java.lang.reflect.* import java.util.* import kotlin.reflect.* abstract class TypeSerializer internal constructor(val type: Class<*>, private val objectType: ObjectType) { internal abstract fun read(input: FastSerializer.Input): Any? internal abstract fun write(output: FastSerializer.Output, value: Any?) internal open fun write(output: FastSerializer.Output, id: Int, value: Any?) { output.writer.writeVarInt(if (output.skipping) objectType.skippingId(id) else id) write(output, value) } } class TypeDesc(val id: Int, val serializer: TypeSerializer) { init { require(id >= 0) { "id $id for type '${serializer.type.canonicalName}' must be >= 0" } require(id <= MaxTypeId) { "id $id for type '${serializer.type.canonicalName}' must be <= $MaxTypeId" } } internal fun write(output: FastSerializer.Output, value: Any?) = serializer.write(output, id, value) } internal class VoidType val NullTypeDesc = TypeDesc(0, object : TypeSerializer(VoidType::class.java, TreeClass) { override fun read(input: FastSerializer.Input): Any? = null override fun write(output: FastSerializer.Output, value: Any?) {} }) internal class ReferenceType val ReferenceTypeDesc = TypeDesc(1, object : TypeSerializer(ReferenceType::class.java, TreeClass) { override fun read(input: FastSerializer.Input) = input.objects!![input.reader.readVarInt()] override fun write(output: FastSerializer.Output, value: Any?) = output.writer.writeVarInt(value as Int) }) val ListTypeDesc = TypeDesc(2, object : TypeSerializer(List::class.java, TreeClass) { override fun read(input: FastSerializer.Input): List<*> { var length = input.reader.readVarInt() val list = mutableListOf<Any?>() while (length-- > 0) list.add(input.read()) return list } override fun write(output: FastSerializer.Output, value: Any?) { val list = value as List<*> output.writer.writeVarInt(list.size) for (e in list) output.write(e) } }) const val FirstTypeId = 3 abstract class BaseTypeSerializer<V : Any> protected constructor( type: Class<V>, val fieldType: FieldType ) : TypeSerializer(type, fieldType.objectType) { protected constructor(type: KClass<V>, fieldType: FieldType) : this(type.javaObjectType, fieldType) init { check(fieldType != FieldType.Class && fieldType != FieldType.List) } final override fun read(input: FastSerializer.Input) = read(input.reader) @Suppress("UNCHECKED_CAST") final override fun write(output: FastSerializer.Output, value: Any?) = write(output.writer, value as V) abstract fun write(writer: Writer, value: V) abstract fun read(reader: Reader): V } private val PrimitiveWrapperType = mapOf( Boolean::class.javaPrimitiveType to Boolean::class.javaObjectType, Byte::class.javaPrimitiveType to Byte::class.javaObjectType, Short::class.javaPrimitiveType to Short::class.javaObjectType, Int::class.javaPrimitiveType to Int::class.javaObjectType, Long::class.javaPrimitiveType to Long::class.javaObjectType, Char::class.javaPrimitiveType to Char::class.javaObjectType, Float::class.javaPrimitiveType to Float::class.javaObjectType, Double::class.javaPrimitiveType to Double::class.javaObjectType ) fun primitiveWrapperType(type: Class<*>): Class<*> = PrimitiveWrapperType.getOrDefault(type, type) internal const val EndFieldId = 0 const val FirstFieldId = EndFieldId + 1 class FieldDesc internal constructor(val id: Int, val serializer: FastSerializer.FieldSerializer) private val RootClasses = setOf( Any::class.java, Exception::class.java, RuntimeException::class.java, Error::class.java, Throwable::class.java ) fun isRootClass(type: Class<*>): Boolean = RootClasses.contains(type) /** * This fast and compact serializer supports the following types (type id's must be >= [FirstTypeId]): * - `null` * - Subclasses of [BaseTypeSerializer] * - [List] (deserialize creates an [ArrayList]) * - enumeration types (an enumeration constant is serialized with its ordinal number) * - class hierarchies with all non-static and non-transient fields * (field names and id's must be unique in the path to its super classes and id's must be >= [FirstFieldId]) * - exceptions (but without fields of [Throwable]; therefore, you should implement [Throwable.message]) * - graphs with cycles * * If [skipping] is set, old contract: * - skips new field * - sets removed field to null or to default value for primitive types */ abstract class FastSerializer protected constructor(val skipping: Boolean) : Serializer { private val class2typeDesc = HashMap<Class<*>, TypeDesc>(64) private val _id2typeSerializer = HashMap<Int, TypeSerializer>(64) init { addType(NullTypeDesc) addType(ReferenceTypeDesc) addType(ListTypeDesc) } val id2typeSerializer: Map<Int, TypeSerializer> get() = TreeMap(_id2typeSerializer) private fun addType(typeDesc: TypeDesc) { require(class2typeDesc.put(typeDesc.serializer.type, typeDesc) == null) { "type '${typeDesc.serializer.type.canonicalName}' already added" } val oldTypeSerializer = _id2typeSerializer.put(typeDesc.id, typeDesc.serializer) check(oldTypeSerializer == null) { "type id ${typeDesc.id} used for '${typeDesc.serializer.type.canonicalName}' " + "and '${oldTypeSerializer!!.type.canonicalName}'" } } protected fun addEnum(id: Int, type: Class<*>) { require(type.isEnum) { "type '${type.canonicalName}' is not an enumeration" } @Suppress("UNCHECKED_CAST") val enumeration = type as Class<Enum<*>> val constants = enumeration.enumConstants addType(TypeDesc(id, object : BaseTypeSerializer<Enum<*>>(enumeration, FieldType.VarInt) { override fun read(reader: Reader) = constants[reader.readVarInt()] override fun write(writer: Writer, value: Enum<*>) = writer.writeVarInt(value.ordinal) })) } protected fun checkClass(type: Class<*>) = require(!type.isEnum) { "type '${type.canonicalName}' is an enumeration" } inner class ClassTypeSerializer internal constructor( type: Class<*>, val graph: Boolean, private val id2fieldSerializer: Map<Int, FieldSerializer> ) : TypeSerializer(type, if (graph) GraphClass else TreeClass) { private val allocator = AllocatorFactory(type) val fieldDescs: List<FieldDesc> init { val fds = mutableListOf<FieldDesc>() for ((id, serializer) in id2fieldSerializer) { require(id >= FirstFieldId) { "id $id for field '${serializer.field}' must be >= $FirstFieldId" } require(id <= MaxFieldId) { "id $id for field '${serializer.field}' must be <= $MaxFieldId" } fds.add(FieldDesc(id, serializer)) } fieldDescs = Collections.unmodifiableList(fds.sortedBy { it.id }) } internal fun fixupFields() { for ((id, serializer) in id2fieldSerializer) serializer.fixup(id) } override fun read(input: Input): Any { val value = allocator() if (graph) input.addToObjects(value) while (true) { val skippingId = input.reader.readVarInt() val id = if (skipping) fieldIdFromSkippingId(skippingId) else skippingId if (id == EndFieldId) return value val fieldSerializer = id2fieldSerializer[id] if (fieldSerializer == null) { if (skipping) fieldTypeFromSkippingId(skippingId).skip(input) else error("class '${type.canonicalName}' doesn't have a field with id $id") } else fieldSerializer.read(input, value) } } override fun write(output: Output, id: Int, value: Any?) { if (graph) { if (output.object2reference == null) output.object2reference = IdentityHashMap(16) val object2reference = output.object2reference val reference = object2reference!![value] if (reference != null) { ReferenceTypeDesc.write(output, reference) return } object2reference[value!!] = object2reference.size } super.write(output, id, value) } override fun write(output: Output, value: Any?) { for (fieldDesc in fieldDescs) fieldDesc.serializer.write(output, value!!) output.writer.writeVarInt(EndFieldId) } } inner class FieldSerializer internal constructor(val field: Field) { private var _typeSerializer: TypeSerializer? = null val typeSerializer: TypeSerializer? get() = _typeSerializer private var id: Int = 0 internal fun fixup(fieldId: Int) { val typeDesc = class2typeDesc[primitiveWrapperType(field.type)] _typeSerializer = typeDesc?.serializer if (_typeSerializer is ClassTypeSerializer) _typeSerializer = null id = if (!skipping) fieldId else when (_typeSerializer) { null -> FieldType.Class ListTypeDesc.serializer -> FieldType.List else -> (_typeSerializer as BaseTypeSerializer<*>).fieldType }.skippingId(fieldId) } internal fun read(input: Input, value: Any) = field.set(value, if (_typeSerializer == null) input.read() else _typeSerializer!!.read(input)) internal fun write(output: Output, value: Any) { val f = field.get(value) if (f != null) { output.writer.writeVarInt(id) if (_typeSerializer == null) output.write(f) else _typeSerializer!!.write(output, f) } } } protected fun addClass(id: Int, type: Class<*>, graph: Boolean, id2field: Map<Int, Field>) { require(!Modifier.isAbstract(type.modifiers)) { "type '${type.canonicalName}' is abstract" } val id2fieldSerializer = mutableMapOf<Int, FieldSerializer>() val name2field = mutableMapOf<String, Field>() for ((fieldId, field) in id2field) { val oldField = name2field.put(field.name, field) require(oldField == null) { "duplicated field name '$field' and '$oldField' not allowed in class hierarchy" } id2fieldSerializer[fieldId] = FieldSerializer(field) } addType(TypeDesc(id, ClassTypeSerializer(type, graph, id2fieldSerializer))) } protected fun addBaseType(typeDesc: TypeDesc) { require(!typeDesc.serializer.type.isEnum) { "base type '${typeDesc.serializer.type.canonicalName}' is an enumeration" } addType(typeDesc) } private fun checkParentClasses() { _id2typeSerializer.forEach { (id, typeSerializer) -> if (id < FirstTypeId) return@forEach if (typeSerializer is ClassTypeSerializer) { var t = typeSerializer.type while (!isRootClass(t)) { if (!Modifier.isAbstract(t.modifiers)) require(class2typeDesc.contains(t)) { "missing base class '${t.canonicalName}'" } t = t.superclass } } } } protected fun fixup() { for (typeDesc in class2typeDesc.values) (typeDesc.serializer as? ClassTypeSerializer)?.fixupFields() checkParentClasses() } internal inner class Input(val reader: Reader) { var objects: MutableList<Any>? = null fun addToObjects(value: Any) { if (objects == null) objects = mutableListOf() objects!!.add(value) } fun read(): Any? { val skippingId = reader.readVarInt() val id = if (skipping) typeIdFromSkippingId(skippingId) else skippingId return (_id2typeSerializer[id] ?: error("no type with id $id")).read(this) } } internal inner class Output(val writer: Writer) { val skipping = [email protected] var object2reference: MutableMap<Any, Int>? = null fun write(value: Any?): Unit = when (value) { null -> NullTypeDesc.write(this, null) is List<*> -> ListTypeDesc.write(this, value) else -> (class2typeDesc[value.javaClass] ?: error("missing type '${value.javaClass.canonicalName}'")) .write(this, value) } } override fun read(reader: Reader) = Input(reader).read() override fun write(writer: Writer, value: Any?) = Output(writer).write(value) }
bsd-3-clause
a95c4bffd79a0438819a433842e344b8
41.294118
113
0.645959
4.314
false
false
false
false
marktony/ZhiHuDaily
app/src/main/java/com/marktony/zhihudaily/util/DateFormatUtil.kt
1
2067
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.util import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * Created by lizhaotailang on 2017/5/21. * * A util class for formatting the date between string and long. */ fun formatZhihuDailyDateLongToString(date: Long): String { val sDate: String val d = Date(date + 24 * 60 * 60 * 1000) val format = SimpleDateFormat("yyyyMMdd") sDate = format.format(d) return sDate } fun formatZhihuDailyDateStringToLong(date: String): Long { var d: Date? = null try { d = SimpleDateFormat("yyyyMMdd").parse(date) } catch (e: ParseException) { e.printStackTrace() } return if (d == null) 0 else d.time } fun formatDoubanMomentDateLongToString(date: Long): String { val sDate: String val d = Date(date) val format = SimpleDateFormat("yyyy-MM-dd") sDate = format.format(d) return sDate } fun formatDoubanMomentDateStringToLong(date: String): Long { var d: Date? = null try { d = SimpleDateFormat("yyyy-MM-dd").parse(date) } catch (e: ParseException) { e.printStackTrace() } return if (d == null) 0 else d.time } fun formatGuokrHandpickTimeStringToLong(date: String): Long { var d: Date? = null try { d = SimpleDateFormat("yyyy-MM-dd").parse(date.substring(0, 10)) } catch (e: ParseException) { e.printStackTrace() } return if (d == null) 0 else d.time }
apache-2.0
d202a8f4704c586152d793e760395609
25.164557
75
0.677794
3.849162
false
false
false
false
Darkyenus/FountainSimulator
src/main/kotlin/com/darkyen/widgets/DataLineWidget.kt
1
5558
package com.darkyen.widgets import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.darkyen.FountainData import com.darkyen.Objects /** * */ class DataLineWidget(private val skin: Skin, private val data: FountainData) : WidgetGroup() { private val moveLeftStyle = Button.ButtonStyle( skin.getDrawable("move-left"), skin.newDrawable("move-left", 0.9f, 0.9f, 0.9f, 1f), skin.newDrawable("move-left", 0.8f, 0.8f, 0.8f, 1f) ) private val moveRightStyle = Button.ButtonStyle( skin.getDrawable("move-right"), skin.newDrawable("move-right", 0.9f, 0.9f, 0.9f, 1f), skin.newDrawable("move-right", 0.8f, 0.8f, 0.8f, 1f) ) private val removeStyle = Button.ButtonStyle( skin.getDrawable("remove"), skin.newDrawable("remove", 0.9f, 0.9f, 0.9f, 1f), skin.newDrawable("remove", 0.8f, 0.8f, 0.8f, 1f) ) fun refreshChildren() { while (children.size < data.count()) { addActor(DataWidget(0, 0f)) } while (children.size > data.count()) { children[children.size - 1].remove() } val totalTime = data.totalHeight @Suppress("UNCHECKED_CAST") (children as Objects<DataWidget>).forEachIndexed { index, actor -> actor.tooltip.hide() actor.removeListener(actor.tooltip) actor.index = index actor.label.setText(data.files[index].nameWithoutExtension()) val height = data.getHeight(index) actor.weight = height / totalTime val problems = StringBuilder() val width = data.textures[index].originalWidth if (width != FountainData.FOUNTAIN_RESOLUTION_WIDTH) { problems.append("Width is ").append(width).append(", preferred width is ").append(FountainData.FOUNTAIN_RESOLUTION_WIDTH).append('\n') } if (height > FountainData.FOUNTAIN_RESOLUTION_MAX_HEIGHT) { // OpenGL will probably reject such image anyway... problems.append("Height is ").append(height).append(", which is more than supported maximum of ").append(FountainData.FOUNTAIN_RESOLUTION_MAX_HEIGHT).append('\n') } if (problems.isEmpty()) { actor.background = dataWidgetBackgroundOK } else { actor.background = dataWidgetBackgroundNotOK problems.setLength(problems.length - 1) actor.tooltipLabel.setText(problems) actor.addListener(actor.tooltip) } } invalidate() } override fun layout() { val padding = 2 val availableWidth = width - (children.size - 1) * padding var x = 0f for (child in children) { val w = (child as DataWidget).weight * availableWidth child.setBounds(x, 0f, w, height) x += w + padding } } private fun moveLeft(index: Int) { val to = (index - 1 + data.count()) % data.count() data.files.swap(index, to) data.textures.swap(index, to) refreshChildren() } private fun moveRight(index: Int) { val to = (index + 1) % data.count() data.files.swap(index, to) data.textures.swap(index, to) refreshChildren() } private fun remove(index: Int) { data.remove(index) refreshChildren() } private val dataWidgetBackgroundOK = skin.newDrawable("white", 0.5f, 0.5f, 0.5f, 1f) private val dataWidgetBackgroundNotOK = skin.newDrawable("white", 0.6f, 0.4f, 0.4f, 1f) init { data.listen { refreshChildren() } } private inner class DataWidget(var index:Int, var weight:Float) : Table([email protected]) { val label = Label("", skin, "font-ui-small", Color(0.94f, 0.94f, 0.94f, 1f)) val tooltipLabel = Label("", skin, "font-ui-small", Color(0.94f, 0.94f, 0.94f, 1f)) val tooltip = Tooltip<Label>(tooltipLabel) init { background = dataWidgetBackgroundOK tooltip.container.background = dataWidgetBackgroundOK tooltip.container.pad(5f) tooltip.setInstant(true) val moveLeft = Button(moveLeftStyle) moveLeft.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { moveLeft.isChecked = false moveLeft(index) } }) val moveRight = Button(moveRightStyle) moveRight.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { moveRight.isChecked = false moveRight(index) } }) val remove = Button(removeStyle) remove.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { remove.isChecked = false remove(index) } }) label.setEllipsis(true) label.setWrap(true) defaults().pad(2f) add(moveLeft) add(moveRight) add(label).grow() add(remove) } } }
mit
a66cfd89a6c62ad44835a530a01df847
32.690909
178
0.570349
4.045124
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/算法/算法书籍/图/加权/PrimMST.kt
1
819
package 算法.算法书籍.图.加权 import edu.princeton.cs.algs4.MinPQ class PrimMST(val g: WeightGraph) { val hEdgeArray = MinPQ<WeightDiEdge>() val minEdgeArray = ArrayList<WeightDiEdge>() val marked = BooleanArray(g.v) { false } init { mst(0) while (!hEdgeArray.isEmpty) { val min = hEdgeArray.delMin() val from = min.either() val other = min.other(from) if (marked[from] && marked[other]) continue minEdgeArray.add(min) if (!marked[from]) mst(from) if (!marked[other]) mst(other) } } fun mst(v: Int) { marked[v] = true for (edge in g.adj(v)) { if (!marked[edge.other(v)]) { hEdgeArray.insert(edge) } } } }
epl-1.0
3345a346fb3874496c11a6ad468b9611
23.30303
55
0.520599
3.379747
false
false
false
false
badoualy/kotlogram
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/auth/ReqSetDhClientParams.kt
1
1794
package com.github.badoualy.telegram.mtproto.tl.auth import com.github.badoualy.telegram.tl.StreamUtils.* import com.github.badoualy.telegram.tl.TLContext import com.github.badoualy.telegram.tl.core.TLMethod import com.github.badoualy.telegram.tl.exception.DeserializationException import java.io.IOException import java.io.InputStream import java.io.OutputStream class ReqSetDhClientParams @JvmOverloads constructor(var nonce: ByteArray = ByteArray(0), var serverNonce: ByteArray = ByteArray(0), var encrypted: ByteArray = ByteArray(0)) : TLMethod<DhGenResult>() { override fun getConstructorId(): Int { return CONSTRUCTOR_ID } @Throws(IOException::class) override fun serializeBody(stream: OutputStream) { writeByteArray(nonce, stream) writeByteArray(serverNonce, stream) writeTLBytes(encrypted, stream) } @Throws(IOException::class) override fun deserializeBody(stream: InputStream, context: TLContext) { nonce = readBytes(16, stream) serverNonce = readBytes(16, stream) encrypted = readTLBytes(stream) } @Throws(IOException::class) override fun deserializeResponse(stream: InputStream, context: TLContext): DhGenResult { val response = context.deserializeMessage(stream) ?: throw DeserializationException("Unable to deserialize response") if (response !is DhGenResult) { throw DeserializationException("Response has incorrect type") } return response } override fun toString(): String { return "set_client_DH_params#f5045f1f" } companion object { @JvmField val CONSTRUCTOR_ID = -184262881 } }
mit
c51fc15bd9a47c604615f5993a657a53
34.9
125
0.675028
4.635659
false
false
false
false
square/sqldelight
sqlite-migrations/src/main/kotlin/com/squareup/sqlite/migrations/ObjectDifferDatabaseComparator.kt
1
1978
package com.squareup.sqlite.migrations import de.danielbechler.diff.ObjectDifferBuilder import de.danielbechler.diff.node.DiffNode class ObjectDifferDatabaseComparator( private val circularReferenceExceptionLogger: ((String) -> Unit)? = null ) : DatabaseComparator<CatalogDatabase> { override fun compare(db1: CatalogDatabase, db2: CatalogDatabase): DatabaseDiff { return ObjectDifferDatabaseDiff(differBuilder().compare(db1.catalog, db2.catalog)) } private fun differBuilder() = ObjectDifferBuilder.startBuilding().apply { filtering().omitNodesWithState(DiffNode.State.UNTOUCHED) filtering().omitNodesWithState(DiffNode.State.CIRCULAR) inclusion().exclude().apply { propertyName("fullName") propertyName("parent") propertyName("exportedForeignKeys") propertyName("importedForeignKeys") propertyName("deferrable") propertyName("initiallyDeferred") // Definition changes aren't important, its just things like comments or whitespace. propertyName("definition") } // Partial columns are used for unresolved columns to avoid cycles. Matching based on string // is fine for our purposes. comparison().ofType(Class.forName("schemacrawler.crawl.ColumnPartial")).toUseEqualsMethod() // Custom error handler for circular reference warnings which allows to override SL4J warning log val circularReferenceExceptionLogger = circularReferenceExceptionLogger if (circularReferenceExceptionLogger != null) { circularReferenceHandling().handleCircularReferenceExceptionsUsing { node -> // The same message as original CircularReferenceExceptionHandler val message = ( "Detected circular reference in node at path ${node.path} " + "Going deeper would cause an infinite loop, so I'll stop looking at " + "this instance along the current path." ) circularReferenceExceptionLogger(message) } } }.build() }
apache-2.0
951a0bd433daf288604b81ac0ce64dee
42.955556
101
0.737108
4.848039
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/output/ObjectGenerator.kt
1
3976
package org.evomaster.core.output import io.swagger.v3.oas.models.OpenAPI import org.evomaster.core.problem.rest.RestActionBuilderV3 import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.problem.rest.RestIndividual import org.evomaster.core.search.gene.optional.CustomMutationRateGene import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.ObjectGene import org.evomaster.core.search.gene.optional.OptionalGene class ObjectGenerator { private lateinit var swagger: OpenAPI private val modelCluster: MutableMap<String, ObjectGene> = mutableMapOf() fun setSwagger(sw: OpenAPI){ swagger = sw modelCluster.clear() RestActionBuilderV3.getModelsFromSwagger(swagger, modelCluster) } fun getSwagger(): OpenAPI{ return swagger } fun longestCommonSubsequence(a: String, b: String): String { if (a.length > b.length) return longestCommonSubsequence(b, a) var res = "" for (ai in 0 until a.length) { for (len in a.length - ai downTo 1) { for (bi in 0 until b.length - len + 1) { if (a.regionMatches(ai, b, bi,len) && len > res.length) { res = a.substring(ai, ai + len) } } } } return res } fun <T> likelyhoodsExtended(parameter: String, candidates: MutableMap<String, T>): MutableMap<Pair<String, String>, Float>{ //TODO BMR: account for empty candidate sets. val result = mutableMapOf<Pair<String, String>, Float>() var sum : Float = 0.toFloat() if (candidates.isEmpty()) return result candidates.forEach { k, v -> for (field in (v as ObjectGene).fields) { val fieldName = field.name val extendedName = "$k${fieldName}" // even if there are not characters in common, a matching field should still have // a probability of being chosen (albeit a small one). val temp = (1.toLong() + longestCommonSubsequence(parameter.toLowerCase(), extendedName.toLowerCase()) .length.toFloat())/ (1.toLong() + Integer.max(parameter.length, extendedName.length).toFloat()) result[Pair(k, fieldName)] = temp sum += temp } } result.forEach { k, u -> result[k] = u/sum } return result } private fun findSelectedGene(selectedGene: Pair<String, String>): Gene { val foundGene = (modelCluster[selectedGene.first]!!).fields.filter{ field -> field.name == selectedGene.second }.first() when (foundGene::class) { OptionalGene::class -> return (foundGene as OptionalGene).gene CustomMutationRateGene::class -> return (foundGene as CustomMutationRateGene<*>).gene else -> return foundGene } } fun addResponseObjects(action: RestCallAction, individual: RestIndividual){ val refs = action.responseRefs.values refs.forEach{ val respObject = swagger.components.schemas.get(it) } } /** * [getNamedReference] returns the ObjectGene with the matching name from the model cluster. * It is meant to be used in conjunction with [containsKey], to check if the key is present and define appropriate * behaviour if it is not present. * If [getNamedReference] is called with a string key that is not contained in the model cluster, the default * behaviour is to return an empty ObjectGene with the name "NotFound". */ fun getNamedReference(name: String): ObjectGene{ return when{ containsKey(name) -> modelCluster.getValue(name) else -> ObjectGene("NotFound", listOf()) } } fun containsKey(name: String): Boolean{ return modelCluster.containsKey(name) } }
lgpl-3.0
f86a5bd8e76eeace17fbe8538ee258d5
36.87619
127
0.626509
4.528474
false
false
false
false
googlecodelabs/android-compose-codelabs
MigrationCodelab/app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantListViewModel.kt
1
2066
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.switchMap import com.google.samples.apps.sunflower.PlantListFragment import com.google.samples.apps.sunflower.data.Plant import com.google.samples.apps.sunflower.data.PlantRepository /** * The ViewModel for [PlantListFragment]. */ class PlantListViewModel internal constructor( plantRepository: PlantRepository, private val savedStateHandle: SavedStateHandle ) : ViewModel() { val plants: LiveData<List<Plant>> = getSavedGrowZoneNumber().switchMap { if (it == NO_GROW_ZONE) { plantRepository.getPlants() } else { plantRepository.getPlantsWithGrowZoneNumber(it) } } fun setGrowZoneNumber(num: Int) { savedStateHandle.set(GROW_ZONE_SAVED_STATE_KEY, num) } fun clearGrowZoneNumber() { savedStateHandle.set(GROW_ZONE_SAVED_STATE_KEY, NO_GROW_ZONE) } fun isFiltered() = getSavedGrowZoneNumber().value != NO_GROW_ZONE private fun getSavedGrowZoneNumber(): MutableLiveData<Int> { return savedStateHandle.getLiveData(GROW_ZONE_SAVED_STATE_KEY, NO_GROW_ZONE) } companion object { private const val NO_GROW_ZONE = -1 private const val GROW_ZONE_SAVED_STATE_KEY = "GROW_ZONE_SAVED_STATE_KEY" } }
apache-2.0
f56157535d7e6aec4db170454c406a1e
32.322581
84
0.729913
4.182186
false
false
false
false
LorittaBot/Loritta
web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/views/BaseView.kt
1
9265
package net.perfectdreams.loritta.cinnamon.showtime.backend.views import com.mrpowergamerbr.loritta.utils.locale.BaseLocale import kotlinx.html.FlowOrInteractiveContent import kotlinx.html.HEAD import kotlinx.html.HTML import kotlinx.html.HTMLTag import kotlinx.html.HtmlBlockTag import kotlinx.html.NAV import kotlinx.html.ScriptType import kotlinx.html.SectioningOrFlowContent import kotlinx.html.head import kotlinx.html.id import kotlinx.html.link import kotlinx.html.meta import kotlinx.html.nav import kotlinx.html.script import kotlinx.html.section import kotlinx.html.styleLink import kotlinx.html.title import kotlinx.html.unsafe import kotlinx.html.visit import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend import java.time.Instant import java.time.format.DateTimeFormatter abstract class BaseView( val showtimeBackend: ShowtimeBackend, val locale: BaseLocale, val i18nContext: I18nContext, val path: String ) { companion object { val versionPrefix = "/v3" val websiteUrl = "https://loritta.website" } val iconManager = showtimeBackend.svgIconManager val hashManager = showtimeBackend.hashManager fun generateHtml(): HTML.() -> (Unit) = { val supportUrl = "https://loritta.website/support" val firefoxUrl = "https://www.mozilla.org/firefox" val chromeUrl = "https://www.google.com/chrome" val edgeUrl = "https://www.microsoft.com/edge" // "br" to "pt-BR", "us" to "en", "es" to "es", "pt" to "pt" val pageLanguage = when (locale.id) { "default" -> "pt-BR" "en-us" -> "en" "es" -> "es" else -> "en" } attributes["lang"] = pageLanguage head { meta(charset = "utf-8") // Necessary for responsive design on phones: If not set, the browsers uses the "Use Desktop Design" meta(name = "viewport", content = "width=device-width, initial-scale=1, viewport-fit=cover") generateMeta() unsafe { raw(""" <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" /> <meta name="msapplication-TileColor" content="#5bbad5" /> """) } styleLink("$versionPrefix/assets/css/style.css?hash=${assetHash("/assets/css/style.css")}") // ===[ SCRIPTS ]=== // Usado para login: A SpicyMorenitta usa esse código ao autenticar via "auth_popup.kts" // Já que é meio difícil chamar códigos de Kotlin/JS na parent window, existe esse método auxiliar para facilitar. // authenticate(p) sendo p = "user identification do Discord" // Também tem umas coisinhas do Google reCAPTCHA // TODO: Fix /* script(type = ScriptType.textJavaScript) { unsafe { raw(""" function authenticate(p) { output.net.perfectdreams.spicymorenitta.utils.AuthUtils.handlePostAuth(p); }; document.domain = "loritta.website"; function onGoogleRecaptchaLoadCallback() { this['spicy-morenitta'].net.perfectdreams.spicymorenitta.utils.GoogleRecaptchaUtils.onRecaptchaLoadCallback(); }; window.addEventListener('load', function () { // Verificar se o usuário está usando o antigo Edge ou MSIE, já que nós não suportamos nenhum desses dois // ; MSIE == MS Internet Explorer // Trident/7.0 == MSIE11 if (/(?:\b(MS)?IE\s+|\bTrident\/7\.0;.*\s+rv:|\bEdge\/)(\d+)/.test(navigator.userAgent)) { alert("${locale.getList("website.unsupportedBrowser", supportUrl, firefoxUrl, chromeUrl, edgeUrl).joinToString("\\n\\n")}") } // Verificar se o SpicyMorenitta foi carregado corretamente if (window.spicyMorenittaLoaded === undefined) { alert("${locale.getList("website.failedToLoadScripts", supportUrl, firefoxUrl, chromeUrl, edgeUrl).joinToString("\\n\\n")}") } }); """) } } */ // TODO: Fix // Detect AdBlock // script(src = "$versionPrefix/adsbygoogle.js") {} // Google Analytics // TODO: Remove later if Plausible is that good deferredScript("https://www.googletagmanager.com/gtag/js?id=UA-53518408-9") script(type = ScriptType.textJavaScript) { unsafe { raw("""window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-53518408-9');""") } } script( src = "https://web-analytics.perfectdreams.net/js/plausible.js", ) { attributes["data-domain"] = "loritta.website" defer = true } // Google AdSense // script(src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js") {} // Google ReCAPTCHA // script(src = "https://www.google.com/recaptcha/api.js?render=explicit&onload=onGoogleRecaptchaLoadCallback") {} // NitroPay script(type = ScriptType.textJavaScript) { unsafe { raw(""" window["nitroAds"] = window["nitroAds"] || { createAd: function() { window.nitroAds.queue.push(["createAd", arguments]); }, queue: [] };""".trimIndent()) } } deferredScript("https://s.nitropay.com/ads-595.js") // App itself deferredScript("/v3/assets/js/showtime-frontend.js?hash=${assetHash("/assets/js/showtime-frontend.js")}") for ((websiteLocaleId, localeName) in listOf("br" to "pt-BR", "us" to "en", "es" to "es", "pt" to "pt")) { link { attributes["rel"] = "alternate" attributes["hreflang"] = localeName attributes["href"] = "$websiteUrl/$websiteLocaleId$path" } } } generateBody() } open fun getTitle(): String = "¯\\_(ツ)_/¯" open fun getFullTitle(): String = "${getTitle()} • Loritta" open fun HEAD.generateMeta() { // Used for Search Engines and in the browser itself title(getFullTitle()) // Used for Search Engines meta("description", content = locale["website.genericDescription"]) // Used for Discord Embeds meta("theme-color", "#29a6fe") // Used in Twitter meta(name = "twitter:card", content = "summary") meta(name = "twitter:site", content = "@LorittaBot") meta(name = "twitter:creator", content = "@MrPowerGamerBR") // Used for Discord Embeds meta(content = locale["website.lorittaWebsite"]) { attributes["property"] = "og:site_name" } meta(content = locale["website.genericDescription"]) { attributes["property"] = "og:description" } meta(content = getTitle()) { attributes["property"] = "og:title" } meta(content = "600") { attributes["property"] = "og:ttl" } val imageUrl = getImageUrl() if (imageUrl != null) { meta(content = "${showtimeBackend.rootConfig.loritta.website}$imageUrl") { attributes["property"] = "og:image" } meta(name = "twitter:card", content = "summary_large_image") } else { meta(content = "https://loritta.website/assets/img/loritta_gabizinha_v1.png") { attributes["property"] = "og:image" } } val pubDate = getPublicationDate() if (pubDate != null) { meta(name = "pubdate", content = DateTimeFormatter.ISO_INSTANT.format(pubDate).toString()) } } abstract fun HTML.generateBody() fun assetHash(asset: String) = hashManager.getAssetHash(asset) fun FlowOrInteractiveContent.customHtmlTag(htmlTag: String, block: HtmlBlockTag.() -> Unit = {}) { val obj = object: HTMLTag(htmlTag, consumer, emptyMap(), inlineTag = false, emptyTag = false), HtmlBlockTag {} obj.visit(block) } fun FlowOrInteractiveContent.sidebarWrapper(block: HtmlBlockTag.() -> Unit = {}) = customHtmlTag("lori-sidebar-wrapper", block) fun SectioningOrFlowContent.leftSidebar(block: NAV.() -> Unit = {}) = nav(classes = "left-sidebar") { id = "left-sidebar" attributes["data-preload-keep-scroll"] = "true" block.invoke(this) } fun SectioningOrFlowContent.rightSidebar(block: HtmlBlockTag.() -> Unit = {}) = section(classes = "right-sidebar") { block.invoke(this) } fun HEAD.deferredScript(src: String) { // Defer = Downloads the file during HTML parsing and will only execute after the parser has completed // Defer also follows the script declaration order! // https://stackoverflow.com/questions/10808109/script-tag-async-defer script(src = src) { defer = true } } open fun getImageUrl(): String? = null open fun getPublicationDate(): Instant? = null }
agpl-3.0
335ca70a6aa4f827c5b6d7fa732d2604
38.521368
174
0.619985
3.934894
false
false
false
false
nguyenhoanglam/ImagePicker
imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/helper/DeviceHelper.kt
1
948
/* * Copyright (C) 2021 Image Picker * Author: Nguyen Hoang Lam <[email protected]> */ package com.nguyenhoanglam.imagepicker.helper import android.content.Context import android.content.Intent import android.os.Build import android.provider.MediaStore import android.widget.Toast import com.nguyenhoanglam.imagepicker.R object DeviceHelper { val isMinSdk29 get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q fun checkCameraAvailability(context: Context): Boolean { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val isAvailable = intent.resolveActivity(context.packageManager) != null if (!isAvailable) { val appContext = context.applicationContext Toast.makeText( appContext, appContext.getString(R.string.imagepicker_error_no_camera), Toast.LENGTH_LONG ).show() } return isAvailable } }
apache-2.0
f7e5bc0dc5f22841402e9754c657c5e2
28.65625
80
0.684599
4.19469
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/client/persistence.kt
1
10941
package at.cpickl.gadsu.client import at.cpickl.gadsu.client.xprops.model.CProps import at.cpickl.gadsu.global.GadsuException import at.cpickl.gadsu.image.MyImage import at.cpickl.gadsu.image.defaultImage import at.cpickl.gadsu.image.toMyImage import at.cpickl.gadsu.image.toSqlBlob import at.cpickl.gadsu.persistence.Jdbcx import at.cpickl.gadsu.persistence.ensureNotPersisted import at.cpickl.gadsu.persistence.ensurePersisted import at.cpickl.gadsu.persistence.toBufferedImage import at.cpickl.gadsu.persistence.toSqlTimestamp import at.cpickl.gadsu.service.IdGenerator import com.google.inject.Inject import org.joda.time.DateTime import org.slf4j.LoggerFactory import org.springframework.jdbc.core.RowMapper import java.sql.Blob private val log = LoggerFactory.getLogger("at.cpickl.gadsu.client.persistence") interface ClientRepository { fun findAll(filterState: ClientState? = null): List<Client> /** * @param client its ID must be null * @return new client instance with a non-null ID */ fun insertWithoutPicture(client: Client): Client fun updateWithoutPicture(client: Client) fun changePicture(client: Client) /** * Will NOT trigger cascade delete! Use ClientService instead. */ fun delete(client: Client) fun findById(id: String): Client } class ClientJdbcRepository @Inject constructor( private val jdbcx: Jdbcx, private val idGenerator: IdGenerator ) : ClientRepository { companion object { val TABLE = "client" } private val log = LoggerFactory.getLogger(javaClass) override fun findAll(filterState: ClientState?): List<Client> { log.debug("findAll(filterState={})", filterState) val clients = if (filterState == null) jdbcx.query("SELECT * FROM $TABLE", Client.ROW_MAPPER) else { jdbcx.query2("SELECT * FROM $TABLE WHERE state = ?", Client.ROW_MAPPER, filterState.sqlCode) } clients.sort() return clients } override fun findById(id: String) = jdbcx.querySingle(Client.ROW_MAPPER, "SELECT * FROM $TABLE WHERE id = ?", id) override fun insertWithoutPicture(client: Client): Client { log.debug("insert(client={})", client) client.ensureNotPersisted() val newId = idGenerator.generate() @Suppress("SENSELESS_COMPARISON") // yes, it can indeed be that way! because of stupid mocking. if (newId === null) { throw GadsuException("IdGenerator did return null, although compile forbids. Are you testing and havent setup a proper mock maybe?! (idGenerator=$idGenerator)") } val sqlInsert = """ INSERT INTO $TABLE ( id, created, firstName, lastName, nickNameInt, nickNameExt, mail, phone, street, zipCode, city, knownBy, dsgvoAccepted, wantReceiveMails, birthday, gender_enum, countryOfOrigin, origin, relationship_enum, job, children, hobbies, note, textImpression, textMedical, textComplaints, textPersonal, textObjective, mainObjective, symptoms, syndrom, tcmNote, category, donation, yyTendency, textYinYang, elementTendency, elements, textWood, textFire, textEarth, textMetal, textWater ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )""" jdbcx.update(sqlInsert, newId, client.created.toSqlTimestamp(), client.firstName, client.lastName, client.nickNameInt, client.nickNameExt, client.contact.mail, client.contact.phone, client.contact.street, client.contact.zipCode, client.contact.city, client.knownBy, client.dsgvoAccepted, client.wantReceiveMails, client.birthday?.toSqlTimestamp(), client.gender.sqlCode, client.countryOfOrigin, client.origin, client.relationship.sqlCode, client.job, client.children, client.hobbies, client.note, client.textImpression, client.textMedical, client.textComplaints, client.textPersonal, client.textObjective, client.textMainObjective, client.textSymptoms, client.textSyndrom, client.tcmNote, client.category.sqlCode, client.donation.sqlCode, client.yyTendency.sqlCode, client.textYinYang, client.elementTendency.sqlCode, client.textFiveElements, client.textWood, client.textFire, client.textEarth, client.textMetal, client.textWater ) return client.copy( id = newId, picture = client.gender.defaultImage ) } override fun updateWithoutPicture(client: Client) { log.debug("update(client={})", client) client.ensurePersisted() jdbcx.updateSingle(""" UPDATE $TABLE SET state = ?, firstName = ?, lastName = ?, nickNameInt = ?, nickNameExt = ?, mail = ?, phone = ?, street = ?, zipCode = ?, city = ?, knownBy = ?, dsgvoAccepted = ?, wantReceiveMails = ?, birthday = ?, gender_enum = ?, countryOfOrigin = ?, origin = ?, relationship_enum = ?, job = ?, children = ?, hobbies = ?, note = ?, textImpression = ?, textMedical = ?, textComplaints = ?, textPersonal = ?, textObjective = ?, mainObjective = ?, symptoms = ?, syndrom = ?, tcmNote = ?, category = ?, donation = ?, yyTendency = ?, textYinYang = ?, elementTendency = ?, elements = ?, textWood = ?, textFire = ?, textEarth = ?, textMetal = ?, textWater = ? WHERE id = ?""", client.state.sqlCode, client.firstName, client.lastName, client.nickNameInt, client.nickNameExt, client.contact.mail, client.contact.phone, client.contact.street, client.contact.zipCode, client.contact.city, client.knownBy, client.dsgvoAccepted, client.wantReceiveMails,client.birthday?.toSqlTimestamp(), client.gender.sqlCode, client.countryOfOrigin, client.origin, client.relationship.sqlCode, client.job, client.children, client.hobbies, client.note, client.textImpression, client.textMedical, client.textComplaints, client.textPersonal, client.textObjective, client.textMainObjective, client.textSymptoms, client.textSyndrom, client.tcmNote, client.category.sqlCode, client.donation.sqlCode, client.yyTendency.sqlCode, client.textYinYang, client.elementTendency.sqlCode, client.textFiveElements, client.textWood, client.textFire, client.textEarth, client.textMetal, client.textWater, // no picture or cprops client.id!!) } override fun changePicture(client: Client) { client.ensurePersisted() jdbcx.updateSingle("UPDATE $TABLE SET picture = ? WHERE id = ?", client.picture.toSqlBlob(), client.id!!) } override fun delete(client: Client) { log.debug("delete(client={})", client) client.ensurePersisted() jdbcx.deleteSingle("DELETE FROM $TABLE WHERE id = ?", client.id!!) } } @Suppress("UNUSED") val Client.Companion.ROW_MAPPER: RowMapper<Client> get() = RowMapper { rs, _ -> log.trace("Transforming database row for client with first name: '{}'", rs.getString("firstName")) val gender = Gender.Enum.parseSqlCode(rs.getString("gender_enum")) Client( id = rs.getString("id"), created = DateTime(rs.getTimestamp("created")), state = ClientState.parseSqlCode(rs.getString("state")), firstName = rs.getString("firstName"), lastName = rs.getString("lastName"), nickNameExt = rs.getString("nickNameExt"), nickNameInt = rs.getString("nickNameInt"), contact = Contact( rs.getString("mail"), rs.getString("phone"), rs.getString("street"), rs.getString("zipCode"), rs.getString("city") ), knownBy = rs.getString("knownBy"), wantReceiveMails = rs.getBoolean("wantReceiveMails"), dsgvoAccepted = rs.getBoolean("dsgvoAccepted"), birthday = rs.getTimestamp("birthday")?.run { DateTime(this) }, gender = gender, countryOfOrigin = rs.getString("countryOfOrigin"), origin = rs.getString("origin"), relationship = Relationship.Enum.parseSqlCode(rs.getString("relationship_enum")), job = rs.getString("job"), children = rs.getString("children"), hobbies = rs.getString("hobbies"), note = rs.getString("note"), textImpression = rs.getString("textImpression"), textMedical = rs.getString("textMedical"), textComplaints = rs.getString("textComplaints"), textPersonal = rs.getString("textPersonal"), textObjective = rs.getString("textObjective"), textMainObjective = rs.getString("mainObjective"), textSymptoms = rs.getString("symptoms"), textSyndrom = rs.getString("syndrom"), yyTendency = YinYangMaybe.Enum.parseSqlCode(rs.getString("yyTendency")), textYinYang = rs.getString("textYinYang"), elementTendency = ElementMaybe.Enum.parseSqlCode(rs.getString("elementTendency")), textFiveElements = rs.getString("elements"), textWood = rs.getString("textWood"), textFire = rs.getString("textFire"), textEarth = rs.getString("textEarth"), textMetal = rs.getString("textMetal"), textWater = rs.getString("textWater"), category = ClientCategory.Enum.parseSqlCode(rs.getString("category")), donation = ClientDonation.Enum.parseSqlCode(rs.getString("donation")), tcmNote = rs.getString("tcmNote"), picture = readFromBlob(rs.getBlob("picture"), gender), cprops = CProps.empty // will be loaded by higher-leveled service layer, who combines this with other repo's result ) } private fun readFromBlob(blob: Blob?, gender: Gender): MyImage { val buffered = blob?.toBufferedImage() if (buffered != null) { log.trace("Loading image for client from database BLOB.") // Files.write(blob.toByteArray(), File("readFromBlob.jpg")) return buffered.toMyImage() } log.trace("No picture stored for client, returning default image based on gender.") return gender.defaultImage }
apache-2.0
59663826f8feaf78cb7455fe84efb9ff
46.159483
207
0.618316
4.413473
false
false
false
false
ThanosFisherman/MayI
buildSrc/src/main/kotlin/LibraryDependency.kt
1
3185
import kotlin.reflect.full.memberProperties private object LibraryVersion { //Core Versions const val koinVersion = "2.1.6" const val timberVersion = "4.7.1" const val coroutinesVersion = "1.3.8" const val ktxCore = "1.3.2" const val multiDexVersion = "1.0.3" const val androidxVersion = "1.2.0" const val lifecycleVersionX = "2.2.0" const val constraintLayoutVersion = "2.1.0-beta01" const val recyclerViewVersion = "1.1.0" const val materialVersion = "1.4.0-alpha01" const val coilVersion = "1.1.1" const val progressButtonVersion = "2.1.0" const val flowBindingsVersion = "0.12.0" } // Versions consts that are used across libraries and Gradle plugins object CoreVersion { const val KOTLIN = "1.4.31" const val KTLINT = "0.36.0" const val NAVIGATION = "2.3.4" const val DESUGARING = "1.1.1" } object LibDependency { const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${CoreVersion.KOTLIN}" const val kotlinReflect = "org.jetbrains.kotlin:kotlin-reflect:${CoreVersion.KOTLIN}" const val ktxCore = "androidx.core:core-ktx:${LibraryVersion.ktxCore}" fun getAll() = LibDependency::class.memberProperties .filter { it.isConst } .map { it.getter.call().toString() } .toSet() } object AppDependency { val desugaring = "com.android.tools:desugar_jdk_libs:${CoreVersion.DESUGARING}" const val multiDex = "com.android.support:multidex:${LibraryVersion.multiDexVersion}" const val androidX = "androidx.appcompat:appcompat:${LibraryVersion.androidxVersion}" const val constraintLayout = "androidx.constraintlayout:constraintlayout:${LibraryVersion.constraintLayoutVersion}" const val ktxCore = "androidx.core:core-ktx:${LibraryVersion.ktxCore}" const val viewModelLiveData = "androidx.lifecycle:lifecycle-extensions:${LibraryVersion.lifecycleVersionX}" const val reactiveStreamsLiveData = "androidx.lifecycle:lifecycle-reactivestreams:${LibraryVersion.lifecycleVersionX}" const val lifecycleLiveData = "androidx.lifecycle:lifecycle-livedata-ktx:${LibraryVersion.lifecycleVersionX}" const val recyclerView = "androidx.recyclerview:recyclerview:${LibraryVersion.recyclerViewVersion}" const val navigationUI = "androidx.navigation:navigation-fragment-ktx:${CoreVersion.NAVIGATION}" const val navigationKtx = "androidx.navigation:navigation-ui-ktx:${CoreVersion.NAVIGATION}" const val coil = "io.coil-kt:coil:${LibraryVersion.coilVersion}" const val material = "com.google.android.material:material:${LibraryVersion.materialVersion}" const val viewFlowBindings = "io.github.reactivecircus.flowbinding:flowbinding-android:${LibraryVersion.flowBindingsVersion}" const val progressButton = "com.github.razir.progressbutton:progressbutton:${LibraryVersion.progressButtonVersion}" const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${CoreVersion.KOTLIN}" const val kotlinReflect = "org.jetbrains.kotlin:kotlin-reflect:${CoreVersion.KOTLIN}" fun getAll() = AppDependency::class.memberProperties .filter { it.isConst } .map { it.getter.call().toString() } .toSet() }
apache-2.0
3a59a9ac09ce62110427e7286cbdbabc
45.838235
129
0.735636
3.986233
false
false
false
false
fluttercommunity/plus_plugins
packages/package_info_plus/package_info_plus/android/src/main/kotlin/dev/fluttercommunity/plus/packageinfo/PackageInfoPlugin.kt
1
5288
package dev.fluttercommunity.plus.packageinfo import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Build import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** PackageInfoPlugin */ class PackageInfoPlugin : MethodCallHandler, FlutterPlugin { private var applicationContext: Context? = null private var methodChannel: MethodChannel? = null /** Plugin registration. */ override fun onAttachedToEngine(binding: FlutterPluginBinding) { applicationContext = binding.applicationContext methodChannel = MethodChannel(binding.binaryMessenger, CHANNEL_NAME) methodChannel!!.setMethodCallHandler(this) } override fun onDetachedFromEngine(binding: FlutterPluginBinding) { applicationContext = null methodChannel!!.setMethodCallHandler(null) methodChannel = null } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { try { if (call.method == "getAll") { val packageManager = applicationContext!!.packageManager val info = packageManager.getPackageInfo(applicationContext!!.packageName, 0) val buildSignature = getBuildSignature(packageManager) val installerPackage = packageManager.getInstallerPackageName(applicationContext!!.packageName); val infoMap = HashMap<String, String>() infoMap.apply { put("appName", info.applicationInfo.loadLabel(packageManager).toString()) put("packageName", applicationContext!!.packageName) put("version", info.versionName) put("buildNumber", getLongVersionCode(info).toString()) if (buildSignature != null) put("buildSignature", buildSignature) if (installerPackage != null) put("installerStore", installerPackage) }.also { resultingMap -> result.success(resultingMap) } } else { result.notImplemented() } } catch (ex: PackageManager.NameNotFoundException) { result.error("Name not found", ex.message, null) } } @Suppress("deprecation") private fun getLongVersionCode(info: PackageInfo): Long { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { info.longVersionCode } else { info.versionCode.toLong() } } @Suppress("deprecation", "PackageManagerGetSignatures") private fun getBuildSignature(pm: PackageManager): String? { return try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { val packageInfo = pm.getPackageInfo( applicationContext!!.packageName, PackageManager.GET_SIGNING_CERTIFICATES ) val signingInfo = packageInfo.signingInfo ?: return null if (signingInfo.hasMultipleSigners()) { signatureToSha1(signingInfo.apkContentsSigners.first().toByteArray()) } else { signatureToSha1(signingInfo.signingCertificateHistory.first().toByteArray()) } } else { val packageInfo = pm.getPackageInfo( applicationContext!!.packageName, PackageManager.GET_SIGNATURES ) val signatures = packageInfo.signatures if (signatures.isNullOrEmpty() || packageInfo.signatures.first() == null) { null } else { signatureToSha1(signatures.first().toByteArray()) } } } catch (e: PackageManager.NameNotFoundException) { null } catch (e: NoSuchAlgorithmException) { null } } // Credits https://gist.github.com/scottyab/b849701972d57cf9562e @Throws(NoSuchAlgorithmException::class) private fun signatureToSha1(sig: ByteArray): String { val digest = MessageDigest.getInstance("SHA1") digest.update(sig) val hashText = digest.digest() return bytesToHex(hashText) } // Credits https://gist.github.com/scottyab/b849701972d57cf9562e private fun bytesToHex(bytes: ByteArray): String { val hexArray = charArrayOf( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ) val hexChars = CharArray(bytes.size * 2) var v: Int for (j in bytes.indices) { v = bytes[j].toInt() and 0xFF hexChars[j * 2] = hexArray[v ushr 4] hexChars[j * 2 + 1] = hexArray[v and 0x0F] } return String(hexChars) } companion object { private const val CHANNEL_NAME = "dev.fluttercommunity.plus/package_info" } }
bsd-3-clause
f5dfe5a26d68c5716e73d536911baca1
38.759398
112
0.616112
4.983977
false
false
false
false
ScreamingHawk/phone-saver
app/src/main/java/link/standen/michael/phonesaver/activity/SaverActivity.kt
1
15569
package link.standen.michael.phonesaver.activity import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.media.MediaScannerConnection import android.net.Uri import android.os.Build import android.os.Bundle import link.standen.michael.phonesaver.R import link.standen.michael.phonesaver.util.LocationHelper import android.provider.OpenableColumns import android.text.Html import android.text.method.LinkMovementMethod import android.view.View import android.webkit.MimeTypeMap import android.widget.* import link.standen.michael.phonesaver.util.DebugLogger import java.io.* import android.widget.TextView import link.standen.michael.phonesaver.saver.LocationSelectTask import link.standen.michael.phonesaver.saver.HandleSingleTextTask import link.standen.michael.phonesaver.data.Pair import link.standen.michael.phonesaver.util.PreferenceHelper /** * An activity to handle saving files. * https://developer.android.com/training/sharing/receive.html */ class SaverActivity : ListActivity() { companion object { const val FILENAME_REGEX = "[^-_.A-Za-z0-9]" const val FILENAME_LENIENT_REGEX = "[\\p{Cntrl}]" const val FILENAME_LENGTH_LIMIT = 100 const val FILENAME_EXT_MATCH_LIMIT = 1000 const val DIRECT_SHARE_FOLDER = "DIRECT_SHARE_FOLDER" } val requestCodeLocationSelect = 1 private lateinit var log: DebugLogger private val preferenceHelper = PreferenceHelper(this) var location: String? = null var convertedMime: String? = null var debugInfo: MutableList<Pair> = mutableListOf() lateinit var returnFromActivityResult: (uri: Uri?) -> Unit override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.saver_activity) log = DebugLogger(this) preferenceHelper.loadPreferences() val directShareLocation = intent?.extras?.getString(DIRECT_SHARE_FOLDER) when { directShareLocation != null -> { location = LocationHelper.addRoot(directShareLocation) useIntent({ finishIntent(it) }) } PreferenceHelper.forceSaving -> loadList() else -> { useIntent({ success -> log.i("Supported: $success") // Success should never be null on a dryRun if (success!!){ loadList() } else { showNotSupported() } }, dryRun=true) } } } /** * Load the list of locations */ private fun loadList() { LocationHelper.loadFolderListWLocationSelect(this)?.let {locations -> when { locations.size > 1 -> { runOnUiThread { findViewById<View>(R.id.loading).visibility = View.GONE // Init list view val listView = findViewById<ListView>(android.R.id.list) listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> if (!PreferenceHelper.locationSelectEnabled || position != 0){ // The first item is the location select. Set location otherwise location = LocationHelper.addRoot(locations[position]) } useIntent({ finishIntent(it) }) } listView.adapter = ArrayAdapter<String>(this, R.layout.saver_list_item, locations.map { if (it.isBlank()) File.separator else it }) } return // await selection } locations.size == 1 -> { // Only one location, just use it if (!PreferenceHelper.locationSelectEnabled) { // Only set location when not using location select location = LocationHelper.addRoot(locations[0]) } useIntent({ finishIntent(it) }) return // activity dead } else -> { runOnUiThread { Toast.makeText(this, R.string.toast_save_init_no_locations, Toast.LENGTH_LONG).show() exitApplication() } return // activity dead } } } runOnUiThread { Toast.makeText(this, R.string.toast_save_init_error, Toast.LENGTH_LONG).show() exitApplication() } return // activity dead } private fun useIntent(callback: (success: Boolean?) -> Unit, dryRun: Boolean = false) { // Get intent action and MIME type val action: String? = intent.action val type: String? = intent.type log.i("Action: $action") log.i("Type: $type") type?.toLowerCase()?.let { if (Intent.ACTION_SEND == action) { return handleSingle(callback, dryRun) } else if (Intent.ACTION_SEND_MULTIPLE == action) { return handleMultiple(callback, dryRun) } if (PreferenceHelper.forceSaving) { // Save the file the best way we can return handleSingle(callback, dryRun) } } log.i("No supporting method") // Failed to reach callback finishIntent(false) } /** * Show the not supported information. */ private fun showNotSupported() { // Hide list runOnUiThread { findViewById<View>(R.id.loading).visibility = View.GONE findViewById<View>(android.R.id.list).visibility = View.GONE // Generate issue text here as should always be English and does not need to be in strings.xml val bobTitle = StringBuilder() bobTitle.append("Support Request - ") bobTitle.append(intent.type) val bobBody = StringBuilder() bobBody.append("Support request. Generated by Phone Saver.%0D%0A") bobBody.append("%0D%0AIntent type: ") bobBody.append(intent.type) bobBody.append("%0D%0AIntent action: ") bobBody.append(intent.action) intent.getStringExtra(Intent.EXTRA_TEXT)?.let { bobBody.append("%0D%0AText: ") bobBody.append(it) } intent.getStringExtra(Intent.EXTRA_SUBJECT)?.let { bobBody.append("%0D%0ASubject: ") bobBody.append(it) } debugInfo.forEach { bobBody.append("%0D%0A${it.key}: ") bobBody.append(it.value) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { intent.getStringExtra(Intent.EXTRA_HTML_TEXT)?.let { bobBody.append("%0D%0AHTML Text: ") bobBody.append(it) } } // Version try { val versionName = packageManager.getPackageInfo(packageName, 0).versionName bobBody.append("%0D%0AApplication Version: ") bobBody.append(versionName) } catch (e: PackageManager.NameNotFoundException) { log.e("Unable to get package version", e) } bobBody.append("%0D%0A%0D%0AMore information: TYPE_ADDITIONAL_INFORMATION_HERE") bobBody.append("%0D%0A%0D%0AThank you") val issueLink = "https://github.com/ScreamingHawk/phone-saver/issues/new?title=" + bobTitle.toString().replace(" ", "%20") + "&body=" + bobBody.toString().replace(" ", "%20").replace("=", "%3D") log.i(issueLink) // Build and show unsupported message val supportView = findViewById<TextView>(R.id.not_supported) @Suppress("DEPRECATION") supportView.text = Html.fromHtml(resources.getString(R.string.not_supported, issueLink)) supportView.movementMethod = LinkMovementMethod.getInstance() findViewById<View>(R.id.not_supported_wrapper).visibility = View.VISIBLE } } /** * Call when the intent is finished */ private fun finishIntent(success: Boolean?, messageId: Int? = null) { // Notify user runOnUiThread { when { messageId != null -> Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show() success == null -> Toast.makeText(this, R.string.toast_save_in_progress, Toast.LENGTH_SHORT).show() success -> Toast.makeText(this, R.string.toast_save_successful, Toast.LENGTH_SHORT).show() else -> Toast.makeText(this, R.string.toast_save_failed, Toast.LENGTH_SHORT).show() } } exitApplication() } /** * Exists the application is the best way available for the Android version */ @SuppressLint("NewApi") private fun exitApplication() { when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> finishAndRemoveTask() Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN -> finishAffinity() else -> finish() } } /** * Handle the saving of single items. */ private fun handleSingle(callback: (success: Boolean?) -> Unit, dryRun: Boolean) { // Try save stream first intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.let { log.d("Text has stream") getFilename(it, intent.type ?: "", dryRun) {filename -> saveUri(it, filename, callback, dryRun) } return } // Save the text intent.getStringExtra(Intent.EXTRA_TEXT)?.let { log.d("Text Extra: $it") HandleSingleTextTask(this, it, intent, dryRun, callback).execute() } ?: callback(false) } /** * Handle the saving of multiple streams. */ private fun handleMultiple(callback: (success: Boolean?) -> Unit, dryRun: Boolean) { val imageUris: ArrayList<Uri>? = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) imageUris?.let { var counter = 0 var completeSuccess = true imageUris.forEach {uri -> getFilename(uri, intent.type ?: "", dryRun) { filename -> saveUri(uri, filename, { success -> counter++ success?.let { completeSuccess = completeSuccess && it } if (counter == imageUris.size){ callback(completeSuccess) } }, dryRun) } } } ?: callback(false) } /** * Save the given uri to filesystem. */ private fun saveUri(uri: Uri, filename: String, callback: (success: Boolean?) -> Unit, dryRun: Boolean) { val destinationFilename = LocationHelper.safeAddPath(location, filename) if (!dryRun) { val sourceFilename = uri.path log.d("Saving $sourceFilename to $destinationFilename") } else { // This method can be skipped when doing a dry run return callback(true) } if (location == null){ // No location, use location select returnFromActivityResult = { if (it == null){ callback(false) } else { val pfd = contentResolver.openFileDescriptor(it, "w") if (pfd == null){ callback(false) } else { val bos = BufferedOutputStream(FileOutputStream(pfd.fileDescriptor)) contentResolver.openInputStream(uri)?.use { bis -> saveStream(bis, bos, null, callback, dryRun) } ?: callback(false) } } } LocationSelectTask(this).save(filename, convertedMime!!) } else { try { contentResolver.openInputStream(uri)?.use { bis -> val fout = File(destinationFilename) if (!fout.exists()) { fout.createNewFile() } val bos = BufferedOutputStream(FileOutputStream(fout, false)) saveStream(bis, bos, destinationFilename, callback, dryRun) } ?: callback(false) } catch (e: FileNotFoundException) { log.e("File not found. Perhaps you are overriding the same file and just deleted it?", e) callback(false) } } } /** * Save a stream to the filesystem. */ fun saveStream(bis: InputStream, bos: OutputStream, destinationFilename: String?, callback: (success: Boolean?) -> Unit, dryRun: Boolean) { if (dryRun){ // This entire method can be skipped when doing a dry run return callback(true) } var success = false try { val buf = ByteArray(1024) var bytesRead = bis.read(buf) while (bytesRead != -1) { bos.write(buf, 0, bytesRead) bytesRead = bis.read(buf) } // Done success = true if (PreferenceHelper.registerMediaServer && destinationFilename != null){ MediaScannerConnection.scanFile(this, arrayOf(destinationFilename), null, null) } } catch (e: IOException) { log.e("Unable to save file", e) } finally { try { bos.close() } catch (e: IOException) { log.e("Unable to close stream", e) } } callback(success) } /** * Get the filename from a Uri. */ private fun getFilename(uri: Uri, mime: String, dryRun: Boolean, callback: (filename: String) -> Unit) { // Find the actual filename if (uri.scheme == "content") { contentResolver.query(uri, null, null, null, null)?.use { if (it.moveToFirst()) { return getFilename(it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME)), mime, dryRun, callback, uri) } } } getFilename(uri.lastPathSegment ?: "default", mime, dryRun, callback, uri) } /** * Get the filename from a string. */ fun getFilename(s: String, mime: String, dryRun: Boolean, callback: (filename: String) -> Unit, uri: Uri? = null) { // Validate the mime type log.d("Converting mime: $mime") convertedMime = mime.replaceAfter(";", "").replace(";", "") log.d("Converted mime: $convertedMime") log.d("Converting filename: $s") var result = s // Take last section after a slash (excluding the slash) .replaceBeforeLast("/", "").replace("/", "") // Remove non-filename characters .replace(Regex(if (PreferenceHelper.useLenientRegex) FILENAME_LENIENT_REGEX else FILENAME_REGEX), "") // Trim whitespace .trim() if (result.length > FILENAME_LENGTH_LIMIT) { // Do not go over the filename length limit result = result.substring(0, FILENAME_LENGTH_LIMIT) } var ext = result.substringAfterLast('.', "") if (!MimeTypeMap.getSingleton().hasExtension(ext)){ // Add file extension MimeTypeMap.getSingleton().getExtensionFromMimeType(convertedMime)?.let { ext = it log.d("Adding extension $it to $result") result += ".$it" } } log.d("Converted filename: $result") if (!dryRun) { location?.let { location -> val destinationFilename = LocationHelper.safeAddPath(location, result) val f = File(destinationFilename) if (f.exists()) { when (PreferenceHelper.saveStrategy) { 0 -> { // Overwrite. Delete the file, so that it will be overridden uri?.let { u -> val sourceFilename = u.path if (sourceFilename?.contains(destinationFilename) == true) { log.w("Aborting! It appears you are saving the file over itself") finishIntent(false, R.string.toast_save_file_exists_self_abort) return } } runOnUiThread { Toast.makeText(this, R.string.toast_save_file_exists_overwrite, Toast.LENGTH_SHORT).show() } log.w("Overwriting $result") f.delete() } 1 -> { // Nothing. Quit log.d("Quitting due to duplicate $result") finishIntent(false, R.string.toast_save_file_exists_fail) return } 2 -> { // Postfix. Add counter before extension log.d("Adding postfix to $result") var i = 1 val before = destinationFilename.substringBeforeLast('.', "") + "." if (ext.isNotBlank()) { ext = ".$ext" } while (File(before + i + ext).exists()) { i++ if (i > FILENAME_EXT_MATCH_LIMIT) { // We have a lot of matches. This is too hard log.w("There are over $FILENAME_EXT_MATCH_LIMIT matches for $before$ext. Aborting.") finishIntent(false, R.string.toast_save_file_exists_fail) return } } // Update the result to contain the new number result = result.substringBeforeLast('.', "") + "." + i + ext } 3 -> { // Request log.e("Not implemented!") throw NotImplementedError("Requesting filename not yet implemented.") } } } } } callback(result) } fun failOnActivityResult(requestCode: Int) { onActivityResult(requestCode, Activity.RESULT_CANCELED, null) } /** * Return from location select */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode){ requestCodeLocationSelect -> { if (resultCode == RESULT_OK){ data?.data?.let {uri -> return returnFromActivityResult(uri) } } else { // Selection cancelled, fail save returnFromActivityResult(null) } } } } }
mit
f78e721d6c2b9438c60bcd248ffea74f
29.055985
116
0.667352
3.583199
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/utilities/Timer.kt
1
449
package net.dinkla.raytracer.utilities class Timer { internal var startTime: Long = 0 internal var endTime: Long = 0 val duration: Long get() = endTime - startTime init { endTime = 0L startTime = endTime } fun start() { startTime = System.currentTimeMillis() endTime = 0L } fun stop() { assert(endTime == 0L) endTime = System.currentTimeMillis() } }
apache-2.0
27265eac56f4108735f9ce3ec05e08ee
16.269231
46
0.570156
4.49
false
false
false
false
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/status/ComposeStatusController.kt
1
9656
package net.yslibrary.monotweety.status import android.annotation.SuppressLint import android.content.Context import android.content.pm.ShortcutManager import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.Observables import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.PublishSubject import net.yslibrary.monotweety.R import net.yslibrary.monotweety.analytics.Analytics import net.yslibrary.monotweety.base.ActionBarController import net.yslibrary.monotweety.base.HasComponent import net.yslibrary.monotweety.base.ObjectWatcherDelegate import net.yslibrary.monotweety.base.ProgressController import net.yslibrary.monotweety.base.findById import net.yslibrary.monotweety.base.hideKeyboard import net.yslibrary.monotweety.status.adapter.ComposeStatusAdapter import net.yslibrary.monotweety.status.adapter.EditorAdapterDelegate import timber.log.Timber import javax.inject.Inject import kotlin.properties.Delegates class ComposeStatusController(private var status: String? = null) : ActionBarController(), HasComponent<ComposeStatusComponent> { override val hasBackButton: Boolean = true override val hasOptionsMenu: Boolean = true override val component: ComposeStatusComponent by lazy { getComponentProvider<ComposeStatusComponent.ComponentProvider>(activity!!) .composeStatusComponent(ComposeStatusViewModule(status)) } val adapterListener = object : ComposeStatusAdapter.Listener { override fun onStatusChanged(status: String) { viewModel.onStatusChanged(status) } } lateinit var bindings: Bindings val statusAdapter: ComposeStatusAdapter by lazy { ComposeStatusAdapter(adapterListener) } @set:[Inject] var viewModel by Delegates.notNull<ComposeStatusViewModel>() @set:[Inject] var objectWatcherDelegate by Delegates.notNull<ObjectWatcherDelegate>() val sendButtonClicks: PublishSubject<Unit> = PublishSubject.create<Unit>() override fun onContextAvailable(context: Context) { super.onContextAvailable(context) Timber.d("status: $status") component.inject(this) reportShortcutUsedIfNeeded(status) analytics.viewEvent(Analytics.VIEW_COMPOSE_STATUS) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val view = inflater.inflate(R.layout.controller_compose_status, container, false) bindings = Bindings(view) setEvents() return view } override fun onAttach(view: View) { super.onAttach(view) initToolbar() } fun setEvents() { // https://code.google.com/p/android/issues/detail?id=161559 // disable animation to avoid duplicated viewholder bindings.list.apply { if (itemAnimator is SimpleItemAnimator) { (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false } adapter = statusAdapter layoutManager = LinearLayoutManager(activity) } // FIXME: this should be handled in ViewModel viewModel.statusInfo.distinctUntilChanged() .map { (status1, valid, length, maxLength) -> EditorAdapterDelegate.Item( status = status1, statusLength = length, maxLength = maxLength, valid = valid, clear = false ) } .distinctUntilChanged() .bindToLifecycle() .subscribeBy { Timber.d("item updated: $it") statusAdapter.updateEditor(it) } viewModel.closeViewRequests .bindToLifecycle() .subscribe { view?.hideKeyboard() activity?.finish() } viewModel.isSendableStatus .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { activity?.invalidateOptionsMenu() } viewModel.progressEvents .skip(1) .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { when (it) { ComposeStatusViewModel.ProgressEvent.IN_PROGRESS -> showLoadingState() ComposeStatusViewModel.ProgressEvent.FINISHED -> hideLoadingState() else -> hideLoadingState() } } viewModel.statusUpdated .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { Timber.d("status updated") toast(getString(R.string.message_tweet_succeeded))?.show() analytics.tweetFromEditor() } viewModel.messages.bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { toastLong(it)?.show() } sendButtonClicks.bindToLifecycle() .subscribe { viewModel.onSendStatus() } } fun initToolbar() { actionBar?.apply { setHomeAsUpIndicator(R.drawable.ic_close_white_24dp) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_compose_status, menu) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) Observables.zip( viewModel.isSendableStatus, viewModel.progressEvents ) { sendable, progress -> sendable to progress } .blockingFirst() .let { menu.findItem(R.id.action_send_tweet)?.isEnabled = it.first && it.second == ComposeStatusViewModel.ProgressEvent.FINISHED } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { R.id.action_send_tweet -> { Timber.d("option - action_send_tweet") sendButtonClicks.onNext(Unit) return true } else -> { return super.onOptionsItemSelected(item) } } } override fun handleBack(): Boolean { Timber.d("handleBack") if (viewModel.canClose) { view?.hideKeyboard() return super.handleBack() } showConfirmCloseDialog() return true } override fun onChangeEnded( changeHandler: ControllerChangeHandler, changeType: ControllerChangeType ) { super.onChangeEnded(changeHandler, changeType) objectWatcherDelegate.handleOnChangeEnded(isDestroyed, changeType) } override fun onDestroy() { super.onDestroy() viewModel.onDestroy() objectWatcherDelegate.handleOnDestroy() } fun showConfirmCloseDialog() { activity?.let { Timber.tag("Dialog").i("showConfirmationCloseDialog") AlertDialog.Builder(it) .setTitle(R.string.label_confirm) .setMessage(R.string.label_cancel_confirm) .setCancelable(true) .setNegativeButton(R.string.label_no) { dialog, _ -> viewModel.onConfirmCloseView(allowCloseView = false) dialog.dismiss() } .setPositiveButton(R.string.label_quit) { _, _ -> viewModel.onConfirmCloseView(allowCloseView = true) view?.hideKeyboard() activity?.onBackPressed() }.show() } } fun showLoadingState() { activity?.invalidateOptionsMenu() getChildRouter(bindings.overlayRoot, null) .setPopsLastView(true) .setRoot( RouterTransaction.with(ProgressController()) .popChangeHandler(FadeChangeHandler()) .pushChangeHandler(FadeChangeHandler()) ) } fun hideLoadingState() { val childRouter = getChildRouter(bindings.overlayRoot, null) if (childRouter.backstackSize == 0) { return } activity?.invalidateOptionsMenu() childRouter.popCurrentController() } @SuppressLint("NewApi") fun reportShortcutUsedIfNeeded(status: String?) { if (status.isNullOrEmpty()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { applicationContext?.getSystemService(ShortcutManager::class.java) ?.reportShortcutUsed("newtweet") } } } inner class Bindings(view: View) { val list = view.findById<RecyclerView>(R.id.list) val overlayRoot = view.findById<FrameLayout>(R.id.overlay_root) } }
apache-2.0
a4941c885a73cc1e3ef3fe45d65c50c1
32.296552
93
0.638463
5.264995
false
false
false
false
AIDEA775/UNCmorfi
app/src/main/java/com/uncmorfi/reservations/AlarmHelper.kt
1
5756
package com.uncmorfi.reservations import android.app.AlarmManager import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.TaskStackBuilder import androidx.core.content.ContextCompat.getSystemService import com.uncmorfi.MainActivity import com.uncmorfi.R import com.uncmorfi.shared.compareToTodayInMillis import java.util.* import java.util.Calendar.* class AlarmHelper { companion object { fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = context.getString(R.string.reservations_channel_name) val descriptionText = context.getString(R.string.reservations_channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText } val notificationManager: NotificationManager = getSystemService(context, NotificationManager::class.java)!! notificationManager.createNotificationChannel(channel) } } fun enableBootReceiver(context: Context) { val receiver = ComponentName(context, BootReceiver::class.java) context.packageManager.setComponentEnabledSetting( receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) } private fun getIntent(context: Context): PendingIntent { return Intent(context, AlarmReceiver::class.java).let { intent -> PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } } fun getNextAlarm(context: Context): Calendar? { val sharedPref = context.getSharedPreferences("prefs", Context.MODE_PRIVATE) val today = Calendar.getInstance().get(DAY_OF_WEEK) val calendar = Calendar.getInstance().apply { set(MINUTE, 0) set(SECOND, 0) set(MILLISECOND, 0) } for (i in today..today+7) { val day = i%7 val value = sharedPref.getInt(day.toString(), -1) if (setAsNextAlarm(calendar, value)) { return calendar } calendar.add(DAY_OF_YEAR, 1) } return null } /* -1 si no está seteado * 1 si es a las 7AM * 2 si es a las 10AM * 3 si es a las 7AM o las 10AM */ private fun setAsNextAlarm(calendar: Calendar, value: Int): Boolean { if (value == 1 || value == 3) { calendar.set(HOUR_OF_DAY, 6) calendar.set(MINUTE, 55) if (calendar.compareToTodayInMillis() > 0) { return true } } if (value == 2 || value == 3) { calendar.set(HOUR_OF_DAY, 9) calendar.set(MINUTE, 55) if (calendar.compareToTodayInMillis() > 0) { return true } } return false } fun scheduleAlarm(context: Context, calendar: Calendar) { val intent = getIntent(context) val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager if (Build.VERSION.SDK_INT >= 19) { alarmManager.setExact( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, intent) } else { alarmManager.set( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, intent) } } fun cancelAlarm(context: Context) { val intent = getIntent(context) val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(intent) } fun makeNotification(context: Context) { val resultIntent = Intent(context, MainActivity::class.java) val resultPendingIntent = TaskStackBuilder.create(context).run { addNextIntentWithParentStack(resultIntent) getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) } val builder = NotificationCompat.Builder(context, CHANNEL_ID) .setContentIntent(resultPendingIntent) .setSmallIcon(R.drawable.nav_ticket) .setContentTitle(context.getString(R.string.reservations_title)) .setContentText(context.getString(R.string.reservations_content)) .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true) with(NotificationManagerCompat.from(context)) { // notificationId es un int único para cada notificación val notificationId = Calendar.getInstance().get(DAY_OF_YEAR) notify(notificationId, builder.build()) } } private const val CHANNEL_ID = "reservations" } }
gpl-3.0
433f1ede90c25a453e66d2450207e6a8
37.10596
98
0.574831
5.34169
false
false
false
false
talhacohen/android
app/src/main/java/com/etesync/syncadapter/resource/LocalTaskList.kt
1
4408
/* * Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter.resource import android.accounts.Account import android.content.ContentValues import android.content.Context import android.net.Uri import android.os.Build import android.os.RemoteException import at.bitfire.ical4android.AndroidTaskList import at.bitfire.ical4android.AndroidTaskListFactory import at.bitfire.ical4android.CalendarStorageException import at.bitfire.ical4android.TaskProvider import com.etesync.syncadapter.model.JournalEntity import org.dmfs.tasks.contract.TaskContract.TaskLists import org.dmfs.tasks.contract.TaskContract.Tasks class LocalTaskList private constructor( account: Account, provider: TaskProvider, id: Long ): AndroidTaskList<LocalTask>(account, provider, LocalTask.Factory, id), LocalCollection<LocalTask> { companion object { val defaultColor = -0x3c1592 // "DAVdroid green" fun tasksProviderAvailable(context: Context): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) return context.packageManager.resolveContentProvider(TaskProvider.ProviderName.OpenTasks.authority, 0) != null else { val provider = TaskProvider.acquire(context, TaskProvider.ProviderName.OpenTasks) provider?.use { return true } return false } } fun create(account: Account, provider: TaskProvider, journalEntity: JournalEntity): Uri { val values = valuesFromCollectionInfo(journalEntity, true) values.put(TaskLists.OWNER, account.name) values.put(TaskLists.SYNC_ENABLED, 1) values.put(TaskLists.VISIBLE, 1) return create(account, provider, values) } private fun valuesFromCollectionInfo(journalEntity: JournalEntity, withColor: Boolean): ContentValues { val info = journalEntity.info val values = ContentValues(3) values.put(TaskLists._SYNC_ID, info.uid) values.put(TaskLists.LIST_NAME, if (info.displayName.isNullOrBlank()) info.uid else info.displayName) if (withColor) values.put(TaskLists.LIST_COLOR, info.color ?: defaultColor) return values } } override val url: String? get() = syncId fun update(journalEntity: JournalEntity, updateColor: Boolean) = update(valuesFromCollectionInfo(journalEntity, updateColor)) override fun findDeleted() = queryTasks("${Tasks._DELETED}!=0", null) override fun findDirty(): List<LocalTask> { val tasks = queryTasks("${Tasks._DIRTY}!=0 AND ${Tasks._DELETED}==0", null) for (localTask in tasks) { val task = requireNotNull(localTask.task) val sequence = task.sequence if (sequence == null) // sequence has not been assigned yet (i.e. this task was just locally created) task.sequence = 0 else task.sequence = sequence + 1 } return tasks } override fun findAll(): List<LocalTask> = queryTasks(null, null) override fun findWithoutFileName(): List<LocalTask> = queryTasks(Tasks._SYNC_ID + " IS NULL", null) override fun findByUid(uid: String): LocalTask? = queryTasks(Tasks._SYNC_ID + " =? ", arrayOf(uid)).firstOrNull() override fun count(): Long { try { val cursor = provider.client.query( TaskProvider.syncAdapterUri(provider.tasksUri(), account), null, Tasks.LIST_ID + "=?", arrayOf(id.toString()), null) try { return cursor?.count?.toLong()!! } finally { cursor?.close() } } catch (e: RemoteException) { throw CalendarStorageException("Couldn't query calendar events", e) } } object Factory: AndroidTaskListFactory<LocalTaskList> { override fun newInstance(account: Account, provider: TaskProvider, id: Long) = LocalTaskList(account, provider, id) } }
gpl-3.0
99458c8577e1b1b72f97989140a465b8
36.649573
126
0.650851
4.569502
false
false
false
false
kibotu/RecyclerViewPresenter
app/src/main/kotlin/net/kibotu/android/recyclerviewpresenter/app/screens/circular/CircularPresenterActivity.kt
1
2822
package net.kibotu.android.recyclerviewpresenter.app.screens.circular import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import net.kibotu.android.recyclerviewpresenter.PresenterAdapter import net.kibotu.android.recyclerviewpresenter.PresenterViewModel import net.kibotu.android.recyclerviewpresenter.app.R import net.kibotu.android.recyclerviewpresenter.app.misc.createRandomImageUrl import net.kibotu.android.recyclerviewpresenter.app.screens.kotlin.LabelPresenter import net.kibotu.android.recyclerviewpresenter.app.screens.kotlin.NumberPresenter import net.kibotu.android.recyclerviewpresenter.app.screens.kotlin.PhotoPresenter import net.kibotu.logger.Logger import net.kibotu.logger.snack /** * Created by [Jan Rabe](https://kibotu.net). */ class CircularPresenterActivity : AppCompatActivity(R.layout.activity_main) { private val list: RecyclerView get() = findViewById(R.id.list) private val swipeRefresh: SwipeRefreshLayout get() = findViewById(R.id.swipeRefresh) private val adapter = PresenterAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) list.layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL) list.adapter = adapter adapter.isCircular = true adapter.registerPresenter(PhotoPresenter()) adapter.registerPresenter(LabelPresenter()) adapter.registerPresenter(NumberPresenter()) adapter.onItemClick { item, view, position -> snack("$position. ${item.model}") Logger.v("onItemClick $position") } adapter.onFocusChange { item, view, hasFocus, position -> Logger.v("onFocusChange $position") } adapter.onCurrentListChanged { previousList, currentList -> Logger.v("onCurrentListChanged ${previousList.size} -> ${currentList.size}") } val items = createItems() adapter.submitList(items) swipeRefresh.setOnRefreshListener { items.shuffle() adapter.submitList(items) swipeRefresh.isRefreshing = false } } private fun createItems() = mutableListOf<PresenterViewModel<*>>().apply { repeat(100) { add(PresenterViewModel(it, R.layout.number_presenter_item)) add(PresenterViewModel(createRandomImageUrl(), R.layout.photo_presenter_item)) add(PresenterViewModel(createRandomImageUrl(), R.layout.label_presenter_item)) } } override fun onDestroy() { adapter.clear() super.onDestroy() } }
apache-2.0
c919a3a3819d93e6b8c314fc08855086
33.851852
95
0.722183
4.907826
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/tvshow/get/TVShowGetSeason.kt
1
1281
package uk.co.ourfriendirony.medianotifier.clients.tmdb.tvshow.get import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder( "air_date", "episode_count", "id", "name", "overview", "poster_path", "season_number" ) class TVShowGetSeason { @get:JsonProperty("air_date") @set:JsonProperty("air_date") @JsonProperty("air_date") var airDate: String? = null @get:JsonProperty("episode_count") @set:JsonProperty("episode_count") @JsonProperty("episode_count") var episodeCount: Int? = null @get:JsonProperty("id") @set:JsonProperty("id") @JsonProperty("id") var id: Int? = null @get:JsonProperty("name") @set:JsonProperty("name") @JsonProperty("name") var name: String? = null @get:JsonProperty("overview") @set:JsonProperty("overview") @JsonProperty("overview") var overview: String? = null @get:JsonProperty("poster_path") @set:JsonProperty("poster_path") @JsonProperty("poster_path") var posterPath: String? = null @get:JsonProperty("season_number") @set:JsonProperty("season_number") @JsonProperty("season_number") var seasonNumber: Int? = null }
apache-2.0
3636605cd056b8af51aab04b29551cd1
24.137255
66
0.666667
3.823881
false
false
false
false
chrisbanes/tivi
api/tmdb/src/main/java/app/tivi/tmdb/TmdbImageUrlProvider.kt
1
2498
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.tmdb private val IMAGE_SIZE_PATTERN = "w(\\d+)$".toRegex() data class TmdbImageUrlProvider( private val baseImageUrl: String = TmdbImageSizes.baseImageUrl, private val posterSizes: List<String> = TmdbImageSizes.posterSizes, private val backdropSizes: List<String> = TmdbImageSizes.backdropSizes, private val logoSizes: List<String> = TmdbImageSizes.logoSizes ) { fun getPosterUrl(path: String, imageWidth: Int): String { return "$baseImageUrl${selectSize(posterSizes, imageWidth)}$path" } fun getBackdropUrl(path: String, imageWidth: Int): String { return "$baseImageUrl${selectSize(backdropSizes, imageWidth)}$path" } fun getLogoUrl(path: String, imageWidth: Int): String { return "$baseImageUrl${selectSize(logoSizes, imageWidth)}$path" } private fun selectSize(sizes: List<String>, imageWidth: Int): String { var previousSize: String? = null var previousWidth = 0 for (i in sizes.indices) { val size = sizes[i] val sizeWidth = extractWidthAsIntFrom(size) ?: continue if (sizeWidth > imageWidth) { if (previousSize != null && imageWidth > (previousWidth + sizeWidth) / 2) { return size } else if (previousSize != null) { return previousSize } } else if (i == sizes.size - 1) { // If we get here then we're larger than the last bucket if (imageWidth < sizeWidth * 2) { return size } } previousSize = size previousWidth = sizeWidth } return previousSize ?: sizes.last() } private fun extractWidthAsIntFrom(size: String): Int? { return IMAGE_SIZE_PATTERN.matchEntire(size)?.groups?.get(1)?.value?.toInt() } }
apache-2.0
1a851ff5660a665cfe10d00ef89041ce
34.685714
91
0.634107
4.359511
false
false
false
false
toastkidjp/Yobidashi_kt
rss/src/main/java/jp/toastkid/rss/extractor/RssUrlFinder.kt
1
2374
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.rss.extractor import jp.toastkid.api.html.HtmlApi import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.rss.R import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * @author toastkidjp */ class RssUrlFinder( private val preferenceApplier: PreferenceApplier, private val contentViewModel: ContentViewModel, private val urlValidator: RssUrlValidator = RssUrlValidator(), private val rssUrlExtractor: RssUrlExtractor = RssUrlExtractor(), private val htmlApi: HtmlApi = HtmlApi(), private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { operator fun invoke( currentUrl: String? ) { if (currentUrl.isNullOrBlank()) { return } if (urlValidator(currentUrl)) { preferenceApplier.saveNewRssReaderTargets(currentUrl) contentViewModel.snackShort("Added $currentUrl") return } CoroutineScope(mainDispatcher).launch { val rssItems = withContext(ioDispatcher) { val response = htmlApi.invoke(currentUrl) ?: return@withContext emptyList<String>() if (!response.isSuccessful) { return@withContext emptyList<String>() } rssUrlExtractor(response.body?.string()) } storeToPreferences(rssItems) } } private fun storeToPreferences(urls: List<String>?) { urls?.firstOrNull { urlValidator(it) } ?.let { preferenceApplier.saveNewRssReaderTargets(it) contentViewModel.snackShort("Added $it") return } contentViewModel.snackShort(R.string.message_failure_extracting_rss) } }
epl-1.0
9ef6d888aa25e3d96eddf8a91fa7d1f8
32.450704
88
0.668071
5.04034
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddCurlyBracesIntention.kt
2
2801
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsPath import org.rust.lang.core.psi.RsUseItem import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.isStarImport import org.rust.lang.core.psi.ext.parentOfType /** * Adds curly braces to singleton imports, changing from this * * ``` * import std::mem; * ``` * * to this: * * ``` * import std::{mem}; * ``` */ class AddCurlyBracesIntention : RsElementBaseIntentionAction<AddCurlyBracesIntention.Context>() { override fun getText() = "Add curly braces" override fun getFamilyName() = text class Context( val useItem: RsUseItem, val path: RsPath ) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val useItem = element.parentOfType<RsUseItem>() ?: return null val path = useItem.path ?: return null if (useItem.useGlobList != null || useItem.isStarImport) return null return Context(useItem, path) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val identifier = ctx.path.referenceNameElement // Remember the caret position, adjusting by the new curly braces val caret = editor.caretModel.offset val newOffset = when { caret < identifier.textOffset -> caret caret < identifier.textOffset + identifier.textLength -> caret + 1 else -> caret + 2 } // Create a new use item that contains a glob list that we can use. // Then extract from it the glob list and the double colon. val newUseItem = RsPsiFactory(project).createUseItem("dummy::{${identifier.text}}") val newGlobList = newUseItem.useGlobList ?: return val newColonColon = newUseItem.coloncolon ?: return val alias = ctx.useItem.alias // If there was an alias before, insert it into the new glob item if (alias != null) { val newGlobItem = newGlobList.children[0] newGlobItem.addAfter(alias, newGlobItem.lastChild) } // Remove the identifier from the path by replacing it with its subpath ctx.path.replace(ctx.path.path ?: return) // Delete the alias of the identifier, if any alias?.delete() // Insert the double colon and glob list into the use item ctx.useItem.addBefore(newColonColon, ctx.useItem.semicolon) ctx.useItem.addBefore(newGlobList, ctx.useItem.semicolon) editor.caretModel.moveToOffset(newOffset) } }
mit
d0fd8f8cb5171c9d122ceb67905f7af5
32.746988
105
0.673331
4.309231
false
false
false
false
pnemonic78/RemoveDuplicates
duplicates-android/app/src/main/java/com/github/duplicates/call/CallLogProvider.kt
1
3746
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.duplicates.call import android.Manifest import android.content.ContentResolver import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.BaseColumns._ID import android.provider.CallLog import android.provider.CallLog.Calls.CACHED_NAME import android.provider.CallLog.Calls.CACHED_NUMBER_LABEL import android.provider.CallLog.Calls.CACHED_NUMBER_TYPE import android.provider.CallLog.Calls.DATE import android.provider.CallLog.Calls.DURATION import android.provider.CallLog.Calls.IS_READ import android.provider.CallLog.Calls.NEW import android.provider.CallLog.Calls.NUMBER import android.provider.CallLog.Calls.TYPE import com.github.duplicates.DuplicateProvider /** * Provide duplicate calls. * * @author moshe.w */ class CallLogProvider(context: Context) : DuplicateProvider<CallLogItem>(context) { override fun getContentUri(): Uri { return CallLog.Calls.CONTENT_URI } override fun getCursorProjection(): Array<String> { return PROJECTION } override fun createItem(cursor: Cursor): CallLogItem { return CallLogItem() } override fun populateItem(cursor: Cursor, item: CallLogItem) { item.id = cursor.getLong(INDEX_ID) item.name = cursor.getString(INDEX_CACHED_NAME) item.numberLabel = cursor.getString(INDEX_CACHED_NUMBER_LABEL) item.numberType = cursor.getInt(INDEX_CACHED_NUMBER_TYPE) item.date = cursor.getLong(INDEX_DATE) item.duration = cursor.getLong(INDEX_DURATION) item.isNew = cursor.getInt(INDEX_NEW) != 0 item.number = cursor.getString(INDEX_NUMBER) item.isRead = cursor.getInt(INDEX_READ) != 0 item.type = cursor.getInt(INDEX_TYPE) } override fun deleteItem(cr: ContentResolver, contentUri: Uri, item: CallLogItem): Boolean { return cr.delete(contentUri, _ID + "=" + item.id, null) > 0 } override fun getReadPermissions(): Array<String> { return PERMISSIONS_READ } override fun getDeletePermissions(): Array<String> { return PERMISSIONS_WRITE } companion object { private val PERMISSIONS_READ = arrayOf("android.permission.READ_CALL_LOG", Manifest.permission.READ_CONTACTS) private val PERMISSIONS_WRITE = arrayOf("android.permission.WRITE_CALL_LOG", Manifest.permission.WRITE_CONTACTS) private val PROJECTION = arrayOf( _ID, CACHED_NAME, CACHED_NUMBER_LABEL, CACHED_NUMBER_TYPE, DATE, DURATION, IS_READ, NEW, NUMBER, TYPE ) private const val INDEX_ID = 0 private const val INDEX_CACHED_NAME = 1 private const val INDEX_CACHED_NUMBER_LABEL = 2 private const val INDEX_CACHED_NUMBER_TYPE = 3 private const val INDEX_DATE = 4 private const val INDEX_DURATION = 5 private const val INDEX_READ = 6 private const val INDEX_NEW = 7 private const val INDEX_NUMBER = 8 private const val INDEX_TYPE = 9 } }
apache-2.0
2d0c51a2eb0d15f493b7c6fe1d26b104
32.747748
95
0.688468
4.276256
false
false
false
false
msebire/intellij-community
platform/configuration-store-impl/testSrc/DoNotSaveDefaults.kt
1
4938
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.async.coroutineDispatchingContext import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.impl.ComponentManagerImpl import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.stateStore import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.createOrLoadProject import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.getDirectoryTree import com.intellij.util.io.move import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.nio.file.Paths internal class DoNotSaveDefaultsTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @JvmField @Rule val tempDir = TemporaryDirectory() @Test fun testApp() = runBlocking { val configDir = Paths.get(PathManager.getConfigPath())!! val newConfigDir = if (configDir.exists()) Paths.get(PathManager.getConfigPath() + "__old") else null if (newConfigDir != null) { newConfigDir.delete() configDir.move(newConfigDir) } try { doTest(ApplicationManager.getApplication() as ApplicationImpl) } finally { configDir.delete() newConfigDir?.move(configDir) } } @Test fun testProject() = runBlocking { createOrLoadProject(tempDir, directoryBased = false) { project -> doTest(project as ProjectImpl) } } private suspend fun doTest(componentManager: ComponentManagerImpl) { // wake up (edt, some configurables want read action) withContext(AppUIExecutor.onUiThread().coroutineDispatchingContext()) { val picoContainer = componentManager.picoContainer ServiceManagerImpl.processAllImplementationClasses(componentManager) { clazz, _ -> val className = clazz.name // CvsTabbedWindow calls invokeLater in constructor if (className != "com.intellij.cvsSupport2.ui.CvsTabbedWindow" && className != "com.intellij.lang.javascript.bower.BowerPackagingService" && !className.endsWith(".MessDetectorConfigurationManager") && className != "org.jetbrains.plugins.groovy.mvc.MvcConsole") { picoContainer.getComponentInstance(className) } true } } val propertyComponent = PropertiesComponent.getInstance() // <property name="file.gist.reindex.count" value="54" /> propertyComponent.unsetValue("file.gist.reindex.count") propertyComponent.unsetValue("android-component-compatibility-check") // <property name="CommitChangeListDialog.DETAILS_SPLITTER_PROPORTION_2" value="1.0" /> propertyComponent.unsetValue("CommitChangeListDialog.DETAILS_SPLITTER_PROPORTION_2") propertyComponent.unsetValue("ts.lib.d.ts.version") propertyComponent.unsetValue("nodejs_interpreter_path.stuck_in_default_project") val useModCountOldValue = System.getProperty("store.save.use.modificationCount") try { System.setProperty("store.save.use.modificationCount", "false") componentManager.stateStore.save(isForceSavingAllSettings = true) } finally { System.setProperty("store.save.use.modificationCount", useModCountOldValue ?: "false") } if (componentManager is Project) { assertThat(Paths.get(componentManager.projectFilePath!!)).doesNotExist() return } val directoryTree = Paths.get(componentManager.stateStore.storageManager.expandMacros(APP_CONFIG)).getDirectoryTree(setOf( "path.macros.xml" /* todo EP to register (provide) macro dynamically */, "stubIndex.xml" /* low-level non-roamable stuff */, UsageStatisticsPersistenceComponent.USAGE_STATISTICS_XML /* SHOW_NOTIFICATION_ATTR in internal mode */, "tomee.extensions.xml", "jboss.extensions.xml", "glassfish.extensions.xml" /* javaee non-roamable stuff, it will be better to fix it */, "dimensions.xml" /* non-roamable sizes of window, dialogs, etc. */, "databaseSettings.xml" /* android garbage */, "updates.xml" )) println(directoryTree) assertThat(directoryTree).isEmpty() } }
apache-2.0
1ab65c3e048d05511fb4fa2e8491fe98
40.15
140
0.751519
4.606343
false
true
false
false
square/duktape-android
zipline-loader/src/commonMain/kotlin/app/cash/zipline/loader/ZiplineLoader.kt
1
14041
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.loader import app.cash.zipline.EventListener import app.cash.zipline.Zipline import app.cash.zipline.loader.internal.fetcher.FsCachingFetcher import app.cash.zipline.loader.internal.fetcher.FsEmbeddedFetcher import app.cash.zipline.loader.internal.fetcher.HttpFetcher import app.cash.zipline.loader.internal.fetcher.LoadedManifest import app.cash.zipline.loader.internal.fetcher.fetch import app.cash.zipline.loader.internal.getApplicationManifestFileName import app.cash.zipline.loader.internal.receiver.FsSaveReceiver import app.cash.zipline.loader.internal.receiver.Receiver import app.cash.zipline.loader.internal.receiver.ZiplineLoadReceiver import app.cash.zipline.loader.internal.systemEpochMsClock import kotlin.coroutines.cancellation.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.internal.ChannelFlow import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import kotlinx.serialization.modules.EmptySerializersModule import kotlinx.serialization.modules.SerializersModule import okio.FileSystem import okio.Path /** * Gets code from an HTTP server, or optional local cache or embedded filesystem, and handles with a * receiver (by default, loads it into a zipline instance). * * Loader attempts to load code as quickly as possible with concurrent network downloads and code * loading. */ class ZiplineLoader internal constructor( private val dispatcher: CoroutineDispatcher, private val manifestVerifier: ManifestVerifier, private val httpFetcher: HttpFetcher, private val eventListener: EventListener, private val nowEpochMs: () -> Long, private val embeddedDir: Path?, private val embeddedFileSystem: FileSystem?, private val cache: ZiplineCache?, ) { constructor( dispatcher: CoroutineDispatcher, manifestVerifier: ManifestVerifier, httpClient: ZiplineHttpClient, eventListener: EventListener = EventListener.NONE, nowEpochMs: () -> Long = systemEpochMsClock, ) : this( dispatcher = dispatcher, manifestVerifier = manifestVerifier, httpFetcher = HttpFetcher(httpClient, eventListener), eventListener = eventListener, nowEpochMs = nowEpochMs, embeddedDir = null, embeddedFileSystem = null, cache = null, ) fun withEmbedded( embeddedDir: Path, embeddedFileSystem: FileSystem ): ZiplineLoader = copy( embeddedDir = embeddedDir, embeddedFileSystem = embeddedFileSystem, ) fun withCache( cache: ZiplineCache, ): ZiplineLoader = copy( cache = cache ) private fun copy( embeddedDir: Path? = this.embeddedDir, embeddedFileSystem: FileSystem? = this.embeddedFileSystem, cache: ZiplineCache? = this.cache, ): ZiplineLoader { return ZiplineLoader( dispatcher = dispatcher, manifestVerifier = manifestVerifier, httpFetcher = httpFetcher, eventListener = eventListener, nowEpochMs = nowEpochMs, embeddedDir = embeddedDir, embeddedFileSystem = embeddedFileSystem, cache = cache, ) } private var concurrentDownloadsSemaphore = Semaphore(3) /** Callers can modify this as desired to change the default network download concurrency level. */ var concurrentDownloads = 3 set(value) { require(value > 0) field = value concurrentDownloadsSemaphore = Semaphore(value) } private val embeddedFetcher: FsEmbeddedFetcher? = run { FsEmbeddedFetcher( embeddedDir = embeddedDir ?: return@run null, embeddedFileSystem = embeddedFileSystem ?: return@run null, ) } private val cachingFetcher: FsCachingFetcher? = run { FsCachingFetcher( cache = cache ?: return@run null, delegate = httpFetcher, ) } /** Fetch modules local-first since we have a hash and all content is the same. */ private val moduleFetchers = listOfNotNull(embeddedFetcher, cachingFetcher ?: httpFetcher) /** * Loads code from [manifestUrlFlow] each time it emits, skipping loads if the code to load is * the same as what's already loaded. * * If the network is unreachable and there is local code newer, then this * will load local code, either from the embedded directory or the cache. * * @param manifestUrlFlow a flow that should emit each time a load should be attempted. This * may emit periodically to trigger polling. It should also emit for loading triggers like * app launch, app foregrounding, and network connectivity changed. */ fun load( applicationName: String, manifestUrlFlow: Flow<String>, serializersModule: SerializersModule = EmptySerializersModule(), initializer: (Zipline) -> Unit = {}, ): Flow<LoadResult> { return flow { var isFirstLoad = true var previousManifest: ZiplineManifest? = null manifestUrlFlow.collect { manifestUrl -> // Each time a manifest URL is emitted, download and initialize a Zipline for that URL. // - skip if the manifest hasn't changed from the previous load. // - pin the application if the load succeeded; unpin if it failed. val now = nowEpochMs() withLifecycleEvents(applicationName, manifestUrl) { val networkManifest = fetchManifestFromNetwork(applicationName, manifestUrl) if (networkManifest.manifest == previousManifest) { // Unchanged. Update freshness timestamp in cache DB. cachingFetcher?.updateFreshAt(applicationName, networkManifest, now) return@withLifecycleEvents } try { val networkZipline = loadFromManifest( applicationName, networkManifest, serializersModule, now, initializer, ) cachingFetcher?.pin(applicationName, networkManifest, now) // Pin after success. emit(LoadResult.Success(networkZipline, networkManifest.freshAtEpochMs)) previousManifest = networkManifest.manifest } catch (e: Exception) { cachingFetcher?.unpin(applicationName, networkManifest, now) // Unpin after failure. emit(LoadResult.Failure(e)) // This thrown exception is caught and not rethrown by withLifecycleEvents throw e } } // If network loading failed (due to network error, or bad code), attempt to load from the // cache or embedded file system. This doesn't update pins! if (previousManifest == null && isFirstLoad) { isFirstLoad = false val localManifest = loadCachedOrEmbeddedManifest(applicationName, now) ?: return@collect withLifecycleEvents(applicationName, manifestUrl = null) { val localZipline = loadFromManifest( applicationName, localManifest, serializersModule, now, initializer, ) emit(LoadResult.Success(localZipline, localManifest.freshAtEpochMs)) previousManifest = localManifest.manifest } } } } } suspend fun loadOnce( applicationName: String, manifestUrl: String, serializersModule: SerializersModule = EmptySerializersModule(), initializer: (Zipline) -> Unit = {}, ): LoadResult = load( applicationName, flowOf(manifestUrl), serializersModule, initializer ).firstOrNull() ?: throw IllegalStateException("loading failed; see EventListener for exceptions") /** * After identifying a manifest to load this fetches all the code, loads it into a JS runtime, * and runs both the user's initializer and the manifest's specified main function. */ internal suspend fun loadFromManifest( applicationName: String, loadedManifest: LoadedManifest, serializersModule: SerializersModule, nowEpochMs: Long, initializer: (Zipline) -> Unit, ): Zipline { val zipline = Zipline.create(dispatcher, serializersModule, eventListener) try { receive(ZiplineLoadReceiver(zipline), loadedManifest, applicationName, nowEpochMs) // Run caller lambda to validate and initialize the loaded code to confirm it works. initializer(zipline) // Run the application after initializer has been run on Zipline engine. loadedManifest.manifest.mainFunction?.let { mainFunction -> zipline.quickJs.evaluate( script = "require('${loadedManifest.manifest.mainModuleId}').$mainFunction()", fileName = "ZiplineLoader.kt", ) } return zipline } catch (e: Exception) { zipline.close() throw e } } suspend fun download( applicationName: String, downloadDir: Path, downloadFileSystem: FileSystem, manifestUrl: String, ) { val manifest = fetchManifestFromNetwork(applicationName, manifestUrl) val manifestWithFreshAt = manifest.encodeFreshAtMs() download( applicationName = applicationName, downloadDir = downloadDir, downloadFileSystem = downloadFileSystem, loadedManifest = manifestWithFreshAt, ) } internal suspend fun download( applicationName: String, downloadDir: Path, downloadFileSystem: FileSystem, loadedManifest: LoadedManifest, ) { val now = nowEpochMs() downloadFileSystem.createDirectories(downloadDir) downloadFileSystem.write(downloadDir / getApplicationManifestFileName(applicationName)) { write(loadedManifest.manifestBytes) } receive(FsSaveReceiver(downloadFileSystem, downloadDir), loadedManifest, applicationName, now) } private suspend fun receive( receiver: Receiver, loadedManifest: LoadedManifest, applicationName: String, nowEpochMs: Long, ) { coroutineScope { val loads = loadedManifest.manifest.modules.map { ModuleJob( applicationName = applicationName, id = it.key, baseUrl = loadedManifest.manifest.baseUrl, nowEpochMs = nowEpochMs, module = it.value, receiver = receiver ) } for (load in loads) { val loadJob = launch { load.run() } val downstreams = loads.filter { load.id in it.module.dependsOnIds } for (downstream in downstreams) { downstream.upstreams += loadJob } } } } private inner class ModuleJob( val applicationName: String, val id: String, val baseUrl: String?, val module: ZiplineManifest.Module, val receiver: Receiver, val nowEpochMs: Long, ) { val upstreams = mutableListOf<Job>() /** * Fetch and receive ZiplineFile module. */ suspend fun run() { val byteString = moduleFetchers.fetch( concurrentDownloadsSemaphore = concurrentDownloadsSemaphore, applicationName = applicationName, id = id, sha256 = module.sha256, nowEpochMs = nowEpochMs, baseUrl = baseUrl, url = module.url, )!! check(byteString.sha256() == module.sha256) { "checksum mismatch for $id" } upstreams.joinAll() withContext(dispatcher) { receiver.receive(byteString, id, module.sha256) } } } /** Wrap [block] in start/end/failed events, recovering gracefully if a flow is canceled. */ private suspend fun withLifecycleEvents( applicationName: String, manifestUrl: String?, block: suspend () -> Unit, ) { val startValue = eventListener.applicationLoadStart(applicationName, manifestUrl) try { block() eventListener.applicationLoadEnd(applicationName, manifestUrl, startValue) } catch (e: CancellationException) { // If emit() threw a CancellationException, consider that emit to be successful. // That's 'cause loadOnce() accepts an element and then immediately cancels the flow. eventListener.applicationLoadEnd(applicationName, manifestUrl, startValue) throw e } catch (e: Exception) { eventListener.applicationLoadFailed(applicationName, manifestUrl, e, startValue) } } private fun loadCachedOrEmbeddedManifest( applicationName: String, nowEpochMs: Long, ): LoadedManifest? { val result = cachingFetcher?.loadPinnedManifest(applicationName, nowEpochMs) ?: embeddedFetcher?.loadEmbeddedManifest(applicationName) ?: return null // Defend against changes to the locally-cached copy. manifestVerifier.verify(result.manifestBytes, result.manifest) return result } private suspend fun fetchManifestFromNetwork( applicationName: String, manifestUrl: String, ): LoadedManifest { val result = concurrentDownloadsSemaphore.withPermit { httpFetcher.fetchManifest( applicationName = applicationName, url = manifestUrl, freshAtEpochMs = nowEpochMs(), ) } // Defend against unauthorized changes in the supply chain. manifestVerifier.verify(result.manifestBytes, result.manifest) return result } }
apache-2.0
76754ad8031afe563d082e75f119d30d
33.841191
101
0.703084
4.831727
false
false
false
false
joan-domingo/Podcasts-RAC1-Android
app/src/main/java/cat/xojan/random1/feature/browser/SectionPodcastListFragment.kt
1
7991
package cat.xojan.random1.feature.browser import android.app.Activity import android.content.Context import android.os.Bundle import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaControllerCompat import android.support.v4.media.session.PlaybackStateCompat import android.util.Log import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import cat.xojan.random1.R import cat.xojan.random1.domain.model.CrashReporter import cat.xojan.random1.feature.BaseFragment import cat.xojan.random1.feature.IsMediaBrowserFragment import cat.xojan.random1.feature.MediaBrowserProvider import cat.xojan.random1.feature.MediaPlayerBaseActivity import cat.xojan.random1.injection.component.BrowseComponent import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.recycler_view_fragment.* import javax.inject.Inject class SectionPodcastListFragment : BaseFragment(), IsMediaBrowserFragment { @Inject internal lateinit var viewModel: BrowserViewModel @Inject internal lateinit var crashReporter: CrashReporter private lateinit var adapter: PodcastListAdapter private val compositeDisposable = CompositeDisposable() private var mediaBrowserProvider: MediaBrowserProvider? = null private var refresh = false companion object { val TAG = SectionPodcastListFragment::class.java.simpleName val ARG_MEDIA_ID = "media_id" fun newInstance(mediaId: String?): SectionPodcastListFragment { val args = Bundle() args.putString(ARG_MEDIA_ID, mediaId) val podcastListFragment = SectionPodcastListFragment() podcastListFragment.arguments = args return podcastListFragment } } override fun onAttach(context: Context) { super.onAttach(context) mediaBrowserProvider = context as MediaPlayerBaseActivity } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { getComponent(BrowseComponent::class.java).inject(this) val view = inflater.inflate(R.layout.recycler_view_fragment, container, false) setHasOptionsMenu(true) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) swipe_refresh.setColorSchemeResources(R.color.colorAccent) swipe_refresh.setProgressBackgroundColorSchemeResource(R.color.colorPrimaryDark) swipe_refresh.setOnRefreshListener { refresh = true onMediaControllerConnected() } recycler_view.layoutManager = LinearLayoutManager(activity) adapter = PodcastListAdapter(viewModel, activity as Activity) recycler_view.adapter = adapter } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { android.R.id.home -> { activity!!.onBackPressed() return true } } return super.onOptionsItemSelected(item) } override fun onStart() { super.onStart() // fetch browsing information to fill the recycler view val mediaBrowser = mediaBrowserProvider?.getMediaBrowser() mediaBrowser?.let { Log.d(TAG, "onStart, onConnected=" + mediaBrowser.isConnected) if (mediaBrowser.isConnected) { onMediaControllerConnected() } } } override fun onResume() { super.onResume() compositeDisposable.add(viewModel.getPodcastStateUpdates() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( {p -> adapter.updatePodcastsState(p)}, {e -> crashReporter.logException(e)} )) } override fun onDestroyView() { super.onDestroyView() compositeDisposable.clear() } override fun onStop() { super.onStop() val mediaBrowser = mediaBrowserProvider?.getMediaBrowser() mediaBrowser?.let { if (mediaBrowser.isConnected) { mediaBrowser.unsubscribe(mediaId()) } } val controller = MediaControllerCompat.getMediaController(activity as Activity) controller?.unregisterCallback(mediaControllerCallback) } override fun onDetach() { super.onDetach() mediaBrowserProvider = null } private fun mediaId(): String { val mediaId = arguments!!.getString(ARG_MEDIA_ID) + "/" + refresh refresh = false return mediaId } override fun onMediaControllerConnected() { if (isDetached) { return } swipe_refresh.isRefreshing = true val mediaBrowser = mediaBrowserProvider?.getMediaBrowser() // Unsubscribing before subscribing is required if this mediaId already has a subscriber // on this MediaBrowser instance. Subscribing to an already subscribed mediaId will replace // the callback, but won't trigger the initial callback.onChildrenLoaded. // // This is temporary: A bug is being fixed that will make subscribe // consistently call onChildrenLoaded initially, no matter if it is replacing an existing // subscriber or not. Currently this only happens if the mediaID has no previous // subscriber or if the media content changes on the service side, so we need to // unsubscribe first. mediaBrowser?.let { val mediaId = mediaId() mediaBrowser.unsubscribe(mediaId) mediaBrowser.subscribe(mediaId, mediaBrowserSubscriptionCallback) } val controller = MediaControllerCompat.getMediaController(activity as Activity) controller?.registerCallback(mediaControllerCallback) } private fun showPodcasts() { empty_list.visibility = View.GONE swipe_refresh.isRefreshing = false recycler_view.visibility = View.VISIBLE } private val mediaBrowserSubscriptionCallback = object : MediaBrowserCompat.SubscriptionCallback() { override fun onChildrenLoaded(parentId: String, children: List<MediaBrowserCompat.MediaItem>) { if (isChildrenError(children)) { handleError(children[0].description) } else { adapter.podcasts = viewModel.updatePodcastState(children) showPodcasts() } } override fun onError(id: String) { val msg = "sectionPodcast fragment subscription onError, id=" + id Log.e(HourByHourListFragment.TAG, msg) crashReporter.logException(msg) } } private val mediaControllerCallback = object : MediaControllerCompat.Callback() { override fun onMetadataChanged(metadata: MediaMetadataCompat?) { super.onMetadataChanged(metadata) if (metadata == null) { return } adapter.notifyDataSetChanged() } override fun onPlaybackStateChanged(state: PlaybackStateCompat?) { super.onPlaybackStateChanged(state) adapter.notifyDataSetChanged() } } private fun handleError(d: MediaDescriptionCompat) { crashReporter.logException(d.description.toString()) empty_list.visibility = View.VISIBLE swipe_refresh.isRefreshing = false recycler_view.visibility = View.GONE } }
mit
627c1139476aa11382c2f718913bc7b2
36.167442
103
0.674884
5.424983
false
false
false
false
rock3r/detekt
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/FinalNewline.kt
1
1063
package io.gitlab.arturbosch.detekt.formatting.wrappers import com.pinterest.ktlint.core.EditorConfig import com.pinterest.ktlint.ruleset.standard.FinalNewlineRule import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.formatting.FormattingRule import io.gitlab.arturbosch.detekt.formatting.merge /** * See <a href="https://ktlint.github.io">ktlint-website</a> for documentation. * * @configuration insertFinalNewLine - report absence or presence of a newline (default: `true`) * * @active since v1.0.0 * @autoCorrect since v1.0.0 * */ class FinalNewline(config: Config) : FormattingRule(config) { override val wrapping = FinalNewlineRule() override val issue = issueFor("Detects missing final newlines") private val insertFinalNewline = valueOrDefault(INSERT_FINAL_NEWLINE, true) override fun editorConfigUpdater(): ((oldEditorConfig: EditorConfig?) -> EditorConfig)? = { EditorConfig.merge(it, insertFinalNewline = insertFinalNewline) } } const val INSERT_FINAL_NEWLINE = "insertFinalNewline"
apache-2.0
551de73691cdc54211227c639309f348
34.433333
96
0.767639
4.072797
false
true
false
false
binaryfoo/emv-bertlv
src/main/java/io/github/binaryfoo/RootDecoder.kt
1
3917
package io.github.binaryfoo import io.github.binaryfoo.decoders.* import io.github.binaryfoo.decoders.apdu.* import io.github.binaryfoo.tlv.CommonVendorErrorMode import io.github.binaryfoo.tlv.Tag import io.github.binaryfoo.tlv.TagRecognitionMode /** * The main entry point. */ class RootDecoder { /** * f(hex string) -> somewhat english description * * @param value Hex string to decode. * @param meta One of the keys in io.github.binaryfoo.RootDecoder#TAG_META_SETS. * @param tagInfo One of the values returned by io.github.binaryfoo.RootDecoder#getTagInfo(java.lang.String). * * @return Somewhat english description. */ fun decode(value: String, meta: String, tagInfo: TagInfo, tagRecognitionMode: TagRecognitionMode = CommonVendorErrorMode): List<DecodedData> { val decodeSession = DecodeSession() decodeSession.tagMetaData = getTagMetaData(meta) decodeSession.tagRecognitionMode = tagRecognitionMode return tagInfo.decoder.decode(value, 0, decodeSession) } fun decode(value: String, meta: String, tag: String): List<DecodedData> { return decode(value, meta, getTagInfo(tag)!!) } fun getTagMetaData(meta: String): TagMetaData { return TAG_META_SETS[meta] ?: EmvTags.METADATA } companion object { private val TAG_META_SETS = linkedMapOf( "EMV" to EmvTags.METADATA, "qVSDC" to QVsdcTags.METADATA, "MSD" to MSDTags.METADATA, "Amex" to AmexTags.METADATA, "UPI" to UpiTags.METADATA ) private val ROOT_TAG_INFO = linkedMapOf( EmvTags.TERMINAL_VERIFICATION_RESULTS to EmvTags.METADATA, EmvTags.TSI to EmvTags.METADATA, EmvTags.APPLICATION_INTERCHANGE_PROFILE to EmvTags.METADATA, EmvTags.CVM_LIST to EmvTags.METADATA, EmvTags.CVM_RESULTS to EmvTags.METADATA, QVsdcTags.CARD_TX_QUALIFIERS to QVsdcTags.METADATA, QVsdcTags.TERMINAL_TX_QUALIFIERS to QVsdcTags.METADATA, "dol" to TagInfo.treeStructured("DOL", "Data Object List", DataObjectListDecoder(), shortBackground = "A list of (tag name, expected length) pairs"), "constructed" to TagInfo.treeStructured("TLV Data", "Constructed TLV data", TLVDecoder(), shortBackground = "A hex string encoding of a list of Tag, Length, Value objects"), "apdu-sequence" to TagInfo.treeStructured("APDUs", "Sequence of Command/Reply APDUs", APDUSequenceDecoder(ReplyAPDUDecoder(TLVDecoder()), SelectCommandAPDUDecoder(), GetProcessingOptionsCommandAPDUDecoder(), ReadRecordAPDUDecoder(), GenerateACAPDUDecoder(), GetDataAPDUDecoder(), ExternalAuthenticateAPDUDecoder(), ComputeCryptoChecksumDecoder(), InternalAuthenticateAPDUDecoder(), VerifyPinAPDUDecoder(), GetChallengeAPDUDecoder(), PutDataAPDUDecoder(), ReadBinaryAPDUDecoder()), shortBackground = "A hex string encoded trace.", longBackground = "Each line should be a hex string encoding of either a Command or Response APDU."), "bit-string" to TagInfo.treeStructured("Bits", "EMV Bit String", ByteLabeller(), shortBackground = "Uses the EMV convention: bytes left to right, bits right to left."), "filled-dol" to TagInfo.treeStructured("Filled DOL", "Data Object List", PopulatedDOLDecoder(), "Two lines: 1st is a DOL. 2nd the values to populate it with.") ) private infix fun Tag.to(that: TagMetaData): Pair<String, TagInfo> = Pair(this.hexString, that.get(this)) @JvmStatic fun getTagInfo(tag: String): TagInfo? { return ROOT_TAG_INFO[tag] } // array because List<TagInfo> and friends seem to show up in .java as List<Object> // at least when using emv-bertlv as a library @JvmStatic fun getSupportedTags(): Array<Map.Entry<String, TagInfo>> { return ROOT_TAG_INFO.entries.toTypedArray() } @JvmStatic fun getAllTagMeta(): Set<String> { return TAG_META_SETS.keys } } }
mit
58f01ae3600392e1f61a2af81b58da26
45.082353
186
0.713556
3.932731
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/BuddyPlaysActivity.kt
1
2497
package com.boardgamegeek.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.fragment.app.Fragment import com.boardgamegeek.R import com.boardgamegeek.extensions.setActionBarCount import com.boardgamegeek.extensions.startActivity import com.boardgamegeek.ui.viewmodel.PlaysViewModel import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent class BuddyPlaysActivity : SimpleSinglePaneActivity() { private val viewModel by viewModels<PlaysViewModel>() private var buddyName = "" private var numberOfPlays = -1 override val optionsMenuId: Int get() = R.menu.text_only override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (buddyName.isNotBlank()) { supportActionBar?.subtitle = buddyName } if (savedInstanceState == null) { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM_LIST) { param(FirebaseAnalytics.Param.CONTENT_TYPE, "BuddyPlays") param(FirebaseAnalytics.Param.ITEM_ID, buddyName) } } viewModel.setUsername(buddyName) viewModel.plays.observe(this) { numberOfPlays = it.data?.sumOf { play -> play.quantity } ?: 0 invalidateOptionsMenu() } } override fun readIntent(intent: Intent) { buddyName = intent.getStringExtra(KEY_BUDDY_NAME).orEmpty() } override fun onCreatePane(intent: Intent): Fragment { return PlaysFragment.newInstanceForBuddy() } override fun onPrepareOptionsMenu(menu: Menu): Boolean { super.onPrepareOptionsMenu(menu) menu.setActionBarCount(R.id.menu_text, numberOfPlays) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { BuddyActivity.startUp(this, buddyName) finish() return true } } return super.onOptionsItemSelected(item) } companion object { private const val KEY_BUDDY_NAME = "BUDDY_NAME" fun start(context: Context, buddyName: String?) { context.startActivity<BuddyPlaysActivity>( KEY_BUDDY_NAME to buddyName, ) } } }
gpl-3.0
9a6a13a42c154cb3a753a4b846989790
30.607595
80
0.667201
4.711321
false
false
false
false
debop/debop4k
debop4k-core/src/test/kotlin/debop4k/core/utils/CsvExKotlinTest.kt
1
1693
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.core.utils import debop4k.core.AbstractCoreKotlinTest import lombok.SneakyThrows import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.io.IOException /** * CsvExKotlinTest * @author debop [email protected] */ class CsvExKotlinTest : AbstractCoreKotlinTest() { @Test @SneakyThrows(IOException::class) fun readPM10() { val input = Resources.getClassPathResourceStream("csv/pm10_station_all.csv") assertThat(input).isNotNull() input!!.use { val records = input.toCSVRecordList() for (record in records) { val stationId = record.get(1).asInt() val endTime = record.get(2).asDateTime("yyyy.MM.dd.HH:mm") val startTime = record.get(3).asDateTime("yyyy.MM.dd.HH:mm") val stationName = record.get(4) log.debug("stationId={}, endTime={}, startTime={}, stationName={}", stationId, endTime, startTime, stationName) assertThat(stationId).isGreaterThan(0) assertThat(stationName).isNotNull() } } } }
apache-2.0
65519397e0df4a8df45c548f68e809a6
31.576923
80
0.700532
3.891954
false
true
false
false
KotlinKit/Reactant
Core/src/main/kotlin/org/brightify/reactant/controller/TabBarController.kt
1
6583
package org.brightify.reactant.controller import android.app.Activity import android.view.Menu import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import com.google.android.material.bottomnavigation.BottomNavigationView import io.reactivex.rxkotlin.addTo import org.brightify.reactant.autolayout.AutoLayout import org.brightify.reactant.autolayout.ConstraintPriority import org.brightify.reactant.autolayout.util.children import org.brightify.reactant.autolayout.util.snp import org.brightify.reactant.controller.util.TransactionManager import org.brightify.reactant.core.util.onChange /** * @author <a href="mailto:[email protected]">Filip Dolnik</a> */ open class TabBarController(private val viewControllers: List<ViewController>): ViewController() { val tabBar: BottomNavigationView get() = tabBar_ ?: viewNotLoadedError() var isTabBarHidden: Boolean by onChange(false) { _, _, _ -> if (!transactionManager.isInTransaction) { clearLayout(false) addViewToHierarchy() } } var selectedViewController: ViewController get() = displayedViewController set(value) { if (selectedViewController != value) { transactionManager.transaction { clearLayout(true) showViewController(value) displayedViewController.viewDidAppear() } } } var selectedViewControllerIndex: Int get() = viewControllers.indexOf(selectedViewController) set(value) { selectedViewController = viewControllers[value] } private var tabBar_: BottomNavigationView? = null private var layoutContent: FrameLayout? = null private var layout: AutoLayout? = null private var displayedViewController: ViewController = viewControllers[0] private val transactionManager = TransactionManager() init { viewControllers.forEach { it.tabBarController = this } } override fun activityDidChange(oldActivity: Activity?) { super.activityDidChange(oldActivity) viewControllers.forEach { it.activity_ = activity_ } } override fun loadView() { super.loadView() tabBar_ = BottomNavigationView(activity) layoutContent = FrameLayout(activity) layout = AutoLayout(activity) view = FrameLayout(activity).children(layout) layout?.children(layoutContent, tabBar) layoutContent?.snp?.makeConstraints { left.right.top.equalToSuperview() bottom.equalTo(tabBar.snp.top) } tabBar.snp.makeConstraints { left.right.bottom.equalToSuperview() } tabBar.snp.setVerticalIntrinsicSizePriority(ConstraintPriority.required) viewControllers.forEach { updateTabBarItem(it) } transactionManager.enabled = true } override fun viewWillAppear() { super.viewWillAppear() tabBar.snp.setVerticalIntrinsicSizePriority(ConstraintPriority.required) tabBar.visibility = View.VISIBLE activity.beforeKeyboardVisibilityChanged.subscribe { if (it) { tabBar.visibility = View.GONE tabBar.snp.setVerticalIntrinsicSizePriority(ConstraintPriority.low) } else { tabBar.snp.setVerticalIntrinsicSizePriority(ConstraintPriority.required) tabBar.visibility = View.VISIBLE } }.addTo(visibleDisposeBag) transactionManager.transaction { clearLayout(false) showViewController(selectedViewController) } } override fun viewDidAppear() { super.viewDidAppear() displayedViewController.viewDidAppear() } override fun viewWillDisappear() { super.viewWillDisappear() displayedViewController.viewWillDisappear() } override fun viewDidDisappear() { super.viewDidDisappear() displayedViewController.viewDidDisappear() } override fun viewDestroyed() { super.viewDestroyed() transactionManager.enabled = false tabBar_ = null layoutContent = null layout = null } override fun deactivated() { super.deactivated() viewControllers.forEach { it.activity_ = null } } override fun onBackPressed(): Boolean = displayedViewController.onBackPressed() override fun destroyViewHierarchy() { super.destroyViewHierarchy() viewControllers.forEach { it.destroyViewHierarchy() } } fun updateTabBarItem(viewController: ViewController) { if (tabBar_ == null) { return } val index = viewControllers.indexOf(viewController) tabBar.menu.removeItem(index) val text = viewController.tabBarItem?.titleRes?.let { activity.getString(it) } ?: "Undefined" val item = tabBar.menu.add(Menu.NONE, index, index, text) viewController.tabBarItem?.imageRes?.let { item.setIcon(it) } item.setOnMenuItemClickListener { selectedViewController = viewControllers[item.itemId] return@setOnMenuItemClickListener false } } fun setTabBarHidden(hidden: Boolean, animated: Boolean = true) { isTabBarHidden = hidden } fun invalidateChild() { if (!transactionManager.isInTransaction) { clearLayout(false) addViewToHierarchy() } } private fun clearLayout(callCallbacks: Boolean) { if (callCallbacks) { displayedViewController.viewWillDisappear() } layoutContent?.removeAllViews() (view as ViewGroup).removeAllViews() if (callCallbacks) { displayedViewController.viewDidDisappear() } } private fun showViewController(viewController: ViewController) { displayedViewController = viewController tabBar.selectedItemId = viewControllers.indexOf(viewController) displayedViewController.tabBarController = this displayedViewController.viewWillAppear() addViewToHierarchy() } private fun addViewToHierarchy() { if (isTabBarHidden) { (view as ViewGroup).addView(displayedViewController.view) } else { layoutContent?.addView(displayedViewController.view) (view as ViewGroup).addView(layout) } } }
mit
2ec325f7aa6c3111c141a7aba3ba045f
28.922727
101
0.65335
5.095201
false
false
false
false
qaware/kubepad
src/main/kotlin/de/qaware/cloud/nativ/kpad/leapmotion/LeapMotionController.kt
1
3033
/* * The MIT License (MIT) * * Copyright (c) 2016 QAware GmbH, Munich, Germany * * 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 de.qaware.cloud.nativ.kpad.leapmotion import com.leapmotion.leap.Controller import com.leapmotion.leap.Gesture import de.qaware.cloud.nativ.kpad.launchpad.LaunchpadController import org.slf4j.Logger import javax.annotation.PostConstruct import javax.annotation.PreDestroy import javax.enterprise.context.ApplicationScoped import javax.inject.Inject /** * The leap Motion controller instance. Creates the actual controller to interact * with the device, registers a listener and translates frames to Launchpad events. * The API controller and listener instances where for some reason not CDI compatible, * wiring resulted in strange NullPointerExceptions. */ @ApplicationScoped open class LeapMotionController @Inject constructor(launchpad: LaunchpadController, private val logger: Logger) { private lateinit var controller: Controller private val listener = LeapMotionListener(launchpad, logger) open var enabled: Boolean = false open var connected: Boolean by listener @PostConstruct open fun connect() { try { controller = Controller(listener) controller.setPolicy(Controller.PolicyFlag.POLICY_BACKGROUND_FRAMES) controller.enableGesture(Gesture.Type.TYPE_SWIPE) controller.enableGesture(Gesture.Type.TYPE_SCREEN_TAP) controller.enableGesture(Gesture.Type.TYPE_KEY_TAP) enabled = true } catch (e: Exception) { enabled = false } catch (e: UnsatisfiedLinkError) { logger.warn("You need to set -Djava.library.path to point to your Leap motion libs.") enabled = false } } @PreDestroy open fun disconnect() { if (enabled) { controller.removeListener(listener) connected = false } } }
mit
c89c0e1079d9214ca11825bddf004b40
38.921053
97
0.717112
4.673344
false
false
false
false
mgolokhov/dodroid
app/src/main/java/doit/study/droid/quiz/ui/QuizMainViewModel.kt
1
4893
package doit.study.droid.quiz.ui import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import doit.study.droid.R import doit.study.droid.quiz.QuizItem import doit.study.droid.quiz.domain.GetSelectedQuizItemsUseCase import doit.study.droid.quiz.domain.IsQuizAnsweredRightUseCase import doit.study.droid.quiz.domain.SaveQuizResultUseCase import doit.study.droid.quiz.domain.ShuffleQuizContentUseCase import doit.study.droid.quiz_summary.ui.ONE_TEST_SUMMARY_TYPE import doit.study.droid.utils.Event import javax.inject.Inject import kotlinx.coroutines.launch import timber.log.Timber class QuizMainViewModel @Inject constructor( private val appContext: Application, private val isQuizAnsweredRightUseCase: IsQuizAnsweredRightUseCase, private val getSelectedQuizItemsUseCase: GetSelectedQuizItemsUseCase, private val shuffleQuizContentUseCase: ShuffleQuizContentUseCase, private val saveQuizResultUseCase: SaveQuizResultUseCase ) : ViewModel() { private val _items = MutableLiveData<List<QuizItem>>() val items: LiveData<List<QuizItem>> = _items private val _actionBarTitle = MutableLiveData<String>() val actionBarTitle: LiveData<String> = _actionBarTitle private val _swipeToResultPageEvent = MutableLiveData<Event<Int>>() val swipeToResultPageEvent: LiveData<Event<Int>> = _swipeToResultPageEvent private val _addResultPageEvent = MutableLiveData<Event<Unit>>() val addResultPageEvent: LiveData<Event<Unit>> = _addResultPageEvent private val questionsLeft: Int? get() = _items.value?.filter { !it.answered }?.size init { Timber.d("init viewmodel $this") loadQuizItems() } private fun loadQuizItems() { viewModelScope.launch { _items.value = shuffleQuizContentUseCase( getSelectedQuizItemsUseCase() ) refreshUi() } } fun refreshUi() { updateQuizProgress() if (isQuizCompleted() && !isPageResultAdded()) { addResultPage() swipeToResultPage() saveResult() } } private fun isPageResultAdded(): Boolean { return _addResultPageEvent.value != null } private fun isQuizCompleted(): Boolean { return questionsLeft == 0 } private fun addResultPage() { _addResultPageEvent.value = Event(Unit) } private fun swipeToResultPage() { _swipeToResultPageEvent.value = Event(getCountForPager()) } private fun updateQuizProgress() { questionsLeft?.let { quantity -> _actionBarTitle.value = ( if (quantity == 0) appContext.getString(R.string.test_completed) else appContext.resources.getQuantityString( R.plurals.numberOfQuestionsInTest, quantity, quantity ) ) } } private fun saveResult() = viewModelScope.launch { saveQuizResultUseCase(_items.value) } fun getTabTitle(position: Int): String { return if (isPageResultAdded() && position == items.value?.size) appContext.resources.getString(R.string.test_result_title) else { items.value?.let { val template = appContext.resources.getString(R.string.test_progress_title) val title = it[position].title val currentPosition = position + 1 val total = it.size String.format( template, title, currentPosition, total ) } ?: "" } } fun getCountForPager(): Int { return items.value?.let { if (isPageResultAdded()) it.size + 1 else it.size } ?: 0 } fun getItemType(position: Int): String { val size = items.value?.size ?: 0 return when (position) { in 0 until size -> { QUIZ_QUESTION_ITEM_TYPE } size -> { ONE_TEST_SUMMARY_TYPE } else -> { "oh, shit" } } } fun getResultCounters(): Pair<Int, Int> { items.value!!.let { all -> val rightAnswers = all.filter { it.answered && isQuizAnsweredRightUseCase(it) }.size val wrongAnswers = all.size - rightAnswers return Pair(rightAnswers, wrongAnswers) } } companion object { private const val MAX_ITEMS_IN_ONE_QUIZ = 10 } }
mit
5881deeeeb7e8b0984b7f612e0ed143e
30.980392
96
0.599019
4.782991
false
false
false
false
valerio-bozzolan/bus-torino
src/it/reyboz/bustorino/backend/mato/MatoAPIFetcher.kt
1
17124
/* BusTO - Backend components Copyright (C) 2021 Fabio Mazza 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 it.reyboz.bustorino.backend.mato import android.content.Context import android.util.Log import com.android.volley.DefaultRetryPolicy import com.android.volley.toolbox.RequestFuture import it.reyboz.bustorino.BuildConfig import it.reyboz.bustorino.backend.* import it.reyboz.bustorino.data.gtfs.GtfsAgency import it.reyboz.bustorino.data.gtfs.GtfsFeed import it.reyboz.bustorino.data.gtfs.GtfsRoute import it.reyboz.bustorino.data.gtfs.MatoPattern import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference import kotlin.collections.ArrayList open class MatoAPIFetcher(val minNumPassaggi: Int) : ArrivalsFetcher { var appContext: Context? = null set(value) { field = value!!.applicationContext } constructor(): this(2) override fun ReadArrivalTimesAll(stopID: String?, res: AtomicReference<Fetcher.Result>?): Palina { stopID!! val now = Calendar.getInstance().time var numMinutes = 0 var palina = Palina(stopID) var numPassaggi = 0 var trials = 0 val numDepartures = 4 while (numPassaggi < minNumPassaggi && trials < 2) { //numDepartures+=2 numMinutes += 20 val future = RequestFuture.newFuture<Palina>() val request = MapiArrivalRequest(stopID, now, numMinutes * 60, numDepartures, res, future, future) if (appContext == null || res == null) { Log.e("BusTO:MatoAPIFetcher", "ERROR: Given null context or null result ref") return Palina(stopID) } val requestQueue = NetworkVolleyManager.getInstance(appContext).requestQueue request.setTag(getVolleyReqTag(MatoQueries.QueryType.ARRIVALS)) requestQueue.add(request) try { val palinaResult = future.get(5, TimeUnit.SECONDS) if (palinaResult!=null) { /*if (BuildConfig.DEBUG) for (r in palinaResult.queryAllRoutes()){ Log.d(DEBUG_TAG, "route " + r.gtfsId + " has " + r.passaggi.size + " passaggi: "+ r.passaggiToString) }*/ palina = palinaResult numPassaggi = palina.minNumberOfPassages } else{ Log.d(DEBUG_TAG, "Result palina is null") } } catch (e: InterruptedException) { e.printStackTrace() res.set(Fetcher.Result.PARSER_ERROR) } catch (e: ExecutionException) { e.printStackTrace() if (res.get() == Fetcher.Result.OK) res.set(Fetcher.Result.SERVER_ERROR) } catch (e: TimeoutException) { res.set(Fetcher.Result.CONNECTION_ERROR) e.printStackTrace() } trials++ } return palina } override fun getSourceForFetcher(): Passaggio.Source { return Passaggio.Source.MatoAPI } companion object{ const val VOLLEY_TAG = "MatoAPIFetcher" const val DEBUG_TAG = "BusTO:MatoAPIFetcher" val REQ_PARAMETERS = mapOf( "Content-Type" to "application/json; charset=utf-8", "DNT" to "1", "Host" to "mapi.5t.torino.it") private val longRetryPolicy = DefaultRetryPolicy(10000,5,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT) fun getVolleyReqTag(type: MatoQueries.QueryType): String{ return when (type){ MatoQueries.QueryType.ALL_STOPS -> VOLLEY_TAG +"_AllStops" MatoQueries.QueryType.ARRIVALS -> VOLLEY_TAG+"_Arrivals" MatoQueries.QueryType.FEEDS -> VOLLEY_TAG +"_Feeds" MatoQueries.QueryType.ROUTES -> VOLLEY_TAG +"_AllRoutes" MatoQueries.QueryType.PATTERNS_FOR_ROUTES -> VOLLEY_TAG + "_PatternsForRoute" } } /** * Get stops from the MatoAPI, set [res] accordingly */ fun getAllStopsGTT(context: Context, res: AtomicReference<Fetcher.Result>?): List<Palina>{ val requestQueue = NetworkVolleyManager.getInstance(context).requestQueue val future = RequestFuture.newFuture<List<Palina>>() val request = VolleyAllStopsRequest(future, future) request.tag = getVolleyReqTag(MatoQueries.QueryType.ALL_STOPS) request.retryPolicy = longRetryPolicy requestQueue.add(request) var palinaList:List<Palina> = mutableListOf() try { palinaList = future.get(120, TimeUnit.SECONDS) res?.set(Fetcher.Result.OK) }catch (e: InterruptedException) { e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) } catch (e: ExecutionException) { e.printStackTrace() res?.set(Fetcher.Result.SERVER_ERROR) } catch (e: TimeoutException) { res?.set(Fetcher.Result.CONNECTION_ERROR) e.printStackTrace() } return palinaList } /* fun makeRequest(type: QueryType?, variables: JSONObject) : String{ type.let { val requestData = JSONObject() when (it){ QueryType.ARRIVALS ->{ requestData.put("operationName","AllStopsDirect") requestData.put("variables", variables) requestData.put("query", MatoQueries.QUERY_ARRIVALS) } else -> { //TODO all other cases } } //todo make the request... //https://pablobaxter.github.io/volley-docs/com/android/volley/toolbox/RequestFuture.html //https://stackoverflow.com/questions/16904741/can-i-do-a-synchronous-request-with-volley } return "" } */ fun parseStopJSON(jsonStop: JSONObject): Palina{ val latitude = jsonStop.getDouble("lat") val longitude = jsonStop.getDouble("lon") val palina = Palina( jsonStop.getString("code"), jsonStop.getString("name"), null, null, latitude, longitude, jsonStop.getString("gtfsId") ) val routesStoppingJSON = jsonStop.getJSONArray("routes") val baseRoutes = mutableListOf<Route>() // get all the possible routes for (i in 0 until routesStoppingJSON.length()){ val routeBaseInfo = routesStoppingJSON.getJSONObject(i) val r = Route(routeBaseInfo.getString("shortName"), Route.Type.UNKNOWN,"") r.setGtfsId(routeBaseInfo.getString("gtfsId").trim()) baseRoutes.add(r) } if (jsonStop.has("desc")){ palina.location = jsonStop.getString("desc") } //there is also "zoneId" which is the zone of the stop (0-> city, etc) if(jsonStop.has("stoptimesForPatterns")) { val routesStopTimes = jsonStop.getJSONArray("stoptimesForPatterns") for (i in 0 until routesStopTimes.length()) { val patternJSON = routesStopTimes.getJSONObject(i) val mRoute = parseRouteStoptimesJSON(patternJSON) //Log.d("BusTO-MapiFetcher") //val directionId = patternJSON.getJSONObject("pattern").getInt("directionId") //TODO: use directionId palina.addRoute(mRoute) for (r in baseRoutes) { if (mRoute.gtfsId != null && r.gtfsId.equals(mRoute.gtfsId)) { baseRoutes.remove(r) break } } } } for (noArrivalRoute in baseRoutes){ palina.addRoute(noArrivalRoute) } //val gtfsRoutes = mutableListOf<>() return palina } fun parseRouteStoptimesJSON(jsonPatternWithStops: JSONObject): Route{ val patternJSON = jsonPatternWithStops.getJSONObject("pattern") val routeJSON = patternJSON.getJSONObject("route") val passaggiJSON = jsonPatternWithStops.getJSONArray("stoptimes") val gtfsId = routeJSON.getString("gtfsId").trim() val passages = mutableListOf<Passaggio>() for( i in 0 until passaggiJSON.length()){ val stoptime = passaggiJSON.getJSONObject(i) val scheduledTime = stoptime.getInt("scheduledArrival") val realtimeTime = stoptime.getInt("realtimeArrival") val realtime = stoptime.getBoolean("realtime") passages.add( Passaggio(realtimeTime,realtime, realtimeTime-scheduledTime, Passaggio.Source.MatoAPI) ) } var routeType = Route.Type.UNKNOWN if (gtfsId[gtfsId.length-1] == 'E') routeType = Route.Type.LONG_DISTANCE_BUS else when( routeJSON.getString("mode").trim()){ "BUS" -> routeType = Route.Type.BUS "TRAM" -> routeType = Route.Type.TRAM } val route = Route( routeJSON.getString("shortName"), patternJSON.getString("headsign"), routeType, passages, ) route.setGtfsId(gtfsId) return route } fun makeRequestParameters(requestName:String, variables: JSONObject, query: String): JSONObject{ val data = JSONObject() data.put("operationName", requestName) data.put("variables", variables) data.put("query", query) return data } fun getFeedsAndAgencies(context: Context, res: AtomicReference<Fetcher.Result>?): Pair<List<GtfsFeed>, ArrayList<GtfsAgency>> { val requestQueue = NetworkVolleyManager.getInstance(context).requestQueue val future = RequestFuture.newFuture<JSONObject>() val request = MatoVolleyJSONRequest(MatoQueries.QueryType.FEEDS, JSONObject(), future, future) request.setRetryPolicy(longRetryPolicy) request.tag = getVolleyReqTag(MatoQueries.QueryType.FEEDS) requestQueue.add(request) val feeds = ArrayList<GtfsFeed>() val agencies = ArrayList<GtfsAgency>() var outObj = "" try { val resObj = future.get(120,TimeUnit.SECONDS) outObj = resObj.toString(1) val feedsJSON = resObj.getJSONArray("feeds") for (i in 0 until feedsJSON.length()){ val resTup = ResponseParsing.parseFeedJSON(feedsJSON.getJSONObject(i)) feeds.add(resTup.first) agencies.addAll(resTup.second) } } catch (e: InterruptedException) { e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) } catch (e: ExecutionException) { e.printStackTrace() res?.set(Fetcher.Result.SERVER_ERROR) } catch (e: TimeoutException) { res?.set(Fetcher.Result.CONNECTION_ERROR) e.printStackTrace() } catch (e: JSONException){ e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) Log.e(DEBUG_TAG, "Downloading feeds: $outObj") } return Pair(feeds,agencies) } fun getRoutes(context: Context, res: AtomicReference<Fetcher.Result>?): ArrayList<GtfsRoute>{ val requestQueue = NetworkVolleyManager.getInstance(context).requestQueue val future = RequestFuture.newFuture<JSONObject>() val params = JSONObject() params.put("feeds","gtt") val request = MatoVolleyJSONRequest(MatoQueries.QueryType.ROUTES, params, future, future) request.tag = getVolleyReqTag(MatoQueries.QueryType.ROUTES) request.retryPolicy = longRetryPolicy requestQueue.add(request) val routes = ArrayList<GtfsRoute>() var outObj = "" try { val resObj = future.get(120,TimeUnit.SECONDS) outObj = resObj.toString(1) val routesJSON = resObj.getJSONArray("routes") for (i in 0 until routesJSON.length()){ val route = ResponseParsing.parseRouteJSON(routesJSON.getJSONObject(i)) routes.add(route) } } catch (e: InterruptedException) { e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) } catch (e: ExecutionException) { e.printStackTrace() res?.set(Fetcher.Result.SERVER_ERROR) } catch (e: TimeoutException) { res?.set(Fetcher.Result.CONNECTION_ERROR) e.printStackTrace() } catch (e: JSONException){ e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) Log.e(DEBUG_TAG, "Downloading feeds: $outObj") } return routes } fun getPatternsWithStops(context: Context, routesGTFSIds: ArrayList<String>, res: AtomicReference<Fetcher.Result>?): ArrayList<MatoPattern>{ val requestQueue = NetworkVolleyManager.getInstance(context).requestQueue val future = RequestFuture.newFuture<JSONObject>() val params = JSONObject() for (r in routesGTFSIds){ if(r.isEmpty()) routesGTFSIds.remove(r) } val routes = JSONArray(routesGTFSIds) params.put("routes",routes) val request = MatoVolleyJSONRequest(MatoQueries.QueryType.PATTERNS_FOR_ROUTES, params, future, future) request.retryPolicy = longRetryPolicy request.tag = getVolleyReqTag(MatoQueries.QueryType.PATTERNS_FOR_ROUTES) requestQueue.add(request) val patterns = ArrayList<MatoPattern>() //var outObj = "" try { val resObj = future.get(60,TimeUnit.SECONDS) //outObj = resObj.toString(1) val routesJSON = resObj.getJSONArray("routes") for (i in 0 until routesJSON.length()){ val patternList = ResponseParsing.parseRoutePatternsStopsJSON(routesJSON.getJSONObject(i)) patterns.addAll(patternList) } } catch (e: InterruptedException) { e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) } catch (e: ExecutionException) { e.printStackTrace() res?.set(Fetcher.Result.SERVER_ERROR) } catch (e: TimeoutException) { res?.set(Fetcher.Result.CONNECTION_ERROR) e.printStackTrace() } catch (e: JSONException){ e.printStackTrace() res?.set(Fetcher.Result.PARSER_ERROR) //Log.e(DEBUG_TAG, "Downloading feeds: $outObj") } /* var numRequests = 0 for(routeName in routesGTFSIds){ if (!routeName.isEmpty()) numRequests++ } val countDownForRequests = CountDownLatch(numRequests) val lockSave = ReentrantLock() //val countDownFor for (routeName in routesGTFSIds){ val pars = JSONObject() pars.put("") } val goodResponseListener = Response.Listener<JSONObject> { } val errorResponseListener = Response.ErrorListener { } */ return patterns } } }
gpl-3.0
2efb0931ec9ffe13a8a316921cc6575c
38.825581
148
0.569843
4.658324
false
false
false
false
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/model/topic/Replies.kt
1
421
package xyz.rankki.psnine.model.topic import me.ghui.fruit.annotations.Pick class Replies { @Pick(value = "body > div.min-inner.mt40 > div.box.mt20 > div.post:has(a.l)") var replies: ArrayList<Reply> = ArrayList() @Pick(value = "div.page:nth-child(1) > ul > li:not(.disabled) > a") private var maxPage: ArrayList<String> = ArrayList(1) fun getMaxPage(): Int = maxPage[maxPage.size - 1].toInt() }
apache-2.0
f13c43d7730698d07ff31009266dc013
27.133333
81
0.669834
3.007143
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/sync/microsoft/Tasks.kt
1
1660
package org.tasks.sync.microsoft import com.squareup.moshi.Json data class Tasks( val value: List<Task>, @field:Json(name = "@odata.nextLink") val nextPage: String?, @field:Json(name = "@odata.deltaLink") val nextDelta: String?, ) { data class Task( @field:Json(name = "@odata.etag") val etag: String? = null, val id: String? = null, val title: String? = null, val body: Body? = null, val importance: Importance = Importance.low, val status: Status = Status.notStarted, val categories: List<String>? = null, val isReminderOn: Boolean = false, val createdDateTime: String? = null, val lastModifiedDateTime: String? = null, val completedDateTime: CompletedDateTime? = null, val linkedResources: List<LinkedResource>? = null, @field:Json(name = "@removed") val removed: Removed? = null, ) { data class Body( val content: String, val contentType: String, ) data class LinkedResource( val applicationName: String, val displayName: String, val externalId: String, val id: String, ) data class Removed( val reason: String, ) data class CompletedDateTime( val dateTime: String, val timeZone: String, ) enum class Importance { low, normal, high, } enum class Status { notStarted, inProgress, completed, waitingOnOthers, deferred, } } }
gpl-3.0
7f6ad810a1c1f3f027799f552c909b78
27.152542
68
0.549398
4.51087
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/compose/edit/AlarmRow.kt
1
8462
package org.tasks.compose.edit import android.content.res.Configuration import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.PermissionStatus import com.google.android.material.composethemeadapter.MdcTheme import com.todoroo.astrid.ui.ReminderControlSetViewModel import org.tasks.R import org.tasks.compose.* import org.tasks.data.Alarm import org.tasks.reminders.AlarmToString import java.util.* @OptIn(ExperimentalPermissionsApi::class, ExperimentalComposeUiApi::class) @Composable fun AlarmRow( vm: ReminderControlSetViewModel = viewModel(), permissionStatus: PermissionStatus, launchPermissionRequest: () -> Unit, alarms: List<Alarm>, ringMode: Int, locale: Locale, addAlarm: (Alarm) -> Unit, deleteAlarm: (Alarm) -> Unit, openRingType: () -> Unit, pickDateAndTime: (replace: Alarm?) -> Unit, ) { TaskEditRow( iconRes = R.drawable.ic_outline_notifications_24px, content = { val viewState = vm.viewState.collectAsStateLifecycleAware().value when (permissionStatus) { PermissionStatus.Granted -> { Alarms( alarms = alarms, ringMode = ringMode, locale = locale, replaceAlarm = { vm.setReplace(it) vm.showAddAlarm(visible = true) }, addAlarm = { vm.showAddAlarm(visible = true) }, deleteAlarm = deleteAlarm, openRingType = openRingType, ) } is PermissionStatus.Denied -> { Column( modifier = Modifier .padding(end = 16.dp) .clickable { launchPermissionRequest() } ) { Spacer(modifier = Modifier.height(20.dp)) Text( text = stringResource(id = R.string.enable_reminders), color = colorResource(id = R.color.red_500), ) Text( text = stringResource(id = R.string.enable_reminders_description), style = MaterialTheme.typography.caption, color = colorResource(id = R.color.red_500), ) Spacer(modifier = Modifier.height(20.dp)) } } } AddAlarmDialog( viewState = viewState, existingAlarms = alarms, addAlarm = { viewState.replace?.let(deleteAlarm) addAlarm(it) }, addRandom = { vm.showRandomDialog(visible = true) }, addCustom = { vm.showCustomDialog(visible = true) }, pickDateAndTime = { pickDateAndTime(viewState.replace) }, dismiss = { vm.showAddAlarm(visible = false) }, ) AddReminderDialog.AddCustomReminderDialog( viewState = viewState, addAlarm = { viewState.replace?.let(deleteAlarm) addAlarm(it) }, closeDialog = { vm.showCustomDialog(visible = false) } ) AddReminderDialog.AddRandomReminderDialog( viewState = viewState, addAlarm = { viewState.replace?.let(deleteAlarm) addAlarm(it) }, closeDialog = { vm.showRandomDialog(visible = false) } ) }, ) } @Composable fun Alarms( alarms: List<Alarm>, ringMode: Int, locale: Locale, replaceAlarm: (Alarm) -> Unit, addAlarm: () -> Unit, deleteAlarm: (Alarm) -> Unit, openRingType: () -> Unit, ) { Column { Spacer(modifier = Modifier.height(8.dp)) alarms.forEach { alarm -> AlarmRow( text = AlarmToString(LocalContext.current, locale).toString(alarm), onClick = { replaceAlarm(alarm) }, remove = { deleteAlarm(alarm) } ) } Row(modifier = Modifier.fillMaxWidth()) { DisabledText( text = stringResource(id = R.string.add_reminder), modifier = Modifier .padding(vertical = 12.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onClick = addAlarm, ) ) Spacer(modifier = Modifier.weight(1f)) if (alarms.isNotEmpty()) { Text( text = stringResource( id = when (ringMode) { 2 -> R.string.ring_nonstop 1 -> R.string.ring_five_times else -> R.string.ring_once } ), style = MaterialTheme.typography.body1.copy( textDecoration = TextDecoration.Underline ), modifier = Modifier .padding(vertical = 12.dp, horizontal = 16.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onClick = openRingType ) ) } } Spacer(modifier = Modifier.height(8.dp)) } } @Composable private fun AlarmRow( text: String, onClick: () -> Unit, remove: () -> Unit, ) { Row( modifier = Modifier .fillMaxWidth() .clickable { onClick() } ) { Text( text = text, modifier = Modifier .padding(vertical = 12.dp) .weight(weight = 1f), ) ClearButton(onClick = remove) } } @OptIn(ExperimentalPermissionsApi::class) @Preview(showBackground = true, widthDp = 320) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, widthDp = 320) @Composable fun NoAlarms() { MdcTheme { AlarmRow( alarms = emptyList(), ringMode = 0, locale = Locale.getDefault(), addAlarm = {}, deleteAlarm = {}, openRingType = {}, permissionStatus = PermissionStatus.Granted, launchPermissionRequest = {}, pickDateAndTime = {}, ) } } @OptIn(ExperimentalPermissionsApi::class) @Preview(showBackground = true, widthDp = 320) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, widthDp = 320) @Composable fun PermissionDenied() { MdcTheme { AlarmRow( alarms = emptyList(), ringMode = 0, locale = Locale.getDefault(), addAlarm = {}, deleteAlarm = {}, openRingType = {}, permissionStatus = PermissionStatus.Denied(true), launchPermissionRequest = {}, pickDateAndTime = {}, ) } }
gpl-3.0
09f7694600d6e5d9c606ad5452fdfc32
34.410042
94
0.524344
5.200983
false
false
false
false
kotlin-everywhere/rpc-servlet
src/test/kotlin/com/github/kotlin_everywhere/rpc/test/nested.kt
1
1625
package com.github.kotlin_everywhere.rpc.test import com.github.kotlin_everywhere.rpc.Remote import org.junit.Assert.assertEquals import org.junit.Test class NestTest { @Test fun testNested() { class Admin : Remote() { val index = get<String>("/") } val remote = object : Remote() { val index = get<String>("/") val admin = Admin() } remote.apply { index { "index" } admin.apply { index { "admin.index" } } } assertEquals("index", remote.client.get("/").result<String>()) assertEquals("admin.index", remote.client.get("/admin/").result<String>()) remote.serverClient { assertEquals("index", it.get("/").result<String>()) assertEquals("admin.index", it.get("/admin/").result<String>()) } } @Test fun testPrefixSeparator() { class C(urlPrefix: String? = null) : Remote(urlPrefix) { val index = get<String>("/c") } class B : Remote() { val index = get<String>("/") } class A : Remote() { val index = get<String>("/") val b = B() val c = C("") } val a = A().apply { index { "a.index" } b.index { "b.index" } c.index { "c.index" } } assertEquals("a.index", a.client.get("/").result<String>()) assertEquals("b.index", a.client.get("/b/").result<String>()) assertEquals("c.index", a.client.get("/c").result<String>()) } }
mit
61159e3abed5e041e39ce89b0aa54fc5
26.083333
82
0.493538
4.13486
false
true
false
false
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/form/Form.kt
1
2592
package net.nemerosa.ontrack.model.form open class Form { private val internalFields: MutableMap<String, Field> = mutableMapOf() fun name(): Form = with( defaultNameField() ) fun password(): Form = with( Password.of("password") .label("Password") .length(40) .validation("Password is required.") ) fun description(): Form = with( Memo.of("description") .label("Description") .optional() .length(500) .rows(3) ) fun dateTime(): Form = with( DateTime.of("dateTime") .label("Date/time") ) fun url(): Form = with(Url.of()) fun with(field: Field): Form { internalFields[field.name] = field return this } fun with(fields: Iterable<Field>): Form { fields.forEach { field -> this.internalFields[field.name] = field } return this } fun getField(name: String): Field? { return internalFields[name] } val fields: Collection<Field> get() = internalFields.values fun name(value: String?): Form { return fill("name", value) } fun description(value: String?): Form { return fill("description", value) } fun fill(name: String, value: Any?): Form { var field: Field? = internalFields[name] if (field != null) { field = field.value(value) internalFields[name] = field } else { throw FormFieldNotFoundException(name) } return this } fun fill(data: Map<String, *>): Form { data.forEach { (name, value) -> if (internalFields.containsKey(name)) { fill(name, value) } } return this } fun append(form: Form): Form { this.internalFields.putAll(form.internalFields) return this } companion object { @JvmStatic fun nameAndDescription(): Form { return Form.create().name().description() } @JvmStatic fun create(): Form { return Form() } @JvmStatic fun defaultNameField(): Text { return Text.of("name") .label("Name") .length(40) .regex("[A-Za-z0-9_\\.\\-]+") .validation("Name is required and must contain only alpha-numeric characters, underscores, points or dashes.") } } }
mit
b17da03e8bfb76069e83e81e578e68f7
24.165049
130
0.509259
4.645161
false
false
false
false
neo4j-contrib/neo4j-apoc-procedures
extended/src/main/kotlin/apoc/nlp/aws/AWSVirtualSentimentVirtualGraph.kt
1
2083
package apoc.nlp.aws import apoc.nlp.NLPVirtualGraph import apoc.result.VirtualGraph import apoc.result.VirtualNode import com.amazonaws.services.comprehend.model.BatchDetectSentimentResult import org.apache.commons.text.WordUtils import org.neo4j.graphdb.Node import org.neo4j.graphdb.Relationship import org.neo4j.graphdb.Transaction data class AWSVirtualSentimentVirtualGraph(private val detectEntitiesResult: BatchDetectSentimentResult, private val sourceNodes: List<Node>): NLPVirtualGraph() { override fun extractDocument(index: Int, sourceNode: Node) : Any? = AWSProcedures.transformResults(index, sourceNode, detectEntitiesResult).value override fun createVirtualGraph(transaction: Transaction?): VirtualGraph { val storeGraph = transaction != null val allNodes: MutableSet<Node> = mutableSetOf() val allRelationships: MutableSet<Relationship> = mutableSetOf() sourceNodes.forEachIndexed { index, sourceNode -> val document = extractDocument(index, sourceNode) as Map<String, Any> val (sentiment, score ) = extractSentiment(document) val node = if (storeGraph) { sourceNode.setProperty("sentiment", sentiment) sourceNode.setProperty("sentimentScore", score) sourceNode } else { val virtualNode = VirtualNode(sourceNode, sourceNode.propertyKeys.toList()) virtualNode.setProperty("sentiment", sentiment) virtualNode.setProperty("sentimentScore", score) virtualNode } allNodes.add(node) } return VirtualGraph("Graph", allNodes, allRelationships, emptyMap()) } companion object { fun extractSentiment(value: Map<String, Any>) : Pair<String, Float> { val sentiment = WordUtils.capitalizeFully(value["sentiment"] as String) val sentimentScore = value["sentimentScore"] as Map<String, Any> return Pair(sentiment, sentimentScore[sentiment.toLowerCase()] as Float) } } }
apache-2.0
ef1608df432c358ffa1fc96fdd383c9a
40.68
162
0.691311
4.832947
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/files/downloader/Transfer.kt
1
1992
/** * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2021 Chris Narkiewicz <[email protected]> * * 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.nextcloud.client.files.downloader import com.owncloud.android.datamodel.OCFile import java.util.UUID /** * This class represents current transfer (download or upload) process state. * This object is immutable by design. * * NOTE: Although [OCFile] object is mutable, it is caused by shortcomings * of legacy design; please behave like an adult and treat it as immutable value. * * @property uuid Unique transfer id * @property state current transfer state * @property progress transfer progress, 0-100 percent * @property file transferred file * @property request initial transfer request * @property direction transfer direction, download or upload */ data class Transfer( val uuid: UUID, val state: TransferState, val progress: Int, val file: OCFile, val request: Request ) { /** * True if download is no longer running, false if it is still being processed. */ val isFinished: Boolean get() = state == TransferState.COMPLETED || state == TransferState.FAILED val direction: Direction get() = when (request) { is DownloadRequest -> Direction.DOWNLOAD is UploadRequest -> Direction.UPLOAD } }
gpl-2.0
9af744eebbf4ec60c4fd0ef4846d937f
35.218182
101
0.731426
4.426667
false
false
false
false
fabmax/binparse
src/main/kotlin/de/fabmax/binparse/FieldDef.kt
1
1134
package de.fabmax.binparse import java.util.* /** * Created by max on 17.11.2015. */ abstract class FieldDef<T : Field<*>>(fieldName: String) { var fieldName = fieldName val qualifiers = HashSet<String>() fun parseField(reader: BinReader, parent: ContainerField<*>): T { val offset = reader.pos val field = parse(reader, parent) field.offset = offset if (!qualifiers.isEmpty()) { field.qualifiers = HashSet<String>(qualifiers) } return field } fun hasQualifier(qualifier: String): Boolean { return qualifiers.contains(qualifier) } protected abstract fun parse(reader: BinReader, parent: ContainerField<*>): T abstract fun write(writer: BinWriter, parent: ContainerField<*>) protected open fun prepareWrite(parent: ContainerField<*>) { if (parent[fieldName].qualifiers != null) { parent[fieldName].qualifiers!!.addAll(qualifiers) } else { parent[fieldName].qualifiers = HashSet<String>(qualifiers) } } abstract fun matchesDef(parent: ContainerField<*>): Boolean }
apache-2.0
a4adbb52e0f3d9c17505f3b9f3081abd
26.682927
81
0.641093
4.609756
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityTCardGallery.kt
1
2627
package com.tamsiree.rxdemo.activity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import com.tamsiree.rxdemo.R import com.tamsiree.rxdemo.adapter.AdapterCardGallery import com.tamsiree.rxkit.interfaces.OnDoIntListener import com.tamsiree.rxkit.view.RxToast import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.view.tcardgralleryview.CardScaleHelper import kotlinx.android.synthetic.main.activity_tcard_grallery.* import java.util.* class ActivityTCardGallery : ActivityBase() { private val mList: MutableList<Int> = ArrayList() private var mCardScaleHelper: CardScaleHelper? = null private var mBlurRunnable: Runnable? = null private var mLastPos = -1 private var linearLayoutManager: LinearLayoutManager? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val decorView = window.decorView val option = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE) decorView.systemUiVisibility = option window.statusBarColor = Color.TRANSPARENT }*/ setContentView(R.layout.activity_tcard_grallery) } override fun initView() { rx_title.setLeftFinish(this) linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) recyclerView.layoutManager = linearLayoutManager recyclerView.adapter = AdapterCardGallery(mList) // val linearSnapHelper = LinearSnapHelper() //将SnapHelper attach 到RecyclrView // linearSnapHelper.attachToRecyclerView(recyclerView) tIndicator.attachToRecyclerView(recyclerView) // mRecyclerView绑定scale效果 // mRecyclerView绑定scale效果 mCardScaleHelper = CardScaleHelper() mCardScaleHelper!!.currentItemPos = 0 mCardScaleHelper!!.attachToRecyclerView(recyclerView, object : OnDoIntListener { override fun doSomething(intValue: Int) { RxToast.normal("选中$intValue") if (mLastPos == intValue) { return } mLastPos = intValue blurView.notifyChange(mList[mLastPos]) } }) } override fun initData() { mList.add(R.drawable.bg_friend) mList.add(R.drawable.ova) mList.add(R.drawable.bg_family) mList.add(R.drawable.bg_splash) recyclerView.adapter?.notifyDataSetChanged() } }
apache-2.0
b1048265d4840c15704b0d39417e9439
37.279412
94
0.688436
4.724138
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/sprite/SpriteContainer.kt
1
2465
package com.tamsiree.rxui.view.loadingview.sprite import android.animation.ValueAnimator import android.graphics.Canvas import android.graphics.Rect /** * @author tamsiree */ abstract class SpriteContainer : Sprite() { private val sprites: Array<Sprite?>? override var color = 0 set(color) { field = color for (i in 0 until childCount) { getChildAt(i)!!.color = color } } private fun initCallBack() { if (sprites != null) { for (sprite in sprites) { sprite?.callback = this } } } open fun onChildCreated(vararg sprites: Sprite?) {} val childCount: Int get() = sprites?.size ?: 0 fun getChildAt(index: Int): Sprite? { return sprites?.get(index) } override fun draw(canvas: Canvas) { super.draw(canvas) drawChild(canvas) } open fun drawChild(canvas: Canvas) { if (sprites != null) { for (sprite in sprites) { val count = canvas.save() sprite?.draw(canvas) canvas.restoreToCount(count) } } } override fun drawSelf(canvas: Canvas?) {} override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) for (sprite in sprites!!) { sprite?.bounds = bounds } } override fun start() { super.start() start(*sprites!!) } override fun stop() { super.stop() stop(*sprites!!) } override fun isRunning(): Boolean { return isRunning(*sprites!!) || super.isRunning() } abstract fun onCreateChild(): Array<Sprite?>? override fun onCreateAnimation(): ValueAnimator? { return null } companion object { fun start(vararg sprites: Sprite?) { for (sprite in sprites) { sprite?.start() } } fun stop(vararg sprites: Sprite?) { for (sprite in sprites) { sprite?.stop() } } fun isRunning(vararg sprites: Sprite?): Boolean { for (sprite in sprites) { if (sprite?.isRunning!!) { return true } } return false } } init { sprites = onCreateChild() initCallBack() onChildCreated(*sprites!!) } }
apache-2.0
6baefc24ce6a669af8534335c66d286f
22.264151
57
0.516836
4.833333
false
false
false
false
vlad1m1r990/KotlinSample
app/src/main/java/com/vlad1m1r/kotlintest/presentation/list/ListFragment.kt
1
4399
/* * Copyright 2017 Vladimir Jovanovic * * 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.vlad1m1r.kotlintest.presentation.list import android.os.Bundle import android.support.annotation.StringRes import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.vlad1m1r.kotlintest.R import com.vlad1m1r.kotlintest.domain.models.PhotoData import com.vlad1m1r.kotlintest.presentation.base.BaseFragment import com.vlad1m1r.kotlintest.presentation.utils.EndlessScrollListener import kotlinx.android.synthetic.main.fragment_list.* import kotlinx.android.synthetic.main.view_error.* import java.util.* class ListFragment : BaseFragment<ListContract.Presenter>(), ListContract.View, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener { lateinit var endlessScrollListener: EndlessScrollListener var listAdapter: ListAdapter? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) // creates adapter in case that fragment was not retained or it's first onViewCreated call so listAdapter == null this.listAdapter = listAdapter ?: ListAdapter() recyclerView.adapter = listAdapter this.endlessScrollListener = object : EndlessScrollListener(recyclerView.layoutManager!!) { override fun onLoadMore(currentPage: Int, totalItemCount: Int) { if (totalItemCount > 1) { presenter!!.loadData(totalItemCount) } } override fun onScroll(firstVisibleItem: Int, dy: Int, scrollPosition: Int) {} } recyclerView.addOnScrollListener(endlessScrollListener) swipeRefresh.setOnRefreshListener(this) // loads data in case that fragment was not retained or it's first onViewCreated call if (listAdapter!!.list.size == 0) presenter?.start() buttonTryAgain.setOnClickListener(this) } override fun loadData() { this.presenter?.loadData() } override fun setPresenter(presenter: ListContract.Presenter) { this.presenter = presenter } override fun showList(list: List<PhotoData>) { (recyclerView.adapter as ListAdapter).list = list } override fun addList(list: List<PhotoData>) { (recyclerView.adapter as ListAdapter).addList(list) } override fun showProgress(show: Boolean) { swipeRefresh.isRefreshing = show viewEmpty.visibility = View.GONE viewError.visibility = View.GONE swipeRefresh.visibility = View.VISIBLE } override fun showError(@StringRes error: Int) { viewEmpty.visibility = View.GONE viewError.visibility = View.VISIBLE textMessageError.setText(error) swipeRefresh.visibility = View.GONE swipeRefresh.isRefreshing = false } override fun showEmptyView() { viewEmpty.visibility = View.VISIBLE viewError.visibility = View.GONE swipeRefresh.visibility = View.GONE swipeRefresh.isRefreshing = false } override fun onRefresh() { this.endlessScrollListener.reset() loadData() } override fun onClick(v: View?) { when (v!!.id) { R.id.buttonTryAgain -> loadData() } } companion object { fun newInstance(): ListFragment = ListFragment() } }
apache-2.0
fbd1f2fffaccdd4dba350268acb6b023
34.475806
140
0.712435
4.860773
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/edit/EditHandler.kt
1
3851
package org.wikipedia.edit import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.PopupMenu import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonPrimitive import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.bridge.CommunicationBridge import org.wikipedia.bridge.CommunicationBridge.JSEventListener import org.wikipedia.descriptions.DescriptionEditUtil import org.wikipedia.page.Page import org.wikipedia.page.PageFragment import org.wikipedia.util.log.L class EditHandler(private val fragment: PageFragment, bridge: CommunicationBridge) : JSEventListener { private var currentPage: Page? = null init { bridge.addListener(TYPE_EDIT_SECTION, this) bridge.addListener(TYPE_ADD_TITLE_DESCRIPTION, this) } override fun onMessage(messageType: String, messagePayload: JsonObject?) { if (!fragment.isAdded) { return } currentPage?.let { if (messageType == TYPE_EDIT_SECTION) { val sectionId = messagePayload?.run { this[PAYLOAD_SECTION_ID]?.jsonPrimitive?.int } ?: 0 if (sectionId == 0 && DescriptionEditUtil.isEditAllowed(it) && it.isArticle) { val tempView = View(fragment.requireContext()) tempView.x = fragment.webView.touchStartX tempView.y = fragment.webView.touchStartY (fragment.view as ViewGroup).addView(tempView) val menu = PopupMenu(fragment.requireContext(), tempView, 0, 0, R.style.PagePopupMenu) menu.menuInflater.inflate(R.menu.menu_page_header_edit, menu.menu) menu.setOnMenuItemClickListener(EditMenuClickListener()) menu.setOnDismissListener { (fragment.view as ViewGroup).removeView(tempView) } menu.show() } else { startEditingSection(sectionId, null) } } else if (messageType == TYPE_ADD_TITLE_DESCRIPTION && DescriptionEditUtil.isEditAllowed(it)) { fragment.verifyBeforeEditingDescription(null, Constants.InvokeSource.PAGE_DESCRIPTION_CTA) } } } private inner class EditMenuClickListener : PopupMenu.OnMenuItemClickListener { override fun onMenuItemClick(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_page_header_edit_description -> { fragment.verifyBeforeEditingDescription(null, Constants.InvokeSource.PAGE_EDIT_PENCIL) true } R.id.menu_page_header_edit_lead_section -> { startEditingSection(0, null) true } else -> false } } } fun setPage(page: Page?) { page?.let { currentPage = it } } fun startEditingSection(sectionID: Int, highlightText: String?) { currentPage?.let { if (sectionID < 0 || sectionID >= it.sections.size) { L.w("Attempting to edit a mismatched section ID.") return } fragment.onRequestEditSection(it.sections[sectionID].id, it.sections[sectionID].anchor, it.title, highlightText) } } fun startEditingArticle() { currentPage?.let { fragment.onRequestEditSection(-1, null, it.title, null) } } companion object { private const val TYPE_EDIT_SECTION = "edit_section" private const val TYPE_ADD_TITLE_DESCRIPTION = "add_title_description" private const val PAYLOAD_SECTION_ID = "sectionId" const val RESULT_REFRESH_PAGE = 1 } }
apache-2.0
1c8a8f615ecb136e8641dc85871b156a
37.89899
124
0.62685
4.754321
false
false
false
false
chadrick-kwag/datalabeling_app
app/src/main/java/com/example/chadrick/datalabeling/Models/thumbnailcachedownload.kt
1
3005
package com.example.chadrick.datalabeling.Models import android.graphics.BitmapFactory import android.os.AsyncTask import android.util.Log import android.widget.ImageView import com.example.chadrick.datalabeling.Tasks.dszipDownloadTask import java.io.File import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL /** * Created by chadrick on 17. 12. 7. */ class thumbnailcachedownload(iv: ImageView?, dsid: Int, savefile: File) : AsyncTask<Void, Int, Int>() { private val serveraddr = ServerInfo.instance.serveraddress private val dsid = dsid private val savefile = savefile private val iv = iv companion object { val TAG = "thumbnailcachedownload" } override fun doInBackground(vararg p0: Void?): Int { val url: URL = URL(serveraddr + "/thumbnail" + "?id=" + dsid.toString()) if (!savefile.exists()) { savefile.parentFile.mkdirs() savefile.createNewFile() } else { // this download task is launched under the assumption that savefile doesn't exist. // but for safety, if it does exist, delete it. savefile.delete() savefile.createNewFile() } val output = FileOutputStream(savefile) val connection: HttpURLConnection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.connect() if (connection.responseCode != HttpURLConnection.HTTP_OK) { Log.d(dszipDownloadTask.TAG, "download attempt fail. " + connection.responseMessage) return 1 } val filelength = connection.contentLength val input = connection.inputStream var data = ByteArray(4096) var total: Long = 0 var count: Int = 0 while (true) { count = input.read(data) if (count == -1) { break } if (isCancelled) { input.close() return 1 } total += count // publishing the progress.... if (filelength > 0) // only if total length is known { // publishProgress((total * 100 / filelength).toInt() as Integer) } output.write(data, 0, count) } input?.close() output?.close() connection?.disconnect() Log.d(TAG, "download finished") return 0 } override fun onProgressUpdate(vararg values: Int?) { super.onProgressUpdate(*values) } override fun onPostExecute(result: Int?) { super.onPostExecute(result) when (result) { 0 -> { val savedbitmap = BitmapFactory.decodeFile(savefile.toString()) iv?.let { it.setImageBitmap(savedbitmap) } } else -> { Log.d(TAG, "error with cache thumbnail download") } } } }
mit
0e8b52c53e3f8278e1f77c13cf28556f
25.359649
103
0.58203
4.680685
false
false
false
false
AndroidX/androidx
privacysandbox/tools/tools-apigenerator/src/test/test-data/values/output/com/sdkwithvalues/PrivacySandboxThrowableParcelConverter.kt
3
1060
package com.sdkwithvalues import java.lang.StackTraceElement public object PrivacySandboxThrowableParcelConverter { public fun fromThrowableParcel(throwableParcel: PrivacySandboxThrowableParcel): Throwable { val exceptionClass = throwableParcel.exceptionClass val errorMessage = throwableParcel.errorMessage val stackTrace = throwableParcel.stackTrace val exception = PrivacySandboxException( "[$exceptionClass] $errorMessage", throwableParcel.cause?.firstOrNull()?.let { fromThrowableParcel(it) } ) for (suppressed in throwableParcel.suppressedExceptions) { exception.addSuppressed(fromThrowableParcel(suppressed)) } exception.stackTrace = stackTrace.map { StackTraceElement( it.declaringClass, it.methodName, it.fileName, it.lineNumber ) }.toTypedArray() return exception } }
apache-2.0
843eaf47069c588449b012b4b89dd2fe
34.333333
95
0.616981
6.347305
false
false
false
false
deva666/anko
anko/library/static/commons/src/dialogs/AndroidSelectors.kt
2
1499
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package org.jetbrains.anko import android.app.Fragment import android.content.Context import android.content.DialogInterface inline fun AnkoContext<*>.selector( title: CharSequence? = null, items: List<CharSequence>, noinline onClick: (DialogInterface, Int) -> Unit ): Unit = ctx.selector(title, items, onClick) inline fun Fragment.selector( title: CharSequence? = null, items: List<CharSequence>, noinline onClick: (DialogInterface, Int) -> Unit ): Unit = activity.selector(title, items, onClick) fun Context.selector( title: CharSequence? = null, items: List<CharSequence>, onClick: (DialogInterface, Int) -> Unit ) { with(AndroidAlertBuilder(this)) { if (title != null) { this.title = title } items(items, onClick) show() } }
apache-2.0
ad55397b406b551ee663babda2ee181a
30.25
75
0.683789
4.175487
false
false
false
false
androidx/androidx
navigation/navigation-fragment/src/androidTest/java/androidx/navigation/fragment/FragmentNavigatorDestinationBuilderTest.kt
3
4982
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.fragment import androidx.fragment.app.Fragment import androidx.navigation.contains import androidx.navigation.createGraph import androidx.navigation.get import androidx.test.annotation.UiThreadTest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertWithMessage import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class TestNavigatorDestinationBuilderTest { @Suppress("DEPRECATION") @get:Rule val activityRule = androidx.test.rule.ActivityTestRule<TestActivity>(TestActivity::class.java) private val fragmentManager get() = activityRule.activity.supportFragmentManager @Suppress("DEPRECATION") @UiThreadTest @Test fun fragment() { val navHostFragment = NavHostFragment() fragmentManager.beginTransaction() .add(android.R.id.content, navHostFragment) .commitNow() val graph = navHostFragment.createGraph(startDestination = DESTINATION_ID) { fragment<BuilderTestFragment>(DESTINATION_ID) } assertWithMessage("Destination should be added to the graph") .that(DESTINATION_ID in graph) .isTrue() assertWithMessage("Fragment class should be set to BuilderTestFragment") .that((graph[DESTINATION_ID] as FragmentNavigator.Destination).className) .isEqualTo(BuilderTestFragment::class.java.name) } @Suppress("DEPRECATION") @UiThreadTest @Test fun fragmentWithBody() { val navHostFragment = NavHostFragment() fragmentManager.beginTransaction() .add(android.R.id.content, navHostFragment) .commitNow() val graph = navHostFragment.createGraph(startDestination = DESTINATION_ID) { fragment<BuilderTestFragment>(DESTINATION_ID) { label = LABEL } } assertWithMessage("Destination should be added to the graph") .that(DESTINATION_ID in graph) .isTrue() assertWithMessage("Fragment class should be set to BuilderTestFragment") .that((graph[DESTINATION_ID] as FragmentNavigator.Destination).className) .isEqualTo(BuilderTestFragment::class.java.name) assertWithMessage("Fragment should have label set") .that(graph[DESTINATION_ID].label) .isEqualTo(LABEL) } @UiThreadTest @Test fun fragmentRoute() { val navHostFragment = NavHostFragment() fragmentManager.beginTransaction() .add(android.R.id.content, navHostFragment) .commitNow() val graph = navHostFragment.createGraph(startDestination = DESTINATION_ROUTE) { fragment<BuilderTestFragment>(DESTINATION_ROUTE) } assertWithMessage("Destination should be added to the graph") .that(DESTINATION_ROUTE in graph) .isTrue() assertWithMessage("Fragment class should be set to BuilderTestFragment") .that((graph[DESTINATION_ROUTE] as FragmentNavigator.Destination).className) .isEqualTo(BuilderTestFragment::class.java.name) } @UiThreadTest @Test fun fragmentWithBodyRoute() { val navHostFragment = NavHostFragment() fragmentManager.beginTransaction() .add(android.R.id.content, navHostFragment) .commitNow() val graph = navHostFragment.createGraph(startDestination = DESTINATION_ROUTE) { fragment<BuilderTestFragment>(DESTINATION_ROUTE) { label = LABEL } } assertWithMessage("Destination should be added to the graph") .that(DESTINATION_ROUTE in graph) .isTrue() assertWithMessage("Fragment class should be set to BuilderTestFragment") .that((graph[DESTINATION_ROUTE] as FragmentNavigator.Destination).className) .isEqualTo(BuilderTestFragment::class.java.name) assertWithMessage("Fragment should have label set") .that(graph[DESTINATION_ROUTE].label) .isEqualTo(LABEL) } } private const val DESTINATION_ID = 1 private const val DESTINATION_ROUTE = "destination" private const val LABEL = "Test" class BuilderTestFragment : Fragment()
apache-2.0
e0edd4d2b5af8e67d2da3f8fb69c9103
39.504065
98
0.689482
5.083673
false
true
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/presentation/PresentationUtils.kt
1
1212
package org.elm.ide.presentation import com.intellij.ide.projectView.PresentationData import com.intellij.navigation.ItemPresentation import com.intellij.psi.PsiElement import org.elm.lang.core.psi.ElmNamedElement import org.elm.lang.core.psi.ElmPsiElement import org.elm.lang.core.psi.elements.ElmValueDeclaration fun getPresentation(psi: ElmPsiElement): ItemPresentation { val name = presentableName(psi) val location = "(in ${psi.containingFile.name})" return PresentationData(name, location, psi.getIcon(0), null) } fun getPresentationForStructure(psi: ElmPsiElement): ItemPresentation { val text = presentableName(psi) // in the structure view, we might want to extend [text] to include // things like the full type annotation for a function declaration. return PresentationData(text, null, psi.getIcon(0), null) } private fun presentableName(element: PsiElement): String? = when (element) { is ElmNamedElement -> element.name is ElmValueDeclaration -> element.declaredNames(includeParameters = false).joinToString { it.name }.takeIf { it.isNotEmpty() } else -> null }
mit
2565e443379c54853f2fd975fad893b6
31.756757
116
0.709571
4.590909
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mcp/McpModuleType.kt
1
1171
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.mcp.util.McpConstants import com.demonwav.mcdev.util.CommonColors import com.demonwav.mcdev.util.SemanticVersion import javax.swing.Icon object McpModuleType : AbstractModuleType<McpModule>("", "") { private const val ID = "MCP_MODULE_TYPE" init { CommonColors.applyStandardColors(colorMap, McpConstants.TEXT_FORMATTING) CommonColors.applyStandardColors(colorMap, McpConstants.CHAT_FORMATTING) } override val platformType = PlatformType.MCP override val icon: Icon? = null override val id = ID override val ignoredAnnotations = emptyList<String>() override val listenerAnnotations = emptyList<String>() override val hasIcon = false override fun generateModule(facet: MinecraftFacet) = McpModule(facet) val MC_1_12_2 = SemanticVersion.release(1, 12, 2) }
mit
01e2a576afc4a9b35ae94ec844496065
28.275
80
0.754056
4.080139
false
false
false
false
pdvrieze/darwinlib
src/main/java/nl/adaptivity/android/darwin/AccountChangeReceiver.kt
1
1042
package nl.adaptivity.android.darwin import android.accounts.Account import android.accounts.AccountManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent class AccountChangeReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action==AccountManager.ACTION_ACCOUNT_REMOVED) { val storedAccount = AuthenticatedWebClientFactory.getStoredAccount(context) if (storedAccount?.name == intent.accountName && storedAccount?.type == intent.accountType) { AuthenticatedWebClientFactory.setStoredAccount(context, null) } } } } internal inline val Intent.accountName: String? get() = extras.getString(AccountManager.KEY_ACCOUNT_NAME) internal inline val Intent.accountType: String? get() = extras.getString(AccountManager.KEY_ACCOUNT_TYPE) internal inline val Intent.account: Account? get() { return Account(accountName ?: return null, accountType ?: return null) }
lgpl-2.1
4de8d1faa1cd18defeab6c5ef437a94c
40.72
105
0.75144
4.714932
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/translations/sorting/TranslationTemplateConfigurable.kt
1
3394
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.sorting import com.demonwav.mcdev.translations.lang.colors.LangSyntaxHighlighter import com.intellij.codeInsight.template.impl.TemplateEditorUtil import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project import com.intellij.util.ui.JBUI import java.awt.BorderLayout import javax.swing.DefaultComboBoxModel import javax.swing.JComboBox import javax.swing.JComponent import javax.swing.JPanel import org.jetbrains.annotations.Nls class TranslationTemplateConfigurable(private val project: Project) : Configurable { private lateinit var panel: JPanel private lateinit var cmbScheme: JComboBox<String> private lateinit var editorPanel: JPanel private lateinit var templateEditor: Editor @Nls override fun getDisplayName() = "Localization Template" override fun getHelpTopic(): String? = null override fun createComponent(): JComponent { return panel } private fun getActiveTemplateText() = when { cmbScheme.selectedIndex == 0 -> TemplateManager.getGlobalTemplateText() !project.isDefault -> TemplateManager.getProjectTemplateText(project) else -> "You must have selected a project for this!" } private fun init() { if (project.isDefault) { cmbScheme.selectedIndex = 0 cmbScheme.model = DefaultComboBoxModel(arrayOf("Global")) } else if (cmbScheme.selectedIndex == 0) { cmbScheme.model = DefaultComboBoxModel(arrayOf("Global", "Project")) } cmbScheme.addActionListener { setupEditor() } setupEditor() } private fun setupEditor() { templateEditor = TemplateEditorUtil.createEditor(false, getActiveTemplateText()) val editorColorsScheme = EditorColorsManager.getInstance().globalScheme val highlighter = LexerEditorHighlighter( LangSyntaxHighlighter(TranslationTemplateLexerAdapter()), editorColorsScheme ) (templateEditor as EditorEx).highlighter = highlighter templateEditor.settings.isLineNumbersShown = true editorPanel.preferredSize = JBUI.size(250, 100) editorPanel.minimumSize = editorPanel.preferredSize editorPanel.removeAll() editorPanel.add(templateEditor.component, BorderLayout.CENTER) } override fun isModified(): Boolean { return templateEditor.document.text != getActiveTemplateText() } override fun apply() { val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(panel)) if (cmbScheme.selectedIndex == 0) { TemplateManager.writeGlobalTemplate(templateEditor.document.text) } else if (project != null) { TemplateManager.writeProjectTemplate(project, templateEditor.document.text) } } override fun reset() { init() } }
mit
1db12e8ef6d321da6d71cbbffc8a2c31
33.282828
101
0.716559
4.961988
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/other/generic/activity/BaseActivity.kt
1
2654
package de.tum.`in`.tumcampusapp.component.other.generic.activity import android.content.Context import android.os.Bundle import android.preference.PreferenceManager import android.view.MenuItem import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import androidx.core.app.NavUtils import de.tum.`in`.tumcampusapp.di.AppComponent import de.tum.`in`.tumcampusapp.di.app import kotlinx.android.synthetic.main.toolbar.toolbar import java.util.Locale import android.content.pm.PackageManager import de.tum.`in`.tumcampusapp.R abstract class BaseActivity( @LayoutRes private val layoutId: Int ) : AppCompatActivity() { val injector: AppComponent by lazy { app.appComponent } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(layoutId) // TODO Refactor if (this !is BaseNavigationActivity) { setSupportActionBar(toolbar) supportActionBar?.let { val parent = NavUtils.getParentActivityName(this) if (parent != null) { it.setDisplayHomeAsUpEnabled(true) it.setHomeButtonEnabled(true) } } } initLanguage(this) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } // load language from user's preferences private fun initLanguage(context: Context) { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) var lang = sharedPreferences.getString("language_preference", null) if (lang == null) { lang = Locale.getDefault().language val availableLangs = resources.getStringArray(R.array.language_values) if (!availableLangs.contains(lang)) lang = "en" val editor = sharedPreferences.edit() editor.putString("language_preference", lang) editor.apply() } val locale = Locale(lang) Locale.setDefault(locale) val config = baseContext.resources.configuration config.setLocale(locale) baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics) val activityInfo = packageManager.getActivityInfo(this.componentName, PackageManager.GET_META_DATA) if (activityInfo.labelRes != 0 && supportActionBar != null) { supportActionBar!!.setTitle(activityInfo.labelRes) } } }
gpl-3.0
c891cba030d35f5e5db75b76f22c8396
33.467532
107
0.675584
5.07457
false
true
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/crdt/commutative/GCounter.kt
1
2785
package org.mitallast.queue.crdt.commutative import com.google.common.base.Preconditions import gnu.trove.impl.sync.TSynchronizedLongLongMap import gnu.trove.map.hash.TLongLongHashMap import gnu.trove.procedure.TLongProcedure import org.mitallast.queue.common.codec.Codec import org.mitallast.queue.common.codec.Message import org.mitallast.queue.crdt.replication.Replicator /** * Using counter vector allows to implement garbage collection */ class GCounter(private val id: Long, private val replica: Long, private val replicator: Replicator) : CmRDT { data class SourceAssign(val value: Long) : CmRDT.SourceUpdate { companion object { val codec = Codec.of( ::SourceAssign, SourceAssign::value, Codec.longCodec() ) } } data class DownstreamAssign(val replica: Long, val value: Long) : CmRDT.DownstreamUpdate { companion object { val codec = Codec.of( ::DownstreamAssign, DownstreamAssign::replica, DownstreamAssign::value, Codec.longCodec(), Codec.longCodec() ) } } private val counterMap = TSynchronizedLongLongMap(TLongLongHashMap()) override fun update(event: Message) { when (event) { is CmRDT.SourceUpdate -> sourceUpdate(event) is CmRDT.DownstreamUpdate -> downstreamUpdate(event) } } override fun shouldCompact(event: Message): Boolean { return event is DownstreamAssign && event.value < counterMap.get(replica) } override fun sourceUpdate(update: CmRDT.SourceUpdate) { when (update) { is SourceAssign -> add(update.value) } } @Synchronized override fun downstreamUpdate(update: CmRDT.DownstreamUpdate) { when (update) { is DownstreamAssign -> { val current = counterMap.get(update.replica) if (current < update.value) { counterMap.put(update.replica, update.value) } } } } fun increment(): Long = add(1) fun add(value: Long): Long { Preconditions.checkArgument(value >= 0, "must be positive") val updated = counterMap.adjustOrPutValue(replica, value, value) replicator.append(id, DownstreamAssign(replica, updated)) return updated } fun value(): Long { val sum = SumProcedure() counterMap.forEachValue(sum) return sum.value } private class SumProcedure : TLongProcedure { internal var value: Long = 0 override fun execute(value: Long): Boolean { this.value += value return true } } }
mit
6cf51f05908dd6c3bd9b3afc14a279d9
29.604396
109
0.614363
4.573071
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course/interactor/CourseIndexingInteractor.kt
2
1198
package org.stepik.android.domain.course.interactor import com.google.firebase.appindexing.Action import com.google.firebase.appindexing.FirebaseAppIndex import com.google.firebase.appindexing.FirebaseUserActions import com.google.firebase.appindexing.builders.Actions import com.google.firebase.appindexing.builders.Indexables import org.stepic.droid.configuration.EndpointResolver import org.stepic.droid.util.StringUtil import org.stepik.android.model.Course import javax.inject.Inject class CourseIndexingInteractor @Inject constructor( private val endpointResolver: EndpointResolver, private val firebaseAppIndex: FirebaseAppIndex, private val firebaseUserActions: FirebaseUserActions ) { private var action: Action? = null fun startIndexing(course: Course) { val title = course.title ?: return val uri = StringUtil.getUriForCourse(endpointResolver.getBaseUrl(), course.slug ?: return) firebaseAppIndex.update(Indexables.newSimple(title, uri)) action = Actions.newView(title, uri) action?.let(firebaseUserActions::start) } fun endIndexing() { action?.let(firebaseUserActions::end) action = null } }
apache-2.0
0d5ead3a149ba69bf41e7b14e85c1623
31.405405
98
0.770451
4.34058
false
false
false
false
y20k/trackbook
app/src/main/java/org/y20k/trackbook/helpers/NotificationHelper.kt
1
5552
/* * NotificationHelper.kt * Implements the NotificationHelper class * A NotificationHelper creates and configures a notification * * This file is part of * TRACKBOOK - Movement Recorder for Android * * Copyright (c) 2016-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT * * Trackbook uses osmdroid - OpenStreetMap-Tools for Android * https://github.com/osmdroid/osmdroid */ package org.y20k.trackbook.helpers import android.app.* import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.RequiresApi import androidx.appcompat.content.res.AppCompatResources import androidx.core.app.NotificationCompat import androidx.core.graphics.drawable.toBitmap import org.y20k.trackbook.Keys import org.y20k.trackbook.MainActivity import org.y20k.trackbook.R import org.y20k.trackbook.TrackerService /* * NotificationHelper class */ class NotificationHelper(private val trackerService: TrackerService) { /* Define log tag */ private val TAG: String = LogHelper.makeLogTag(NotificationHelper::class.java) /* Main class variables */ private val notificationManager: NotificationManager = trackerService.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager /* Creates notification */ fun createNotification(trackingState: Int, trackLength: Float, duration: Long, useImperial: Boolean): Notification { // create notification channel if necessary if (shouldCreateNotificationChannel()) { createNotificationChannel() } // Build notification val builder = NotificationCompat.Builder(trackerService, Keys.NOTIFICATION_CHANNEL_RECORDING) builder.setContentIntent(showActionPendingIntent) builder.setSmallIcon(R.drawable.ic_notification_icon_small_24dp) builder.setContentText(getContentString(trackerService, duration, trackLength, useImperial)) // add icon and actions for stop, resume and show when (trackingState) { Keys.STATE_TRACKING_ACTIVE -> { builder.setContentTitle(trackerService.getString(R.string.notification_title_trackbook_running)) builder.addAction(stopAction) builder.setLargeIcon(AppCompatResources.getDrawable(trackerService, R.drawable.ic_notification_icon_large_tracking_active_48dp)!!.toBitmap()) } else -> { builder.setContentTitle(trackerService.getString(R.string.notification_title_trackbook_not_running)) builder.addAction(resumeAction) builder.addAction(showAction) builder.setLargeIcon(AppCompatResources.getDrawable(trackerService, R.drawable.ic_notification_icon_large_tracking_stopped_48dp)!!.toBitmap()) } } return builder.build() } /* Build context text for notification builder */ private fun getContentString(context: Context, duration: Long, trackLength: Float, useImperial: Boolean): String { return "${LengthUnitHelper.convertDistanceToString(trackLength, useImperial)} • ${DateTimeHelper.convertToReadableTime(context, duration)}" } /* Checks if notification channel should be created */ private fun shouldCreateNotificationChannel() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !nowPlayingChannelExists() /* Checks if notification channel exists */ @RequiresApi(Build.VERSION_CODES.O) private fun nowPlayingChannelExists() = notificationManager.getNotificationChannel(Keys.NOTIFICATION_CHANNEL_RECORDING) != null /* Create a notification channel */ @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel() { val notificationChannel = NotificationChannel(Keys.NOTIFICATION_CHANNEL_RECORDING, trackerService.getString(R.string.notification_channel_recording_name), NotificationManager.IMPORTANCE_LOW) .apply { description = trackerService.getString(R.string.notification_channel_recording_description) } notificationManager.createNotificationChannel(notificationChannel) } /* Notification pending intents */ private val stopActionPendingIntent = PendingIntent.getService( trackerService,14, Intent(trackerService, TrackerService::class.java).setAction(Keys.ACTION_STOP),PendingIntent.FLAG_IMMUTABLE) private val resumeActionPendingIntent = PendingIntent.getService( trackerService, 16, Intent(trackerService, TrackerService::class.java).setAction(Keys.ACTION_RESUME),PendingIntent.FLAG_IMMUTABLE) private val showActionPendingIntent: PendingIntent? = TaskStackBuilder.create(trackerService).run { addNextIntentWithParentStack(Intent(trackerService, MainActivity::class.java)) getPendingIntent(10, PendingIntent.FLAG_IMMUTABLE) } /* Notification actions */ private val stopAction = NotificationCompat.Action( R.drawable.ic_notification_action_stop_24dp, trackerService.getString(R.string.notification_pause), stopActionPendingIntent) private val resumeAction = NotificationCompat.Action( R.drawable.ic_notification_action_resume_36dp, trackerService.getString(R.string.notification_resume), resumeActionPendingIntent) private val showAction = NotificationCompat.Action( R.drawable.ic_notification_action_show_36dp, trackerService.getString(R.string.notification_show), showActionPendingIntent) }
mit
9aebc7de96b99473b40f0fa699f75944
40.425373
158
0.73964
4.9955
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt
1
4225
package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTrigger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.DashHistory import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.InitialResult import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.ResolvedResult import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.I8n import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import javax.inject.Inject class DashInitializePodViewModel @Inject constructor( private val omnipodManager: OmnipodDashManager, injector: HasAndroidInjector, logger: AAPSLogger, private val sp: SP, private val podStateManager: OmnipodDashPodStateManager, private val rh: ResourceHelper, private val history: DashHistory, aapsSchedulers: AapsSchedulers ) : InitializePodViewModel(injector, logger, aapsSchedulers) { override fun isPodInAlarm(): Boolean = false // TODO override fun isPodActivationTimeExceeded(): Boolean = false // TODO override fun isPodDeactivatable(): Boolean = true // TODO override fun doExecuteAction(): Single<PumpEnactResult> = Single.create { source -> val lowReservoirAlertEnabled = sp.getBoolean(R.string.key_omnipod_common_low_reservoir_alert_enabled, true) val lowReservoirAlertUnits = sp.getInt(R.string.key_omnipod_common_low_reservoir_alert_units, 10) val lowReservoirAlertTrigger = if (lowReservoirAlertEnabled) { AlertTrigger.ReservoirVolumeTrigger((lowReservoirAlertUnits * 10).toShort()) } else null super.disposable += omnipodManager.activatePodPart1(lowReservoirAlertTrigger) .ignoreElements() .andThen(podStateManager.updateLowReservoirAlertSettings(lowReservoirAlertEnabled, lowReservoirAlertUnits)) .andThen( history.createRecord( OmnipodCommandType.INITIALIZE_POD, initialResult = InitialResult.SENT, resolveResult = ResolvedResult.SUCCESS, resolvedAt = System.currentTimeMillis(), ).ignoreElement() ) .subscribeBy( onError = { throwable -> logger.error(LTag.PUMP, "Error in Pod activation part 1", throwable) source.onSuccess( PumpEnactResult(injector) .success(false) .comment(I8n.textFromException(throwable, rh)) ) }, onComplete = { logger.debug("Pod activation part 1 completed") source.onSuccess(PumpEnactResult(injector).success(true)) } ) } @StringRes override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_initialize_pod_title @StringRes override fun getTextId() = R.string.omnipod_dash_pod_activation_wizard_initialize_pod_text }
agpl-3.0
40146813b5ec3e392d9407c251d7cc3b
48.705882
123
0.701538
4.907085
false
false
false
false
rinp/javaQuiz
src/main/kotlin/xxx/jq/scheduled/Scheduled.kt
1
3299
package xxx.jq.scheduled import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import org.springframework.util.StopWatch import xxx.jq.entity.Account import xxx.jq.entity.BaseEntity import xxx.jq.entity.Quiz import xxx.jq.entity.ResultHeader import xxx.jq.service.AccountService import xxx.jq.service.QuizService import xxx.jq.service.ResultHeaderService import java.time.Duration import javax.transaction.Transactional import org.springframework.transaction.annotation.Transactional as SpringTransactional /** * @author rinp * @since 2015/11/11 */ @Component open class Scheduled { @Autowired lateinit open var quizSer: QuizService @Autowired lateinit open var accountSer: AccountService @Autowired lateinit open var headerService: ResultHeaderService data class Count(val answer: Int, val correct: Int, val time: Duration) { operator fun plus(p: Count): Count { return this.copy(this.answer + p.answer, this.correct + p.correct, this.time + p.time) } } @Scheduled(initialDelay = 1000, fixedDelay = 10000) @Transactional fun backgroundUpdate() { val watch = StopWatch() watch.start() val aggregate = headerService.findByAggregate() if (aggregate.isEmpty()) { return } aggregate.groupBy { it.createdBy } .mapValues { it.value.map { Count(it.answerCount, it.correctCount, it.executeTime) }.reduce { p1, p2 -> p1 + p2 } } .map { it.key.addCount(it.value) } .updateAll() println("check point s"); val flatMap = aggregate.map { it.results } println("check point s1:,$flatMap"); aggregate.flatMap { it.results } .groupBy { it.quiz } .mapValues { val list = it.value Count(list.size, list.filter { it.correct }.size, list.map { it.executeTime }.reduce { d1, d2 -> d1 + d2 }) } .map { it.key.addCount(it.value) } .updateAll() println("check point e"); aggregate.map { it.copy(aggregate = true) } .updateAll() watch.stop() log.info("update time: ${watch.totalTimeMillis} ms") } companion object { val log = LoggerFactory.getLogger(Scheduled::class.java) } fun Account.addCount(value: Count): Account { return this.copy(answerCount = answerCount + value.answer, correctCount = correctCount + value.correct, executeTime = executeTime + value.time) } fun Quiz.addCount(value: Count): Quiz { return this.copy(answerCount = answerCount + value.answer, correctCount = correctCount + value.correct, executeTime = executeTime + value.time) } fun <E : BaseEntity> Iterable<E>.updateAll() { when (this.firstOrNull()) { is Account -> accountSer.updateAll(this.map { it as Account }) is Quiz -> quizSer.updateAll(this.map { it as Quiz }) is ResultHeader -> headerService.updateAll(this.map { it as ResultHeader }) else -> { } } } }
mit
13a2677a7ecc597b7c685bbaf960ce5d
30.721154
151
0.637769
4.202548
false
false
false
false
Maccimo/intellij-community
platform/service-container/src/com/intellij/serviceContainer/ConstructorParameterResolver.kt
4
4995
// 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.serviceContainer import com.intellij.diagnostic.PluginException import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.extensions.PluginId import org.picocontainer.ComponentAdapter import java.lang.reflect.Constructor @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val badAppLevelClasses = java.util.Set.of( "com.intellij.execution.executors.DefaultDebugExecutor", "org.apache.http.client.HttpClient", "org.apache.http.impl.client.CloseableHttpClient", "com.intellij.openapi.project.Project" ) internal class ConstructorParameterResolver { fun isResolvable(componentManager: ComponentManagerImpl, requestorKey: Any, requestorClass: Class<*>, requestorConstructor: Constructor<*>, expectedType: Class<*>, pluginId: PluginId, isExtensionSupported: Boolean): Boolean { if (expectedType === ComponentManager::class.java || findTargetAdapter(componentManager, expectedType, requestorKey, requestorClass, requestorConstructor, pluginId) != null) { return true } return isExtensionSupported && componentManager.extensionArea.findExtensionByClass(expectedType) != null } fun resolveInstance(componentManager: ComponentManagerImpl, requestorKey: Any, requestorClass: Class<*>, requestorConstructor: Constructor<*>, expectedType: Class<*>, pluginId: PluginId): Any? { if (expectedType === ComponentManager::class.java) { return componentManager } if (isLightService(expectedType)) { throw PluginException( "Do not use constructor injection for light services (requestorClass=$requestorClass, requestedService=$expectedType)", pluginId ) } val adapter = findTargetAdapter(componentManager, expectedType, requestorKey, requestorClass, requestorConstructor, pluginId) ?: return handleUnsatisfiedDependency(componentManager, requestorClass, expectedType, pluginId) return when { adapter is BaseComponentAdapter -> { // project level service Foo wants application level service Bar - adapter component manager should be used instead of current adapter.getInstance(adapter.componentManager, null) } componentManager.parent == null -> adapter.getComponentInstance(componentManager) else -> componentManager.getComponentInstance(adapter.componentKey) } } private fun handleUnsatisfiedDependency(componentManager: ComponentManagerImpl, requestorClass: Class<*>, expectedType: Class<*>, pluginId: PluginId): Any? { val extension = componentManager.extensionArea.findExtensionByClass(expectedType) ?: return null val message = "Do not use constructor injection to get extension instance (requestorClass=${requestorClass.name}, extensionClass=${expectedType.name})" val app = componentManager.getApplication() @Suppress("SpellCheckingInspection") if (app != null && app.isUnitTestMode && pluginId.idString != "org.jetbrains.kotlin" && pluginId.idString != "Lombook Plugin") { throw PluginException(message, pluginId) } else { LOG.warn(message) } return extension } } private fun findTargetAdapter(componentManager: ComponentManagerImpl, expectedType: Class<*>, requestorKey: Any, requestorClass: Class<*>, requestorConstructor: Constructor<*>, pluginId: PluginId): ComponentAdapter? { val byKey = componentManager.getComponentAdapter(expectedType) if (byKey != null && requestorKey != byKey.componentKey) { return byKey } val className = expectedType.name if (componentManager.parent == null) { if (badAppLevelClasses.contains(className)) { return null } } else if (className == "com.intellij.configurationStore.StreamProvider" || className == "com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl" || className == "com.intellij.openapi.roots.impl.CompilerModuleExtensionImpl" || className == "com.intellij.openapi.roots.impl.JavaModuleExternalPathsImpl") { return null } if (componentManager.isGetComponentAdapterOfTypeCheckEnabled) { LOG.error(PluginException("getComponentAdapterOfType is used to get ${expectedType.name} (requestorClass=${requestorClass.name}, requestorConstructor=${requestorConstructor})." + "\n\nProbably constructor should be marked as NonInjectable.", pluginId)) } return componentManager.getComponentAdapterOfType(expectedType) ?: componentManager.parent?.getComponentAdapterOfType(expectedType) }
apache-2.0
6ea9a4ef187516379311b3aa06c045e3
46.580952
182
0.700501
5.501101
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/message/html/EmailSectionExtractor.kt
2
3779
package com.fsck.k9.message.html /** * Extract sections from a plain text email. * * A section consists of all consecutive lines of the same quote depth. Quote characters and spaces at the beginning of * a line are stripped and not part of the section's content. * * ### Example: * * ``` * On 2018-01-25 Alice <[email protected]> wrote: * > Hi Bob * * Hi Alice * ``` * * This message consists of three sections with the following contents: * * `On 2018-01-25 Alice <[email protected]> wrote:` * * `Hi Bob` * * `Hi Alice` */ class EmailSectionExtractor private constructor(val text: String) { private val sections = mutableListOf<EmailSection>() private var sectionBuilder = EmailSection.Builder(text, 0) private var sectionStartIndex = 0 private var newlineIndex = -1 private var startOfContentIndex = 0 private var isStartOfLine = true private var spaces = 0 private var quoteDepth = 0 private var currentQuoteDepth = 0 fun extract(): List<EmailSection> { text.forEachIndexed { index, character -> if (isStartOfLine) { detectQuoteCharacters(index, character) } else if (character == '\n') { addQuotedLineToSection(endIndex = index + 1) } if (character == '\n') { newlineIndex = index resetForStartOfLine() } } completeLastSection() return sections } private fun detectQuoteCharacters(index: Int, character: Char) { when (character) { ' ' -> spaces++ '>' -> { if (quoteDepth == 0 && currentQuoteDepth == 0) { addUnquotedLineToSection(newlineIndex + 1) } currentQuoteDepth++ spaces = 0 } '\n' -> { if (quoteDepth != currentQuoteDepth) { finishSection() sectionStartIndex = index - spaces } if (currentQuoteDepth > 0) { sectionBuilder.addBlankSegment(startIndex = index - spaces, endIndex = index + 1) } } else -> { isStartOfLine = false startOfContentIndex = index - spaces if (quoteDepth != currentQuoteDepth) { finishSection() sectionStartIndex = startOfContentIndex } } } } private fun addUnquotedLineToSection(endIndex: Int) { if (sectionStartIndex != endIndex) { sectionBuilder.addSegment(0, sectionStartIndex, endIndex) } } private fun addQuotedLineToSection(startIndex: Int = startOfContentIndex, endIndex: Int) { if (currentQuoteDepth > 0) { sectionBuilder.addSegment(spaces, startIndex, endIndex) } } private fun finishSection() { appendSection() sectionBuilder = EmailSection.Builder(text, currentQuoteDepth) quoteDepth = currentQuoteDepth } private fun completeLastSection() { if (quoteDepth == 0) { sectionBuilder.addSegment(0, sectionStartIndex, text.length) } else if (!isStartOfLine) { sectionBuilder.addSegment(spaces, startOfContentIndex, text.length) } appendSection() } private fun appendSection() { if (sectionBuilder.hasSegments) { sections.add(sectionBuilder.build()) } } private fun resetForStartOfLine() { isStartOfLine = true currentQuoteDepth = 0 spaces = 0 } companion object { fun extract(text: String) = EmailSectionExtractor(text).extract() } }
apache-2.0
dcf693cc3f39d7b9e34e45d7921495f5
28.992063
119
0.571051
4.741531
false
false
false
false
fcostaa/kotlin-rxjava-android
library/cache/src/androidTest/kotlin/com/github/felipehjcosta/marvelapp/cache/CacheDatabaseTest.kt
1
6490
package com.github.felipehjcosta.marvelapp.cache import androidx.room.Room import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.felipehjcosta.marvelapp.cache.data.CharacterRelations import com.github.felipehjcosta.marvelapp.cache.data.CharactersDao import com.github.felipehjcosta.marvelapp.cache.data.SummaryEntity import com.github.felipehjcosta.marvelapp.cache.data.UrlEntity import io.reactivex.observers.TestObserver import org.junit.After import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.TimeUnit @RunWith(AndroidJUnit4::class) class CacheDatabaseTest { private val cacheDatabase: CacheDatabase = Room.inMemoryDatabaseBuilder( getApplicationContext(), CacheDatabase::class.java ).build() private val charactersDao: CharactersDao = cacheDatabase.charactersDao() @After fun tearDown() { cacheDatabase.close() } @Test fun ensureEmptyCharacterEntityByIdWhenDataDoesNotExist() { val itemsObserver = TestObserver.create<CharacterRelations>() charactersDao.findById(42L).subscribe(itemsObserver) itemsObserver.await(500L, TimeUnit.MILLISECONDS) itemsObserver.assertNoValues() } @Test fun ensureFindCharacterEntityByIdWhenDataExists() { val characterRelations = createFixture() charactersDao.insert(characterRelations) val itemsObserver = TestObserver.create<CharacterRelations>() charactersDao.findById(42L).subscribe(itemsObserver) itemsObserver.await(500L, TimeUnit.MILLISECONDS) itemsObserver.assertValue { it == characterRelations } } @Test fun ensureEmptyCharacterEntitiesWhenDataDoesNotExist() { val itemsObserver = TestObserver.create<List<CharacterRelations>>() charactersDao.all().subscribe(itemsObserver) itemsObserver.await(500L, TimeUnit.MILLISECONDS) itemsObserver.assertValue { it == emptyList<List<CharacterRelations>>() } } @Test fun ensureFindAllCharacterEntitiesWhenDataExists() { val characterRelations = createFixture() charactersDao.insert(characterRelations) val itemsObserver = TestObserver.create<List<CharacterRelations>>() charactersDao.all().subscribe(itemsObserver) itemsObserver.await(500L, TimeUnit.MILLISECONDS) itemsObserver.assertValue { it[0] == characterRelations } } private fun createFixture(): CharacterRelations { return CharacterRelations().apply { character.apply { id = 42L name = "Iron Man" description = "Wounded, captured and forced to build a weapon by his enemies, billionaire industrialist Tony Stark instead created an advanced suit of armor to save his life and escape captivity. Now with a new outlook on life, Tony uses his money and intelligence to make the world a safer, better place as Iron Man." resourceURI = "http://gateway.marvel.com/v1/public/characters/1009368" } urls = listOf( UrlEntity( type = "detail", url = "http://marvel.com/characters/29/iron_man?utm_campaign=apiRef&utm_source=9549585bdad28d04622dcd45ed0238aa" ) ) thumbnail.apply { path = "http://i.annihil.us/u/prod/marvel/i/mg/9/c0/527bb7b37ff55" extension = "jpg" } comicListRelations.apply { comicList.apply { available = 2287 collectionURI = "http://gateway.marvel.com/v1/public/characters/1009368/comics" } comicListSummary = listOf( SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/comics/43495", name = "A+X (2012) #2" ), SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/comics/43506", name = "A+X (2012) #7" ) ) } storyListRelations.apply { storyListEntity.apply { available = 3256 collectionURI = "http://gateway.marvel.com/v1/public/characters/1009368/stories" } storyListSummary = listOf( SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/stories/670", name = "X-MEN (2004) #186", type = "cover" ), SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/stories/892", name = "Cover #892", type = "cover" ) ) } eventListRelations.apply { eventListEntity.apply { available = 29 collectionURI = "http://gateway.marvel.com/v1/public/characters/1009368/events" } eventListSummary = listOf( SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/events/116", name = "Acts of Vengeance!" ), SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/events/303", name = "Age of X" ) ) } seriesListRelations.apply { seriesListEntity.apply { available = 543 collectionURI = "http://gateway.marvel.com/v1/public/characters/1009368/series" } seriesListSummary = listOf( SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/series/16450", name = "A+X (2012 - Present)" ), SummaryEntity( resourceURI = "http://gateway.marvel.com/v1/public/series/7524", name = "Adam: Legend of the Blue Marvel (2008)" ) ) } } } }
mit
9b0cdbc92e3672f10877321b150264d4
34.469945
324
0.569183
4.905518
false
true
false
false
pyamsoft/pydroid
autopsy/src/main/java/com/pyamsoft/pydroid/autopsy/SystemBars.kt
1
1275
/* * Copyright 2022 Peter Kenji Yamanaka * * 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.pyamsoft.pydroid.autopsy import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.res.colorResource import com.google.accompanist.systemuicontroller.rememberSystemUiController @Composable internal fun SystemBars() { val isLightStatusBar = !isSystemInDarkTheme() val controller = rememberSystemUiController() val color = colorResource(R.color.crash_background_color) SideEffect { controller.setSystemBarsColor( color = color, darkIcons = isLightStatusBar, isNavigationBarContrastEnforced = false, ) } }
apache-2.0
9a6b954db2d44042953372e73444e6ca
32.552632
75
0.767059
4.473684
false
false
false
false
omaraa/ImageSURF
src/main/kotlin/imagesurf/reader/ShortReader.kt
1
2094
package imagesurf.reader import imagesurf.feature.FeatureReader import net.mintern.primitive.Primitive class ShortReader(private val values: Array<ShortArray>, private val classIndex: Int) : FeatureReader { constructor(values: List<Any?>, classIndex: Int) : this(toShorts(values), classIndex) private val numClasses = values[classIndex].toSet().size override fun getNumClasses(): Int { return numClasses } override fun getClassValue(instanceIndex: Int): Int { return values[classIndex][instanceIndex].toInt() and BIT_MASK } override fun getValue(instanceIndex: Int, attributeIndex: Int): Double { return (values[attributeIndex][instanceIndex].toInt() and BIT_MASK).toDouble() } override fun getSortedIndices(attributeIndex: Int, instanceIndices: IntArray): IntArray { val attributeArray = values[attributeIndex] return instanceIndices.copyOf(instanceIndices.size) .also { Primitive.sort(it) { i1, i2 -> (attributeArray[i1].toInt() and BIT_MASK).compareTo((attributeArray[i2].toInt() and BIT_MASK)) } } } override fun getNumInstances(): Int = values[classIndex].size override fun getNumFeatures(): Int = values.size override fun getClassIndex(): Int = classIndex companion object { private const val BIT_MASK: Int = 0xff private fun toShorts(shortArrays: Any): Array<ShortArray> = when (shortArrays) { is List<*> -> shortArrays.map { it as ShortArray }.toTypedArray() is Array<*> -> shortArrays.map { it as ShortArray }.toTypedArray() else -> throw RuntimeException("Failed to read $shortArrays using ShortReader") } } override fun withFeatures(indices: List<Int>): FeatureReader = indices.filter { index: Int -> index != getClassIndex() && index >= 0 } .map { values[it] } .plusElement( values[classIndex] ) .let { ShortReader(it, it.lastIndex) } }
gpl-3.0
058daeb02bb581033bb177eec0f25117
37.090909
128
0.639446
4.592105
false
false
false
false
EmmanuelMess/AmazeFileManager
app/src/main/java/com/amaze/filemanager/utils/GenericExt.kt
2
2103
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.utils /** * Allow null checks on more than one parameters at the same time. * Alternative of doing nested p1?.let p2?.let */ inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, R : Any> safeLet( p1: T1?, p2: T2?, p3: T3?, p4: T4?, p5: T5?, block: (T1, T2, T3, T4, T5) -> R? ): R? { return if (p1 != null && p2 != null && p3 != null && p4 != null && p5 != null) block( p1, p2, p3, p4, p5 ) else null } /** * Allow null checks on more than one parameters at the same time. * Alternative of doing nested p1?.let p2?.let */ inline fun <T1 : Any, T2 : Any, T3 : Any, R : Any> safeLet( p1: T1?, p2: T2?, p3: T3?, block: (T1, T2, T3) -> R? ): R? { return if (p1 != null && p2 != null && p3 != null) block( p1, p2, p3 ) else null } /** * Allow null checks on more than one parameters at the same time. * Alternative of doing nested p1?.let p2?.let */ inline fun <T1 : Any, T2 : Any, R : Any> safeLet( p1: T1?, p2: T2?, block: (T1, T2) -> R? ): R? { return if (p1 != null && p2 != null) block( p1, p2 ) else null }
gpl-3.0
ef36ddb4e75ea2eb99ee51c5564bd8cd
29.042857
107
0.621969
3.124814
false
false
false
false
jmsloat/dailyprogrammer
208_ascii_grid/src/ascii_gradient.kt
1
1068
package com.sloat.dailyprogrammer import java.io.File import java.util import java.util.ArrayList import kotlin.* fun main(args: Array<String>) { AsciiGrid() } class AsciiGrid { val inputLines = File("infile.txt").readLines() var grid: Grid = readGrid(inputLines.get(0)) val gradiekkntCharacters = inputLines.get(1).toCharList() init { printGrid(grid) calculateGradient(grid) } data class Grid(val width: Int = -1, val height: Int = -1, var contents: Array<Array<Char>>) fun readGrid(line: String) : Grid { val (w, h) = line.split(' ') val cols = Array(w.toInt(), {it -> '.'}) val chars = Array(h.toInt(), {it -> cols.copyOf()}) return Grid(w.toInt(), h.toInt(), chars) } fun printGrid(g: Grid): Unit { g.contents[2].set(3, 'H') for(row in g.contents) { for(col in row) { print(col.toString()) } println("") } } fun calculateGradient(g: Grid) { print("Going...") } }
mit
fc578e2899789aaae04ef9e685bf036c
19.169811
96
0.557116
3.501639
false
false
false
false
blindpirate/gradle
build-logic/basics/src/main/kotlin/gradlebuild/basics/BuildEnvironment.kt
1
4844
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.basics import gradlebuild.basics.BuildParams.CI_ENVIRONMENT_VARIABLE import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.file.Directory import org.gradle.api.provider.Provider import org.gradle.internal.os.OperatingSystem fun Project.repoRoot() = layout.projectDirectory.parentOrRoot() private fun Directory.parentOrRoot(): Directory = if (this.file("version.txt").asFile.exists()) { this } else { val parent = dir("..") when { parent.file("version.txt").asFile.exists() -> parent this == parent -> throw IllegalStateException("Cannot find 'version.txt' file in root of repository") else -> parent.parentOrRoot() } } /** * We use command line Git instead of JGit, because JGit's [Repository.resolve] does not work with worktrees. */ fun Project.currentGitBranch() = git(layout.projectDirectory, "rev-parse", "--abbrev-ref", "HEAD") fun Project.currentGitCommit() = git(layout.projectDirectory, "rev-parse", "HEAD") @Suppress("UnstableApiUsage") private fun Project.git(checkoutDir: Directory, vararg args: String): Provider<String> { val execOutput = providers.exec { workingDir = checkoutDir.asFile isIgnoreExitValue = true commandLine = listOf("git", *args) if (OperatingSystem.current().isWindows) { commandLine = listOf("cmd", "/c") + commandLine } } return execOutput.result.zip(execOutput.standardOutput.asBytes) { execResult, output -> when { execResult.exitValue == 0 -> String(output).trim() checkoutDir.asFile.resolve(".git/HEAD").exists() -> { // Read commit id directly from filesystem val headRef = checkoutDir.asFile.resolve(".git/HEAD").readText() .replace("ref: ", "").trim() checkoutDir.asFile.resolve(".git/$headRef").readText().trim() } else -> "<unknown>" // It's a source distribution, we don't know. } } } // pre-test/master/queue/alice/feature -> master // pre-test/release/current/bob/bugfix -> release fun toPreTestedCommitBaseBranch(actualBranch: String): String = when { actualBranch.startsWith("pre-test/") -> actualBranch.substringAfter("/").substringBefore("/") else -> actualBranch } object BuildEnvironment { /** * A selection of environment variables injected into the enviroment by the `codeql-env.sh` script. */ private val CODEQL_ENVIRONMENT_VARIABLES = arrayOf( "CODEQL_JAVA_HOME", "CODEQL_EXTRACTOR_JAVA_SCRATCH_DIR", "CODEQL_ACTION_RUN_MODE", "CODEQL_ACTION_VERSION", "CODEQL_DIST", "CODEQL_PLATFORM", "CODEQL_RUNNER" ) private val architecture = System.getProperty("os.arch").toLowerCase() val isCiServer = CI_ENVIRONMENT_VARIABLE in System.getenv() val isTravis = "TRAVIS" in System.getenv() val isJenkins = "JENKINS_HOME" in System.getenv() val isGhActions = "GITHUB_ACTIONS" in System.getenv() val isCodeQl: Boolean by lazy { // This logic is kept here instead of `codeql-analysis.init.gradle` because that file will hopefully be removed in the future. // Removing that file is waiting on the GitHub team fixing an issue in Autobuilder logic. CODEQL_ENVIRONMENT_VARIABLES.any { it in System.getenv() } } val jvm = org.gradle.internal.jvm.Jvm.current() val javaVersion = JavaVersion.current() val isWindows = OperatingSystem.current().isWindows val isLinux = OperatingSystem.current().isLinux val isMacOsX = OperatingSystem.current().isMacOsX val isIntel: Boolean = architecture == "x86_64" || architecture == "x86" val isSlowInternetConnection get() = System.getProperty("slow.internet.connection", "false")!!.toBoolean() val agentNum: Int get() { if (System.getenv().containsKey("USERNAME")) { val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "") if (Regex("""\d+""").containsMatchIn(agentNumEnv)) { return agentNumEnv.toInt() } } return 1 } }
apache-2.0
70ae4c59aba4a0b6cfa8fc7fcd819390
35.69697
134
0.662882
4.23797
false
false
false
false
GunoH/intellij-community
plugins/settings-repository/src/git/dirCacheEditor.kt
2
7155
// 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.settingsRepository.git import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.deleteWithParentsIfEmpty import com.intellij.util.io.exists import com.intellij.util.io.toByteArray import org.eclipse.jgit.dircache.BaseDirCacheEditor import org.eclipse.jgit.dircache.DirCache import org.eclipse.jgit.dircache.DirCacheEntry import org.eclipse.jgit.internal.JGitText import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.FileMode import org.eclipse.jgit.lib.Repository import java.io.File import java.io.FileInputStream import java.text.MessageFormat private val EDIT_CMP = Comparator<PathEdit> { o1, o2 -> val a = o1.path val b = o2.path DirCache.cmp(a, a.size, b, b.size) } /** * Don't copy edits, * DeletePath (renamed to DeleteFile) accepts raw path * Pass repository to apply */ class DirCacheEditor(edits: List<PathEdit>, private val repository: Repository, dirCache: DirCache, estimatedNumberOfEntries: Int) : BaseDirCacheEditor(dirCache, estimatedNumberOfEntries) { private val edits = edits.sortedWith(EDIT_CMP) override fun commit(): Boolean { if (edits.isEmpty()) { // No changes? Don't rewrite the index. // cache.unlock() return true } return super.commit() } override fun finish() { if (!edits.isEmpty()) { applyEdits() replace() } } private fun applyEdits() { val maxIndex = cache.entryCount var lastIndex = 0 for (edit in edits) { var entryIndex = cache.findEntry(edit.path, edit.path.size) val missing = entryIndex < 0 if (entryIndex < 0) { entryIndex = -(entryIndex + 1) } val count = Math.min(entryIndex, maxIndex) - lastIndex if (count > 0) { fastKeep(lastIndex, count) } lastIndex = if (missing) entryIndex else cache.nextEntry(entryIndex) if (edit is DeleteFile) { continue } if (edit is DeleteDirectory) { lastIndex = cache.nextEntry(edit.path, edit.path.size, entryIndex) continue } if (missing) { val entry = DirCacheEntry(edit.path) edit.apply(entry, repository) if (entry.rawMode == 0) { throw IllegalArgumentException(MessageFormat.format(JGitText.get().fileModeNotSetForPath, entry.pathString)) } fastAdd(entry) } else if (edit is AddFile || edit is AddLoadedFile) { // apply to first entry and remove others val firstEntry = cache.getEntry(entryIndex) val entry: DirCacheEntry if (firstEntry.isMerged) { entry = firstEntry } else { entry = DirCacheEntry(edit.path) entry.creationTime = firstEntry.creationTime } edit.apply(entry, repository) fastAdd(entry) } else { // apply to all entries of the current path (different stages) for (i in entryIndex until lastIndex) { val entry = cache.getEntry(i) edit.apply(entry, repository) fastAdd(entry) } } } val count = maxIndex - lastIndex if (count > 0) { fastKeep(lastIndex, count) } } } interface PathEdit { val path: ByteArray fun apply(entry: DirCacheEntry, repository: Repository) } abstract class PathEditBase(final override val path: ByteArray) : PathEdit private fun encodePath(path: String): ByteArray { val bytes = Charsets.UTF_8.encode(path).toByteArray() if (SystemInfo.isWindows) { for (i in 0 until bytes.size) { if (bytes[i].toChar() == '\\') { bytes[i] = '/'.toByte() } } } return bytes } class AddFile(private val pathString: String) : PathEditBase(encodePath(pathString)) { override fun apply(entry: DirCacheEntry, repository: Repository) { val file = File(repository.workTree, pathString) entry.fileMode = FileMode.REGULAR_FILE val length = file.length() entry.setLength(length) entry.lastModified = file.lastModified() val input = FileInputStream(file) val inserter = repository.newObjectInserter() try { entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, length, input)) inserter.flush() } finally { inserter.close() input.close() } } } class AddLoadedFile(path: String, private val content: ByteArray, private val lastModified: Long = System.currentTimeMillis()) : PathEditBase( encodePath(path)) { override fun apply(entry: DirCacheEntry, repository: Repository) { entry.fileMode = FileMode.REGULAR_FILE entry.length = content.size entry.lastModified = lastModified val inserter = repository.newObjectInserter() inserter.use { entry.setObjectId(it.insert(Constants.OBJ_BLOB, content)) it.flush() } } } fun DeleteFile(path: String): DeleteFile = DeleteFile(encodePath(path)) class DeleteFile(path: ByteArray) : PathEditBase(path) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } class DeleteDirectory(entryPath: String) : PathEditBase( encodePath(if (entryPath.endsWith('/') || entryPath.isEmpty()) entryPath else "$entryPath/")) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } fun Repository.edit(edit: PathEdit) { edit(listOf(edit)) } fun Repository.edit(edits: List<PathEdit>) { if (edits.isEmpty()) { return } val dirCache = lockDirCache() try { DirCacheEditor(edits, this, dirCache, dirCache.entryCount + 4).commit() } finally { dirCache.unlock() } } private class DirCacheTerminator(dirCache: DirCache) : BaseDirCacheEditor(dirCache, 0) { override fun finish() { replace() } } fun Repository.deleteAllFiles(deletedSet: MutableSet<String>? = null, fromWorkingTree: Boolean = true) { val dirCache = lockDirCache() try { if (deletedSet != null) { for (i in 0 until dirCache.entryCount) { val entry = dirCache.getEntry(i) if (entry.fileMode == FileMode.REGULAR_FILE) { deletedSet.add(entry.pathString) } } } DirCacheTerminator(dirCache).commit() } finally { dirCache.unlock() } if (fromWorkingTree) { val files = workTree.listFiles { file -> file.name != Constants.DOT_GIT } if (files != null) { for (file in files) { FileUtil.delete(file) } } } } fun Repository.writePath(path: String, bytes: ByteArray) { edit(AddLoadedFile(path, bytes)) FileUtil.writeToFile(File(workTree, path), bytes) } fun Repository.deletePath(path: String, isFile: Boolean = true, fromWorkingTree: Boolean = true) { edit((if (isFile) DeleteFile(path) else DeleteDirectory(path))) if (fromWorkingTree) { val workTree = workTree.toPath() val ioFile = workTree.resolve(path) if (ioFile.exists()) { ioFile.deleteWithParentsIfEmpty(workTree, isFile) } } }
apache-2.0
ecd3aa5461ea458770a419dffcd531bb
28.089431
189
0.674493
4.046946
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-auth/jvm/src/io/ktor/server/auth/OAuth1a.kt
1
12389
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.util.* import io.ktor.util.pipeline.* import kotlinx.coroutines.* import java.io.* import java.time.* import java.util.* import javax.crypto.* import javax.crypto.spec.* internal suspend fun PipelineContext<Unit, ApplicationCall>.oauth1a( client: HttpClient, dispatcher: CoroutineDispatcher, providerLookup: ApplicationCall.() -> OAuthServerSettings?, urlProvider: ApplicationCall.(OAuthServerSettings) -> String ) { val provider = call.providerLookup() if (provider is OAuthServerSettings.OAuth1aServerSettings) { val token = call.oauth1aHandleCallback() withContext(dispatcher) { val callbackRedirectUrl = call.urlProvider(provider) if (token == null) { val t = simpleOAuth1aStep1(client, provider, callbackRedirectUrl) call.redirectAuthenticateOAuth1a(provider, t) } else { try { val accessToken = requestOAuth1aAccessToken(client, provider, token) call.authentication.principal(accessToken) } catch (ioe: IOException) { call.oauthHandleFail(callbackRedirectUrl) } } } } } internal fun ApplicationCall.oauth1aHandleCallback(): OAuthCallback.TokenPair? { val token = parameters[HttpAuthHeader.Parameters.OAuthToken] val verifier = parameters[HttpAuthHeader.Parameters.OAuthVerifier] return when { token != null && verifier != null -> OAuthCallback.TokenPair(token, verifier) else -> null } } internal suspend fun simpleOAuth1aStep1( client: HttpClient, settings: OAuthServerSettings.OAuth1aServerSettings, callbackUrl: String, nonce: String = generateNonce(), extraParameters: List<Pair<String, String>> = emptyList() ): OAuthCallback.TokenPair = simpleOAuth1aStep1( client, settings.consumerSecret + "&", settings.requestTokenUrl, callbackUrl, settings.consumerKey, nonce, extraParameters ) private suspend fun simpleOAuth1aStep1( client: HttpClient, secretKey: String, baseUrl: String, callback: String, consumerKey: String, nonce: String = generateNonce(), extraParameters: List<Pair<String, String>> = emptyList() ): OAuthCallback.TokenPair { val authHeader = createObtainRequestTokenHeaderInternal( callback = callback, consumerKey = consumerKey, nonce = nonce ).signInternal(HttpMethod.Post, baseUrl, secretKey, extraParameters) val url = baseUrl.appendUrlParameters(extraParameters.formUrlEncode()) val response = client.post(url) { header(HttpHeaders.Authorization, authHeader.render(HeaderValueEncoding.URI_ENCODE)) header(HttpHeaders.Accept, ContentType.Any.toString()) } val body = response.bodyAsText() try { if (response.status != HttpStatusCode.OK) { throw IOException("Bad response: $response") } val parameters = body.parseUrlEncodedParameters() require(parameters[HttpAuthHeader.Parameters.OAuthCallbackConfirmed] == "true") { "Response parameter oauth_callback_confirmed should be true" } return OAuthCallback.TokenPair( parameters[HttpAuthHeader.Parameters.OAuthToken]!!, parameters[HttpAuthHeader.Parameters.OAuthTokenSecret]!! ) } catch (cause: Throwable) { throw IOException("Failed to acquire request token due to $body", cause) } } internal suspend fun ApplicationCall.redirectAuthenticateOAuth1a( settings: OAuthServerSettings.OAuth1aServerSettings, requestToken: OAuthCallback.TokenPair ) { redirectAuthenticateOAuth1a(settings.authorizeUrl, requestToken.token) } internal suspend fun ApplicationCall.redirectAuthenticateOAuth1a(authenticateUrl: String, requestToken: String) { val url = authenticateUrl.appendUrlParameters( "${HttpAuthHeader.Parameters.OAuthToken}=${requestToken.encodeURLParameter()}" ) respondRedirect(url) } internal suspend fun requestOAuth1aAccessToken( client: HttpClient, settings: OAuthServerSettings.OAuth1aServerSettings, callbackResponse: OAuthCallback.TokenPair, nonce: String = generateNonce(), extraParameters: Map<String, String> = emptyMap() ): OAuthAccessTokenResponse.OAuth1a = requestOAuth1aAccessToken( client, settings.consumerSecret + "&", // TODO?? settings.accessTokenUrl, settings.consumerKey, token = callbackResponse.token, verifier = callbackResponse.tokenSecret, nonce = nonce, extraParameters = extraParameters, accessTokenInterceptor = settings.accessTokenInterceptor ) private suspend fun requestOAuth1aAccessToken( client: HttpClient, secretKey: String, baseUrl: String, consumerKey: String, token: String, verifier: String, nonce: String = generateNonce(), extraParameters: Map<String, String> = emptyMap(), accessTokenInterceptor: (HttpRequestBuilder.() -> Unit)? ): OAuthAccessTokenResponse.OAuth1a { val params = listOf(HttpAuthHeader.Parameters.OAuthVerifier to verifier) + extraParameters.toList() val authHeader = createUpgradeRequestTokenHeaderInternal(consumerKey, token, nonce) .signInternal(HttpMethod.Post, baseUrl, secretKey, params) // some of really existing OAuth servers don't support other accept header values so keep it val body = client.post(baseUrl) { header(HttpHeaders.Authorization, authHeader.render(HeaderValueEncoding.URI_ENCODE)) header(HttpHeaders.Accept, "*/*") // some of really existing OAuth servers don't support other accept header values so keep it setBody( WriterContent( { params.formUrlEncodeTo(this) }, ContentType.Application.FormUrlEncoded ) ) accessTokenInterceptor?.invoke(this) }.body<String>() try { val parameters = body.parseUrlEncodedParameters() return OAuthAccessTokenResponse.OAuth1a( parameters[HttpAuthHeader.Parameters.OAuthToken] ?: throw OAuth1aException.MissingTokenException(), parameters[HttpAuthHeader.Parameters.OAuthTokenSecret] ?: throw OAuth1aException.MissingTokenException(), parameters ) } catch (cause: OAuth1aException) { throw cause } catch (cause: Throwable) { throw IOException("Failed to acquire request token due to $body", cause) } } /** * Creates an HTTP authentication header for OAuth1a obtain token request. */ @Deprecated( "This is going to become internal. Please file a ticket and clarify, why do you need it.", level = DeprecationLevel.ERROR ) @Suppress("unused") public fun createObtainRequestTokenHeader( callback: String, consumerKey: String, nonce: String, timestamp: LocalDateTime = LocalDateTime.now() ): HttpAuthHeader.Parameterized = createObtainRequestTokenHeaderInternal(callback, consumerKey, nonce, timestamp) /** * Creates an HTTP auth header for OAuth1a obtain token request. */ private fun createObtainRequestTokenHeaderInternal( callback: String, consumerKey: String, nonce: String, timestamp: LocalDateTime = LocalDateTime.now() ): HttpAuthHeader.Parameterized = HttpAuthHeader.Parameterized( authScheme = AuthScheme.OAuth, parameters = mapOf( HttpAuthHeader.Parameters.OAuthCallback to callback, HttpAuthHeader.Parameters.OAuthConsumerKey to consumerKey, HttpAuthHeader.Parameters.OAuthNonce to nonce, HttpAuthHeader.Parameters.OAuthSignatureMethod to "HMAC-SHA1", HttpAuthHeader.Parameters.OAuthTimestamp to timestamp.toEpochSecond(ZoneOffset.UTC).toString(), HttpAuthHeader.Parameters.OAuthVersion to "1.0" ) ) /** * Creates an HTTP auth header for OAuth1a upgrade token request. */ @Deprecated( "This is going to become internal. " + "Please file a ticket and clarify, why do you need it.", level = DeprecationLevel.ERROR ) @Suppress("unused") internal fun createUpgradeRequestTokenHeader( consumerKey: String, token: String, nonce: String, timestamp: LocalDateTime = LocalDateTime.now() ): HttpAuthHeader.Parameterized = createUpgradeRequestTokenHeaderInternal(consumerKey, token, nonce, timestamp) /** * Creates an HTTP auth header for OAuth1a upgrade token request. */ private fun createUpgradeRequestTokenHeaderInternal( consumerKey: String, token: String, nonce: String, timestamp: LocalDateTime = LocalDateTime.now() ): HttpAuthHeader.Parameterized = HttpAuthHeader.Parameterized( authScheme = AuthScheme.OAuth, parameters = mapOf( HttpAuthHeader.Parameters.OAuthConsumerKey to consumerKey, HttpAuthHeader.Parameters.OAuthToken to token, HttpAuthHeader.Parameters.OAuthNonce to nonce, HttpAuthHeader.Parameters.OAuthSignatureMethod to "HMAC-SHA1", HttpAuthHeader.Parameters.OAuthTimestamp to timestamp.toEpochSecond(ZoneOffset.UTC).toString(), HttpAuthHeader.Parameters.OAuthVersion to "1.0" ) ) /** * Signs an HTTP auth header. */ @Deprecated( "This is going to become internal. " + "Please file a ticket and clarify, why do you need it.", level = DeprecationLevel.ERROR ) @Suppress("unused") public fun HttpAuthHeader.Parameterized.sign( method: HttpMethod, baseUrl: String, key: String, parameters: List<Pair<String, String>> ): HttpAuthHeader.Parameterized = signInternal(method, baseUrl, key, parameters) /** * Signs an HTTP auth header. */ private fun HttpAuthHeader.Parameterized.signInternal( method: HttpMethod, baseUrl: String, key: String, parameters: List<Pair<String, String>> ): HttpAuthHeader.Parameterized = withParameter( HttpAuthHeader.Parameters.OAuthSignature, signatureBaseStringInternal(this, method, baseUrl, parameters.toHeaderParamsList()).hmacSha1(key) ) /** * Builds an OAuth1a signature base string as per RFC. */ @Deprecated( "This is going to become internal. " + "Please file a ticket and clarify, why do you need it.", level = DeprecationLevel.ERROR ) @Suppress("unused") public fun signatureBaseString( header: HttpAuthHeader.Parameterized, method: HttpMethod, baseUrl: String, parameters: List<HeaderValueParam> ): String = signatureBaseStringInternal(header, method, baseUrl, parameters) /** * Builds an OAuth1a signature base string as per RFC. */ internal fun signatureBaseStringInternal( header: HttpAuthHeader.Parameterized, method: HttpMethod, baseUrl: String, parameters: List<HeaderValueParam> ): String = listOf( method.value.toUpperCasePreservingASCIIRules(), baseUrl, parametersString(header.parameters + parameters) ).joinToString("&") { it.encodeURLParameter() } private fun String.hmacSha1(key: String): String { val keySpec = SecretKeySpec(key.toByteArray(), "HmacSHA1") val mac = Mac.getInstance("HmacSHA1") mac.init(keySpec) return Base64.getEncoder().encodeToString(mac.doFinal(this.toByteArray())) } private fun parametersString(parameters: List<HeaderValueParam>): String = parameters.map { it.name.encodeURLParameter() to it.value.encodeURLParameter() } .sortedWith(compareBy<Pair<String, String>> { it.first }.then(compareBy { it.second })) .joinToString("&") { "${it.first}=${it.second}" } /** * An OAuth1a server error. */ public sealed class OAuth1aException(message: String) : Exception(message) { /** * Thrown when an OAuth1a server didn't provide access token. */ public class MissingTokenException : OAuth1aException("The OAuth1a server didn't provide access token") /** * Represents any other OAuth1a error. */ @Deprecated("This is no longer thrown.", level = DeprecationLevel.ERROR) public class UnknownException(message: String) : OAuth1aException(message) }
apache-2.0
f602f2a826c6144ec197234604a8ee7f
33.997175
119
0.714101
4.605576
false
false
false
false
marius-m/wt4
buildSrc/src/main/java/lt/markmerkk/export/executor/JBundlerScriptJ11Unix.kt
1
2167
package lt.markmerkk.export.executor import org.gradle.api.Project import java.io.File import lt.markmerkk.export.tasks.JBundleResource import java.lang.UnsupportedOperationException /** * Script executor for Java11, Unix platform */ class JBundlerScriptJ11Unix( private val project: Project, private val bundleResource: JBundleResource ): JBundlerScriptProvider { private val jPackage = File(bundleResource.jdk14HomeDir, "/bin/jpackage") private val rootDir = project.rootDir private val scriptDir = File(bundleResource.scriptsDir, "/build-package-j11.sh") init { assert(jPackage.exists()) { "Cannot find 'jpackage' at path ${jPackage.absolutePath}" } } override fun scriptCommand(): List<String> { val scriptArgs = BuildScriptArgs( j11Home = bundleResource.jdk11HomeDir.absolutePath, j14Home = bundleResource.jdk14HomeDir.absolutePath, appVersion = bundleResource.versionName, appName = bundleResource.appName, appDescription = "Jira worklog app", appVendor = "MM", appMainJar = bundleResource.mainJar.name, appMainClass = bundleResource.mainClassName, imageType = bundleResource.packageType, buildDir = project.buildDir.absolutePath, input = bundleResource.inputDir.absolutePath, output = bundleResource.bundlePath.absolutePath, appIcon = bundleResource.appIcon.absolutePath, jvmArgs = bundleResource.jvmOptions.joinToString(" "), platformArgs = emptyList() ) return listOf( "sh", scriptDir.absolutePath ).plus(scriptArgs.components) } override fun bundle(): String = throw UnsupportedOperationException() override fun debugPrint() { println("Using JDK11: ${bundleResource.jdk11HomeDir}") println("Using JRE: ${bundleResource.jdk14HomeDir}") println("Using Main JAR: ${bundleResource.mainJar}") println("Exec: ${scriptCommand()}") } }
apache-2.0
4ab78cea49e2a018cd3ec6e4c7918445
35.745763
84
0.643286
4.869663
false
false
false
false
AntonovAlexander/activecore
hwast/src/hw_exec.kt
1
4952
/* * hw_exec.kt * * Created on: 05.06.2019 * Author: Alexander Antonov <[email protected]> * License: See LICENSE file for details */ package hwast class hw_opcode (val default_string : String) val OP_COMMENT = hw_opcode("//") val OP1_ASSIGN = hw_opcode("=") val OP2_ARITH_ADD = hw_opcode("+") val OP2_ARITH_SUB = hw_opcode("-") val OP2_ARITH_MUL = hw_opcode("*") val OP2_ARITH_DIV = hw_opcode("/") val OP2_ARITH_MOD = hw_opcode("%") val OP2_ARITH_SLL = hw_opcode("<<") val OP2_ARITH_SRL = hw_opcode(">>") val OP2_ARITH_SRA = hw_opcode(">>>") val OP1_COMPLEMENT = hw_opcode("-") val OP1_LOGICAL_NOT = hw_opcode("!") val OP2_LOGICAL_AND = hw_opcode("&&") val OP2_LOGICAL_OR = hw_opcode("||") val OP2_LOGICAL_G = hw_opcode(">") val OP2_LOGICAL_L = hw_opcode("<") val OP2_LOGICAL_GEQ = hw_opcode(">=") val OP2_LOGICAL_LEQ = hw_opcode("<=") val OP2_LOGICAL_EQ2 = hw_opcode("==") val OP2_LOGICAL_NEQ2 = hw_opcode("!=") val OP2_LOGICAL_EQ4 = hw_opcode("===") val OP2_LOGICAL_NEQ4 = hw_opcode("!==") val OP1_BITWISE_NOT = hw_opcode("~") val OP2_BITWISE_AND = hw_opcode("&") val OP2_BITWISE_OR = hw_opcode("|") val OP2_BITWISE_XOR = hw_opcode("^") val OP2_BITWISE_XNOR = hw_opcode("^~") val OP1_REDUCT_AND = hw_opcode("&") val OP1_REDUCT_NAND = hw_opcode("~&") val OP1_REDUCT_OR = hw_opcode("|") val OP1_REDUCT_NOR = hw_opcode("~|") val OP1_REDUCT_XOR = hw_opcode("^") val OP1_REDUCT_XNOR = hw_opcode("^~") val OP2_INDEXED = hw_opcode("indexed") val OP3_RANGED = hw_opcode("ranged") val OP2_SUBSTRUCT = hw_opcode("subStruct") val OPS_CNCT = hw_opcode("cnct") val OP1_IF = hw_opcode("if") val OP1_CASE = hw_opcode("case") val OP1_CASEBRANCH = hw_opcode("casebrach") val OP1_WHILE = hw_opcode("while") enum class WHILE_TRAILER { EMPTY, INCR_COUNTER } // container for operation open class hw_exec(val opcode : hw_opcode) { var while_trailer = WHILE_TRAILER.EMPTY var params = ArrayList<hw_param>() var dsts = ArrayList<hw_var>() var rdvars = ArrayList<hw_var>() var wrvars = ArrayList<hw_var>() var genvars = ArrayList<hw_var>() var expressions = ArrayList<hw_exec>() var subStructvar_name = "UNDEF" var iftargets = ArrayList<hw_var>() var priority_conditions = ArrayList<hw_param>() var comment = "" var cursor = 0 fun ResetCursor() { cursor = expressions.size } fun SetCursor(new_val : Int) { cursor = new_val } fun AddWrVar(new_var : hw_var) { var real_var = new_var if (new_var is hw_var_frac) real_var = new_var.src_var if (!wrvars.contains(real_var)) wrvars.add(real_var) if (new_var is hw_var_frac) { for (depow_frac in new_var.depow_fractions) { if (depow_frac is hw_frac_V) AddRdVar(depow_frac.index) if (depow_frac is hw_frac_CV) AddRdVar(depow_frac.lsb) if (depow_frac is hw_frac_VC) AddRdVar(depow_frac.msb) if (depow_frac is hw_frac_VV) { AddRdVar(depow_frac.lsb) AddRdVar(depow_frac.msb) } } } real_var.write_done = true } fun AddRdVar(new_var : hw_var) { var real_var = new_var if (new_var is hw_var_frac) real_var = new_var.src_var if (!rdvars.contains(real_var)) rdvars.add(real_var) if (new_var is hw_var_frac) { for (depow_frac in new_var.depow_fractions) { if (depow_frac is hw_frac_V) AddRdVar(depow_frac.index) if (depow_frac is hw_frac_CV) AddRdVar(depow_frac.lsb) if (depow_frac is hw_frac_VC) AddRdVar(depow_frac.msb) if (depow_frac is hw_frac_VV) { AddRdVar(depow_frac.lsb) AddRdVar(depow_frac.msb) } } } real_var.read_done = true } fun AddGenVar(new_genvar : hw_var) { var added_var = new_genvar if (added_var is hw_var_frac) added_var = added_var.src_var if (!genvars.contains(added_var)) genvars.add(added_var) } fun AddParam(new_param : hw_param) { params.add(new_param) if (new_param is hw_var) AddRdVar(new_param) } fun AddParams(new_params : ArrayList<hw_param>) { for(new_param in new_params) AddParam(new_param) } fun AddDst(new_dst : hw_var) { dsts.add(new_dst) AddWrVar(new_dst) } fun AddDsts(new_dsts : ArrayList<hw_var>) { for (new_dst in new_dsts) AddDst(new_dst) } fun AddIfTargetVar(new_ifvar : hw_var) { if (!iftargets.contains(new_ifvar)) iftargets.add(new_ifvar) } }
apache-2.0
f69da5a599988e0a9d0c79f25be9da38
29.380368
71
0.558966
3.05114
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/source/Source.kt
2
3240
package eu.kanade.tachiyomi.source import android.graphics.drawable.Drawable import eu.kanade.tachiyomi.extension.ExtensionManager 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.model.toChapterInfo import eu.kanade.tachiyomi.source.model.toMangaInfo import eu.kanade.tachiyomi.source.model.toPageUrl import eu.kanade.tachiyomi.source.model.toSChapter import eu.kanade.tachiyomi.source.model.toSManga import eu.kanade.tachiyomi.util.lang.awaitSingle import rx.Observable import tachiyomi.source.model.ChapterInfo import tachiyomi.source.model.MangaInfo import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * A basic interface for creating a source. It could be an online source, a local source, etc... */ interface Source : tachiyomi.source.Source { /** * Id for the source. Must be unique. */ override val id: Long /** * Name of the source. */ override val name: String override val lang: String get() = "" /** * Returns an observable with the updated details for a manga. * * @param manga the manga to update. */ @Deprecated( "Use the 1.x API instead", ReplaceWith("getMangaDetails") ) fun fetchMangaDetails(manga: SManga): Observable<SManga> = throw IllegalStateException("Not used") /** * Returns an observable with all the available chapters for a manga. * * @param manga the manga to update. */ @Deprecated( "Use the 1.x API instead", ReplaceWith("getChapterList") ) fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = throw IllegalStateException("Not used") // TODO: remove direct usages on this method /** * Returns an observable with the list of pages a chapter has. * * @param chapter the chapter. */ @Deprecated( "Use the 1.x API instead", ReplaceWith("getPageList") ) fun fetchPageList(chapter: SChapter): Observable<List<Page>> = Observable.empty() /** * [1.x API] Get the updated details for a manga. */ @Suppress("DEPRECATION") override suspend fun getMangaDetails(manga: MangaInfo): MangaInfo { val sManga = manga.toSManga() val networkManga = fetchMangaDetails(sManga).awaitSingle() sManga.copyFrom(networkManga) return sManga.toMangaInfo() } /** * [1.x API] Get all the available chapters for a manga. */ @Suppress("DEPRECATION") override suspend fun getChapterList(manga: MangaInfo): List<ChapterInfo> { return fetchChapterList(manga.toSManga()).awaitSingle() .map { it.toChapterInfo() } } /** * [1.x API] Get the list of pages a chapter has. */ @Suppress("DEPRECATION") override suspend fun getPageList(chapter: ChapterInfo): List<tachiyomi.source.model.Page> { return fetchPageList(chapter.toSChapter()).awaitSingle() .map { it.toPageUrl() } } } fun Source.icon(): Drawable? = Injekt.get<ExtensionManager>().getAppIconForSource(this) fun Source.getPreferenceKey(): String = "source_$id"
apache-2.0
c71f25ca03feed75a0c83a308be9a260
30.153846
109
0.68179
4.175258
false
false
false
false
emoji-gen/Emoji-Android
app/src/main/java/moe/pine/emoji/adapter/setting/SettingTeamListAdapter.kt
1
1544
package moe.pine.emoji.adapter.setting import android.content.Context import android.support.annotation.LayoutRes import android.support.annotation.UiThread import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import io.realm.Realm import io.realm.Sort import kotlinx.android.synthetic.main.fragment_setting_team_list.* import moe.pine.emoji.R import moe.pine.emoji.model.realm.SlackTeam import moe.pine.emoji.view.setting.TeamListItemView /** * Adapter for setting team list * Created by pine on May 14, 2017. */ class SettingTeamListAdapter( context: Context, @LayoutRes val layoutId: Int = R.layout.view_setting_team_list_item ) : ArrayAdapter<SlackTeam>(context, layoutId) { override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val inflater = LayoutInflater.from(this.context) if (super.getCount() == 0) { return inflater.inflate(R.layout.view_setting_team_list_empty_item, parent, false) } var view = convertView as? TeamListItemView if (view == null) { view = inflater.inflate(this.layoutId, parent, false) as TeamListItemView } val item = this.getItem(position) view.team = item return view } override fun getCount(): Int { return Math.max(super.getCount(), 1) } fun replaceAll(items: List<SlackTeam>) { this.clear() this.addAll(items) } }
mit
fa43c86cdedb9030d793c3e619d3fb42
28.711538
94
0.70013
3.979381
false
false
false
false