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
google/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/models/SettingsPreferences.kt
1
2017
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.customize.transferSettings.models enum class SettingsPreferencesKind { Laf, SyntaxScheme, Keymap, RecentProjects, Plugins, None; companion object { val noneList = listOf(None) val keysWithoutNone = values().toList() - noneList } } data class SettingsPreferences( var laf: Boolean = true, var syntaxScheme: Boolean = true, var keymap: Boolean = true, var otherSettings: Boolean = true, var recentProjects: Boolean = true, var plugins: Boolean = true ) { operator fun set(index: SettingsPreferencesKind, value: Boolean) { when (index) { SettingsPreferencesKind.Laf -> laf = value SettingsPreferencesKind.SyntaxScheme -> syntaxScheme = value SettingsPreferencesKind.Keymap -> keymap = value SettingsPreferencesKind.RecentProjects -> recentProjects = value SettingsPreferencesKind.Plugins -> plugins = value SettingsPreferencesKind.None -> {} } } operator fun get(index: SettingsPreferencesKind): Boolean { return when (index) { SettingsPreferencesKind.Laf -> laf SettingsPreferencesKind.SyntaxScheme -> syntaxScheme SettingsPreferencesKind.Keymap -> keymap SettingsPreferencesKind.RecentProjects -> recentProjects SettingsPreferencesKind.Plugins -> plugins SettingsPreferencesKind.None -> false } } fun toList(settings: Settings): List<Pair<SettingsPreferencesKind, Boolean>> { return listOf( SettingsPreferencesKind.Laf to laf, SettingsPreferencesKind.SyntaxScheme to syntaxScheme, SettingsPreferencesKind.Keymap to keymap, SettingsPreferencesKind.RecentProjects to (recentProjects && settings.recentProjects.isNotEmpty()), SettingsPreferencesKind.Plugins to (plugins && settings.plugins.isNotEmpty()) ) } fun toListOfTrue(settings: Settings) = toList(settings).filter { it.second }.map { it.first } }
apache-2.0
4d57886d2cf4f08d139dd0b30ae93d52
36.37037
120
0.73525
4.594533
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceEntityExtensionDelegate.kt
3
2746
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.impl import com.intellij.workspaceModel.storage.WorkspaceEntity import org.jetbrains.deft.annotations.Child import kotlin.reflect.KCallable import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KType import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.extensionReceiverParameter import kotlin.reflect.full.isSubclassOf class WorkspaceEntityExtensionDelegate<T> { operator fun getValue(thisRef: WorkspaceEntity, property: KProperty<*>): T { thisRef as WorkspaceEntityBase val workspaceEntitySequence = thisRef.referrers(property.returnTypeKClass.java, property.findTargetField(thisRef).name) val returnType = property.returnType val result: Any? = if (returnType.isCollection) { workspaceEntitySequence.toList() } else { if (returnType.isMarkedNullable) { workspaceEntitySequence.singleOrNull() } else { workspaceEntitySequence.single() } } return result as T } operator fun setValue(thisRef: WorkspaceEntity, property: KProperty<*>, value: T?) { thisRef as ModifiableWorkspaceEntityBase<*> val entities = if (value is List<*>) value else listOf(value) thisRef.linkExternalEntity(property.returnTypeKClass, property.isChildProperty, entities as List<WorkspaceEntity?>) } private val KProperty<*>.isChildProperty: Boolean get() { if (returnType.isCollection) return true return returnType.annotations.any { it.annotationClass == Child::class } } @Suppress("UNCHECKED_CAST") private val KProperty<*>.returnTypeKClass: KClass<out WorkspaceEntity> get() { return if (returnType.isCollection) { returnType.arguments.first().type?.classifier as KClass<out WorkspaceEntity> } else { returnType.classifier as KClass<out WorkspaceEntity> } } private val KType.isCollection: Boolean get() = (classifier as KClass<*>).isSubclassOf(List::class) private fun KProperty<*>.findTargetField(entity: WorkspaceEntity): KCallable<*> { val expectedFieldType = if (entity is ModifiableWorkspaceEntityBase<*>) { entity.getEntityClass() } else { (extensionReceiverParameter?.type?.classifier as? KClass<*>)?.java ?: error("Unexpected behaviour at detecting extension field's receiver type") } return returnTypeKClass.declaredMemberProperties.find { member -> return@find expectedFieldType == member.returnTypeKClass.java } ?: error("Unexpected behaviour in detecting link to $expectedFieldType at $returnTypeKClass") } }
apache-2.0
a687d2d23216add7693312b3d42a9a31
37.676056
150
0.740714
4.947748
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSealedClassToEnumIntention.kt
1
7776
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementDescriptionUtil import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringDescriptionLocation import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.liftToExpected import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("convert.to.enum.class") ) { override fun applicabilityRange(element: KtClass): TextRange? { val nameIdentifier = element.nameIdentifier ?: return null val sealedKeyword = element.modifierList?.getModifier(KtTokens.SEALED_KEYWORD) ?: return null val classDescriptor = element.resolveToDescriptorIfAny() ?: return null if (classDescriptor.getSuperClassNotAny() != null) return null return TextRange(sealedKeyword.startOffset, nameIdentifier.endOffset) } override fun applyTo(element: KtClass, editor: Editor?) { val project = element.project val klass = element.liftToExpected() as? KtClass ?: element val searchAction = { HierarchySearchRequest(klass, klass.useScope, false).searchInheritors().mapNotNull { it.unwrapped } } val subclasses: List<PsiElement> = if (element.isPhysical) project.runSynchronouslyWithProgress(KotlinBundle.message("searching.inheritors"), true, searchAction) ?: return else searchAction().map { subClass -> // search finds physical elements try { PsiTreeUtil.findSameElementInCopy(subClass, klass.containingFile) } catch (_: IllegalStateException) { return } } val subclassesByContainer: Map<KtClass?, List<PsiElement>> = subclasses.sortedBy { it.textOffset }.groupBy { if (it !is KtObjectDeclaration) return@groupBy null if (it.superTypeListEntries.size != 1) return@groupBy null val containingClass = it.containingClassOrObject as? KtClass ?: return@groupBy null if (containingClass != klass && containingClass.liftToExpected() != klass) return@groupBy null containingClass } val inconvertibleSubclasses: List<PsiElement> = subclassesByContainer[null] ?: emptyList() if (inconvertibleSubclasses.isNotEmpty()) { return showError( KotlinBundle.message("all.inheritors.must.be.nested.objects.of.the.class.itself.and.may.not.inherit.from.other.classes.or.interfaces"), inconvertibleSubclasses, project, editor ) } @Suppress("UNCHECKED_CAST") val nonSealedClasses = (subclassesByContainer.keys as Set<KtClass>).filter { !it.isSealed() } if (nonSealedClasses.isNotEmpty()) { return showError( KotlinBundle.message("all.expected.and.actual.classes.must.be.sealed.classes"), nonSealedClasses, project, editor ) } if (subclassesByContainer.isNotEmpty()) { subclassesByContainer.forEach { (currentClass, currentSubclasses) -> processClass(currentClass!!, currentSubclasses, project) } } else { processClass(klass, emptyList(), project) } } private fun showError(@Nls message: String, elements: List<PsiElement>, project: Project, editor: Editor?) { if (elements.firstOrNull()?.isPhysical == false) return val elementDescriptions = elements.map { ElementDescriptionUtil.getElementDescription(it, RefactoringDescriptionLocation.WITHOUT_PARENT) } @NlsSafe val errorText = buildString { append(message) append(KotlinBundle.message("following.problems.are.found")) elementDescriptions.sorted().joinTo(this) } return CommonRefactoringUtil.showErrorHint(project, editor, errorText, text, null) } private fun processClass(klass: KtClass, subclasses: List<PsiElement>, project: Project) { val needSemicolon = klass.declarations.size > subclasses.size val movedDeclarations = run { val subclassesSet = subclasses.toSet() klass.declarations.filter { it in subclassesSet } } val psiFactory = KtPsiFactory(project) val comma = psiFactory.createComma() val semicolon = psiFactory.createSemicolon() val constructorCallNeeded = klass.hasExplicitPrimaryConstructor() || klass.secondaryConstructors.isNotEmpty() val entriesToAdd = movedDeclarations.mapIndexed { i, subclass -> subclass as KtObjectDeclaration val entryText = buildString { append(subclass.name) if (constructorCallNeeded) { append((subclass.superTypeListEntries.firstOrNull() as? KtSuperTypeCallEntry)?.valueArgumentList?.text ?: "()") } } val entry = psiFactory.createEnumEntry(entryText) subclass.body?.let { body -> entry.add(body) } if (i < movedDeclarations.lastIndex) { entry.add(comma) } else if (needSemicolon) { entry.add(semicolon) } entry } movedDeclarations.forEach { it.delete() } klass.removeModifier(KtTokens.SEALED_KEYWORD) if (klass.isInterface()) { klass.getClassOrInterfaceKeyword()?.replace(psiFactory.createClassKeyword()) } klass.addModifier(KtTokens.ENUM_KEYWORD) if (entriesToAdd.isNotEmpty()) { val firstEntry = entriesToAdd .reversed() .asSequence() .map { klass.addDeclarationBefore(it, null) } .last() // TODO: Add formatter rule firstEntry.parent.addBefore(psiFactory.createNewLine(), firstEntry) } else if (needSemicolon) { klass.declarations.firstOrNull()?.let { anchor -> val delimiter = anchor.parent.addBefore(semicolon, anchor).reformatted() delimiter.reformatted() } } } }
apache-2.0
c09a9569e42071ee10abdc2f569473ed
41.966851
158
0.674897
5.177097
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/learn/OpenLessonActivities.kt
1
18075
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn import com.intellij.ide.scratch.ScratchFileService import com.intellij.ide.scratch.ScratchRootType import com.intellij.ide.startup.StartupManagerEx import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Computable import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresEdt import training.dsl.LessonUtil import training.dsl.impl.LessonContextImpl import training.dsl.impl.LessonExecutor import training.lang.LangManager import training.lang.LangSupport import training.learn.course.KLesson import training.learn.course.Lesson import training.learn.course.LessonType import training.learn.lesson.LessonManager import training.project.ProjectUtils import training.statistic.StatisticBase import training.statistic.StatisticLessonListener import training.ui.LearnToolWindowFactory import training.ui.LearningUiManager import training.util.findLanguageByID import training.util.isLearningProject import training.util.learningToolWindow import java.io.IOException internal object OpenLessonActivities { private val LOG = logger<OpenLessonActivities>() @RequiresEdt fun openLesson(projectWhereToStartLesson: Project, lesson: Lesson) { LOG.debug("${projectWhereToStartLesson.name}: start openLesson method") // Stop the current lesson (if any) LessonManager.instance.stopLesson() val activeToolWindow = LearningUiManager.activeToolWindow ?: LearnToolWindowFactory.learnWindowPerProject[projectWhereToStartLesson].also { LearningUiManager.activeToolWindow = it } if (activeToolWindow != null && activeToolWindow.project != projectWhereToStartLesson) { // maybe we need to add some confirmation dialog? activeToolWindow.setModulesPanel() } if (LessonManager.instance.lessonShouldBeOpenedCompleted(lesson)) { // TODO: Do not stop lesson in another toolwindow IFT-110 LearningUiManager.activeToolWindow?.setLearnPanel() ?: error("No active toolwindow in $projectWhereToStartLesson") LessonManager.instance.openLessonPassed(lesson as KLesson, projectWhereToStartLesson) return } try { val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language for learning plugin is not defined") var learnProject = LearningUiManager.learnProject if (learnProject != null && !isLearningProject(learnProject, langSupport)) { learnProject = null // We are in the project from another course } LOG.debug("${projectWhereToStartLesson.name}: trying to get cached LearnProject ${learnProject != null}") if (learnProject == null) learnProject = findLearnProjectInOpenedProjects(langSupport) LOG.debug("${projectWhereToStartLesson.name}: trying to find LearnProject in opened projects ${learnProject != null}") if (learnProject != null) LearningUiManager.learnProject = learnProject when { lesson.lessonType == LessonType.SCRATCH -> { LOG.debug("${projectWhereToStartLesson.name}: scratch based lesson") } learnProject == null || learnProject.isDisposed -> { if (!isLearningProject(projectWhereToStartLesson, langSupport)) { //1. learnProject == null and current project has different name then initLearnProject and register post startup open lesson LOG.debug("${projectWhereToStartLesson.name}: 1. learnProject is null or disposed") initLearnProject(projectWhereToStartLesson) { LOG.debug("${projectWhereToStartLesson.name}: 1. ... LearnProject has been started") openLessonWhenLearnProjectStart(lesson, it) LOG.debug("${projectWhereToStartLesson.name}: 1. ... open lesson when learn project has been started") } return } else { LOG.debug( "${projectWhereToStartLesson.name}: 0. learnProject is null but the current project (${projectWhereToStartLesson.name})" + "is LearnProject then just getFileInLearnProject") LearningUiManager.learnProject = projectWhereToStartLesson learnProject = projectWhereToStartLesson } } learnProject.isOpen && projectWhereToStartLesson != learnProject -> { LOG.debug("${projectWhereToStartLesson.name}: 3. LearnProject is opened but not focused. Ask user to focus to LearnProject") askSwitchToLearnProjectBack(learnProject, projectWhereToStartLesson) return } learnProject.isOpen && projectWhereToStartLesson == learnProject -> { LOG.debug("${projectWhereToStartLesson.name}: 4. LearnProject is the current project") } else -> { throw Exception("Unable to start Learn project") } } if (lesson.lessonType.isProject) { if (projectWhereToStartLesson != learnProject) { LOG.error(Exception("Invalid learning project initialization: projectWhereToStartLesson = $projectWhereToStartLesson, learnProject = $learnProject")) return } cleanupAndOpenLesson(projectWhereToStartLesson, lesson) } else { openLessonForPreparedProject(projectWhereToStartLesson, lesson) } } catch (e: Exception) { LOG.error(e) } } private fun cleanupAndOpenLesson(project: Project, lessonToOpen: Lesson) { val lessons = CourseManager.instance.lessonsForModules.filter { it.lessonType == LessonType.PROJECT } runBackgroundableTask(LearnBundle.message("learn.project.initializing.process"), project = project) { LangManager.getInstance().getLangSupport()?.cleanupBeforeLessons(project) for (lesson in lessons) { lesson.cleanup(project) } invokeLater { openLessonForPreparedProject(project, lessonToOpen) } } } private fun openLessonForPreparedProject(project: Project, lesson: Lesson) { val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language should be defined by now") val vf: VirtualFile? = if (lesson.lessonType == LessonType.SCRATCH) { LOG.debug("${project.name}: scratch based lesson") getScratchFile(project, lesson, langSupport.filename) } else { LOG.debug("${project.name}: 4. LearnProject is the current project") getFileInLearnProject(lesson) } if (lesson.lessonType != LessonType.SCRATCH) { ProjectUtils.closeAllEditorsInProject(project) } if (lesson.lessonType != LessonType.SCRATCH || LearningUiManager.learnProject == project) { // do not change view environment for scratch lessons in user project hideOtherViews(project) } // We need to ensure that the learning panel is initialized showLearnPanel(project) LOG.debug("${project.name}: Add listeners to lesson") addStatisticLessonListenerIfNeeded(project, lesson) //open next lesson if current is passed LOG.debug("${project.name}: Set lesson view") LearningUiManager.activeToolWindow = LearnToolWindowFactory.learnWindowPerProject[project]?.also { it.setLearnPanel() } LOG.debug("${project.name}: XmlLesson onStart()") lesson.onStart() //to start any lesson we need to do 4 steps: //1. open editor or find editor LOG.debug("${project.name}: PREPARING TO START LESSON:") LOG.debug("${project.name}: 1. Open or find editor") var textEditor: TextEditor? = null if (vf != null && FileEditorManager.getInstance(project).isFileOpen(vf)) { val editors = FileEditorManager.getInstance(project).getEditors(vf) for (fileEditor in editors) { if (fileEditor is TextEditor) { textEditor = fileEditor } } } if (vf != null && textEditor == null) { val editors = FileEditorManager.getInstance(project).openFile(vf, true, true) for (fileEditor in editors) { if (fileEditor is TextEditor) { textEditor = fileEditor } } if (textEditor == null) { LOG.error("Cannot open editor for $vf") if (lesson.lessonType == LessonType.SCRATCH) { invokeLater { runWriteAction { vf.delete(this) } } } } } //2. set the focus on this editor //FileEditorManager.getInstance(project).setSelectedEditor(vf, TextEditorProvider.getInstance().getEditorTypeId()); LOG.debug("${project.name}: 2. Set the focus on this editor") if (vf != null) FileEditorManager.getInstance(project).openEditor(OpenFileDescriptor(project, vf), true) //4. Process lesson LOG.debug("${project.name}: 4. Process lesson") if (lesson is KLesson) processDslLesson(lesson, textEditor, project, vf) else error("Unknown lesson format") } private fun processDslLesson(lesson: KLesson, textEditor: TextEditor?, projectWhereToStartLesson: Project, vf: VirtualFile?) { val executor = LessonExecutor(lesson, projectWhereToStartLesson, textEditor?.editor, vf) val lessonContext = LessonContextImpl(executor) LessonManager.instance.initDslLesson(textEditor?.editor, lesson, executor) lesson.lessonContent(lessonContext) executor.startLesson() } private fun hideOtherViews(project: Project) { ApplicationManager.getApplication().invokeLater { LessonUtil.hideStandardToolwindows(project) } } private fun addStatisticLessonListenerIfNeeded(currentProject: Project, lesson: Lesson) { val statLessonListener = StatisticLessonListener(currentProject) if (!lesson.lessonListeners.any { it is StatisticLessonListener }) lesson.addLessonListener(statLessonListener) } private fun openReadme(project: Project) { val manager = ProjectRootManager.getInstance(project) val root = manager.contentRoots[0] val readme = root?.findFileByRelativePath("README.md") ?: return FileEditorManager.getInstance(project).openFile(readme, true, true) } fun openOnboardingFromWelcomeScreen(onboarding: Lesson) { StatisticBase.logLearnProjectOpenedForTheFirstTime(StatisticBase.LearnProjectOpeningWay.ONBOARDING_PROMOTER) initLearnProject(null) { project -> StartupManager.getInstance(project).runAfterOpened { invokeLater { if (onboarding.properties.canStartInDumbMode) { CourseManager.instance.openLesson(project, onboarding) } else { DumbService.getInstance(project).runWhenSmart { CourseManager.instance.openLesson(project, onboarding) } } } } } } fun openLearnProjectFromWelcomeScreen() { StatisticBase.logLearnProjectOpenedForTheFirstTime(StatisticBase.LearnProjectOpeningWay.LEARN_IDE) initLearnProject(null) { project -> StartupManager.getInstance(project).runAfterOpened { invokeLater { openReadme(project) hideOtherViews(project) showLearnPanel(project) CourseManager.instance.unfoldModuleOnInit = null // Try to fix PyCharm double startup indexing :( val openWhenSmart = { showLearnPanel(project) DumbService.getInstance(project).runWhenSmart { showLearnPanel(project) } } Alarm().addRequest(openWhenSmart, 500) } } } } private fun showLearnPanel(project: Project) { learningToolWindow(project)?.show() } @RequiresEdt private fun openLessonWhenLearnProjectStart(lesson: Lesson, myLearnProject: Project) { if (lesson.properties.canStartInDumbMode) { openLessonForPreparedProject(myLearnProject, lesson) return } fun openLesson() { val toolWindowManager = ToolWindowManager.getInstance(myLearnProject) val learnToolWindow = toolWindowManager.getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW) if (learnToolWindow != null) { DumbService.getInstance(myLearnProject).runWhenSmart { // Try to fix PyCharm double startup indexing :( val openWhenSmart = { DumbService.getInstance(myLearnProject).runWhenSmart { openLessonForPreparedProject(myLearnProject, lesson) } } Alarm().addRequest(openWhenSmart, 500) } } } val startupManager = StartupManager.getInstance(myLearnProject) if (startupManager is StartupManagerEx && startupManager.postStartupActivityPassed()) { openLesson() } else { startupManager.registerPostStartupActivity { openLesson() } } } @Throws(IOException::class) private fun getScratchFile(project: Project, lesson: Lesson, filename: String): VirtualFile { var vf: VirtualFile? = null val languageByID = findLanguageByID(lesson.languageId) if (CourseManager.instance.mapModuleVirtualFile.containsKey(lesson.module)) { vf = CourseManager.instance.mapModuleVirtualFile[lesson.module] ScratchFileService.getInstance().scratchesMapping.setMapping(vf, languageByID) } if (vf == null || !vf.isValid) { //while module info is not stored //find file if it is existed vf = ScratchFileService.getInstance().findFile(ScratchRootType.getInstance(), filename, ScratchFileService.Option.existing_only) if (vf != null) { FileEditorManager.getInstance(project).closeFile(vf) ScratchFileService.getInstance().scratchesMapping.setMapping(vf, languageByID) } if (vf == null || !vf.isValid) { vf = ScratchRootType.getInstance().createScratchFile(project, filename, languageByID, "") assert(vf != null) } CourseManager.instance.registerVirtualFile(lesson.module, vf!!) } return vf } private fun askSwitchToLearnProjectBack(learnProject: Project, currentProject: Project) { Messages.showInfoMessage(currentProject, LearnBundle.message("dialog.askToSwitchToLearnProject.message", learnProject.name), LearnBundle.message("dialog.askToSwitchToLearnProject.title")) } @Throws(IOException::class) private fun getFileInLearnProject(lesson: Lesson): VirtualFile? { if (!lesson.properties.openFileAtStart) { LOG.debug("${lesson.name} does not open any file at the start") return null } val function = object : Computable<VirtualFile> { override fun compute(): VirtualFile { val learnProject = LearningUiManager.learnProject!! val existedFile = lesson.existedFile ?: lesson.module.primaryLanguage.projectSandboxRelativePath val manager = ProjectRootManager.getInstance(learnProject) if (existedFile != null) { val root = manager.contentRoots[0] val findFileByRelativePath = root?.findFileByRelativePath(existedFile) if (findFileByRelativePath != null) return findFileByRelativePath } val fileName = existedFile ?: lesson.fileName var lessonVirtualFile: VirtualFile? = null var roots = manager.contentSourceRoots if (roots.isEmpty()) { roots = manager.contentRoots } for (file in roots) { if (file.name == fileName) { lessonVirtualFile = file break } else { lessonVirtualFile = file.findChild(fileName) if (lessonVirtualFile != null) { break } } } if (lessonVirtualFile == null) { lessonVirtualFile = roots[0].createChildData(this, fileName) } CourseManager.instance.registerVirtualFile(lesson.module, lessonVirtualFile) return lessonVirtualFile } } val vf = ApplicationManager.getApplication().runWriteAction(function) assert(vf is VirtualFile) return vf } private fun initLearnProject(projectToClose: Project?, postInitCallback: (learnProject: Project) -> Unit) { val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language for learning plugin is not defined") //if projectToClose is open findLearnProjectInOpenedProjects(langSupport)?.let { postInitCallback(it) return } if (!ApplicationManager.getApplication().isUnitTestMode && projectToClose != null) if (!NewLearnProjectUtil.showDialogOpenLearnProject(projectToClose)) return //if user abort to open lesson in a new Project try { NewLearnProjectUtil.createLearnProject(projectToClose, langSupport) { learnProject -> langSupport.applyToProjectAfterConfigure().invoke(learnProject) LearningUiManager.learnProject = learnProject runInEdt { postInitCallback(learnProject) } } } catch (e: IOException) { LOG.error(e) } } private fun findLearnProjectInOpenedProjects(langSupport: LangSupport): Project? { val openProjects = ProjectManager.getInstance().openProjects return openProjects.firstOrNull { isLearningProject(it, langSupport) } } }
apache-2.0
02ec7e83b23798ed6ab3ae9e2fe1d62e
39.348214
159
0.702075
4.878543
false
false
false
false
AM5800/piano
src/main/kotlin/core/composition/CompositionBuilder.kt
1
903
package core.composition import core.notion.Tonality import org.jscience.mathematics.number.Rational class CompositionBuilder(val title: String) { private var currentTonality: Tonality? = null private var currentTimeSignature: Rational? = null private val bars = mutableListOf<Bar>() fun tonality(tonality: Tonality) { currentTonality = tonality } fun timeSignature(duration: Rational) { currentTimeSignature = duration } fun bar(init: BarBuilder.() -> Unit) { val tonality = currentTonality ?: throw Exception("Tonality not set") val timeSignature = currentTimeSignature ?: throw Exception("Time signature not set") val builder = BarBuilder(tonality, timeSignature) builder.init() bars.add(builder.createBar()) } fun createComposition(): Composition { return Composition(title, bars) } }
lgpl-3.0
16412892add0ea05e60d0e6e06b920ea
28.16129
93
0.689922
4.320574
false
false
false
false
Kotlin/kotlinx.coroutines
benchmarks/src/jmh/kotlin/benchmarks/ChannelProducerConsumerBenchmark.kt
1
4884
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.selects.select import org.openjdk.jmh.annotations.* import org.openjdk.jmh.infra.Blackhole import java.lang.Integer.max import java.util.concurrent.ForkJoinPool import java.util.concurrent.Phaser import java.util.concurrent.ThreadLocalRandom import java.util.concurrent.TimeUnit /** * Benchmark to measure channel algorithm performance in terms of average time per `send-receive` pair; * actually, it measures the time for a batch of such operations separated into the specified number of consumers/producers. * It uses different channels (rendezvous, buffered, unlimited; see [ChannelCreator]) and different dispatchers * (see [DispatcherCreator]). If the [_3_withSelect] property is set, it invokes `send` and * `receive` via [select], waiting on a local dummy channel simultaneously, simulating a "cancellation" channel. * * Please, be patient, this benchmark takes quite a lot of time to complete. */ @Warmup(iterations = 3, time = 500, timeUnit = TimeUnit.MICROSECONDS) @Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MICROSECONDS) @Fork(value = 3) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) open class ChannelProducerConsumerBenchmark { @Param private var _0_dispatcher: DispatcherCreator = DispatcherCreator.FORK_JOIN @Param private var _1_channel: ChannelCreator = ChannelCreator.RENDEZVOUS @Param("0", "1000") private var _2_coroutines: Int = 0 @Param("false", "true") private var _3_withSelect: Boolean = false @Param("1", "2", "4") // local machine // @Param("1", "2", "4", "8", "12") // local machine // @Param("1", "2", "4", "8", "16", "32", "64", "128", "144") // dasquad // @Param("1", "2", "4", "8", "16", "32", "64", "96") // Google Cloud private var _4_parallelism: Int = 0 private lateinit var dispatcher: CoroutineDispatcher private lateinit var channel: Channel<Int> @InternalCoroutinesApi @Setup fun setup() { dispatcher = _0_dispatcher.create(_4_parallelism) channel = _1_channel.create() } @Benchmark fun spmc() { if (_2_coroutines != 0) return val producers = max(1, _4_parallelism - 1) val consumers = 1 run(producers, consumers) } @Benchmark fun mpmc() { val producers = if (_2_coroutines == 0) (_4_parallelism + 1) / 2 else _2_coroutines / 2 val consumers = producers run(producers, consumers) } private fun run(producers: Int, consumers: Int) { val n = APPROX_BATCH_SIZE / producers * producers val phaser = Phaser(producers + consumers + 1) // Run producers repeat(producers) { GlobalScope.launch(dispatcher) { val dummy = if (_3_withSelect) _1_channel.create() else null repeat(n / producers) { produce(it, dummy) } phaser.arrive() } } // Run consumers repeat(consumers) { GlobalScope.launch(dispatcher) { val dummy = if (_3_withSelect) _1_channel.create() else null repeat(n / consumers) { consume(dummy) } phaser.arrive() } } // Wait until work is done phaser.arriveAndAwaitAdvance() } private suspend fun produce(element: Int, dummy: Channel<Int>?) { if (_3_withSelect) { select<Unit> { channel.onSend(element) {} dummy!!.onReceive {} } } else { channel.send(element) } doWork() } private suspend fun consume(dummy: Channel<Int>?) { if (_3_withSelect) { select<Unit> { channel.onReceive {} dummy!!.onReceive {} } } else { channel.receive() } doWork() } } enum class DispatcherCreator(val create: (parallelism: Int) -> CoroutineDispatcher) { FORK_JOIN({ parallelism -> ForkJoinPool(parallelism).asCoroutineDispatcher() }) } enum class ChannelCreator(private val capacity: Int) { RENDEZVOUS(Channel.RENDEZVOUS), // BUFFERED_1(1), BUFFERED_2(2), // BUFFERED_4(4), BUFFERED_32(32), BUFFERED_128(128), BUFFERED_UNLIMITED(Channel.UNLIMITED); fun create(): Channel<Int> = Channel(capacity) } private fun doWork(): Unit = Blackhole.consumeCPU(ThreadLocalRandom.current().nextLong(WORK_MIN, WORK_MAX)) private const val WORK_MIN = 50L private const val WORK_MAX = 100L private const val APPROX_BATCH_SIZE = 100000
apache-2.0
79acc1ba2958d5a2ffe506368072d346
31.56
124
0.623669
4.019753
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-server/src/main/kotlin/slatekit/server/ktor/KtorResponses.kt
1
1069
package slatekit.server.ktor import io.ktor.application.ApplicationCall import io.ktor.http.HttpStatusCode import io.ktor.response.respondBytes import slatekit.common.types.ContentData import slatekit.common.types.ContentTypes import slatekit.results.* object KtorResponses { fun status(status: Status): HttpStatusCode { val info = Codes.toHttp(status) val code = info.first val desc = info.second.desc return HttpStatusCode(code, desc) } suspend fun respond(call: ApplicationCall, result:Outcome<ContentData>) { return when(result) { is Success -> { val contentType = io.ktor.http.ContentType.parse(result.value.tpe.http) val status = status(result.status) call.respondBytes(result.value.data, contentType, status) } is Failure -> { val status = status(result.status) call.respondBytes(byteArrayOf(), io.ktor.http.ContentType.parse(ContentTypes.Json.http), status) } } } }
apache-2.0
ffcd563cf93710ed4e89afd2df7d243c
32.4375
112
0.65014
4.510549
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/runtime/collections/array0.kt
1
822
package runtime.collections.array0 import kotlin.test.* @Test fun runTest() { // Create instances of all array types. val byteArray = ByteArray(5) println(byteArray.size.toString()) val charArray = CharArray(6) println(charArray.size.toString()) val shortArray = ShortArray(7) println(shortArray.size.toString()) val intArray = IntArray(8) println(intArray.size.toString()) val longArray = LongArray(9) println(longArray.size.toString()) val floatArray = FloatArray(10) println(floatArray.size.toString()) val doubleArray = FloatArray(11) println(doubleArray.size.toString()) val booleanArray = BooleanArray(12) println(booleanArray.size.toString()) val stringArray = Array<String>(13, { i -> ""}) println(stringArray.size.toString()) }
apache-2.0
187e146127937ac56e9ba789b508e232
23.939394
51
0.692214
4.089552
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/MapTest/filterOutProjectedTo.kt
2
892
import kotlin.test.* fun <T> assertStaticTypeIs(value: T) {} fun box() { val map: Map<out String, Int> = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val filteredByKey = map.filterTo(mutableMapOf()) { it.key[0] == 'b' } assertStaticTypeIs<MutableMap<String, Int>>(filteredByKey) assertEquals(mapOf("b" to 3), filteredByKey) val filteredByKey2 = map.filterKeys { it[0] == 'b' } assertStaticTypeIs<Map<String, Int>>(filteredByKey2) assertEquals(mapOf("b" to 3), filteredByKey2) val filteredByValue = map.filterNotTo(hashMapOf()) { it.value != 2 } assertStaticTypeIs<HashMap<String, Int>>(filteredByValue) assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue) val filteredByValue2 = map.filterValues { it % 2 == 0 } assertStaticTypeIs<Map<String, Int>>(filteredByValue2) assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2) }
apache-2.0
5107ccce62609b311508d2f06b091ab5
37.782609
83
0.672646
3.378788
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/multifileClasses/optimized/overlappingFuns.kt
2
559
// TARGET_BACKEND: JVM // IGNORE_LIGHT_ANALYSIS // WITH_RUNTIME // KOTLIN_CONFIGURATION_FLAGS: +JVM.INHERIT_MULTIFILE_PARTS // FILE: box.kt import a.* fun box(): String = ok() // FILE: part1.kt @file:[JvmName("MultifileClass") JvmMultifileClass] package a private fun overlapping() = "oops #1" // FILE: part2.kt @file:[JvmName("MultifileClass") JvmMultifileClass] package a private fun overlapping() = "OK" fun ok() = overlapping() // FILE: part3.kt @file:[JvmName("MultifileClass") JvmMultifileClass] package a private fun overlapping() = "oops #2"
apache-2.0
9c5230d46cfe8089aa8699355a82b592
18.275862
59
0.711986
3.327381
false
false
false
false
redundent/kotlin-xml-builder
kotlin-xml-builder/src/main/kotlin/org/redundent/kotlin/xml/XmlBuilder.kt
1
3441
package org.redundent.kotlin.xml import org.w3c.dom.Document import org.xml.sax.InputSource import java.io.File import java.io.InputStream import javax.xml.parsers.DocumentBuilderFactory import kotlin.math.min import org.w3c.dom.Node as W3CNode internal fun getLineEnding(printOptions: PrintOptions) = if (printOptions.pretty) System.lineSeparator() else "" /** * Creates a new xml document with the specified root element name * * @param root The root element name * @param encoding The encoding to use for the xml prolog * @param version The XML specification version to use for the xml prolog and attribute encoding * @param namespace Optional namespace object to use to build the name of the attribute. This will also an xmlns * attribute for this value * @param init The block that defines the content of the xml */ fun xml(root: String, encoding: String? = null, version: XmlVersion? = null, namespace: Namespace? = null, init: (Node.() -> Unit)? = null): Node { val node = Node(buildName(root, namespace)) if (encoding != null) { node.encoding = encoding } if (version != null) { node.version = version } if (init != null) { node.init() } if (namespace != null) { node.namespace(namespace) } return node } /** * Creates a new xml document with the specified root element name * * @param name The name of the element * @param init The block that defines the content of the xml */ fun node(name: String, namespace: Namespace? = null, init: (Node.() -> Unit)? = null): Node { val node = Node(buildName(name, namespace)) if (init != null) { node.init() } return node } fun parse(f: File): Node = parse(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f)) fun parse(uri: String): Node = parse(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(uri)) fun parse(inputSource: InputSource): Node = parse(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputSource)) fun parse(inputStream: InputStream): Node = parse(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream)) fun parse(inputStream: InputStream, systemId: String): Node = parse(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream, systemId)) fun parse(document: Document): Node { val root = document.documentElement val result = xml(root.tagName) copyAttributes(root, result) val children = root.childNodes (0 until children.length) .map(children::item) .forEach { copy(it, result) } return result } private fun copy(source: W3CNode, dest: Node) { when (source.nodeType) { W3CNode.ELEMENT_NODE -> { val cur = dest.element(source.nodeName) copyAttributes(source, cur) val children = source.childNodes (0 until children.length) .map(children::item) .forEach { copy(it, cur) } } W3CNode.CDATA_SECTION_NODE -> { dest.cdata(source.nodeValue) } W3CNode.TEXT_NODE -> { dest.text(source.nodeValue.trim { it.isWhitespace() || it == '\r' || it == '\n' }) } } } private fun copyAttributes(source: W3CNode, dest: Node) { val attributes = source.attributes if (attributes == null || attributes.length == 0) { return } (0 until attributes.length) .map(attributes::item) .forEach { if (it.nodeName.startsWith("xmlns")) { dest.namespace(it.nodeName.substring(min(6, it.nodeName.length)), it.nodeValue) } else { dest.attribute(it.nodeName, it.nodeValue) } } }
apache-2.0
fd81e0c17f9aa60a17922e884abf40fc
29.184211
155
0.715199
3.529231
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/Subscription.kt
1
605
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Information about the user's subscription. * * @param renewal Information about the user's next renewal. * @param trial Information about the user's trial period. * @param billing Information about the user's billing info. */ @JsonClass(generateAdapter = true) data class Subscription( @Json(name = "renewal") val renewal: SubscriptionRenewal? = null, @Json(name = "trial") val trial: SubscriptionTrial? = null, @Json(name = "billing") val billing: Billing? = null )
mit
531a07b9ec2eb8240e9b0e6e00d94a50
24.208333
60
0.715702
3.928571
false
false
false
false
smmribeiro/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
9
11156
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.builtInWebServer import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.roots.impl.OrderEntryUtil import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PlatformUtils internal data class SuitableRoot(val file: VirtualFile, val moduleQualifier: String?) private class DefaultWebServerRootsProvider : WebServerRootsProvider() { override fun resolve(path: String, project: Project, pathQuery: PathQuery): PathInfo? { val pathToFileManager = WebServerPathToFileManager.getInstance(project) var effectivePath = path if (PlatformUtils.isIntelliJ()) { val index = effectivePath.indexOf('/') if (index > 0 && !effectivePath.regionMatches(0, project.name, 0, index, !SystemInfo.isFileSystemCaseSensitive)) { val moduleName = effectivePath.substring(0, index) val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) } if (module != null && !module.isDisposed) { effectivePath = effectivePath.substring(index + 1) val resolver = pathToFileManager.getResolver(effectivePath) val result = RootProvider.values().asSequence().map { findByRelativePath(effectivePath, it.getRoots(module.rootManager), resolver, moduleName, pathQuery) }.find { it != null } ?: findInModuleLibraries(effectivePath, module, resolver, pathQuery) if (result != null) { return result } } } } val resolver = pathToFileManager.getResolver(effectivePath) val modules = runReadAction { ModuleManager.getInstance(project).modules } if (pathQuery.useVfs) { var oldestParent = path.indexOf("/").let { if (it > 0) path.substring(0, it) else null } if (oldestParent == null && path.isNotEmpty() && !path.contains('.')) { // maybe it is a top-level directory? (in case of dart projects - web) oldestParent = path } if (oldestParent != null) { for ((file, moduleQualifier) in pathToFileManager.parentToSuitableRoot.get(oldestParent)!!) { file.findFileByRelativePath(path)?.let { return PathInfo(null, it, file, moduleQualifier) } } } } else { for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } findByRelativePath(path, rootProvider.getRoots(module.rootManager), resolver, null, pathQuery)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } if (!pathQuery.searchInLibs) { // yes, if !searchInLibs, config.json is also not checked return null } fun findByConfigJson(): PathInfo? { // https://youtrack.jetbrains.com/issue/WEB-24283 for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (resolver.resolve("config.json", root, pathQuery = pathQuery) != null) { resolver.resolve("index.html", root, pathQuery = pathQuery)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } } return null } val exists = pathToFileManager.pathToExistShortTermCache.getIfPresent("config.json") if (exists == null || exists) { val result = findByConfigJson() pathToFileManager.pathToExistShortTermCache.put("config.json", result != null) if (result != null) { return result } } return findInLibraries(project, effectivePath, resolver, pathQuery) } override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? { return runReadAction { val directoryIndex = DirectoryIndex.getInstance(project) val info = directoryIndex.getInfoForFile(file) // we serve excluded files if (!info.isExcluded(file) && !info.isInProject(file)) { // javadoc jars is "not under project", but actually is, so, let's check library or SDK if (file.fileSystem == JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null } else { var root = info.sourceRoot val isRootNameOptionalInPath: Boolean val isLibrary: Boolean if (root == null) { isRootNameOptionalInPath = false root = info.contentRoot if (root == null) { root = info.libraryClassRoot if (root == null) { // https://youtrack.jetbrains.com/issue/WEB-20598 return@runReadAction null } isLibrary = true } else { isLibrary = false } } else { isLibrary = info.isInLibrarySource(file) isRootNameOptionalInPath = !isLibrary } var module = info.module if (isLibrary && module == null) { for (entry in directoryIndex.getOrderEntries(info)) { if (OrderEntryUtil.isModuleLibraryOrderEntry(entry)) { module = entry.ownerModule break } } } PathInfo(null, file, root, getModuleNameQualifier(project, module), isLibrary, isRootNameOptionalInPath = isRootNameOptionalInPath) } } } } internal enum class RootProvider { SOURCE { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.sourceRoots }, CONTENT { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.contentRoots }, EXCLUDED { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.excludeRoots }; abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> } private val ORDER_ROOT_TYPES by lazy { val javaDocRootType = getJavadocOrderRootType() if (javaDocRootType == null) arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) else arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) } private fun getJavadocOrderRootType(): OrderRootType? { return try { JavadocOrderRootType.getInstance() } catch (e: Throwable) { null } } private fun findInModuleLibraries(path: String, module: Module, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { val index = path.indexOf('/') if (index <= 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return ORDER_ROOT_TYPES.asSequence().map { findInModuleLevelLibraries(module, it) { root, _ -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null } }.firstOrNull { it != null } } private fun findInLibraries(project: Project, path: String, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { val index = path.indexOf('/') if (index < 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return findInLibrariesAndSdk(project, ORDER_ROOT_TYPES) { root, _ -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null } } private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? { val javaDocRootType = getJavadocOrderRootType() ?: return null return findInLibrariesAndSdk(project, arrayOf(javaDocRootType)) { root, module -> if (VfsUtilCore.isAncestor(root, file, false)) PathInfo(null, file, root, getModuleNameQualifier(project, module), true) else null } } internal fun getModuleNameQualifier(project: Project, module: Module?): String? { return if (module != null && PlatformUtils.isIntelliJ() && !(module.name.equals(project.name, ignoreCase = true) || compareNameAndProjectBasePath(module.name, project))) module.name else null } private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: FileResolver, moduleName: String?, pathQuery: PathQuery): PathInfo? { return roots.asSequence() .map { resolver.resolve(path, it, moduleName, pathQuery = pathQuery) } .firstOrNull { it != null } } private fun findInLibrariesAndSdk(project: Project, rootTypes: Array<OrderRootType>, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { fun findInLibraryTable(table: LibraryTable, rootType: OrderRootType) = table.libraryIterator.asSequence() .flatMap { it.getFiles(rootType).asSequence() } .map { fileProcessor(it, null) } .firstOrNull { it != null } fun findInProjectSdkOrInAll(rootType: OrderRootType): PathInfo? { val inSdkFinder = { sdk: Sdk -> sdk.rootProvider.getFiles(rootType).asSequence().map { fileProcessor(it, null) }.firstOrNull { it != null } } val projectSdk = ProjectRootManager.getInstance(project).projectSdk return projectSdk?.let(inSdkFinder) ?: ProjectJdkTable.getInstance().allJdks.asSequence().filter { it === projectSdk }.map { inSdkFinder(it) }.firstOrNull { it != null } } return rootTypes.asSequence().map { rootType -> runReadAction { findInLibraryTable(LibraryTablesRegistrar.getInstance().getLibraryTable(project), rootType) ?: findInProjectSdkOrInAll(rootType) ?: ModuleManager.getInstance(project).modules.asSequence().filter { !it.isDisposed }.map { findInModuleLevelLibraries(it, rootType, fileProcessor) }.firstOrNull { it != null } ?: findInLibraryTable(LibraryTablesRegistrar.getInstance().libraryTable, rootType) } }.find { it != null } } private fun findInModuleLevelLibraries(module: Module, rootType: OrderRootType, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { return module.rootManager.orderEntries.asSequence() .filter { it is LibraryOrderEntry && it.isModuleLevel } .flatMap { it.getFiles(rootType).asSequence() } .map { fileProcessor(it, module) } .firstOrNull { it != null } }
apache-2.0
c8b97a15a483125e9736187a40afeca0
39.423913
185
0.688508
4.745215
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GHPRDetailsModelImpl.kt
9
992
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.details import com.intellij.collaboration.ui.SingleValueModel import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState class GHPRDetailsModelImpl(private val valueModel: SingleValueModel<GHPullRequest>) : GHPRDetailsModel { override val number: String get() = valueModel.value.number.toString() override val title: String get() = valueModel.value.title override val description: String get() = valueModel.value.body override val state: GHPullRequestState get() = valueModel.value.state override val isDraft: Boolean get() = valueModel.value.isDraft override fun addAndInvokeDetailsChangedListener(listener: () -> Unit) = valueModel.addAndInvokeListener { listener() } }
apache-2.0
200b5dd61360884eb3baf623546b18a5
42.173913
140
0.785282
4.331878
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/FormattingCollector.kt
2
4711
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.javadoc.PsiDocComment import org.jetbrains.kotlin.idea.j2k.IdeaDocCommentConverter import org.jetbrains.kotlin.nj2k.tree.JKComment import org.jetbrains.kotlin.nj2k.tree.JKFormattingOwner import org.jetbrains.kotlin.utils.addToStdlib.safeAs class FormattingCollector { private val commentCache = mutableMapOf<PsiElement, JKComment>() fun takeFormattingFrom( element: JKFormattingOwner, psi: PsiElement?, saveLineBreaks: Boolean, takeTrailingComments: Boolean, takeLeadingComments: Boolean ) { if (psi == null) return val (leftTokens, rightTokens) = psi.collectComments(takeTrailingComments, takeLeadingComments) element.trailingComments += leftTokens element.leadingComments += rightTokens if (saveLineBreaks) { element.hasLeadingLineBreak = psi.hasLineBreakAfter() element.hasTrailingLineBreak = psi.hasLineBreakBefore() } } fun takeLineBreaksFrom(element: JKFormattingOwner, psi: PsiElement?) { if (psi == null) return element.hasLeadingLineBreak = psi.hasLineBreakAfter() element.hasTrailingLineBreak = psi.hasLineBreakBefore() } private fun PsiElement.asComment(): JKComment? { if (this in commentCache) return commentCache.getValue(this) val token = when (this) { is PsiDocComment -> JKComment( IdeaDocCommentConverter.convertDocComment( this ) ) is PsiComment -> JKComment(text, indent()) else -> null } ?: return null commentCache[this] = token return token } private fun PsiComment.indent(): String? = takeIf { parent is PsiCodeBlock }?.prevSibling?.safeAs<PsiWhiteSpace>()?.let { space -> val text = space.text if (space.prevSibling is PsiStatement) text.indexOfFirst(StringUtil::isLineBreak).takeIf { it != -1 }?.let { text.substring(it + 1) } ?: text else text } private fun Sequence<PsiElement>.toComments(): List<JKComment> = takeWhile { it is PsiComment || it is PsiWhiteSpace || it.text == ";" } .mapNotNull { it.asComment() } .toList() fun PsiElement.leadingCommentsWithParent(): Sequence<JKComment> { val innerElements = leadingComments() return (if (innerElements.lastOrNull()?.nextSibling == null && this is PsiKeyword) innerElements + parent?.leadingComments().orEmpty() else innerElements).mapNotNull { it.asComment() } } private fun PsiElement.trailingCommentsWithParent(): Sequence<JKComment> { val innerElements = trailingComments() return (if (innerElements.firstOrNull()?.prevSibling == null && this is PsiKeyword) innerElements + parent?.trailingComments().orEmpty() else innerElements).mapNotNull { it.asComment() } } private fun PsiElement.isNonCodeElement() = this is PsiComment || this is PsiWhiteSpace || textMatches(";") || textLength == 0 private fun PsiElement.leadingComments() = generateSequence(nextSibling) { it.nextSibling } .takeWhile { it.isNonCodeElement() } private fun PsiElement.trailingComments() = generateSequence(prevSibling) { it.prevSibling } .takeWhile { it.isNonCodeElement() } private fun PsiElement.hasLineBreakBefore() = trailingComments().any { it is PsiWhiteSpace && it.textContains('\n') } private fun PsiElement.hasLineBreakAfter() = leadingComments().any { it is PsiWhiteSpace && it.textContains('\n') } private fun PsiElement.collectComments( takeTrailingComments: Boolean, takeLeadingComments: Boolean ): Pair<List<JKComment>, List<JKComment>> { val leftInnerTokens = children.asSequence().toComments().asReversed() val rightInnerTokens = when { children.isEmpty() -> emptyList() else -> generateSequence(children.last()) { it.prevSibling } .toComments() .asReversed() } val leftComments = (leftInnerTokens + if (takeTrailingComments) trailingCommentsWithParent() else emptySequence()).asReversed() val rightComments = rightInnerTokens + if (takeLeadingComments) leadingCommentsWithParent() else emptySequence() return leftComments to rightComments } }
apache-2.0
5e5587614d156bca45474b887ed36fa8
41.45045
158
0.668223
5.006376
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/branch/RecentBranchesService.kt
1
3046
package zielu.gittoolbox.branch import com.intellij.openapi.project.Project import com.intellij.serviceContainer.NonInjectable import git4idea.GitBranch import zielu.gittoolbox.repo.GtRepository import zielu.gittoolbox.store.RecentBranch import zielu.gittoolbox.util.AppUtil import java.time.Instant internal class RecentBranchesService @NonInjectable constructor( private val facade: RecentBranchesFacade ) { constructor() : this(RecentBranchesFacade()) fun branchSwitch(previousBranch: GitBranch, currentBranch: GitBranch, repository: GtRepository) { val now = facade.now() val recentBranches = facade.getRecentBranchesFromStore(repository) if (recentBranches.isEmpty()) { val previous = createRecentBranch(previousBranch, now.minusSeconds(1)) val current = createRecentBranch(currentBranch, now) facade.storeRecentBranches(listOf(current, previous), repository) } else { updateRecentBranches(createRecentBranch(currentBranch, now), repository) } } fun switchToBranchFromOther(currentBranch: GitBranch, repository: GtRepository) { val current = createRecentBranch(currentBranch, facade.now()) val recentBranches = facade.getRecentBranchesFromStore(repository) if (recentBranches.isEmpty()) { facade.storeRecentBranches(listOf(current), repository) } else { updateRecentBranches(current, repository) } } fun switchFromBranchToOther(previousBranch: GitBranch, repository: GtRepository) { val previous = createRecentBranch(previousBranch, facade.now()) val recentBranches = facade.getRecentBranchesFromStore(repository) if (recentBranches.isEmpty()) { facade.storeRecentBranches(listOf(previous), repository) } else { updateRecentBranches(previous, repository) } } private fun createRecentBranch(branch: GitBranch, instant: Instant): RecentBranch { return RecentBranch(branch.name, instant.epochSecond) } private fun updateRecentBranches(latestBranch: RecentBranch, repository: GtRepository) { synchronized(this) { val recentBranches = facade.getRecentBranchesFromStore(repository).toMutableList() recentBranches.removeIf { repository.findLocalBranch(it.branchName) == null } recentBranches.removeIf { it.branchName == latestBranch.branchName } recentBranches.add(latestBranch) recentBranches .sortByDescending { it.lastUsedInstant } val trimmedToLimit = recentBranches.take(HISTORY_LIMIT) facade.storeRecentBranches(trimmedToLimit, repository) } } fun getRecentBranches(repository: GtRepository): List<GitBranch> { val recentBranches = facade.getRecentBranchesFromStore(repository) return recentBranches .sortedBy { it.lastUsedInstant } .mapNotNull { repository.findLocalBranch(it.branchName) } } companion object { private const val HISTORY_LIMIT = 5 fun getInstance(project: Project): RecentBranchesService { return AppUtil.getServiceInstance(project, RecentBranchesService::class.java) } } }
apache-2.0
a7a2bdec47cbfe1203862bb9e47bdb4f
36.146341
99
0.761983
4.671779
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexTumbler.kt
7
9124
// 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.util.indexing import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileTypes.FileTypeEvent import com.intellij.openapi.fileTypes.FileTypeListener import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbModeTask import com.intellij.openapi.project.DumbService import com.intellij.openapi.roots.AdditionalLibraryRootsProvider import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.psi.stubs.StubIndexExtension import com.intellij.util.concurrency.Semaphore import com.intellij.util.indexing.IndexingFlag.cleanupProcessedFlag import org.jetbrains.annotations.NonNls import java.util.* class FileBasedIndexTumbler(private val reason: @NonNls String) { private val fileBasedIndex = FileBasedIndex.getInstance() as FileBasedIndexImpl private val dumbModeSemaphore = Semaphore() private var nestedLevelCount = 0 private var snapshot: FbiSnapshot? = null private var fileTypeTracker: FileTypeTracker? = null fun turnOff() { val app = ApplicationManager.getApplication() LOG.assertTrue(app.isDispatchThread) LOG.assertTrue(!app.isWriteAccessAllowed) try { if (nestedLevelCount == 0) { val headless = app.isHeadlessEnvironment if (!headless) { val wasUp = dumbModeSemaphore.isUp dumbModeSemaphore.down() if (wasUp) { for (project in ProjectUtil.getOpenProjects()) { val dumbService = DumbService.getInstance(project) dumbService.cancelAllTasksAndWait() MyDumbModeTask(dumbModeSemaphore).queue(project) } } } LOG.assertTrue(fileTypeTracker == null) fileTypeTracker = FileTypeTracker() fileBasedIndex.waitUntilIndicesAreInitialized() fileBasedIndex.performShutdown(true, reason) fileBasedIndex.dropRegisteredIndexes() val indexesAreOk = RebuildStatus.isOk() RebuildStatus.reset() IndexingStamp.dropTimestampMemoryCaches() LOG.assertTrue(snapshot == null) if (indexesAreOk) { snapshot = FbiSnapshot.Impl.capture() } else { snapshot = FbiSnapshot.RebuildRequired } } } finally { nestedLevelCount++ } } @JvmOverloads fun turnOn(beforeIndexTasksStarted: Runnable? = null) { LOG.assertTrue(ApplicationManager.getApplication().isWriteThread) nestedLevelCount-- if (nestedLevelCount == 0) { try { fileBasedIndex.loadIndexes() val headless = ApplicationManager.getApplication().isHeadlessEnvironment if (headless) { fileBasedIndex.waitUntilIndicesAreInitialized() } if (!headless) { dumbModeSemaphore.up() } val runRescanning = CorruptionMarker.requireInvalidation() || (Registry.`is`("run.index.rescanning.on.plugin.load.unload") || snapshot is FbiSnapshot.RebuildRequired || FbiSnapshot.Impl.isRescanningRequired(snapshot as FbiSnapshot.Impl, FbiSnapshot.Impl.capture())) if (runRescanning) { beforeIndexTasksStarted?.run() cleanupProcessedFlag() for (project in ProjectUtil.getOpenProjects()) { UnindexedFilesUpdater(project, reason).queue(project) } LOG.info("Index rescanning has been started after `$reason`") } else { LOG.info("Index rescanning has been skipped after `$reason`") } } finally { fileTypeTracker?.let { Disposer.dispose(it) } fileTypeTracker = null snapshot = null } } } companion object { private val LOG = logger<FileBasedIndexTumbler>() private class MyDumbModeTask(val semaphore: Semaphore) : DumbModeTask() { override fun performInDumbMode(indicator: ProgressIndicator) { indicator.text = IndexingBundle.message("indexes.reloading") semaphore.waitFor() } override fun toString(): String { return "Plugin loading/unloading" } override fun tryMergeWith(taskFromQueue: DumbModeTask): DumbModeTask? = if (taskFromQueue is MyDumbModeTask && taskFromQueue.semaphore === semaphore) this else null } } } internal sealed class FbiSnapshot { internal object RebuildRequired : FbiSnapshot() internal data class Impl(private val ideIndexVersion: MyIdeIndexVersion) : FbiSnapshot() { companion object { fun capture(): Impl { val additionalLibraryRootsProvider: SortedSet<String> = AdditionalLibraryRootsProvider.EP_NAME.extensionList.map { it.toString() }.toSortedSet() val indexableSetContributor: SortedSet<String> = IndexableSetContributor.EP_NAME.extensionList.map { it.debugName }.toSortedSet() val baseIndexes: Map<String, String> = emptyMap() val fileBasedIndexVersions = IndexInfrastructureVersionBase.fileBasedIndexVersions(FileBasedIndexExtension.EXTENSION_POINT_NAME.extensionList) { it.version.toString() } val stubIndexVersions = IndexInfrastructureVersionBase.stubIndexVersions(StubIndexExtension.EP_NAME.extensionList) val stubFileElementTypeVersions = IndexInfrastructureVersionBase.stubFileElementTypeVersions() val compositeBinaryStubFileBuilderVersions = IndexInfrastructureVersionBase.getAllCompositeBinaryFileStubBuilderVersions() return Impl(MyIdeIndexVersion(additionalLibraryRootsProvider, indexableSetContributor, baseIndexes, fileBasedIndexVersions, stubIndexVersions, stubFileElementTypeVersions, compositeBinaryStubFileBuilderVersions)) } fun isRescanningRequired(oldFbiSnapshot: Impl, newFbiSnapshot: Impl): Boolean { val oldVersion = oldFbiSnapshot.ideIndexVersion val newVersion = newFbiSnapshot.ideIndexVersion if (oldVersion.myBaseIndexes != newVersion.myBaseIndexes) { return true } if (oldVersion.myStubFileElementTypeVersions != newVersion.myStubFileElementTypeVersions) { return true } if (oldVersion.myCompositeBinaryStubFileBuilderVersions != newVersion.myCompositeBinaryStubFileBuilderVersions) { return true } if (oldVersion.myStubIndexVersions != newVersion.myStubIndexVersions) { return true } if (oldVersion.myFileBasedIndexVersions.entries.containsAll(newVersion.myFileBasedIndexVersions.entries) && oldVersion.additionalLibraryRootsProvider.containsAll(newVersion.additionalLibraryRootsProvider) && oldVersion.indexableSetContributor.containsAll(newVersion.indexableSetContributor)) { return false } return true } } } } internal class MyIdeIndexVersion(val additionalLibraryRootsProvider: SortedSet<String>, val indexableSetContributor: SortedSet<String>, baseIndexes: Map<String, String>, fileBasedIndexVersions: Map<String, FileBasedIndexVersionInfo>, stubIndexVersions: Map<String, String>, stubFileElementTypeVersions: Map<String, String>, compositeBinaryStubFileBuilderVersions: Map<String, String>) : IndexInfrastructureVersionBase( baseIndexes, fileBasedIndexVersions, stubIndexVersions, stubFileElementTypeVersions, compositeBinaryStubFileBuilderVersions) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as MyIdeIndexVersion if (additionalLibraryRootsProvider != other.additionalLibraryRootsProvider) return false if (indexableSetContributor != other.indexableSetContributor) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + additionalLibraryRootsProvider.hashCode() result = 31 * result + indexableSetContributor.hashCode() return result } } private class FileTypeTracker: Disposable { var changed: Boolean = false init { ApplicationManager.getApplication().messageBus.connect(this).subscribe(FileTypeManager.TOPIC, object : FileTypeListener { override fun beforeFileTypesChanged(event: FileTypeEvent) { changed = true } }) } override fun dispose() = Unit }
apache-2.0
24ffbc190dbb52a0484b44baa756fd90
38.331897
158
0.688404
5.231651
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddAnnotationTargetFix.kt
2
10111
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors.WRONG_ANNOTATION_TARGET import org.jetbrains.kotlin.diagnostics.Errors.WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.runOnExpectAndAllActuals import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.AnnotationTargetLists.EMPTY import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_CLASSIFIER import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_CONSTRUCTOR import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_EXPRESSION import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_LOCAL_VARIABLE import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_MEMBER_FUNCTION import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_MEMBER_PROPERTY import org.jetbrains.kotlin.resolve.AnnotationTargetLists.T_VALUE_PARAMETER_WITHOUT_VAL import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddAnnotationTargetFix(annotationEntry: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry) { override fun getText() = KotlinBundle.message("fix.add.annotation.target") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val annotationEntry = element ?: return val (annotationClass, annotationClassDescriptor) = annotationEntry.toAnnotationClass() ?: return val requiredAnnotationTargets = annotationEntry.getRequiredAnnotationTargets(annotationClass, annotationClassDescriptor, project) if (requiredAnnotationTargets.isEmpty()) return val psiFactory = KtPsiFactory(annotationEntry) annotationClass.runOnExpectAndAllActuals(useOnSelf = true) { it.safeAs<KtClass>()?.addAnnotationTargets(requiredAnnotationTargets, psiFactory) } } companion object : KotlinSingleIntentionActionFactory() { private fun KtAnnotationEntry.toAnnotationClass(): Pair<KtClass, ClassDescriptor>? { val context = analyze(BodyResolveMode.PARTIAL) val annotationDescriptor = context[BindingContext.ANNOTATION, this] ?: return null val annotationTypeDescriptor = annotationDescriptor.type.constructor.declarationDescriptor as? ClassDescriptor ?: return null val annotationClass = (DescriptorToSourceUtils.descriptorToDeclaration(annotationTypeDescriptor) as? KtClass)?.takeIf { it.isAnnotation() && it.isWritable } ?: return null return annotationClass to annotationTypeDescriptor } override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtAnnotationEntry>? { if (diagnostic.factory != WRONG_ANNOTATION_TARGET && diagnostic.factory != WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET) { return null } val entry = diagnostic.psiElement as? KtAnnotationEntry ?: return null val (annotationClass, annotationClassDescriptor) = entry.toAnnotationClass() ?: return null if (entry.getRequiredAnnotationTargets(annotationClass, annotationClassDescriptor, entry.project).isEmpty()) return null return AddAnnotationTargetFix(entry) } } } private fun KtAnnotationEntry.getRequiredAnnotationTargets( annotationClass: KtClass, annotationClassDescriptor: ClassDescriptor, project: Project ): List<KotlinTarget> { val ignoreAnnotationTargets = if (annotationClassDescriptor.hasRequiresOptInAnnotation()) { setOf(AnnotationTarget.EXPRESSION, AnnotationTarget.FILE, AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER) } else emptySet() val annotationTargetValueNames = AnnotationTarget.values().toSet().minus(ignoreAnnotationTargets).map { it.name } if (annotationTargetValueNames.isEmpty()) return emptyList() val requiredTargets = getActualTargetList() if (requiredTargets.isEmpty()) return emptyList() val searchScope = GlobalSearchScope.allScope(project) val otherReferenceRequiredTargets = ReferencesSearch.search(annotationClass, searchScope).mapNotNull { reference -> if (reference.element is KtNameReferenceExpression) { // Kotlin annotation reference.element.getNonStrictParentOfType<KtAnnotationEntry>()?.takeIf { it != this }?.getActualTargetList() } else { // Java annotation (reference.element.parent as? PsiAnnotation)?.getActualTargetList() } }.flatten().toSet() return (requiredTargets + otherReferenceRequiredTargets).asSequence() .distinct() .filter { it.name in annotationTargetValueNames } .sorted() .toList() } private fun ClassDescriptor.hasRequiresOptInAnnotation() = annotations.any { it.fqName == FqName("kotlin.RequiresOptIn") } private fun getActualTargetList(annotated: PsiTarget): AnnotationTargetList { return when (annotated) { is PsiClass -> T_CLASSIFIER is PsiMethod -> when { annotated.isConstructor -> T_CONSTRUCTOR else -> T_MEMBER_FUNCTION } is PsiExpression -> T_EXPRESSION is PsiField -> T_MEMBER_PROPERTY(backingField = true, delegate = false) is PsiLocalVariable -> T_LOCAL_VARIABLE is PsiParameter -> T_VALUE_PARAMETER_WITHOUT_VAL else -> EMPTY } } private fun PsiAnnotation.getActualTargetList(): List<KotlinTarget> { val annotated = parent.parent as? PsiTarget ?: return emptyList() return getActualTargetList(annotated).defaultTargets } private fun KtAnnotationEntry.getActualTargetList(): List<KotlinTarget> { val annotatedElement = getStrictParentOfType<KtModifierList>()?.owner as? KtElement ?: getStrictParentOfType<KtAnnotatedExpression>()?.baseExpression ?: getStrictParentOfType<KtFile>() ?: return emptyList() val targetList = AnnotationChecker.getActualTargetList(annotatedElement, null, BindingTraceContext().bindingContext) val useSiteTarget = this.useSiteTarget ?: return targetList.defaultTargets val annotationUseSiteTarget = useSiteTarget.getAnnotationUseSiteTarget() val target = KotlinTarget.USE_SITE_MAPPING[annotationUseSiteTarget] ?: return emptyList() if (annotationUseSiteTarget == AnnotationUseSiteTarget.FIELD) { if (KotlinTarget.MEMBER_PROPERTY !in targetList.defaultTargets && KotlinTarget.TOP_LEVEL_PROPERTY !in targetList.defaultTargets) { return emptyList() } val property = annotatedElement as? KtProperty if (property != null && (LightClassUtil.getLightClassPropertyMethods(property).backingField == null || property.hasDelegate())) { return emptyList() } } else { if (target !in with(targetList) { defaultTargets + canBeSubstituted + onlyWithUseSiteTarget }) { return emptyList() } } return listOf(target) } private fun KtClass.addAnnotationTargets(annotationTargets: List<KotlinTarget>, psiFactory: KtPsiFactory) { val retentionAnnotationName = StandardNames.FqNames.retention.shortName().asString() if (annotationTargets.any { it == KotlinTarget.EXPRESSION }) { val retentionEntry = annotationEntries.firstOrNull { it.typeReference?.text == retentionAnnotationName } val newRetentionEntry = psiFactory.createAnnotationEntry( "@$retentionAnnotationName(${StandardNames.FqNames.annotationRetention.shortName()}.${AnnotationRetention.SOURCE.name})" ) if (retentionEntry == null) { addAnnotationEntry(newRetentionEntry) } else { retentionEntry.replace(newRetentionEntry) } } val targetAnnotationName = StandardNames.FqNames.target.shortName().asString() val targetAnnotationEntry = annotationEntries.find { it.typeReference?.text == targetAnnotationName } ?: run { val text = "@$targetAnnotationName${annotationTargets.toArgumentListString()}" addAnnotationEntry(psiFactory.createAnnotationEntry(text)) return } val valueArgumentList = targetAnnotationEntry.valueArgumentList if (valueArgumentList == null) { val text = annotationTargets.toArgumentListString() targetAnnotationEntry.add(psiFactory.createCallArguments(text)) } else { val arguments = targetAnnotationEntry.valueArguments.mapNotNull { it.getArgumentExpression()?.text } for (target in annotationTargets) { val text = target.asNameString() if (text !in arguments) valueArgumentList.addArgument(psiFactory.createArgument(text)) } } } private fun List<KotlinTarget>.toArgumentListString() = joinToString(separator = ", ", prefix = "(", postfix = ")") { it.asNameString() } private fun KotlinTarget.asNameString() = "${StandardNames.FqNames.annotationTarget.shortName().asString()}.$name"
apache-2.0
fea9f1fdcf6c972d628947a36b053403
49.054455
158
0.745821
5.358241
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/mock/factories/PXClientFactory.kt
1
2146
package com.kickstarter.mock.factories import android.content.Context import com.kickstarter.libs.Build import com.kickstarter.libs.perimeterx.PerimeterXClient import okhttp3.Response import rx.Observable import rx.subjects.PublishSubject import java.util.HashMap open class MockPXClient(build: Build) : PerimeterXClient(build) { private val headers: PublishSubject<HashMap<String, String>> = PublishSubject.create() private val isManagerReady: PublishSubject<Boolean> = PublishSubject.create() private val captchaSuccess: PublishSubject<Boolean> = PublishSubject.create() override val headersAdded: Observable<HashMap<String, String>> get() = this.headers override val isCaptchaSuccess: Observable<Boolean> get() = this.captchaSuccess override val isReady: Observable<Boolean> get() = this.isManagerReady override fun visitorId() = "VID" override fun httpHeaders(): MutableMap<String, String> = mutableMapOf("h1" to "value1", "h2" to "value2") override fun start(context: Context) { headers.onNext(hashMapOf()) isManagerReady.onNext(true) } override fun isChallenged(body: String) = true override fun intercept(response: Response) { captchaSuccess.onNext(true) } } class MockPXClientNotChallenged(build: Build) : MockPXClient(build) { override fun isChallenged(body: String) = false override fun intercept(response: Response) { // no captcha emitted } } class MockPXClientCaptchaCanceled(build: Build) : MockPXClient(build) { private val captchaCanceled: PublishSubject<String> = PublishSubject.create() override val isCaptchaCanceled: Observable<String> get() = this.captchaCanceled override fun intercept(response: Response) { captchaCanceled.onNext("Back Button") } } class PXClientFactory private constructor() { companion object { fun pxChallengedSuccessful(build: Build) = MockPXClient(build) fun pxChallengedCanceled(build: Build) = MockPXClientCaptchaCanceled(build) fun pxNotChallenged(build: Build) = MockPXClientNotChallenged(build) } }
apache-2.0
5a56ebb0f47638f33d7a60899a6f821d
33.063492
109
0.732992
4.34413
false
false
false
false
ingokegel/intellij-community
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUi.kt
1
17554
// 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.ui.branch.dashboard import com.intellij.dvcs.branch.GroupingKey import com.intellij.icons.AllIcons import com.intellij.ide.CommonActionsManager import com.intellij.ide.DataManager import com.intellij.ide.DefaultTreeExpander import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ActionPlaces.VCS_LOG_BRANCHES_PLACE import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.IdeBorderFactory.createBorder import com.intellij.ui.JBColor import com.intellij.ui.OnePixelSplitter import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.speedSearch.SpeedSearch import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.StatusText.getDefaultEmptyText import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy import com.intellij.vcs.log.VcsLogBranchLikeFilter import com.intellij.vcs.log.VcsLogFilterCollection import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogApplicationSettings import com.intellij.vcs.log.impl.VcsLogContentProvider.MAIN_LOG_ID import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.impl.VcsLogManager.BaseVcsLogUiFactory import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties import com.intellij.vcs.log.ui.VcsLogColorManager import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import com.intellij.vcs.log.ui.VcsLogUiImpl import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx import com.intellij.vcs.log.ui.frame.MainFrame import com.intellij.vcs.log.ui.frame.ProgressStripe import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.VisiblePackRefresher import com.intellij.vcs.log.visible.VisiblePackRefresherImpl import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import com.intellij.vcs.log.visible.filters.with import com.intellij.vcs.log.visible.filters.without import git4idea.i18n.GitBundle.message import git4idea.i18n.GitBundleExtensions.messagePointer import git4idea.repo.GitRepository import git4idea.ui.branch.dashboard.BranchesDashboardActions.DeleteBranchAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.FetchAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.NewBranchAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowBranchDiffAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowMyBranchesAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.ToggleFavoriteAction import git4idea.ui.branch.dashboard.BranchesDashboardActions.UpdateSelectedBranchAction import org.jetbrains.annotations.ApiStatus import java.awt.Component import java.awt.datatransfer.DataFlavor import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JComponent import javax.swing.TransferHandler import javax.swing.event.TreeSelectionListener internal class BranchesDashboardUi(project: Project, private val logUi: BranchesVcsLogUi) : Disposable { private val uiController = BranchesDashboardController(project, this) private val tree = BranchesTreeComponent(project).apply { accessibleContext.accessibleName = message("git.log.branches.tree.accessible.name") } private val filteringTree = FilteringBranchesTree(project, tree, uiController, place = VCS_LOG_BRANCHES_PLACE, disposable = this) private val branchViewSplitter = BranchViewSplitter() private val branchesTreePanel = BranchesTreePanel().withBorder(createBorder(JBColor.border(), SideBorder.LEFT)) private val branchesScrollPane = ScrollPaneFactory.createScrollPane(filteringTree.component, true) private val branchesProgressStripe = ProgressStripe(branchesScrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) private val branchesTreeWithLogPanel = simplePanel() private val mainPanel = simplePanel().apply { DataManager.registerDataProvider(this, uiController) } private val branchesSearchFieldPanel = simplePanel() private val branchesSearchField = filteringTree.installSearchField().apply { textEditor.border = JBUI.Borders.emptyLeft(5) accessibleContext.accessibleName = message("git.log.branches.search.field.accessible.name") // fixme: this needs to be dynamic accessibleContext.accessibleDescription = message("git.log.branches.search.field.accessible.description", KeymapUtil.getFirstKeyboardShortcutText("Vcs.Log.FocusTextFilter")) } private val branchesSearchFieldWrapper = NonOpaquePanel(branchesSearchField).apply(UIUtil::setNotOpaqueRecursively) private lateinit var branchesPanelExpandableController: ExpandablePanelController private val treeSelectionListener = TreeSelectionListener { if (!branchesPanelExpandableController.isExpanded()) return@TreeSelectionListener val ui = logUi val properties = ui.properties if (properties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) { updateLogBranchFilter() } else if (properties[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY]) { navigateToSelectedBranch(false) } } internal fun updateLogBranchFilter() { val ui = logUi val selectedFilters = filteringTree.getSelectedBranchFilters() val oldFilters = ui.filterUi.filters val newFilters = if (selectedFilters.isNotEmpty()) { oldFilters.without(VcsLogBranchLikeFilter::class.java).with(VcsLogFilterObject.fromBranches(selectedFilters)) } else { oldFilters.without(VcsLogBranchLikeFilter::class.java) } ui.filterUi.filters = newFilters } internal fun navigateToSelectedBranch(focus: Boolean) { val selectedReference = filteringTree.getSelectedBranchFilters().singleOrNull() ?: return logUi.vcsLog.jumpToReference(selectedReference, focus) } internal fun toggleGrouping(key: GroupingKey, state: Boolean) { filteringTree.toggleGrouping(key, state) } internal fun isGroupingEnabled(key: GroupingKey) = filteringTree.isGroupingEnabled(key) internal fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> { return filteringTree.getSelectedRepositories(branchInfo) } internal fun getSelectedRemotes(): Set<RemoteInfo> { return filteringTree.getSelectedRemotes() } internal fun getRootsToFilter(): Set<VirtualFile> { val roots = logUi.logData.roots.toSet() if (roots.size == 1) return roots return VcsLogUtil.getAllVisibleRoots(roots, logUi.filterUi.filters) } private val BRANCHES_UI_FOCUS_TRAVERSAL_POLICY = object : ComponentsListFocusTraversalPolicy() { override fun getOrderedComponents(): List<Component> = listOf(filteringTree.component, logUi.table, logUi.changesBrowser.preferredFocusedComponent, logUi.filterUi.textFilterComponent.textEditor) } private val showBranches get() = logUi.properties.get(SHOW_GIT_BRANCHES_LOG_PROPERTY) init { initMainUi() installLogUi() toggleBranchesPanelVisibility() } @RequiresEdt private fun installLogUi() { uiController.registerDataPackListener(logUi.logData) uiController.registerLogUiPropertiesListener(logUi.properties) uiController.registerLogUiFilterListener(logUi.filterUi) branchesSearchFieldWrapper.setVerticalSizeReferent(logUi.toolbar) branchViewSplitter.secondComponent = logUi.mainLogComponent mainPanel.add(branchesTreeWithLogPanel) filteringTree.component.addTreeSelectionListener(treeSelectionListener) } @RequiresEdt private fun disposeBranchesUi() { branchViewSplitter.secondComponent.removeAll() uiController.removeDataPackListener(logUi.logData) uiController.removeLogUiPropertiesListener(logUi.properties) filteringTree.component.removeTreeSelectionListener(treeSelectionListener) } private fun initMainUi() { val diffAction = ShowBranchDiffAction() diffAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Diff.ShowDiff"), branchesTreeWithLogPanel) val deleteAction = DeleteBranchAction() val shortcuts = KeymapUtil.getActiveKeymapShortcuts("SafeDelete").shortcuts + KeymapUtil.getActiveKeymapShortcuts( "EditorDeleteToLineStart").shortcuts deleteAction.registerCustomShortcutSet(CustomShortcutSet(*shortcuts), branchesTreeWithLogPanel) createFocusFilterFieldAction(branchesSearchFieldWrapper) installPasteAction(filteringTree) val toggleFavoriteAction = ToggleFavoriteAction() val fetchAction = FetchAction(this) val showMyBranchesAction = ShowMyBranchesAction(uiController) val newBranchAction = NewBranchAction() val updateSelectedAction = UpdateSelectedBranchAction() val defaultTreeExpander = DefaultTreeExpander(filteringTree.component) val commonActionsManager = CommonActionsManager.getInstance() val expandAllAction = commonActionsManager.createExpandAllHeaderAction(defaultTreeExpander, branchesTreePanel) val collapseAllAction = commonActionsManager.createCollapseAllHeaderAction(defaultTreeExpander, branchesTreePanel) val actionManager = ActionManager.getInstance() val hideBranchesAction = actionManager.getAction("Git.Log.Hide.Branches") val settings = actionManager.getAction("Git.Log.Branches.Settings") val group = DefaultActionGroup() group.add(hideBranchesAction) group.add(Separator()) group.add(newBranchAction) group.add(updateSelectedAction) group.add(deleteAction) group.add(diffAction) group.add(showMyBranchesAction) group.add(fetchAction) group.add(toggleFavoriteAction) group.add(actionManager.getAction("Git.Log.Branches.Navigate.Log.To.Selected.Branch")) group.add(Separator()) group.add(settings) group.add(actionManager.getAction("Git.Log.Branches.Grouping.Settings")) group.add(expandAllAction) group.add(collapseAllAction) val toolbar = actionManager.createActionToolbar("Git.Log.Branches", group, false) toolbar.setTargetComponent(branchesTreePanel) val branchesButton = ExpandStripeButton(messagePointer("action.Git.Log.Show.Branches.text"), AllIcons.Actions.ArrowExpand) .apply { border = createBorder(JBColor.border(), SideBorder.RIGHT) addActionListener { if (logUi.properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) { logUi.properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, true) } } } branchesSearchFieldPanel.withBackground(UIUtil.getListBackground()).withBorder(createBorder(JBColor.border(), SideBorder.BOTTOM)) branchesSearchFieldPanel.addToCenter(branchesSearchFieldWrapper) branchesTreePanel.addToTop(branchesSearchFieldPanel).addToCenter(branchesProgressStripe) branchesPanelExpandableController = ExpandablePanelController(toolbar.component, branchesButton, branchesTreePanel) branchViewSplitter.firstComponent = branchesTreePanel branchesTreeWithLogPanel.addToLeft(branchesPanelExpandableController.expandControlPanel).addToCenter(branchViewSplitter) mainPanel.isFocusCycleRoot = true mainPanel.focusTraversalPolicy = BRANCHES_UI_FOCUS_TRAVERSAL_POLICY } fun toggleBranchesPanelVisibility() { branchesPanelExpandableController.toggleExpand(showBranches) updateBranchesTree(true) } private fun createFocusFilterFieldAction(searchField: Component) { DumbAwareAction.create { e -> val project = e.getRequiredData(CommonDataKeys.PROJECT) if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(filteringTree.component) != null) { IdeFocusManager.getInstance(project).requestFocus(searchField, true) } else { IdeFocusManager.getInstance(project).requestFocus(filteringTree.component, true) } }.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Find"), branchesTreePanel) } private fun installPasteAction(tree: FilteringBranchesTree) { tree.component.actionMap.put(TransferHandler.getPasteAction().getValue(Action.NAME), object: AbstractAction () { override fun actionPerformed(e: ActionEvent?) { val speedSearch = tree.searchModel.speedSearch as? SpeedSearch ?: return val pasteContent = CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor) // the same filtering logic as in javax.swing.text.PlainDocument.insertString (e.g. DnD to search field) ?.let { StringUtil.convertLineSeparators(it, " ") } speedSearch.type(pasteContent) speedSearch.update() } }) } inner class BranchesTreePanel : BorderLayoutPanel(), DataProvider { override fun getData(dataId: String): Any? { return when { GIT_BRANCHES.`is`(dataId) -> filteringTree.getSelectedBranches() GIT_BRANCH_FILTERS.`is`(dataId) -> filteringTree.getSelectedBranchFilters() BRANCHES_UI_CONTROLLER.`is`(dataId) -> uiController VcsLogInternalDataKeys.LOG_UI_PROPERTIES.`is`(dataId) -> logUi.properties else -> null } } } fun getMainComponent(): JComponent { return mainPanel } fun updateBranchesTree(initial: Boolean) { if (showBranches) { filteringTree.update(initial) } } fun refreshTree() { filteringTree.refreshTree() } fun refreshTreeModel() { filteringTree.refreshNodeDescriptorsModel() } fun startLoadingBranches() { filteringTree.component.emptyText.text = message("action.Git.Loading.Branches.progress") branchesTreePanel.isEnabled = false branchesProgressStripe.startLoading() } fun stopLoadingBranches() { filteringTree.component.emptyText.text = getDefaultEmptyText() branchesTreePanel.isEnabled = true branchesProgressStripe.stopLoading() } override fun dispose() { disposeBranchesUi() } } internal class BranchesVcsLogUiFactory(logManager: VcsLogManager, logId: String, filters: VcsLogFilterCollection? = null) : BaseVcsLogUiFactory<BranchesVcsLogUi>(logId, filters, logManager.uiProperties, logManager.colorManager) { override fun createVcsLogUiImpl(logId: String, logData: VcsLogData, properties: MainVcsLogUiProperties, colorManager: VcsLogColorManager, refresher: VisiblePackRefresherImpl, filters: VcsLogFilterCollection?) = BranchesVcsLogUi(logId, logData, colorManager, properties, refresher, filters) } internal class BranchesVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager, uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher, initialFilters: VcsLogFilterCollection?) : VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, initialFilters) { private val branchesUi = BranchesDashboardUi(logData.project, this) .also { branchesUi -> Disposer.register(this, branchesUi) } internal val mainLogComponent: JComponent get() = mainFrame internal val changesBrowser: ChangesBrowserBase get() = mainFrame.changesBrowser override fun createMainFrame(logData: VcsLogData, uiProperties: MainVcsLogUiProperties, filterUi: VcsLogFilterUiEx, isEditorDiffPreview: Boolean) = MainFrame(logData, this, uiProperties, filterUi, isEditorDiffPreview, this) .apply { isFocusCycleRoot = false focusTraversalPolicy = null //new focus traversal policy will be configured include branches tree } override fun getMainComponent() = branchesUi.getMainComponent() } @ApiStatus.Internal val SHOW_GIT_BRANCHES_LOG_PROPERTY = object : VcsLogProjectTabsProperties.CustomBooleanTabProperty("Show.Git.Branches") { override fun defaultValue(logId: String) = logId == MAIN_LOG_ID } @ApiStatus.Internal val CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY = object : VcsLogApplicationSettings.CustomBooleanProperty("Change.Log.Filter.on.Branch.Selection") { override fun defaultValue() = false } @ApiStatus.Internal val NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY = object : VcsLogApplicationSettings.CustomBooleanProperty("Navigate.Log.To.Branch.on.Branch.Selection") { override fun defaultValue() = false } private class BranchViewSplitter(first: JComponent? = null, second: JComponent? = null) : OnePixelSplitter(false, "vcs.branch.view.splitter.proportion", 0.3f) { init { firstComponent = first secondComponent = second } }
apache-2.0
7a85d5f2aaae942d5c9e4b293b3cd305
43.780612
140
0.77498
5.060248
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/database/playlist/PlaylistStreamEntry.kt
3
1362
package org.schabi.newpipe.database.playlist import androidx.room.ColumnInfo import androidx.room.Embedded import org.schabi.newpipe.database.LocalItem import org.schabi.newpipe.database.playlist.model.PlaylistStreamEntity import org.schabi.newpipe.database.stream.model.StreamEntity import org.schabi.newpipe.database.stream.model.StreamStateEntity import org.schabi.newpipe.extractor.stream.StreamInfoItem data class PlaylistStreamEntry( @Embedded val streamEntity: StreamEntity, @ColumnInfo(name = StreamStateEntity.STREAM_PROGRESS_MILLIS, defaultValue = "0") val progressMillis: Long, @ColumnInfo(name = PlaylistStreamEntity.JOIN_STREAM_ID) val streamId: Long, @ColumnInfo(name = PlaylistStreamEntity.JOIN_INDEX) val joinIndex: Int ) : LocalItem { @Throws(IllegalArgumentException::class) fun toStreamInfoItem(): StreamInfoItem { val item = StreamInfoItem(streamEntity.serviceId, streamEntity.url, streamEntity.title, streamEntity.streamType) item.duration = streamEntity.duration item.uploaderName = streamEntity.uploader item.uploaderUrl = streamEntity.uploaderUrl item.thumbnailUrl = streamEntity.thumbnailUrl return item } override fun getLocalItemType(): LocalItem.LocalItemType { return LocalItem.LocalItemType.PLAYLIST_STREAM_ITEM } }
gpl-3.0
7f638a58d3b6db49a102f2d79f1eba2e
33.923077
120
0.769457
4.480263
false
false
false
false
josecefe/Rueda
src/es/um/josecefe/rueda/resolutor/Nodo.kt
1
8103
/* * Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero * * 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 es.um.josecefe.rueda.resolutor import es.um.josecefe.rueda.modelo.AsignacionDiaV5 import es.um.josecefe.rueda.modelo.Dia import java.util.* /** * Nodo * Clase que se usa por diversor Resolutores como nodo del árbol de busqueda. * * @author josecefe */ internal class Nodo : Comparable<Nodo> { companion object { private const val DEBUG = true } private val padre: Nodo? private val eleccion: AsignacionDiaV5? private val vecesConductor: ByteArray val nivel: Int private val costeAcumulado: Int val cotaInferior: Int val cotaSuperior: Int private val contexto: ContextoResolucionHeuristico var costeEstimado: Int = 0 private set constructor(contexto: ContextoResolucionHeuristico) { this.contexto = contexto padre = null eleccion = null vecesConductor = ByteArray(contexto.participantes.size) cotaInferior = 0 costeAcumulado = cotaInferior cotaSuperior = Integer.MAX_VALUE costeEstimado = cotaSuperior nivel = -1 } private constructor(padre: Nodo, nuevaAsignacion: AsignacionDiaV5, contexto: ContextoResolucionHeuristico) { this.contexto = contexto this.padre = padre nivel = padre.nivel + 1 eleccion = nuevaAsignacion costeAcumulado = padre.costeAcumulado + nuevaAsignacion.coste vecesConductor = padre.vecesConductor.copyOf(padre.vecesConductor.size) val conductores = nuevaAsignacion.conductoresArray var maximo = 0 var maxCS = 0 var maxCI = 0 var total = 0 var totalMinRes = 0 var totalMaxRes = 0 var minimo = Integer.MAX_VALUE var minCI = Integer.MAX_VALUE var minCS = Integer.MAX_VALUE val terminal = contexto.dias.size == nivel + 1 //int sum = 0; //nuevaAsignacion.getConductores().stream().forEachOrdered(ic -> ++vecesConductor[ic]); for (i in vecesConductor.indices) { if (contexto.participantesConCoche[i]) { //sum = vecesConductor[i]; if (conductores[i]) { ++vecesConductor[i] } total += vecesConductor[i].toInt() val vecesConductorVirt = (vecesConductor[i].toFloat() * contexto.coefConduccion[i] + 0.5f).toInt() if (vecesConductorVirt > maximo) { maximo = vecesConductorVirt } if (vecesConductorVirt < minimo) { minimo = vecesConductorVirt } if (!terminal) { val vecesConductorVirtCS = (((vecesConductor[i] + contexto.maxVecesCondDia[contexto.ordenExploracionDias[nivel + 1]][i]) * contexto.coefConduccion[i]) + 0.5f).toInt() if (vecesConductorVirtCS > maxCS) { maxCS = vecesConductorVirtCS } if (vecesConductorVirtCS < minCS) { minCS = vecesConductorVirtCS } val vecesConductorVirtCI = (((vecesConductor[i] + contexto.minVecesCondDia[contexto.ordenExploracionDias[nivel + 1]][i]) * contexto.coefConduccion[i]) + 0.5f).toInt() if (vecesConductorVirtCI > maxCI) { maxCI = vecesConductorVirtCI } if (vecesConductorVirtCI < minCI) { minCI = vecesConductorVirtCI } if (contexto.estrategia == Resolutor.Estrategia.MINCONDUCTORES) { totalMaxRes += contexto.maxVecesCondDia[contexto.ordenExploracionDias[nivel + 1]][i] totalMinRes += contexto.minVecesCondDia[contexto.ordenExploracionDias[nivel + 1]][i] } } } } if (terminal) { //Es terminal if (contexto.estrategia == Resolutor.Estrategia.EQUILIBRADO) { cotaInferior = maximo * PESO_MAXIMO_VECES_CONDUCTOR + (maximo - minimo) * PESO_DIF_MAX_MIN_VECES_CONDUCTOR + costeAcumulado cotaSuperior = cotaInferior } else { // estrategia == Estrategia.MINCONDUCTORES cotaInferior = maximo * PESO_MAXIMO_VECES_CONDUCTOR + total * PESO_TOTAL_CONDUCTORES + (maximo - minimo) * PESO_DIF_MAX_MIN_VECES_CONDUCTOR + costeAcumulado cotaSuperior = cotaInferior } } else if (contexto.estrategia == Resolutor.Estrategia.EQUILIBRADO) { cotaInferior = maxCI * PESO_MAXIMO_VECES_CONDUCTOR + (maxCI - minCS) * PESO_DIF_MAX_MIN_VECES_CONDUCTOR + costeAcumulado + contexto.mejorCosteDia[contexto.ordenExploracionDias[nivel + 1]] cotaSuperior = maxCS * PESO_MAXIMO_VECES_CONDUCTOR + (maxCS - minCI) * PESO_DIF_MAX_MIN_VECES_CONDUCTOR + costeAcumulado + contexto.peorCosteDia[contexto.ordenExploracionDias[nivel + 1]] + 1 // Añadimos el 1 para evitar un bug que nos haría perder una solución } else { // estrategia == Estrategia.MINCONDUCTORES cotaInferior = maxCI * PESO_MAXIMO_VECES_CONDUCTOR + (total + totalMinRes) * PESO_TOTAL_CONDUCTORES + (maxCI - minCS) * PESO_DIF_MAX_MIN_VECES_CONDUCTOR + costeAcumulado + contexto.mejorCosteDia[contexto.ordenExploracionDias[nivel + 1]] cotaSuperior = maxCS * PESO_MAXIMO_VECES_CONDUCTOR + (total + totalMaxRes) * PESO_TOTAL_CONDUCTORES + (maxCS - minCI) * PESO_DIF_MAX_MIN_VECES_CONDUCTOR + costeAcumulado + contexto.peorCosteDia[contexto.ordenExploracionDias[nivel + 1]] + 1 // Añadimos el 1 para evitar un bug que nos haría perder una solución } if (DEBUG && (cotaInferior < padre.cotaInferior || cotaSuperior > padre.cotaSuperior || cotaSuperior < cotaInferior)) { System.err.println("*****************\n**** ¡LIADA!:\n --> Padre=$padre\n --> Hijo=${this}") } calculaCosteEstimado() } fun calculaCosteEstimado() { costeEstimado = (contexto.pesoCotaInferiorNum * cotaInferior + cotaSuperior * (contexto.pesoCotaInferiorDen - contexto.pesoCotaInferiorNum)) / contexto.pesoCotaInferiorDen } private val dia: Dia? get() = if (nivel >= 0) contexto.dias[contexto.ordenExploracionDias[nivel]] else null val solucion: MutableMap<Dia, AsignacionDiaV5> get() { val solucion: MutableMap<Dia, AsignacionDiaV5> = padre?.solucion ?: HashMap() if (nivel >= 0) { solucion[dia!!] = eleccion!! } return solucion } fun generaHijos(): List<Nodo> = contexto.solucionesCandidatas[contexto.dias[contexto.ordenExploracionDias[nivel + 1]]]!!.map { generaHijo(it) } private fun generaHijo(solDia: AsignacionDiaV5): Nodo = Nodo(this, solDia, contexto) override fun compareTo(other: Nodo): Int { return costeEstimado - other.costeEstimado } override fun hashCode(): Int { return Objects.hash(this.eleccion, padre, nivel) } override fun equals(other: Any?): Boolean = this === other || (other != null && other is Nodo && nivel == other.nivel && eleccion == other.eleccion && padre == other.padre) override fun toString(): String = String.format("Nodo{nivel=%d, estimado=%,d, inferior=%,d, superior=%,d}", nivel, costeEstimado, cotaInferior, cotaSuperior) }
gpl-3.0
8588bca72bc18724cac51fbd05dc72a5
49.59375
321
0.632119
3.536479
false
false
false
false
vovagrechka/fucking-everything
pieces/pieces-100/src/main/java/pieces100/Context1.kt
1
4214
package pieces100 //import alraune.* import vgrechka.* import java.sql.Timestamp class Context1 private constructor() : WithDebugId by WithDebugId.Impl(this) , WithPlaceholderStrings by WithPlaceholderStrings.Impl() { val deferredJsShitters = mutableListOf<() -> Unit>() val ftbShitters = mutableListOf<(JSScriptBuilder) -> Unit>() var titleInput by notNullOnce<TextControlBuilder.begin>(noisy) var filePicker by notNullOnce<FilePicker>(noisy) val buttonBars = mutableListOf<ButtonBarWithTicker>() val errorBannerDomid by nextJsIdentDel() val jsOnDomReady by JsBufferWithPlaceholders(beforeCodeObtained = {lazyRunDeferredJsShitters}) val jsOnShown by JsBufferWithPlaceholders(beforeCodeObtained = {lazyRunDeferredJsShitters}) var jsDefaultFormAction by PlaceholderString("console.log('Kinda default action')") var overwriteOptimisticShit = false var skipWritingToDatabase = false var stuff = Context1Stuff() var projectStuff = Context1ProjectStuff() var propComparison = PropComparison(); class PropComparison { val text = Text(); class Text { var before: String? = null var after: String? = null } } fun withStuff(amend: (Context1Stuff) -> Context1Stuff, block: () -> Unit) { val orig = stuff try { stuff = amend(stuff) block() } finally { stuff = orig } } fun <T> withProjectStuff(amend: (Context1ProjectStuff) -> Context1ProjectStuff, block: () -> T): T { val orig = projectStuff try { projectStuff = amend(projectStuff) return block() } finally { projectStuff = orig } } companion object { val noisy = false fun putNew(): Context1 { val c1 = Context1().putIntoSpaghetti_requiringNotAlreadyInDish() if (noisy) { clogStackTrace(StackCaptureException(), "***** Put ${c1.debugId} into dish ${Spaghetti.the.topDish()!!.debugId}") } return c1 } fun maybe(): Context1? { return Spaghetti.the.maybeGet_checkingSingleInThatDish(Context1::class) } fun get() = Spaghetti.the.get_checkingSingleInThatDish(Context1::class) } fun formSubmissionIife(code: String) { ftbShitters += { it.ln(jsIife(code)) } } fun onDomReadyPlusOnShown() = jsOnDomReady.code + ";" + jsOnShown.code fun deferJsShitter(block: () -> Unit) { deferredJsShitters += block } val lazyRunDeferredJsShitters by lazy { deferredJsShitters.forEach {it()} } } fun <Shit> withNewContext1(matk: MainAndTieKnots<Shit, Context1>): ShitWithContext<Shit, Context1> { var context by notNullOnce<Context1>() var shit by place<Shit>() withNewSpaghettiDish( before = {context = Context1.putNew()}, main = {shit = matk.main(context)}, tieKnots = { matk.tieKnots?.invoke(context) } ) return ShitWithContext(shit, context) } fun <Shit> withNewContext1(tieKnots: ((Context1) -> Unit)? = null, main: (Context1) -> Shit): ShitWithContext<Shit, Context1> = withNewContext1(MainAndTieKnots(tieKnots, main)) fun j_killme_withNewContext1(main: Runnable): ShitWithContext<Unit, Context1> = withNewContext1 {main.run()} data class Context1Stuff( var surroundHrefAttrWithIgnoreWhenCheckingForStaleness: Boolean = false, var imposedTime: Timestamp? = null ) fun <T> dyna(block: (Context1ProjectStuff) -> T): T { var res by once<T>() fun fart() { val c1 = Context1.get() val orig = c1.projectStuff.copy() try { res = block(c1.projectStuff) } finally { c1.projectStuff = orig } } if (Context1.maybe() == null) { withNewContext1 {fart()} } else { fart() } return res } fun <T> dyna0(block: (Context1Stuff) -> T): T { val c1 = Context1.get() val orig = c1.stuff.copy() try { return block(c1.stuff) } finally { c1.stuff = orig } }
apache-2.0
e6f5367ce64fdb69abfef6792c5086e6
25.173913
129
0.617703
3.89464
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceWithIgnoreCaseEqualsInspection.kt
1
4126
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ReplaceWithIgnoreCaseEqualsInspection : AbstractKotlinInspection() { companion object { private val caseConversionFunctionFqNames = listOf(FqName("kotlin.text.toUpperCase"), FqName("kotlin.text.toLowerCase")).associateBy { it.shortName().asString() } private fun KtExpression.callInfo(): Pair<KtCallExpression, String>? { val call = (this as? KtQualifiedExpression)?.callExpression ?: this as? KtCallExpression ?: return null val calleeText = call.calleeExpression?.text ?: return null return call to calleeText } private fun KtCallExpression.fqName(context: BindingContext): FqName? { return getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull() } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = binaryExpressionVisitor(fun(binaryExpression: KtBinaryExpression) { if (binaryExpression.operationToken != KtTokens.EQEQ) return val (leftCall, leftCalleeText) = binaryExpression.left?.callInfo() ?: return val (rightCall, rightCalleeText) = binaryExpression.right?.callInfo() ?: return if (leftCalleeText != rightCalleeText) return val caseConversionFunctionFqName = caseConversionFunctionFqNames[leftCalleeText] ?: return val context = binaryExpression.analyze(BodyResolveMode.PARTIAL) val leftCallFqName = leftCall.fqName(context) ?: return val rightCallFqName = rightCall.fqName(context) ?: return if (leftCallFqName != rightCallFqName) return if (leftCallFqName != caseConversionFunctionFqName) return holder.registerProblem( binaryExpression, KotlinBundle.message("inspection.replace.with.ignore.case.equals.display.name"), ReplaceFix(), ) }) private class ReplaceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.0", "equals(..., ignoreCase = true)") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val binary = descriptor.psiElement as? KtBinaryExpression ?: return val (leftCall, _) = binary.left?.callInfo() ?: return val (rightCall, _) = binary.right?.callInfo() ?: return val psiFactory = KtPsiFactory(project) val leftReceiver = leftCall.getQualifiedExpressionForSelector()?.receiverExpression val rightReceiver = rightCall.getQualifiedExpressionForSelector()?.receiverExpression ?: psiFactory.createThisExpression() val newExpression = if (leftReceiver != null) { psiFactory.createExpressionByPattern("$0.equals($1, ignoreCase = true)", leftReceiver, rightReceiver) } else { psiFactory.createExpressionByPattern("equals($0, ignoreCase = true)", rightReceiver) } binary.replace(newExpression) } } }
apache-2.0
6705cced76cfb8316f570fa5f46b0763
49.938272
134
0.714978
5.276215
false
false
false
false
djkovrik/YapTalker
data/src/main/java/com/sedsoftware/yaptalker/data/mapper/SearchPageResultsMapper.kt
1
1649
package com.sedsoftware.yaptalker.data.mapper import com.sedsoftware.yaptalker.data.parsed.SearchTopicsPageParsed import com.sedsoftware.yaptalker.domain.entity.BaseEntity import com.sedsoftware.yaptalker.domain.entity.base.SearchTopicItem import com.sedsoftware.yaptalker.domain.entity.base.SearchTopicsPageInfo import io.reactivex.functions.Function import java.util.ArrayList import javax.inject.Inject class SearchPageResultsMapper @Inject constructor() : Function<SearchTopicsPageParsed, List<BaseEntity>> { companion object { private const val TOPICS_PER_PAGE = 25 } override fun apply(from: SearchTopicsPageParsed): List<BaseEntity> { val result: MutableList<BaseEntity> = ArrayList(TOPICS_PER_PAGE) with(from) { result.add( SearchTopicsPageInfo( hasNextPage = hasNextPage.isNotEmpty(), searchId = searchId ) ) topics.forEach { topic -> result.add( SearchTopicItem( title = topic.title, link = topic.link, isPinned = topic.isPinned.isNotEmpty(), isClosed = topic.isClosed.isNotEmpty(), forumTitle = topic.forumTitle, forumLink = topic.forumLink, rating = topic.rating.toInt(), answers = topic.answers.toInt(), lastPostDate = topic.lastPostDate ) ) } } return result } }
apache-2.0
1b011972b8a651b5c868434c9020c96a
33.354167
106
0.576713
5.251592
false
false
false
false
androidx/androidx
compose/ui/ui-tooling/src/androidMain/kotlin/androidx/compose/ui/tooling/PreviewActivity.kt
3
5704
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.tooling import android.content.pm.ApplicationInfo import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.material.ExtendedFloatingActionButton import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.currentComposer import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier /** * Activity used to run `@Composable` previews from Android Studio. * * The supported `@Composable` functions either have no parameters, or have only parameters with * default values and/or *one* parameter annotated with `@PreviewParameter`. * * The `@Composable` fully qualified name must be passed to this Activity through intent parameters, * using `composable` as the key. When deploying Compose Previews with `@PreviewParameter` * annotated parameters, the provider should be specified as an intent parameter as well, using * the key `parameterProviderClassName`. Optionally, `parameterProviderIndex` can also be set to * display a specific provider value instead of all of them. * * @suppress */ class PreviewActivity : ComponentActivity() { private val TAG = "PreviewActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE == 0) { Log.d(TAG, "Application is not debuggable. Compose Preview not allowed.") finish() return } intent?.getStringExtra("composable")?.let { setComposableContent(it) } } @Suppress("DEPRECATION") @OptIn(ExperimentalComposeUiApi::class) private fun setComposableContent(composableFqn: String) { Log.d(TAG, "PreviewActivity has composable $composableFqn") val className = composableFqn.substringBeforeLast('.') val methodName = composableFqn.substringAfterLast('.') intent.getStringExtra("parameterProviderClassName")?.let { parameterProvider -> setParameterizedContent(className, methodName, parameterProvider) return@setComposableContent } Log.d(TAG, "Previewing '$methodName' without a parameter provider.") setContent { ComposableInvoker.invokeComposable( className, methodName, currentComposer ) } } /** * Sets the activity content according to a given `@PreviewParameter` provider. If * `parameterProviderIndex` is also set, the content will be a single `@Composable` that uses * the `parameterProviderIndex`-th value in the provider's sequence as the argument value. * Otherwise, the content will display a FAB that changes the argument value on click, cycling * through all the values in the provider's sequence. */ @Suppress("DEPRECATION") @OptIn(ExperimentalComposeUiApi::class) private fun setParameterizedContent( className: String, methodName: String, parameterProvider: String ) { Log.d(TAG, "Previewing '$methodName' with parameter provider: '$parameterProvider'") val previewParameters = getPreviewProviderParameters( parameterProvider.asPreviewProviderClass(), intent.getIntExtra("parameterProviderIndex", -1) ) // Handle the case where parameterProviderIndex is not provided. In this case, instead of // showing an arbitrary value (e.g. the first one), we display a FAB that can be used to // cycle through all the values. if (previewParameters.size > 1) { setContent { val index = remember { mutableStateOf(0) } Scaffold( content = { padding -> Box(Modifier.padding(padding)) { ComposableInvoker.invokeComposable( className, methodName, currentComposer, previewParameters[index.value] ) } }, floatingActionButton = { ExtendedFloatingActionButton( text = { Text("Next") }, onClick = { index.value = (index.value + 1) % previewParameters.size } ) } ) } } else { setContent { ComposableInvoker.invokeComposable( className, methodName, currentComposer, *previewParameters ) } } } }
apache-2.0
a6ca39ef89cabf8c2273fdd32b09552c
39.169014
100
0.643058
5.406635
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/InstantQueryResultBinder.kt
3
2919
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver.query.result import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XMemberName.Companion.packageMember import androidx.room.compiler.codegen.XPropertySpec import androidx.room.ext.AndroidTypeNames import androidx.room.ext.RoomTypeNames import androidx.room.solver.CodeGenScope /** * Instantly runs and returns the query. */ class InstantQueryResultBinder(adapter: QueryResultAdapter?) : QueryResultBinder(adapter) { override fun convertAndReturn( roomSQLiteQueryVar: String, canReleaseQuery: Boolean, dbProperty: XPropertySpec, inTransaction: Boolean, scope: CodeGenScope ) { scope.builder.apply { addStatement("%N.assertNotSuspendingTransaction()", dbProperty) } val transactionWrapper = if (inTransaction) { scope.builder.transactionWrapper(dbProperty.name) } else { null } transactionWrapper?.beginTransactionWithControlFlow() scope.builder.apply { val shouldCopyCursor = adapter?.shouldCopyCursor() == true val outVar = scope.getTmpVar("_result") val cursorVar = scope.getTmpVar("_cursor") addLocalVariable( name = cursorVar, typeName = AndroidTypeNames.CURSOR, assignExpr = XCodeBlock.of( language, "%M(%N, %L, %L, %L)", RoomTypeNames.DB_UTIL.packageMember("query"), dbProperty, roomSQLiteQueryVar, if (shouldCopyCursor) "true" else "false", "null" ) ) beginControlFlow("try").apply { adapter?.convert(outVar, cursorVar, scope) transactionWrapper?.commitTransaction() addStatement("return %L", outVar) } nextControlFlow("finally").apply { addStatement("%L.close()", cursorVar) if (canReleaseQuery) { addStatement("%L.release()", roomSQLiteQueryVar) } } endControlFlow() } transactionWrapper?.endTransactionWithControlFlow() } }
apache-2.0
141cfb8091ce8611a8cb3763b0986e39
36.909091
91
0.620075
4.998288
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/actions/actions.kt
5
4766
// 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.lang.documentation.ide.actions import com.intellij.codeInsight.lookup.LookupManager import com.intellij.ide.impl.dataRules.GetDataRule import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.documentation.ide.DocumentationBrowserFacade import com.intellij.lang.documentation.ide.IdeDocumentationTargetProvider import com.intellij.lang.documentation.ide.impl.DocumentationBrowser import com.intellij.lang.documentation.ide.impl.DocumentationHistory import com.intellij.lang.documentation.psi.psiDocumentationTarget import com.intellij.lang.documentation.symbol.impl.symbolDocumentationTargets import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.psi.util.PsiUtilBase import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.accessibility.ScreenReader import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @JvmField val DOCUMENTATION_TARGETS: DataKey<List<DocumentationTarget>> = DataKey.create("documentation.targets") @JvmField val DOCUMENTATION_BROWSER: DataKey<DocumentationBrowserFacade> = DataKey.create("documentation.browser") internal val DOCUMENTATION_POPUP: DataKey<JBPopup> = DataKey.create("documentation.popup") internal const val PRIMARY_GROUP_ID: String = "Documentation.PrimaryGroup" internal const val TOGGLE_SHOW_IN_POPUP_ACTION_ID: String = "Documentation.ToggleShowInPopup" internal const val TOGGLE_AUTO_SHOW_ACTION_ID: String = "Documentation.ToggleAutoShow" internal const val TOGGLE_AUTO_UPDATE_ACTION_ID: String = "Documentation.ToggleAutoUpdate" internal fun primaryActions(): List<AnAction> = groupActions(PRIMARY_GROUP_ID) internal fun navigationActions(): List<AnAction> = groupActions("Documentation.Navigation") private fun groupActions(groupId: String) = listOf(*requireNotNull(ActionUtil.getActionGroup(groupId)).getChildren(null)) internal fun registerBackForwardActions(component: JComponent) { EmptyAction.registerWithShortcutSet("Documentation.Back", CustomShortcutSet( KeyboardShortcut.fromString(if (ScreenReader.isActive()) "alt LEFT" else "LEFT"), KeymapUtil.parseMouseShortcut("button4"), ), component) EmptyAction.registerWithShortcutSet("Documentation.Forward", CustomShortcutSet( KeyboardShortcut.fromString(if (ScreenReader.isActive()) "alt RIGHT" else "RIGHT"), KeymapUtil.parseMouseShortcut("button5") ), component) } class DocumentationTargetsDataRule : GetDataRule { override fun getData(dataProvider: DataProvider): List<DocumentationTarget>? { return ContainerUtil.nullize(documentationTargetsInner(dataProvider)) } } private fun documentationTargetsInner(dataProvider: DataProvider): List<DocumentationTarget> { val project = CommonDataKeys.PROJECT.getData(dataProvider) ?: return emptyList() val editor = CommonDataKeys.EDITOR.getData(dataProvider) if (editor != null) { val editorTargets = targetsFromEditor(project, editor, editor.caretModel.offset) if (editorTargets != null) { return editorTargets } } val symbols = CommonDataKeys.SYMBOLS.getData(dataProvider) if (!symbols.isNullOrEmpty()) { val symbolTargets = symbolDocumentationTargets(project, symbols) if (symbolTargets.isNotEmpty()) { return symbolTargets } } val targetElement = CommonDataKeys.PSI_ELEMENT.getData(dataProvider) if (targetElement != null) { return listOf(psiDocumentationTarget(targetElement, null)) } return emptyList() } @ApiStatus.Internal fun targetsFromEditor(project: Project, editor: Editor, offset: Int): List<DocumentationTarget>? { val file = PsiUtilBase.getPsiFileInEditor(editor, project) ?: return null val ideTargetProvider = IdeDocumentationTargetProvider.getInstance(project) val lookup = LookupManager.getActiveLookup(editor) if (lookup != null) { val lookupElement = lookup.currentItem ?: return null val target = ideTargetProvider.documentationTarget(editor, file, lookupElement) ?: return null return listOf(target) } return ContainerUtil.nullize(ideTargetProvider.documentationTargets(editor, file, offset)) } internal fun documentationHistory(dc: DataContext): DocumentationHistory? { return documentationBrowser(dc)?.history } internal fun documentationBrowser(dc: DataContext): DocumentationBrowser? { return dc.getData(DOCUMENTATION_BROWSER) as? DocumentationBrowser }
apache-2.0
08ffa3369c0e06c9f120068dcbe54af1
44.390476
121
0.798363
4.59595
false
false
false
false
GunoH/intellij-community
platform/core-api/src/com/intellij/openapi/progress/cancellation.kt
2
5324
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Internal package com.intellij.openapi.progress import com.intellij.concurrency.withThreadContext import com.intellij.openapi.application.asContextElement import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.ThrowableComputable import com.intellij.util.ConcurrencyUtil import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus.Internal import kotlin.coroutines.EmptyCoroutineContext private val LOG: Logger = Logger.getInstance("#com.intellij.openapi.progress") fun <X> withCurrentJob(job: Job, action: () -> X): X = Cancellation.withCurrentJob(job, ThrowableComputable(action)) @Deprecated( "Renamed to `withCurrentJob`", replaceWith = ReplaceWith( "withCurrentJob(job, action)", "com.intellij.openapi.progress.withCurrentJob" ) ) fun <X> withJob(job: Job, action: () -> X): X = withCurrentJob(job, action) /** * Ensures that the current thread has an [associated job][Cancellation.currentJob]. * * If there is a [global indicator][ProgressManager.getGlobalProgressIndicator], then the new job is created, * and it becomes a "child" of the global progress indicator * (the cancellation of the indicator is cancels the job). * Otherwise, if there is already an associated job, then it's used as is. * Otherwise, when the current thread does not have an associated job or indicator, then the [IllegalStateException] is thrown. * * This method is designed as a bridge to run the code, which is relying on the newer [Cancellation] mechanism, * from the code, which is run under older progress indicators. * This method is expected to continue working when the progress indicator is replaced with a current job. * * @throws ProcessCanceledException if there was a global indicator and it was cancelled * @throws CancellationException if there was a current job it was cancelled */ @Internal fun <T> ensureCurrentJob(action: (Job) -> T): T { return ensureCurrentJobInner(allowOrphan = false, action) } internal fun <T> ensureCurrentJobAllowingOrphan(action: (Job) -> T): T { return ensureCurrentJobInner(allowOrphan = true, action) } private fun <T> ensureCurrentJobInner(allowOrphan: Boolean, action: (Job) -> T): T { val indicator = ProgressManager.getGlobalProgressIndicator() if (indicator != null) { return ensureCurrentJob(indicator, action) } val currentJob = Cancellation.currentJob() if (currentJob != null) { return action(currentJob) } if (!allowOrphan) { LOG.error("There is no ProgressIndicator or Job in this thread, the current job is not cancellable.") } val orphanJob = Job(parent = null) return executeWithJobAndCompleteIt(orphanJob) { action(orphanJob) } } /** * @throws ProcessCanceledException if [indicator] is cancelled, * or a child coroutine is started and failed */ internal fun <T> ensureCurrentJob(indicator: ProgressIndicator, action: (currentJob: Job) -> T): T { val currentJob = Job(parent = null) // no job parent, the "parent" is the indicator val indicatorWatcher = cancelWithIndicator(currentJob, indicator) val progressModality = ProgressManager.getInstance().currentProgressModality?.asContextElement() ?: EmptyCoroutineContext return try { ProgressManager.getInstance().silenceGlobalIndicator { executeWithJobAndCompleteIt(currentJob) { withThreadContext(progressModality).use { action(currentJob) } } } } catch (ce: IndicatorCancellationException) { throw ProcessCanceledException(ce) } catch (ce: CurrentJobCancellationException) { throw ProcessCanceledException(ce) } finally { indicatorWatcher.cancel() } } private fun cancelWithIndicator(job: Job, indicator: ProgressIndicator): Job { return CoroutineScope(Dispatchers.IO).launch(CoroutineName("indicator watcher")) { while (!indicator.isCanceled) { delay(ConcurrencyUtil.DEFAULT_TIMEOUT_MS) } try { indicator.checkCanceled() error("A cancelled indicator must throw PCE") } catch (pce: ProcessCanceledException) { job.cancel(IndicatorCancellationException(pce)) } } } /** * Associates the calling thread with a [job], invokes [action], and completes the job. * @return action result */ @Internal fun <X> executeWithJobAndCompleteIt( job: CompletableJob, action: () -> X, ): X { try { val result: X = withCurrentJob(job, action) job.complete() return result } catch (ce: CancellationException) { job.cancel(ce) throw ce } catch (e: Throwable) { // `job.completeExceptionally(e)` will fail parent Job, // which is not desired when this Job is a read action Job. // // ReadAction.computeCancellable { // throw X // } // X will be re-thrown, but the caller is not expected to become cancelled // since it might catch X and act accordingly. // // Ideally, completeExceptionally should be used because it's more correct semantically, // but read job must not fail its parent regardless of whether the parent is supervisor: // https://github.com/Kotlin/kotlinx.coroutines/issues/3409 job.cancel(CancellationException(null, e)) throw e } }
apache-2.0
809226575f9d0abfdc742123cc30c0ac
34.731544
127
0.728212
4.2592
false
false
false
false
Briseus/Lurker
app/src/main/java/torille/fi/lurkforreddit/subreddit/SubredditFragment.kt
1
8713
package torille.fi.lurkforreddit.subreddit import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.facebook.drawee.backends.pipeline.Fresco import dagger.android.support.DaggerFragment import kotlinx.android.synthetic.main.fragment_subreddit.* import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.launch import timber.log.Timber import torille.fi.lurkforreddit.R import torille.fi.lurkforreddit.comments.CommentActivity import torille.fi.lurkforreddit.customTabs.CustomTabActivityHelper import torille.fi.lurkforreddit.data.models.view.Post import torille.fi.lurkforreddit.data.models.view.Subreddit import torille.fi.lurkforreddit.media.FullscreenActivity import torille.fi.lurkforreddit.utils.DisplayHelper import torille.fi.lurkforreddit.utils.MediaHelper import javax.inject.Inject /** * A simple [Fragment] subclass. * Use the [SubredditFragment.newInstance] factory method to * create an instance of this fragment. */ class SubredditFragment @Inject constructor() : DaggerFragment(), SubredditContract.View { private val customTabActivityHelper: CustomTabActivityHelper = CustomTabActivityHelper() private var refreshing: Boolean = false private lateinit var mListAdapter: PostsAdapter private lateinit var mLayoutManager: LinearLayoutManager @Inject lateinit var mActionsListener: SubredditContract.Presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mListAdapter = PostsAdapter( mClickListener, Fresco.getImagePipeline() ) DisplayHelper.init(context!!) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_subreddit, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val context = context!! mLayoutManager = LinearLayoutManager(context) mLayoutManager.orientation = LinearLayoutManager.VERTICAL postRecyclerView.layoutManager = mLayoutManager postRecyclerView.setHasFixedSize(true) postRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { private val PREFETCH_SIZE = 2 internal var pastVisiblesItems: Int = 0 internal var visibleItemCount: Int = 0 internal var totalItemCount: Int = 0 internal var lastFetch = 0 internal var scrolledItems: Int = 0 override fun onScrolled(recyclerV: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerV, dx, dy) if (dy > 0) { visibleItemCount = mLayoutManager.childCount totalItemCount = mLayoutManager.itemCount pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition() scrolledItems = visibleItemCount + pastVisiblesItems if (lastFetch == 0) { mListAdapter.prefetchImages(2, PREFETCH_SIZE, totalItemCount) } if (!refreshing && scrolledItems > lastFetch) { lastFetch = scrolledItems + (PREFETCH_SIZE - 1) launch { mListAdapter.prefetchImages( lastFetch, PREFETCH_SIZE, totalItemCount ) } } if (!refreshing && scrolledItems >= totalItemCount - 4) { refreshing = true Timber.d("Last item reached, getting more!") recyclerV?.post { mActionsListener.loadMorePosts() } } } } }) postRecyclerView.adapter = mListAdapter refreshLayout.setColorSchemeColors( ContextCompat.getColor(context, R.color.colorPrimary), ContextCompat.getColor(context, R.color.colorAccent), ContextCompat.getColor(context, R.color.colorPrimaryDark) ) refreshLayout.setOnRefreshListener { mListAdapter.clear() mActionsListener.loadPosts() } } override fun onResume() { super.onResume() mActionsListener.takeView(this) } override fun onStart() { super.onStart() customTabActivityHelper.bindCustomTabsService(activity) } override fun onStop() { super.onStop() setProgressIndicator(false) customTabActivityHelper.unbindCustomTabsService(activity) } override fun onDestroy() { super.onDestroy() mActionsListener.dropView() } /** * Listeners for clicks in the Recyclerview */ private val mClickListener = object : postClickListener { override fun onButtonClick(url: String) { mActionsListener.openCustomTabs(url) } override fun onPostClick(clickedPost: Post) { mActionsListener.openComments(clickedPost) } override fun onMediaClick(post: Post) { mActionsListener.openMedia(post) } override fun onRetryClick() { mActionsListener.retry() } } override fun setProgressIndicator(active: Boolean) { view?.apply { // Make sure setRefreshing() is called after the layout is done with everything else. refreshLayout.isRefreshing = active } } override fun showPosts(posts: List<Post>, nextpage: String) { mListAdapter.addAll(posts) } override fun setListProgressIndicator(active: Boolean) { mListAdapter.setRefreshing(active) } override fun addMorePosts(posts: List<Post>, nextpage: String) { mListAdapter.addMorePosts(posts) refreshing = false } override fun showCustomTabsUI(url: String) { val activity = activity launch(UI) { CustomTabActivityHelper.openCustomTab( activity, MediaHelper.createCustomTabIntentAsync( activity!!, customTabActivityHelper.session ).await(), url ) { _, _ -> val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } } } override fun showMedia(post: Post) { val intent = Intent(context, FullscreenActivity::class.java) intent.putExtra(FullscreenActivity.EXTRA_POST, post) intent.putExtra(FullscreenActivity.EXTRA_URL, post.previewImage) startActivity(intent) } override fun showCommentsUI(clickedPost: Post) { val intent = Intent(context, CommentActivity::class.java) intent.putExtra(CommentActivity.EXTRA_CLICKED_POST, clickedPost) startActivity(intent) } override fun launchCustomActivity(clickedPost: Post) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(clickedPost.url)) startActivity(intent) } override fun onError(errorText: String) { Toast.makeText(context, errorText, Toast.LENGTH_SHORT).show() } override fun setListErrorButton(active: Boolean) { mListAdapter.setListLoadingError(active) } internal interface postClickListener { fun onButtonClick(url: String) fun onPostClick(clickedPost: Post) fun onMediaClick(post: Post) fun onRetryClick() } companion object { val ARGUMENT_SUBREDDIT = "subreddit" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @param subreddit Chosen subreddit. * * * @return A new instance of fragment SubredditFragment. */ fun newInstance(subreddit: Subreddit): SubredditFragment { val fragment = SubredditFragment() val args = Bundle() args.putParcelable(ARGUMENT_SUBREDDIT, subreddit) fragment.arguments = args return fragment } } }
mit
9a62bc55cf71df1b9d79ce0b16e46d5d
32.129278
97
0.638586
5.303104
false
false
false
false
JetBrains/kotlin-native
klib/src/main/kotlin/org/jetbrains/kotlin/cli/klib/main.kt
3
9815
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.cli.klib // TODO: Extract `library` package as a shared jar? import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.konan.target.Distribution import org.jetbrains.kotlin.konan.target.PlatformManager import org.jetbrains.kotlin.konan.util.DependencyProcessor import org.jetbrains.kotlin.library.unpackZippedKonanLibraryTo import org.jetbrains.kotlin.konan.util.KlibMetadataFactories import org.jetbrains.kotlin.backend.common.serialization.metadata.DynamicTypeDeserializer import org.jetbrains.kotlin.descriptors.konan.isNativeStdlib import org.jetbrains.kotlin.builtins.konan.KonanBuiltIns import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.deserialization.PlatformDependentTypeTransformer import org.jetbrains.kotlin.util.Logger import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf import org.jetbrains.kotlin.konan.library.KonanLibrary import org.jetbrains.kotlin.konan.library.resolverByName import org.jetbrains.kotlin.konan.util.KonanHomeProvider import org.jetbrains.kotlin.library.KLIB_FILE_EXTENSION_WITH_DOT import org.jetbrains.kotlin.library.metadata.parseModuleHeader import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.util.removeSuffixIfPresent import kotlin.system.exitProcess internal val KlibFactories = KlibMetadataFactories(::KonanBuiltIns, DynamicTypeDeserializer, PlatformDependentTypeTransformer.None) fun printUsage() { println("Usage: klib <command> <library> <options>") println("where the commands are:") println("\tinfo\tgeneral information about the library") println("\tinstall\tinstall the library to the local repository") println("\tcontents\tlist contents of the library") println("\tsignatures\tlist of ID signatures in the library") println("\tremove\tremove the library from the local repository") println("and the options are:") println("\t-repository <path>\twork with the specified repository") println("\t-target <name>\tinspect specifics of the given target") println("\t-print-signatures [true|false]\tprint ID signature for every declaration (only for \"contents\" command)") } private fun parseArgs(args: Array<String>): Map<String, List<String>> { val commandLine = mutableMapOf<String, MutableList<String>>() for (index in args.indices step 2) { val key = args[index] if (key[0] != '-') { throw IllegalArgumentException("Expected a flag with initial dash: $key") } if (index + 1 == args.size) { throw IllegalArgumentException("Expected an value after $key") } val value = listOf(args[index + 1]) commandLine[key]?.addAll(value) ?: commandLine.put(key, value.toMutableList()) } return commandLine } class Command(args: Array<String>) { init { if (args.size < 2) { printUsage() exitProcess(0) } } val verb = args[0] val library = args[1] val options = parseArgs(args.drop(2).toTypedArray()) } fun warn(text: String) { println("warning: $text") } fun error(text: String): Nothing { kotlin.error("error: $text") } object KlibToolLogger : Logger { override fun warning(message: String) = org.jetbrains.kotlin.cli.klib.warn(message) override fun error(message: String) = org.jetbrains.kotlin.cli.klib.warn(message) override fun fatal(message: String) = org.jetbrains.kotlin.cli.klib.error(message) override fun log(message: String) = println(message) } val defaultRepository = File(DependencyProcessor.localKonanDir.resolve("klib").absolutePath) open class ModuleDeserializer(val library: ByteArray) { protected val moduleHeader: KlibMetadataProtoBuf.Header get() = parseModuleHeader(library) val moduleName: String get() = moduleHeader.moduleName val packageFragmentNameList: List<String> get() = moduleHeader.packageFragmentNameList } class Library(val libraryNameOrPath: String, val requestedRepository: String?, val target: String) { val repository = requestedRepository?.File() ?: defaultRepository fun info() { val library = libraryInRepoOrCurrentDir(repository, libraryNameOrPath) val headerAbiVersion = library.versions.abiVersion val headerCompilerVersion = library.versions.compilerVersion val headerLibraryVersion = library.versions.libraryVersion val headerMetadataVersion = library.versions.metadataVersion val headerIrVersion = library.versions.irVersion val moduleName = ModuleDeserializer(library.moduleHeaderData).moduleName println("") println("Resolved to: ${library.libraryName.File().absolutePath}") println("Module name: $moduleName") println("ABI version: $headerAbiVersion") println("Compiler version: ${headerCompilerVersion}") println("Library version: $headerLibraryVersion") println("Metadata version: $headerMetadataVersion") println("IR version: $headerIrVersion") if (library is KonanLibrary) { val targets = library.targetList.joinToString(", ") print("Available targets: $targets\n") } } fun install() { if (!repository.exists) { warn("Repository does not exist: $repository. Creating.") repository.mkdirs() } val libraryTrueName = File(libraryNameOrPath).name.removeSuffixIfPresent(KLIB_FILE_EXTENSION_WITH_DOT) val library = libraryInCurrentDir(libraryNameOrPath) val installLibDir = File(repository, libraryTrueName) if (installLibDir.exists) installLibDir.deleteRecursively() library.libraryFile.unpackZippedKonanLibraryTo(installLibDir) } fun remove(blind: Boolean = false) { if (!repository.exists) error("Repository does not exist: $repository") val library = try { val library = libraryInRepo(repository, libraryNameOrPath) if (blind) warn("Removing The previously installed $libraryNameOrPath from $repository.") library } catch (e: Throwable) { if (!blind) println(e.message) null } library?.libraryFile?.deleteRecursively() } fun contents(output: Appendable, printSignatures: Boolean) { val module = loadModule() val signatureRenderer = if (printSignatures) DefaultIdSignatureRenderer("// ID signature: ") else IdSignatureRenderer.NO_SIGNATURE val printer = DeclarationPrinter(output, DefaultDeclarationHeaderRenderer, signatureRenderer) printer.print(module) } fun signatures(output: Appendable) { val module = loadModule() val printer = SignaturePrinter(output, DefaultIdSignatureRenderer()) printer.print(module) } private fun loadModule(): ModuleDescriptor { val storageManager = LockBasedStorageManager("klib") val library = libraryInRepoOrCurrentDir(repository, libraryNameOrPath) val versionSpec = LanguageVersionSettingsImpl(currentLanguageVersion, currentApiVersion) val module = KlibFactories.DefaultDeserializedDescriptorFactory.createDescriptorAndNewBuiltIns(library, versionSpec, storageManager, null) val defaultModules = mutableListOf<ModuleDescriptorImpl>() if (!module.isNativeStdlib()) { val resolver = resolverByName( emptyList(), distributionKlib = Distribution(KonanHomeProvider.determineKonanHome()).klib, skipCurrentDir = true, logger = KlibToolLogger ) resolver.defaultLinks(false, true, true).mapTo(defaultModules) { KlibFactories.DefaultDeserializedDescriptorFactory.createDescriptor(it, versionSpec, storageManager, module.builtIns, null) } } (defaultModules + module).let { allModules -> allModules.forEach { it.setDependencies(allModules) } } return module } } val currentLanguageVersion = LanguageVersion.LATEST_STABLE val currentApiVersion = ApiVersion.LATEST_STABLE fun libraryInRepo(repository: File, name: String) = resolverByName(listOf(repository.absolutePath), skipCurrentDir = true, logger = KlibToolLogger).resolve(name) fun libraryInCurrentDir(name: String) = resolverByName(emptyList(), logger = KlibToolLogger).resolve(name) fun libraryInRepoOrCurrentDir(repository: File, name: String) = resolverByName(listOf(repository.absolutePath), logger = KlibToolLogger).resolve(name) fun main(args: Array<String>) { val command = Command(args) val targetManager = PlatformManager(KonanHomeProvider.determineKonanHome()) .targetManager(command.options["-target"]?.last()) val target = targetManager.targetName val repository = command.options["-repository"]?.last() val printSignatures = command.options["-print-signatures"]?.last()?.toBoolean() == true val library = Library(command.library, repository, target) when (command.verb) { "contents" -> library.contents(System.out, printSignatures) "signatures" -> library.signatures(System.out) "info" -> library.info() "install" -> library.install() "remove" -> library.remove() else -> error("Unknown command ${command.verb}.") } }
apache-2.0
8c41cf82239dca6080cbcc621f51bdfc
39.390947
146
0.71513
4.645054
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/search/AbstractHLImplementationSearcherTest.kt
2
1920
// 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.fir.search import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.search.searches.DefinitionsScopedSearch import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import java.nio.file.Paths abstract class AbstractHLImplementationSearcherTest : KotlinLightCodeInsightFixtureTestCase() { fun doTest(testFilePath: String) { myFixture.configureByFile(testFilePath) as KtFile val declarationAtCaret = myFixture.elementAtCaret.parentOfType<KtDeclaration>(withSelf = true) ?: error("No declaration found at caret") val result = DefinitionsScopedSearch.search(declarationAtCaret).toList() val actual = render(result) KotlinTestUtils.assertEqualsToSibling(Paths.get(testFilePath), ".result.kt", actual) } @OptIn(ExperimentalStdlibApi::class) private fun render(declarations: List<PsiElement>): String = buildList { for (declaration in declarations) { val name = declaration.getKotlinFqName() ?: declaration.declarationName() add(declaration::class.simpleName!! + ": " + name) } }.sorted().joinToString(separator = "\n") private fun PsiElement.declarationName() = when (this) { is KtNamedDeclaration -> nameAsSafeName.asString() is PsiNameIdentifierOwner -> nameIdentifier?.text ?: "<no name>" else -> error("Unknown declaration ${this::class.simpleName}") } }
apache-2.0
7dd0e8c9fea302bb07c43471acd71ac5
45.853659
120
0.753125
4.740741
false
true
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/getModuleInfo.kt
1
13054
// 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.caches.project import com.intellij.ide.scratch.ScratchFileService import com.intellij.ide.scratch.ScratchRootType import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.idea.core.isInTestSourceContentKotlinAware import org.jetbrains.kotlin.idea.core.script.ScriptRelatedModuleNameFile import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.highlighter.OutsidersPsiFileSupportUtils import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.isInSourceContentWithoutInjected import org.jetbrains.kotlin.idea.util.isKotlinBinary import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition import org.jetbrains.kotlin.scripting.definitions.runReadAction import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.sure import org.jetbrains.kotlin.utils.yieldIfNotNull var PsiFile.forcedModuleInfo: ModuleInfo? by UserDataProperty(Key.create("FORCED_MODULE_INFO")) @JvmOverloads fun PsiElement.getModuleInfo(createSourceLibraryInfoForLibraryBinaries: Boolean = true): IdeaModuleInfo = this.collectInfos(ModuleInfoCollector.NotNullTakeFirst, createSourceLibraryInfoForLibraryBinaries) fun PsiElement.getNullableModuleInfo(): IdeaModuleInfo? = this.collectInfos(ModuleInfoCollector.NullableTakeFirst) fun PsiElement.getModuleInfos(): Sequence<IdeaModuleInfo> = this.collectInfos(ModuleInfoCollector.ToSequence) fun ModuleInfo.findSdkAcrossDependencies(): SdkInfo? { val project = (this as? IdeaModuleInfo)?.project ?: return null return SdkInfoCache.getInstance(project).findOrGetCachedSdk(this) } fun IdeaModuleInfo.findJvmStdlibAcrossDependencies(): LibraryInfo? { val project = project ?: return null return KotlinStdlibCache.getInstance(project).findStdlibInModuleDependencies(this) } fun getModuleInfoByVirtualFile(project: Project, virtualFile: VirtualFile): IdeaModuleInfo? = collectInfosByVirtualFile( project, virtualFile, treatAsLibrarySource = false, onOccurrence = { return@getModuleInfoByVirtualFile it } ) fun getBinaryLibrariesModuleInfos(project: Project, virtualFile: VirtualFile) = collectModuleInfosByType<BinaryModuleInfo>( project, virtualFile ) fun getLibrarySourcesModuleInfos(project: Project, virtualFile: VirtualFile) = collectModuleInfosByType<LibrarySourceInfo>( project, virtualFile ) fun getScriptRelatedModuleInfo(project: Project, virtualFile: VirtualFile): ModuleSourceInfo? { val moduleRelatedModuleInfo = getModuleRelatedModuleInfo(project, virtualFile) if (moduleRelatedModuleInfo != null) { return moduleRelatedModuleInfo } return if (ScratchFileService.getInstance().getRootType(virtualFile) is ScratchRootType) { val scratchModule = ScriptRelatedModuleNameFile[project, virtualFile]?.let { ModuleManager.getInstance(project).findModuleByName(it) } scratchModule?.testSourceInfo() ?: scratchModule?.productionSourceInfo() } else null } private typealias VirtualFileProcessor<T> = (Project, VirtualFile, Boolean) -> T private sealed class ModuleInfoCollector<out T>( val onResult: (IdeaModuleInfo?) -> T, val onFailure: (String) -> T, val virtualFileProcessor: VirtualFileProcessor<T> ) { object NotNullTakeFirst : ModuleInfoCollector<IdeaModuleInfo>( onResult = { it ?: NotUnderContentRootModuleInfo }, onFailure = { reason -> LOG.error("Could not find correct module information.\nReason: $reason") NotUnderContentRootModuleInfo }, virtualFileProcessor = processor@{ project, virtualFile, isLibrarySource -> collectInfosByVirtualFile( project, virtualFile, isLibrarySource ) { return@processor it ?: NotUnderContentRootModuleInfo } } ) object NullableTakeFirst : ModuleInfoCollector<IdeaModuleInfo?>( onResult = { it }, onFailure = { reason -> LOG.warn("Could not find correct module information.\nReason: $reason") null }, virtualFileProcessor = processor@{ project, virtualFile, isLibrarySource -> collectInfosByVirtualFile( project, virtualFile, isLibrarySource ) { return@processor it } } ) object ToSequence : ModuleInfoCollector<Sequence<IdeaModuleInfo>>( onResult = { result -> result?.let { sequenceOf(it) } ?: emptySequence() }, onFailure = { reason -> LOG.warn("Could not find correct module information.\nReason: $reason") emptySequence() }, virtualFileProcessor = { project, virtualFile, isLibrarySource -> sequence { collectInfosByVirtualFile( project, virtualFile, isLibrarySource ) { yieldIfNotNull(it) } } } ) } private fun <T> PsiElement.collectInfos( c: ModuleInfoCollector<T>, createSourceLibraryInfoForLibraryBinaries: Boolean = true ): T { (containingFile?.forcedModuleInfo as? IdeaModuleInfo)?.let { return c.onResult(it) } if (this is KtLightElement<*, *>) { return this.processLightElement(c) } collectModuleInfoByUserData(this).firstOrNull()?.let { return c.onResult(it) } val containingFile = containingFile ?: return c.onFailure("Analyzing element of type ${this::class.java} with no containing file\nText:\n$text") val containingKtFile = containingFile as? KtFile containingKtFile?.analysisContext?.let { return it.collectInfos(c) } containingKtFile?.doNotAnalyze?.let { return c.onFailure("Should not analyze element: $text in file ${containingKtFile.name}\n$it") } val explicitModuleInfo = containingKtFile?.forcedModuleInfo ?: (containingKtFile?.originalFile as? KtFile)?.forcedModuleInfo if (explicitModuleInfo is IdeaModuleInfo) { return c.onResult(explicitModuleInfo) } if (containingKtFile is KtCodeFragment) { val context = containingKtFile.getContext() ?: return c.onFailure("Analyzing code fragment of type ${containingKtFile::class.java} with no context element\nText:\n${containingKtFile.getText()}") return context.collectInfos(c) } val virtualFile = containingFile.originalFile.virtualFile ?: return c.onFailure("Analyzing element of type ${this::class.java} in non-physical file $containingFile of type ${containingFile::class.java}\nText:\n$text") val isScript = runReadAction { containingKtFile?.isScript() == true } if (isScript) { getModuleRelatedModuleInfo(project, virtualFile)?.let { return c.onResult(it) } val script = runReadAction { containingKtFile?.script } script?.let { containingKtFile?.findScriptDefinition()?.let { return c.onResult(ScriptModuleInfo(project, virtualFile, it)) } } } val isCompiled = (containingFile as? KtFile)?.isCompiled val isLibrarySource = if (createSourceLibraryInfoForLibraryBinaries) { isCompiled ?: false } else { isCompiled == false } return c.virtualFileProcessor( project, virtualFile, isLibrarySource ) } private fun <T> KtLightElement<*, *>.processLightElement(c: ModuleInfoCollector<T>): T { val decompiledClass = this.getParentOfType<KtLightClassForDecompiledDeclaration>(strict = false) if (decompiledClass != null) { return c.virtualFileProcessor( project, containingFile.virtualFile.sure { "Decompiled class should be build from physical file" }, false ) } val element = kotlinOrigin ?: when (this) { is KtLightClassForFacade -> this.files.first() else -> return c.onFailure("Light element without origin is referenced by resolve:\n$this\n${this.clsDelegate.text}") } return element.collectInfos(c) } private inline fun <T> collectInfosByVirtualFile( project: Project, virtualFile: VirtualFile, treatAsLibrarySource: Boolean, onOccurrence: (IdeaModuleInfo?) -> T ): T { collectModuleInfoByUserData(project, virtualFile).map(onOccurrence) val moduleRelatedModuleInfo = getModuleRelatedModuleInfo(project, virtualFile) if (moduleRelatedModuleInfo != null) { onOccurrence(moduleRelatedModuleInfo) } val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project) projectFileIndex.getOrderEntriesForFile(virtualFile).forEach { it.toIdeaModuleInfo(project, virtualFile, treatAsLibrarySource).map(onOccurrence) } val isBinary = virtualFile.fileType.isKotlinBinary() val scriptConfigurationManager = ScriptConfigurationManager.getInstance(project) if (isBinary && virtualFile in scriptConfigurationManager.getAllScriptsDependenciesClassFilesScope()) { if (treatAsLibrarySource) { onOccurrence(ScriptDependenciesSourceInfo.ForProject(project)) } else { onOccurrence(ScriptDependenciesInfo.ForProject(project)) } } if (!isBinary && virtualFile in scriptConfigurationManager.getAllScriptDependenciesSourcesScope()) { onOccurrence(ScriptDependenciesSourceInfo.ForProject(project)) } return onOccurrence(null) } private fun getModuleRelatedModuleInfo(project: Project, virtualFile: VirtualFile): ModuleSourceInfo? { val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project) val module = projectFileIndex.getModuleForFile(virtualFile) if (module != null && !module.isDisposed) { val moduleFileIndex = ModuleRootManager.getInstance(module).fileIndex if (moduleFileIndex.isInTestSourceContentKotlinAware(virtualFile)) { return module.testSourceInfo() } else if (moduleFileIndex.isInSourceContentWithoutInjected(virtualFile)) { return module.productionSourceInfo() } } val fileOrigin = OutsidersPsiFileSupportUtils.getOutsiderFileOrigin(project, virtualFile) if (fileOrigin != null) { return getModuleRelatedModuleInfo(project, fileOrigin) } return null } private inline fun <reified T : IdeaModuleInfo> collectModuleInfosByType(project: Project, virtualFile: VirtualFile): Collection<T> { val result = linkedSetOf<T>() collectInfosByVirtualFile(project, virtualFile, treatAsLibrarySource = false) { result.addIfNotNull(it as? T) } return result } private fun OrderEntry.toIdeaModuleInfo( project: Project, virtualFile: VirtualFile, treatAsLibrarySource: Boolean = false ): List<IdeaModuleInfo> { if (this is ModuleOrderEntry) return emptyList() if (!isValid) return emptyList() when (this) { is LibraryOrderEntry -> { val library = library ?: return emptyList() if (!treatAsLibrarySource && ProjectRootsUtil.isLibraryClassFile(project, virtualFile)) { return createLibraryInfo(project, library) } else if (treatAsLibrarySource || ProjectRootsUtil.isLibraryFile(project, virtualFile)) { return createLibraryInfo(project, library).map { it.sourcesModuleInfo } } } is JdkOrderEntry -> { return listOf(SdkInfo(project, jdk ?: return emptyList())) } else -> return emptyList() } return emptyList() } /** * @see [org.jetbrains.kotlin.types.typeUtil.closure]. */ fun <T> Collection<T>.lazyClosure(f: (T) -> Collection<T>): Sequence<T> = sequence { if (isEmpty()) return@sequence var sizeBeforeIteration = 0 yieldAll(this@lazyClosure) var yieldedCount = size var elementsToCheck = this@lazyClosure while (yieldedCount > sizeBeforeIteration) { val toAdd = hashSetOf<T>() elementsToCheck.forEach { val neighbours = f(it) yieldAll(neighbours) yieldedCount += neighbours.size toAdd.addAll(neighbours) } elementsToCheck = toAdd sizeBeforeIteration = yieldedCount } }
apache-2.0
98db588287f34c6343a89784d521f0b7
37.281525
167
0.708978
5.036265
false
false
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/kotlin/KotlinBinaries.kt
2
2158
// 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.intellij.build.kotlin import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.impl.addToClasspathAgent.AddToClasspathUtil import java.nio.file.Files import java.nio.file.Path /** * Sets up Kotlin compiler (downloaded from Marketplace) which is required for JPS to compile the repository */ internal class KotlinBinaries(private val communityHome: BuildDependenciesCommunityRoot, private val messages: BuildMessages) { val kotlinCompilerHome: Path by lazy { val compilerHome = KotlinCompilerDependencyDownloader.downloadAndExtractKotlinCompiler(communityHome) val kotlinc = compilerHome.resolve("bin/kotlinc") check(Files.exists(kotlinc)) { "Kotlin compiler home is missing under the path: $compilerHome" } compilerHome } private val kotlinJpsPlugin: Path by lazy { val jpsPlugin = KotlinCompilerDependencyDownloader.downloadKotlinJpsPlugin(communityHome) jpsPlugin } suspend fun loadKotlinJpsPluginToClassPath() { val required = KotlinCompilerDependencyDownloader.getKotlinJpsPluginVersion(communityHome) val current = getCurrentKotlinJpsPluginVersionFromClassPath() if (current != null) { check(current == required) { "Currently loaded Kotlin JPS plugin version is '$current', but required '$required'" } // already loaded return } messages.info("Loading Kotlin JPS plugin from $kotlinJpsPlugin") AddToClasspathUtil.addToClassPathViaAgent(listOf(kotlinJpsPlugin)) val afterLoad = getCurrentKotlinJpsPluginVersionFromClassPath() check(afterLoad == required) { "Loaded Kotlin JPS plugin version '$afterLoad', but required '$required'" } } private fun getCurrentKotlinJpsPluginVersionFromClassPath(): String? { val stream = javaClass.classLoader.getResourceAsStream("META-INF/compiler.version") ?: return null return stream.use { stream.readAllBytes().decodeToString() } } }
apache-2.0
a84d3cba90bf87e47f7d46bdd3768b39
40.519231
127
0.773865
4.893424
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/colorpicker/LightCalloutPopup.kt
4
5346
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.colorpicker import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.registry.Registry import com.intellij.ui.BalloonImpl import com.intellij.ui.JBColor import com.intellij.ui.awt.RelativePoint import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Color import java.awt.Point import java.awt.Rectangle import javax.swing.JComponent /** * A popup balloon that appears on above a given location with an arrow pointing this location. * * The popup is automatically dismissed when the user clicks outside. * * @param content The content in Popup Window */ class LightCalloutPopup(val content: JComponent, val closedCallback: (() -> Unit)? = null, val cancelCallBack: (() -> Unit)? = null, val beforeShownCallback: (() -> Unit)? = null ) { private var balloon: Balloon? = null fun getBalloon(): Balloon? = balloon /** * @param parentComponent The anchor component. Can be null. * @param location The position relates to [parentComponent]. If [parentComponent] is null, position will relate to * the top-left point of screen. * @param position The popup position, see [Balloon.Position]. The default value is [Balloon.Position.below]. */ @JvmOverloads fun show( parentComponent: JComponent? = null, location: Point, position: Balloon.Position = Balloon.Position.below ) { // Let's cancel any previous balloon shown by this instance of ScenePopup if (balloon != null) { cancel() } balloon = createPopup(content).apply { addListener(object : JBPopupListener { override fun beforeShown(event: LightweightWindowEvent) { beforeShownCallback?.invoke() } override fun onClosed(event: LightweightWindowEvent) { if (event.isOk) { closedCallback?.invoke() } else { cancelCallBack?.invoke() } } }) if (this is BalloonImpl) { setHideListener { closedCallback?.invoke() hide() } } val relativePoint = if (parentComponent != null) { RelativePoint(parentComponent, location) } else { RelativePoint(location) } show(relativePoint, position) } } fun close() { balloon?.hide(true) } fun cancel() { balloon?.hide(false) } fun getPointerColor(showingPoint: RelativePoint, component: JComponent): Color? { val saturationBrightnessComponent = UIUtil.findComponentOfType(component, SaturationBrightnessComponent::class.java) if (saturationBrightnessComponent != null) { if (Registry.`is`("ide.color.picker.new.pipette") && saturationBrightnessComponent.pipetteMode) { return saturationBrightnessComponent.parent.background } val point = showingPoint.getPoint(saturationBrightnessComponent) val size = saturationBrightnessComponent.size val location = saturationBrightnessComponent.location val x1 = location.x val y1 = location.y val x2 = x1 + size.width val y2 = y1 + size.height val x = if (point.x < x1) x1 else if (point.x > x2) x2 else point.x val y = if (point.y < y1) y1 else if (point.y > y2) y2 else point.y if (y == y2) return null return saturationBrightnessComponent.getColorByPoint(Point(x,y)) } return null } private fun createPopup(component: JComponent) = JBPopupFactory.getInstance().createBalloonBuilder(component) .setFillColor(PICKER_BACKGROUND_COLOR) .setBorderColor(JBColor.border()) .setBorderInsets(JBUI.insets(1)) .setAnimationCycle(Registry.intValue("ide.tooltip.animationCycle")) .setShowCallout(true) .setPositionChangeYShift(2) .setHideOnKeyOutside(false) .setHideOnAction(false) .setBlockClicksThroughBalloon(true) .setRequestFocus(true) .setDialogMode(false) .createBalloon() } private val emptyRectangle = Rectangle(0, 0, 0, 0) /** * Return true if there is enough space in the application window below [location] * in the [parentComponent] coordinates to show [content]. */ fun canShowBelow(parentComponent: JComponent, location: Point, content: JComponent): Boolean { val relativePoint = RelativePoint(parentComponent, location) val windowBounds = UIUtil.getWindow(parentComponent)?.bounds ?: emptyRectangle return relativePoint.screenPoint.y + content.preferredSize.height < windowBounds.y + windowBounds.height }
apache-2.0
9007ef5a0b5c733781c6df54041e575a
32.841772
120
0.695847
4.346341
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/leakingThis/test.kt
13
1109
class First { val x: String init { use(this) // NPE! Leaking this x = foo() // NPE! Own function } fun foo() = x } fun use(first: First) = first.x.hashCode() abstract class Second { val x: String init { use(this) // Leaking this in non-final x = bar() // Own function in non-final foo() // Non-final function call } private fun bar() = foo() abstract fun foo(): String } fun use(second: Second) = second.x class SecondDerived : Second() { val y = x // null! override fun foo() = y } open class Third { open var x: String constructor() { x = "X" // Non-final property access } } class ThirdDerived : Third() { override var x: String = "Y" set(arg) { field = "$arg$y" } val y = "" } class Fourth { val x: String get() = y val y = x // null! } annotation class AllOpen @AllOpen class A { private val x = "A" + System.currentTimeMillis() val y = "A" + System.currentTimeMillis() init { x.toByteArray() y.toByteArray() } }
apache-2.0
f36459dc25e4860cd43e739d7c8b62e1
14.857143
52
0.54193
3.520635
false
false
false
false
smmribeiro/intellij-community
platform/platform-api/src/com/intellij/openapi/observable/properties/OperationUtil.kt
1
2142
// 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. @file:JvmName("OperationUtil") package com.intellij.openapi.observable.properties import com.intellij.openapi.Disposable /** * Creates observable property that represents logic negation (!) operation for passed property. */ operator fun ObservableProperty<Boolean>.not(): ObservableProperty<Boolean> = operation(this) { !it } /** * Creates observable property that represents logic and (&&) operation between values of two passed properties. */ infix fun ObservableProperty<Boolean>.and(property: ObservableProperty<Boolean>): ObservableProperty<Boolean> = operation(this, property) { l, r -> l && r } /** * Creates observable property that represents logic or (||) operation between values of two passed properties. */ infix fun ObservableProperty<Boolean>.or(property: ObservableProperty<Boolean>): ObservableProperty<Boolean> = operation(this, property) { l, r -> l || r } private fun <T, R> operation( property: ObservableProperty<T>, operation: (T) -> R ): ObservableProperty<R> = object : AbstractDelegateObservableProperty<R>(property) { override fun get(): R = operation(property.get()) } private fun <T1, T2, R> operation( left: ObservableProperty<T1>, right: ObservableProperty<T2>, operation: (T1, T2) -> R ): ObservableProperty<R> = object : AbstractDelegateObservableProperty<R>(left, right) { override fun get(): R = operation(left.get(), right.get()) } private abstract class AbstractDelegateObservableProperty<T>( private val properties: List<ObservableProperty<*>> ) : ObservableProperty<T> { constructor(vararg properties: ObservableProperty<*>) : this(properties.toList()) override fun afterChange(listener: (T) -> Unit) { for (property in properties) { property.afterChange { listener(get()) } } } override fun afterChange(listener: (T) -> Unit, parentDisposable: Disposable) { for (property in properties) { property.afterChange({ listener(get()) }, parentDisposable) } } }
apache-2.0
1f774c875c249c66f13755a51c7cfa24
34.716667
158
0.725957
4.275449
false
false
false
false
NlRVANA/Unity
app/src/test/java/com/zwq65/unity/algorithm/sort/QuickSortTest.kt
1
3189
package com.zwq65.unity.algorithm.sort import org.junit.Test /** *================================================ * 快速排序 * * 快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小, * 然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。 * 1.从第一个元素开始,该元素可以认为已经被排序 * 2.取出下一个元素,在已经排序的元素序列中从后向前扫描 * 3.如果该元素(已排序)大于新元素,将该元素移到下一位置 * 4.重复步骤 3,直到找到已排序的元素小于或者等于新元素的位置 * 5.将新元素插入到该位置后 * 6.重复步骤 2~5 * * 快速排序总结: * 对于快速排序的时间度取决于其递归的深度,如果递归深度又决定于每次关键值得取值所以在最好的情况下每次都取到数组中间值,那么此时算法时间复杂度最优为 O(nlogn)。当然最坏情况就是之前我们分析的有序数组,那么每次都需要进行 n 次比较则 时间复杂度为 O(n²),但是在平均情况 时间复杂度为 O(nlogn) * 空间复杂度为 O(1)。 * 快速排序为不稳定排序。 * * Created by NIRVANA on 2018/3/2 * Contact with <[email protected]> *================================================ */ class QuickSortTest { companion object { val array = arrayOf(11, 23, 3, 6564, 342, 545, 7, 5) } @Test fun sort() { //外层循环控制需要排序的趟数(从1开始因为将第0位看成了有序数据) quickSort(array, 0, 7) for (item in array) { println(item) } } /** * 快速排序 * * @param arr * @param L 指向数组第一个元素 * @param R 指向数组最后一个元素 */ private fun quickSort(arr: Array<Int>, L: Int, R: Int) { var i = L var j = R //支点 val pivot = arr[(L + R) / 2] //左右两端进行扫描,只要两端还没有交替,就一直扫描 while (i <= j) { //寻找直到比支点大的数 while (pivot > arr[i]) i++ //寻找直到比支点小的数 while (pivot < arr[j]) j-- //此时已经分别找到了比支点小的数(右边)、比支点大的数(左边),它们进行交换 if (i <= j) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp i++ j-- } } //上面一个while保证了第一趟排序支点的左边比支点小,支点的右边比支点大了。 //“左边”再做排序,直到左边剩下一个数(递归出口) if (L < j) quickSort(arr, L, j) //“右边”再做排序,直到右边剩下一个数(递归出口) if (i < R) quickSort(arr, i, R) } }
apache-2.0
805ea33ff60dadc9117eebf22da799b8
24.0125
158
0.509
2.244669
false
false
false
false
tooploox/android-versioning-plugin
src/test/kotlin/versioning/TestUtils.kt
1
630
package versioning import org.gradle.api.Project import versioning.model.Scope const val TAG_PREFIX = "releases/" private const val PROPERTY_SCOPE = "scope" private const val PROPERTY_VERSIONED = "versioned" fun createGitDescribeString(lastVersion: String, commitsSinceLastTag: Int = 0, currentSha: String? = null) = if (commitsSinceLastTag > 0) "$TAG_PREFIX$lastVersion-$commitsSinceLastTag-g${currentSha!!}" else lastVersion fun Project.addScopeProperty(scope: Scope) = extensions.add(PROPERTY_SCOPE, scope.name) fun Project.addVersionedProperty(versioned: Boolean) = extensions.add(PROPERTY_VERSIONED, versioned)
apache-2.0
25674e40049288a2efa4babd6e8149d1
38.375
117
0.787302
3.9375
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/stream-debugger/src/com/intellij/debugger/streams/ui/impl/ValueWithPositionImpl.kt
4
1826
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.streams.ui.impl import com.intellij.debugger.streams.trace.TraceElement import com.intellij.debugger.streams.ui.ValueWithPosition /** * @author Vitaliy.Bibaev */ data class ValueWithPositionImpl(override val traceElement: TraceElement) : ValueWithPosition { companion object { val INVALID_POSITION = Int.MIN_VALUE val DEFAULT_VISIBLE_VALUE = false val DEFAULT_HIGHLIGHTING_VALUE = false } private var myPosition: Int = INVALID_POSITION private var myIsVisible: Boolean = DEFAULT_VISIBLE_VALUE private var myIsHighlighted: Boolean = DEFAULT_HIGHLIGHTING_VALUE override fun equals(other: Any?): Boolean { return other != null && other is ValueWithPosition && traceElement == other.traceElement } override fun hashCode(): Int = traceElement.hashCode() override val isVisible: Boolean get() = myIsVisible override val position: Int get() = myPosition override val isHighlighted: Boolean get() = myIsHighlighted fun updateToInvalid(): Boolean = updateProperties(INVALID_POSITION, DEFAULT_VISIBLE_VALUE, DEFAULT_HIGHLIGHTING_VALUE) fun setInvalid() = setProperties(INVALID_POSITION, DEFAULT_VISIBLE_VALUE, DEFAULT_HIGHLIGHTING_VALUE) fun updateProperties(position: Int, isVisible: Boolean, isHighlighted: Boolean): Boolean { val changed = myPosition != position || myIsVisible != isVisible || myIsHighlighted != isHighlighted setProperties(position, isVisible, isHighlighted) return changed } fun setProperties(position: Int, isVisible: Boolean, isHighlighted: Boolean) { myPosition = position myIsHighlighted = isHighlighted myIsVisible = isVisible } }
apache-2.0
d500df24a217e95888fbeff90ff8585b
33.471698
140
0.75356
4.576441
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/groups/GroupsFragment.kt
1
9413
package com.ivanovsky.passnotes.presentation.groups 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 androidx.activity.OnBackPressedCallback import androidx.activity.addCallback import androidx.lifecycle.observe import androidx.recyclerview.widget.GridLayoutManager import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.entity.Group import com.ivanovsky.passnotes.data.entity.Note import com.ivanovsky.passnotes.data.entity.Template import com.ivanovsky.passnotes.databinding.GroupsFragmentBinding import com.ivanovsky.passnotes.extensions.setItemVisibility import com.ivanovsky.passnotes.presentation.core.BaseFragment import com.ivanovsky.passnotes.presentation.core.DatabaseInteractionWatcher import com.ivanovsky.passnotes.presentation.core.dialog.ConfirmationDialog import com.ivanovsky.passnotes.presentation.core.extensions.getMandarotyArgument import com.ivanovsky.passnotes.presentation.core.extensions.setupActionBar import com.ivanovsky.passnotes.presentation.core.extensions.showToastMessage import com.ivanovsky.passnotes.presentation.core.extensions.withArguments import com.ivanovsky.passnotes.presentation.groups.dialog.ChooseOptionDialog import com.ivanovsky.passnotes.presentation.navigation.NavigationMenuViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class GroupsFragment : BaseFragment() { private val viewModel: GroupsViewModel by viewModel() private val args by lazy { getMandarotyArgument<GroupsArgs>(ARGUMENTS) } private lateinit var binding: GroupsFragmentBinding private var backCallback: OnBackPressedCallback? = null private var menu: Menu? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = GroupsFragmentBinding.inflate(inflater, container, false) .also { it.lifecycleOwner = viewLifecycleOwner it.viewModel = viewModel } setupRecyclerView() return binding.root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { this.menu = menu inflater.inflate(R.menu.groups, menu) viewModel.isMenuVisible.value?.let { menu.setItemVisibility(R.id.menu_lock, it) menu.setItemVisibility(R.id.menu_more, it) menu.setItemVisibility(R.id.menu_search, it) } viewModel.isAddTemplatesMenuVisible.value?.let { menu.setItemVisibility(R.id.menu_add_templates, it) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { viewModel.onBackClicked() true } R.id.menu_lock -> { viewModel.onLockButtonClicked() true } R.id.menu_add_templates -> { viewModel.onAddTemplatesClicked() true } R.id.menu_search -> { viewModel.onSearchButtonClicked() true } R.id.menu_settings -> { viewModel.onSettingsButtonClicked() true } else -> super.onOptionsItemSelected(item) } } override fun onStart() { super.onStart() backCallback = requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) { viewModel.onBackClicked() } navigationViewModel.setVisibleItems( NavigationMenuViewModel.createNavigationItemsForDbScreens() ) navigationViewModel.setNavigationEnabled(true) } override fun onStop() { super.onStop() backCallback?.remove() backCallback = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner.lifecycle.addObserver(DatabaseInteractionWatcher(this)) setupActionBar { setHomeAsUpIndicator(null) setDisplayHomeAsUpEnabled(true) } subscribeToLiveData() viewModel.start(args) } private fun subscribeToLiveData() { viewModel.showToastEvent.observe(viewLifecycleOwner) { message -> showToastMessage(message) } viewModel.screenTitle.observe(viewLifecycleOwner) { setupActionBar { title = it } } viewModel.isMenuVisible.observe(viewLifecycleOwner) { menu?.setItemVisibility(R.id.menu_lock, it) menu?.setItemVisibility(R.id.menu_more, it) menu?.setItemVisibility(R.id.menu_search, it) } viewModel.isAddTemplatesMenuVisible.observe(viewLifecycleOwner) { menu?.setItemVisibility(R.id.menu_add_templates, it) } viewModel.showNewEntryDialogEvent.observe(viewLifecycleOwner) { templates -> showNewEntryDialog(templates) } viewModel.showGroupActionsDialogEvent.observe(viewLifecycleOwner) { group -> showGroupActionsDialog(group) } viewModel.showNoteActionsDialogEvent.observe(viewLifecycleOwner) { note -> showNoteActionsDialog(note) } viewModel.showRemoveConfirmationDialogEvent.observe(viewLifecycleOwner) { (group, note) -> showRemoveConfirmationDialog(group, note) } viewModel.showAddTemplatesDialogEvent.observe(viewLifecycleOwner) { showAddTemplatesDialog() } } private fun setupRecyclerView() { (binding.recyclerView.layoutManager as? GridLayoutManager)?.let { it.spanCount = COLUMN_COUNT } } private fun showNewEntryDialog(templates: List<Template>) { val templateEntries = templates.map { template -> template.title } val entries = listOf(getString(R.string.new_item_entry_standard_note)) + templateEntries + listOf(getString(R.string.new_item_entry_new_group)) val dialog = ChooseOptionDialog.newInstance(getString(R.string.create), entries) dialog.onItemClickListener = { itemIdx -> when (itemIdx) { 0 -> viewModel.onCreateNewNoteClicked() entries.size - 1 -> viewModel.onCreateNewGroupClicked() else -> viewModel.onCreateNewNoteFromTemplateClicked(templates[itemIdx - 1]) } } dialog.show(childFragmentManager, ChooseOptionDialog.TAG) } private fun showGroupActionsDialog(group: Group) { val entries = resources.getStringArray(R.array.item_actions_entries) val dialog = ChooseOptionDialog.newInstance(null, entries.toList()) dialog.onItemClickListener = { itemIdx -> when (itemIdx) { // TODO: refactor, move menu creation to VM 0 -> viewModel.onEditGroupClicked(group) 1 -> viewModel.onRemoveGroupClicked(group) 2 -> viewModel.onCutGroupClicked(group) } } dialog.show(childFragmentManager, ChooseOptionDialog.TAG) } private fun showNoteActionsDialog(note: Note) { val entries = resources.getStringArray(R.array.item_actions_entries) val dialog = ChooseOptionDialog.newInstance(null, entries.toList()) dialog.onItemClickListener = { itemIdx -> when (itemIdx) { // TODO: refactor, move menu creation to VM 0 -> viewModel.onEditNoteClicked(note) 1 -> viewModel.onRemoveNoteClicked(note) 2 -> viewModel.onCutNoteClicked(note) } } dialog.show(childFragmentManager, ChooseOptionDialog.TAG) } private fun showRemoveConfirmationDialog(group: Group?, note: Note?) { val message = if (note != null) { getString(R.string.note_remove_confirmation_message, note.title) } else { getString(R.string.group_remove_confirmation_message) } val dialog = ConfirmationDialog.newInstance( message, getString(R.string.yes), getString(R.string.no) ) dialog.onConfirmationLister = { viewModel.onRemoveConfirmed(group, note) } dialog.show(childFragmentManager, ConfirmationDialog.TAG) } private fun showAddTemplatesDialog() { val dialog = ConfirmationDialog.newInstance( getString(R.string.add_templates_confirmation_message), getString(R.string.yes), getString(R.string.no) ).apply { onConfirmationLister = { viewModel.onAddTemplatesConfirmed() } } dialog.show(childFragmentManager, ConfirmationDialog.TAG) } companion object { private const val ARGUMENTS = "arguments" private const val COLUMN_COUNT = 3 fun newInstance(args: GroupsArgs) = GroupsFragment().withArguments { putParcelable(ARGUMENTS, args) } } }
gpl-2.0
096b54d0e308f2a4208bd56264428107
34.524528
98
0.657814
5.039079
false
false
false
false
kerubistan/kerub
src/test/kotlin/com/github/kerubistan/kerub/data/ispn/IspnDaoBaseTest.kt
2
1425
package com.github.kerubistan.kerub.data.ispn import com.github.kerubistan.kerub.audit.AuditManager import com.github.kerubistan.kerub.data.EventListener import com.github.kerubistan.kerub.model.Entity import com.nhaarman.mockito_kotlin.mock import org.infinispan.Cache import org.infinispan.manager.DefaultCacheManager import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test class IspnDaoBaseTest { data class TestEntity(override var id: String = "TEST") : Entity<String> class TestDao(cache: Cache<String, TestEntity>, eventListener: EventListener, auditManager: AuditManager) : ListableIspnDaoBase<TestEntity, String>(cache, eventListener, auditManager) { override fun getEntityClass(): Class<TestEntity> { return TestEntity::class.java } } private var cacheManager: DefaultCacheManager? = null var cache: Cache<String, TestEntity>? = null var dao: IspnDaoBase<TestEntity, String>? = null private val eventListener: EventListener = mock() private val auditManager = mock<AuditManager>() @Before fun setup() { cacheManager = DefaultCacheManager() cacheManager!!.start() cache = cacheManager!!.getCache("test") dao = TestDao(cache!!, eventListener, auditManager) } @After fun cleanup() { cacheManager?.stop() } @Test fun get() { val orig = TestEntity() cache!!["A"] = orig val entity = dao!!["A"] Assert.assertEquals(orig, entity) } }
apache-2.0
15beeaf017bf413c395d98fc0309a370
25.90566
106
0.757193
3.663239
false
true
false
false
duftler/clouddriver
cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/cats/sql/controllers/CatsSqlAdminController.kt
1
4671
package com.netflix.spinnaker.cats.sql.controllers import com.netflix.spinnaker.cats.sql.cache.SqlSchemaVersion import com.netflix.spinnaker.fiat.shared.FiatPermissionEvaluator import com.netflix.spinnaker.kork.sql.config.SqlProperties import com.netflix.spinnaker.security.AuthenticatedRequest import org.jooq.SQLDialect import org.jooq.impl.DSL import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.security.authentication.BadCredentialsException import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.sql.DriverManager // TODO: Replace validatePermissions() with a to-be-implemented fiat isAdmin() decorator @ConditionalOnProperty("sql.cache.enabled") @EnableConfigurationProperties(SqlProperties::class) @RestController @RequestMapping("/admin/db") class CatsSqlAdminController( private val fiat: FiatPermissionEvaluator, private val properties: SqlProperties ) { companion object { private val log by lazy { LoggerFactory.getLogger(CatsSqlAdminController::class.java) } } @PutMapping(path = ["/truncate/{namespace}"]) fun truncateTables( @PathVariable("namespace") truncateNamespace: String, @Value("\${sql.table-namespace:#{null}}") currentNamespace: String? ): CleanTablesResult { validatePermissions() validateParams(currentNamespace, truncateNamespace) val conn = DriverManager.getConnection( properties.migration.jdbcUrl, properties.migration.user, properties.migration.password ) val tablesTruncated = mutableListOf<String>() val sql = "show tables like 'cats_v${SqlSchemaVersion.current()}_${truncateNamespace}_%'" conn.use { c -> val jooq = DSL.using(c, SQLDialect.MYSQL) val rs = jooq.fetch(sql).intoResultSet() while (rs.next()) { val table = rs.getString(1) val truncateSql = "truncate table `$table`" log.info("Truncating $table") jooq.query(truncateSql).execute() tablesTruncated.add(table) } } return CleanTablesResult(tableCount = tablesTruncated.size, tables = tablesTruncated) } @PutMapping(path = ["/drop/{namespace}"]) fun dropTables( @PathVariable("namespace") dropNamespace: String, @Value("\${sql.table-namespace:#{null}}") currentNamespace: String? ): CleanTablesResult { validatePermissions() validateParams(currentNamespace, dropNamespace) val conn = DriverManager.getConnection( properties.migration.jdbcUrl, properties.migration.user, properties.migration.password ) val tablesDropped = mutableListOf<String>() val sql = "show tables like 'cats_v${SqlSchemaVersion.current()}_${dropNamespace}_%'" conn.use { c -> val jooq = DSL.using(c, SQLDialect.MYSQL) val rs = jooq.fetch(sql).intoResultSet() while (rs.next()) { val table = rs.getString(1) val dropSql = "drop table `$table`" log.info("Dropping $table") jooq.query(dropSql).execute() tablesDropped.add(table) } } return CleanTablesResult(tableCount = tablesDropped.size, tables = tablesDropped) } private fun validateParams(currentNamespace: String?, targetNamespace: String) { if (currentNamespace == null) { throw IllegalStateException("truncate can only be called when sql.tableNamespace is set") } if (!targetNamespace.matches("""^\w+$""".toRegex())) { throw IllegalArgumentException("tableNamespace can only contain characters [a-z, A-Z, 0-9, _]") } if (currentNamespace.toLowerCase() == targetNamespace.toLowerCase()) { throw IllegalArgumentException("truncate cannot be called for the currently active namespace") } } private fun validatePermissions() { val user = AuthenticatedRequest.getSpinnakerUser() if (!user.isPresent) { throw BadCredentialsException("Unauthorized") } try { val perms = fiat.getPermission(user.get()) if (!perms.isAdmin) { throw BadCredentialsException("Unauthorized") } } catch (e: Exception) { log.error("Failed looking up fiat permissions for user ${user.get()}") throw BadCredentialsException("Unauthorized", e) } } } data class CleanTablesResult( val tableCount: Int, val tables: Collection<String> )
apache-2.0
36c9c1d8b2ee4ddb2d3e851db265607a
32.364286
101
0.724042
4.423295
false
false
false
false
hazuki0x0/YuzuBrowser
module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/preference/FloatSeekbarPreference.kt
1
5007
package jp.hazuki.yuzubrowser.ui.preference import android.app.AlertDialog import android.content.Context import android.content.res.TypedArray import android.text.InputType import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.EditText import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import androidx.preference.DialogPreference import androidx.preference.Preference import jp.hazuki.yuzubrowser.ui.R class FloatSeekbarPreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs) { private val mSeekMin: Int private val mSeekMax: Int private val mDenominator: Int var value: Float = 0.toFloat() set(value) { field = value persistFloat(value) } init { var a = context.obtainStyledAttributes(attrs, R.styleable.SeekbarPreference) mSeekMin = a.getInt(R.styleable.SeekbarPreference_seekMin, 0) mSeekMax = a.getInt(R.styleable.SeekbarPreference_seekMax, 100) a.recycle() a = context.obtainStyledAttributes(attrs, R.styleable.FloatSeekbarPreference) mDenominator = a.getInt(R.styleable.FloatSeekbarPreference_denominator, 0) a.recycle() } override fun onGetDefaultValue(a: TypedArray?, index: Int): Any { return a!!.getFloat(index, -1f) } override fun onSetInitialValue(defaultValue: Any?) { value = defaultValue as? Float ?: getPersistedFloat(value) } class PreferenceDialog : YuzuPreferenceDialog() { private var mTempValue: Int = 0 override fun onCreateDialogView(context: Context): View { val pref = preference as FloatSeekbarPreference val view = LayoutInflater.from(getContext()).inflate(R.layout.seekbar_preference, null) val textView = view.findViewById<TextView>(R.id.countTextView) val seekbar = view.findViewById<SeekBar>(R.id.seekBar) seekbar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener { override fun onStopTrackingTouch(seekBar: SeekBar) { mTempValue = seekBar.progress textView.text = ((mTempValue + pref.mSeekMin) / pref.mDenominator.toFloat()).toString() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { textView.text = ((progress + pref.mSeekMin) / pref.mDenominator.toFloat()).toString() } }) seekbar.max = pref.mSeekMax - pref.mSeekMin mTempValue = (pref.value * pref.mDenominator).toInt() - pref.mSeekMin seekbar.progress = mTempValue view.findViewById<View>(R.id.prevImageButton).setOnClickListener { if (mTempValue > 0) seekbar.progress = --mTempValue } view.findViewById<View>(R.id.nextImageButton).setOnClickListener { if (mTempValue < pref.mSeekMax - pref.mSeekMin) seekbar.progress = ++mTempValue } textView.setOnClickListener { val edittext = EditText(getContext()) edittext.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL edittext.setText(((mTempValue + pref.mSeekMin) / pref.mDenominator.toFloat()).toString()) AlertDialog.Builder(getContext()) .setView(edittext) .setPositiveButton(android.R.string.ok) { _, _ -> try { val value = (java.lang.Float.parseFloat(edittext.text.toString()) * pref.mDenominator).toInt() if (value >= pref.mSeekMin && value <= pref.mSeekMax) mTempValue = value - pref.mSeekMin seekbar.progress = mTempValue } catch (e: NumberFormatException) { e.printStackTrace() } } .setNegativeButton(android.R.string.cancel, null) .show() } return view } override fun onDialogClosed(positiveResult: Boolean) { val pref = preference as FloatSeekbarPreference if (positiveResult) { if (pref.callChangeListener(mTempValue + pref.mSeekMin)) { pref.value = (mTempValue + pref.mSeekMin) / pref.mDenominator.toFloat() } } } companion object { fun newInstance(preference: Preference): YuzuPreferenceDialog { return YuzuPreferenceDialog.newInstance(PreferenceDialog(), preference) } } } }
apache-2.0
1db7b35b2d7d810fb2942dc9e7e4c822
40.380165
126
0.604953
4.923304
false
false
false
false
Yorxxx/played-next-kotlin
app/src/test/java/com/piticlistudio/playednext/domain/interactor/game/LoadGameUseCaseTest.kt
1
2295
package com.piticlistudio.playednext.domain.interactor.game import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import com.piticlistudio.playednext.domain.model.Game import com.piticlistudio.playednext.domain.repository.GameRepository import com.piticlistudio.playednext.test.factory.GameFactory.Factory.makeGame import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.subscribers.TestSubscriber import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.MockitoAnnotations class LoadGameUseCaseTest { @Nested @DisplayName("Given a LoadGameUseCase instance") inner class LoadGameUseCaseInstance { @Mock lateinit var repository: GameRepository private val gameId = 10 private var useCase: LoadGameUseCase? = null @BeforeEach internal fun setUp() { MockitoAnnotations.initMocks(this) useCase = LoadGameUseCase(repository) } @Nested @DisplayName("When execute is called") inner class ExecuteIsCalled { private var testObserver: TestSubscriber<Game>? = null val result = makeGame() @BeforeEach internal fun setup() { val flowable = Flowable.create<Game>({ it.onNext(result) }, BackpressureStrategy.MISSING) whenever(repository.load(gameId)).thenReturn(flowable) testObserver = useCase?.execute(gameId)!!.test() } @Test @DisplayName("Then requests repository") fun requestsRepository() { verify(repository).load(gameId) } @Test @DisplayName("Then emits without errors") fun withoutErrors() { assertNotNull(testObserver) testObserver?.apply { assertNoErrors() assertNotComplete() assertValue(result) } } } } }
mit
26a1582f971171b7b9aa7a681f0018fb
31.289855
105
0.631373
5.275862
false
true
false
false
Litote/kmongo
kmongo-property/src/main/kotlin/org/litote/kmongo/Indexes.kt
1
4091
/* * Copyright (C) 2016/2022 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo import com.mongodb.client.model.Indexes import org.bson.BsonDocument import org.bson.BsonInt32 import org.bson.conversions.Bson import kotlin.reflect.KProperty /** * Create an index key for an ascending index on the given fields. * * @param properties the properties, which must contain at least one * @return the index specification * @mongodb.driver.manual core/indexes indexes */ fun ascendingIndex(vararg properties: KProperty<*>): Bson = Indexes.ascending(properties.map { it.path() }) /** * Create an index key for an ascending index on the given fields. * * @param properties the properties, which must contain at least one * @return the index specification * @mongodb.driver.manual core/indexes indexes */ fun ascendingIndex(properties: Iterable<KProperty<*>>): Bson = Indexes.ascending(properties.map { it.path() }) /** * Create an index key for a descending index on the given fields. * * @param properties the properties, which must contain at least one * @return the index specification * @mongodb.driver.manual core/indexes indexes */ fun descendingIndex(vararg properties: KProperty<*>): Bson = Indexes.descending(properties.map { it.path() }) /** * Create an index key for a descending index on the given fields. * * @param properties the properties, which must contain at least one * @return the index specification * @mongodb.driver.manual core/indexes indexes */ fun descendingIndex(properties: Iterable<KProperty<*>>): Bson = Indexes.descending(properties.map { it.path() }) /** * Create an index key for an 2dsphere index on the given fields. * * @param properties the properties, which must contain at least one * @return the index specification * @mongodb.driver.manual core/2dsphere 2dsphere Index */ fun geo2dsphere(vararg properties: KProperty<*>): Bson = Indexes.geo2dsphere(properties.map { it.path() }) /** * Create an index key for an 2dsphere index on the given fields. * * @param properties the properties, which must contain at least one * @return the index specification * @mongodb.driver.manual core/2dsphere 2dsphere Index */ fun geo2dsphere(properties: Iterable<KProperty<*>>): Bson = Indexes.geo2dsphere(properties.map { it.path() }) /** * Create an index key for a text index on the given property. * * @return the index specification * @mongodb.driver.manual core/text text index */ fun <T> KProperty<T>.textIndex(): Bson = Indexes.text(path()) /** * Create an index key for a hashed index on the given property. * * @return the index specification * @mongodb.driver.manual core/hashed hashed index */ fun <T> KProperty<T>.hashedIndex(): Bson = Indexes.hashed(path()) /** * Create a compound index specifications. If any properties are repeated, the last one takes precedence. * * @param indexes the index specifications * @return the compound index specification * @mongodb.driver.manual core/index-compound compoundIndex */ fun index(vararg properties: Pair<KProperty<*>, Boolean>): Bson = index(properties.toMap()) /** * Create a compound multiple index specifications. * If any properties are repeated, the last one takes precedence. * * @param indexes the index specifications * @return the compound index specification * @mongodb.driver.manual core/index-compound compoundIndex */ fun index(properties: Map<KProperty<*>, Boolean>): Bson = Indexes.compoundIndex(properties.map { BsonDocument(it.key.path(), BsonInt32(if (it.value) 1 else -1)) })
apache-2.0
6f21a170b9cb9f5aa510d4a982e85adf
34.885965
112
0.741628
4.022616
false
false
false
false
osfans/trime
app/src/main/java/com/osfans/trime/data/db/draft/DraftHelper.kt
1
3476
package com.osfans.trime.data.db.draft import android.content.Context import androidx.room.Room import com.osfans.trime.data.AppPrefs import com.osfans.trime.data.db.Database import com.osfans.trime.data.db.DatabaseBean import com.osfans.trime.data.db.DatabaseDao import com.osfans.trime.ime.core.Trime import com.osfans.trime.util.StringUtils.mismatch import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import timber.log.Timber object DraftHelper : CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { private lateinit var dftDb: Database private lateinit var dftDao: DatabaseDao private val mutex = Mutex() var itemCount: Int = 0 private set private suspend fun updateItemCount() { itemCount = dftDao.itemCount() } private val limit get() = AppPrefs.defaultInstance().other.draftLimit.toInt() private val output get() = AppPrefs.defaultInstance().other.draftOutputRules var lastBean: DatabaseBean? = null fun init(context: Context) { dftDb = Room .databaseBuilder(context, Database::class.java, "draft.db") .addMigrations(Database.MIGRATION_3_4) .build() dftDao = dftDb.databaseDao() launch { updateItemCount() } } suspend fun get(id: Int) = dftDao.get(id) suspend fun getAll() = dftDao.getAll() suspend fun pin(id: Int) = dftDao.updatePinned(id, true) suspend fun unpin(id: Int) = dftDao.updatePinned(id, false) suspend fun updateText(id: Int, text: String) = dftDao.updateText(id, text) suspend fun delete(id: Int) { dftDao.delete(id) updateItemCount() } suspend fun deleteAll(skipUnpinned: Boolean = true) { if (skipUnpinned) { dftDao.deleteAllUnpinned() } else { dftDao.deleteAll() } } fun onInputEventChanged() { if (!(limit != 0 && this::dftDao.isInitialized)) return Trime.getService() .currentInputConnection ?.let { DatabaseBean.fromInputConnection(it) } ?.takeIf { it.text!!.isNotBlank() && it.text.mismatch(output.toTypedArray()) } ?.let { b -> Timber.d("Accept $b") launch { mutex.withLock { val all = dftDao.getAll() var pinned = false all.find { b.text == it.text }?.let { dftDao.delete(it.id) pinned = it.pinned } val rowId = dftDao.insert(b.copy(pinned = pinned)) removeOutdated() updateItemCount() dftDao.get(rowId)?.let { lastBean = it } } } } } private suspend fun removeOutdated() { val all = dftDao.getAll() if (all.size > limit) { val outdated = all .map { if (it.pinned) it.copy(id = Int.MAX_VALUE) else it } .sortedBy { it.id } .subList(0, all.size - limit) dftDao.delete(outdated) } } }
gpl-3.0
244d60d48c4f942ba57af975b209cff1
31.185185
94
0.572209
4.334165
false
false
false
false
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/Expression.kt
1
1394
package org.jetbrains.exposed.sql import java.util.* class QueryBuilder(val prepared: Boolean) { val args = ArrayList<Pair<IColumnType, Any?>>() fun <T> registerArgument(sqlType: IColumnType, argument: T) = registerArguments(sqlType, listOf(argument)).single() fun <T> registerArguments(sqlType: IColumnType, arguments: Iterable<T>): List<String> { val argumentsAndStrings = arguments.map { it to sqlType.valueToString(it) }.sortedBy { it.second } return argumentsAndStrings.map { if (prepared) { args.add(sqlType to it.first) "?" } else { it.second } } } } abstract class Expression<out T> { private val _hashCode by lazy { toString().hashCode() } abstract fun toSQL(queryBuilder: QueryBuilder): String override fun equals(other: Any?): Boolean = (other as? Expression<*>)?.toString() == toString() override fun hashCode(): Int = _hashCode override fun toString(): String = toSQL(QueryBuilder(false)) companion object { inline fun <T> build(builder: SqlExpressionBuilder.()->Expression<T>): Expression<T> = SqlExpressionBuilder.builder() } } abstract class ExpressionWithColumnType<out T> : Expression<T>() { // used for operations with literals abstract val columnType: IColumnType }
mit
894cd21f0466aac2ee99db5f3218d9b0
29.304348
119
0.640603
4.570492
false
false
false
false
Tenkiv/Tekdaqc-JVM-Library
src/test/kotlin/com/tenkiv/tekdaqc/communication/command/queue/QueueCallbackSpec.kt
2
2238
package com.tenkiv.tekdaqc.communication.command.queue import com.tenkiv.tekdaqc.communication.tasks.ITaskComplete import com.tenkiv.tekdaqc.hardware.ATekdaqc import com.tenkiv.tekdaqc.serializeToAny import io.kotlintest.matchers.plusOrMinus import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.ShouldSpec /** * Class to test QueueCallbacks */ class QueueCallbackSpec : ShouldSpec({ "Queue Callback Spec"{ var taskCompleteCheck = false var taskFailedCheck = false val callbackListener = object : ITaskComplete { override fun onTaskSuccess(tekdaqc: ATekdaqc?) { taskCompleteCheck = true } override fun onTaskFailed(tekdaqc: ATekdaqc?) { taskFailedCheck = true } } var queueCallback: QueueCallback should("Initialize correctly") { queueCallback = QueueCallback(callbackListener) queueCallback = QueueCallback(listOf(callbackListener)) queueCallback = QueueCallback(listOf(callbackListener),false) } should("Have sane values"){ queueCallback = QueueCallback() queueCallback.isInternalDelimiter shouldBe false queueCallback.removeCallback(callbackListener) queueCallback.addCallback(callbackListener) queueCallback.removeCallback(callbackListener) } should("Send callbacks successfully"){ queueCallback = QueueCallback() queueCallback.addCallback(callbackListener) queueCallback.success(null) queueCallback.failure(null) taskCompleteCheck shouldBe true taskFailedCheck shouldBe true } should("Serialize"){ queueCallback = QueueCallback() queueCallback.uid = uid queueCallback.uid shouldBe uid.plusOrMinus(uidVariance) val obj = serializeToAny(queueCallback) (obj is QueueCallback) shouldBe true (obj as QueueCallback).uid shouldBe uid.plusOrMinus(uidVariance) } } }){ companion object { const val uid = 10.0 const val uidVariance = 0.0001 } }
apache-2.0
d40b8d74f54806dea2acb52734fa1dd9
24.735632
76
0.6479
5.228972
false
false
false
false
vincent-maximilian/slakoverflow
src/main/kotlin/jmailen/slakoverflow/stackoverflow/QuestionPage.kt
1
668
package jmailen.slakoverflow.stackoverflow import jmailen.jsoup.DocumentProvider import org.jsoup.nodes.Document class QuestionPage(val questionId: Int, documentProvider: DocumentProvider = DocumentProvider()) { val page: Document init { page = documentProvider.documentAt(url()) } fun url() = "http://stackoverflow.com/questions/$questionId" fun answerUrl(answerId: Int) = "http://stackoverflow.com/a/$answerId" fun questionPostHtml() = page.select("#question .post-text").first().html().trim() fun answerPostHtml(answerId: Int) = page.select("#answer-$answerId .post-text").first().html().trim() }
mit
d47914265e3d2a7238f980c899887b5c
28.043478
98
0.69012
4.024096
false
false
false
false
azizbekian/Spyur
app/src/main/kotlin/com/incentive/yellowpages/ui/detail/maps/MapsActivity.kt
1
3766
package com.incentive.yellowpages.ui.detail.maps import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.support.annotation.NonNull import android.widget.Toast import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.maps.MapsInitializer import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.incentive.yellowpages.R import com.incentive.yellowpages.data.model.ListingResponse import com.incentive.yellowpages.misc.hasVersionM import com.incentive.yellowpages.ui.base.BaseActivity import com.incentive.yellowpages.ui.detail.maps.MapsPresenter.Companion.LOCATION_PERMISSION_REQUEST_CODE import com.incentive.yellowpages.utils.PermissionUtils import java.util.* import javax.inject.Inject class MapsActivity : BaseActivity(), MapsView { companion object { fun launch(context: Context, @NonNull listingResponse: ListingResponse) { val intent = Intent(context, MapsActivity::class.java) intent.putParcelableArrayListExtra( MapsPresenter.KEY_COORDINATES, ArrayList<Parcelable>(listingResponse.contactInfos)) context.startActivity(intent) } fun launch(activity: Activity, latLng: LatLng?) { val intent = Intent(activity, MapsActivity::class.java) intent.putExtra(MapsPresenter.KEY_SINGLE_COORDINATE, latLng) activity.startActivity(intent) } } @Inject lateinit var presenter: MapsPresenter override fun onCreate(savedInstanceState: Bundle?) { MapsInitializer.initialize(applicationContext) super.onCreate(savedInstanceState) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) setContentView(R.layout.activity_map) activityComponent.injectActivityComponent(this) presenter.create(this, intent = intent) } override fun onStart() { super.onStart() presenter.start() } override fun onResume() { super.onResume() presenter.resume() } override fun onPause() { presenter.pause() if (isFinishing) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } super.onPause() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (!presenter.permissionResult(requestCode, permissions, grantResults)) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } override fun initApiClient() { presenter.setupApiClient(GoogleApiClient.Builder(this)) } override fun initMap() { val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync({ presenter.onMapReady(it) }) } override fun showMessage(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } @SuppressLint("NewApi") override fun shouldAskPermission(permissionArr: Array<String>): Boolean = hasVersionM() && !PermissionUtils.isPermissionsGranted(this, permissionArr) override fun askForPermission(permissionArr: Array<String>) { PermissionUtils.requestPermissions(this, LOCATION_PERMISSION_REQUEST_CODE, permissionArr) } override fun showMissingPermissionError() { PermissionUtils.PermissionDeniedDialog.newInstance(false) .show(supportFragmentManager, "dialog") } override fun fetchActivity(): Activity = this }
gpl-2.0
5f1d60ece159e1b7a16d94e173e29164
34.196262
119
0.718003
4.791349
false
false
false
false
DyingSwan/creativepoo
company/14502/occidere/main.kt
1
1764
import java.io.BufferedReader import java.io.BufferedWriter import java.io.InputStreamReader import java.io.OutputStreamWriter var N = 0 var M = 0 var map = Array<Array<Int>>(0, {Array<Int>(0, {0})}) val dx = intArrayOf(-1, 1, 0, 0) val dy = intArrayOf(0, 0, -1, 1) fun main(args: Array<String>){ val br = BufferedReader(InputStreamReader(System.`in`)) val bw = BufferedWriter(OutputStreamWriter(System.out)) var line = br.readLine().split(" ") N = line[0].toInt(); M = line[1].toInt() map = Array<Array<Int>>(N, {Array<Int>(M, {0})}) for(i in 0 until N){ line = br.readLine().split(" ") for(j in 0 until M) map[i][j] = line[j].toInt() } bw.write(buildWall(map, 0).toString()) bw.close() br.close() } fun buildWall(map: Array<Array<Int>>, step: Int): Int { if(step == 3) return getSafe(map) var safe = -1 for(i in 0 until N) for(j in 0 until M) if(map[i][j]==0){ map[i][j] = 1 safe = Math.max(buildWall(map, step+1), safe) map[i][j] = 0 } return safe } fun getSafe(map: Array<Array<Int>>): Int { var area = 0 var backup = copy(map) for(i in 0 until N) for(j in 0 until M) if(backup[i][j]==2) spreadVirus(backup, i, j) for(i in 0 until N) for(j in 0 until M) if(backup[i][j]==0) area++ return area } fun spreadVirus(map: Array<Array<Int>>, x: Int, y: Int) { for(i in 0 until 4){ var ax = x+dx[i] var ay = y+dy[i] if(isInRange(ax, ay) && map[ax][ay]==0){ map[ax][ay] = 2 spreadVirus(map, ax, ay) } } } fun isInRange(x: Int, y: Int): Boolean { return (0<=x&&x<N) && (0<=y&&y<M) } fun copy(map: Array<Array<Int>>): Array<Array<Int>> { var newArr = Array<Array<Int>>(N, {Array<Int>(M, {0})}) for(i in 0 until N) for(j in 0 until M) newArr[i][j] = map[i][j] return newArr }
apache-2.0
1a1aa17bc957ec8de4832fa30568fc18
21.05
57
0.606576
2.419753
false
false
false
false
google/grpc-kapt
processor-annotations/src/main/kotlin/com/google/api/grpc/kapt/GrpcServer.kt
1
1990
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.grpc.kapt import kotlin.reflect.KClass /** * Marks a gRPC service implementation. * * The fully qualified name of the service will be: [packageName].[name] * * A [marshaller] can be provided to override the default [GrpcMarshaller] and * must be a singleton object that implements [MarshallerProvider]. * * Example: * ``` * import com.google.api.grpc.kapt.GrpcServer * import kotlinx.coroutines.channels.ReceiveChannel * * @GrpcServer("Ask") * class MyServiceServer : MyService, CoroutineScope { * // implement the interface... * } * * @GrpcClient("Ask") * interface MyService { * // a unary method (most common type) * suspend fun ask(question: Question): Answer * * // server streaming * suspend fun lecture(topic: Question): ReceiveChannel<Answer> * * // client streaming * suspend fun listen(questions: ReceiveChannel<Question>): Answer * * // bidirectional streaming * suspend fun debate(questions: ReceiveChannel<Question>): ReceiveChannel<Answer> * } * * // Create a server * val server = MyServiceServer().asGrpcServer(8080) * server.start() * ``` */ @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.CLASS) annotation class GrpcServer( val name: String = "", val packageName: String = "", val marshaller: KClass<*> = Unit::class, val suffix: String = "Impl" )
apache-2.0
a07ff645ae4fa2d0872c179f0337078b
29.151515
86
0.703518
4.06953
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/RustNumericLiteralImpl.kt
1
3799
package org.rust.lang.core.psi.impl import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElementVisitor import com.intellij.psi.tree.IElementType import org.rust.lang.core.psi.RustLiteral import org.rust.lang.core.psi.RustLiteralTokenType import org.rust.lang.core.psi.RustTokenElementTypes.FLOAT_LITERAL import org.rust.lang.core.psi.RustTokenElementTypes.INTEGER_LITERAL import org.rust.lang.core.psi.visitors.RustVisitorEx class RustNumericLiteralImpl(type: IElementType, text: CharSequence) : RustLiteral.Number(type, text) { override val valueAsLong: Long? get() = this.valueString ?.filter { it != '_' } ?.let { // We do not expect negative values, because they are treated as // unary expressions, not literals, in our lexing/parsing code. val (start, radix) = when (it.take(2)) { "0b" -> 2 to 2 "0o" -> 2 to 8 "0x" -> 2 to 16 else -> 0 to 10 } try { java.lang.Long.parseLong(it.substring(start), radix) // TODO: Replace this with: (when we migrate to Java 8) // java.lang.Long.parseUnsignedLong(it.substring(start), radix) } catch(e: NumberFormatException) { null } } override val valueAsDouble: Double? get() = this.valueString ?.filter { it != '_' } ?.let { try { it.toDouble() } catch(e: NumberFormatException) { null } } override val possibleSuffixes: Collection<String> get() = when (elementType) { INTEGER_LITERAL -> VALID_INTEGER_SUFFIXES FLOAT_LITERAL -> VALID_FLOAT_SUFFIXES else -> error("unreachable") } override val isInt: Boolean get() = elementType == INTEGER_LITERAL override val isFloat: Boolean get() = elementType == FLOAT_LITERAL override fun toString(): String = "RustNumericLiteralImpl($elementType)" override fun computeOffsets(): Offsets { val (start, digits) = when (text.take(2)) { "0b" -> 2 to BIN_DIGIT "0o" -> 2 to OCT_DIGIT "0x" -> 2 to HEX_DIGIT else -> 0 to DEC_DIGIT } var hasExponent = false text.substring(start).forEachIndexed { i, ch -> if (!hasExponent && ch in EXP_CHARS) { hasExponent = true } else if (ch !in digits && ch !in NUM_OTHER_CHARS) { return Offsets( value = TextRange.create(0, i + start), suffix = TextRange(i + start, textLength)) } } return Offsets(value = TextRange.allOf(text)) } override fun accept(visitor: PsiElementVisitor) = when (visitor) { is RustVisitorEx -> visitor.visitNumericLiteral(this) else -> super.accept(visitor) } companion object { private val VALID_INTEGER_SUFFIXES = listOf("u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", "isize", "usize") private val VALID_FLOAT_SUFFIXES = listOf("f32", "f64") private const val DEC_DIGIT = "0123456789" private const val BIN_DIGIT = "01" private const val OCT_DIGIT = "01234567" private const val HEX_DIGIT = "0123456789abcdefABCDEF" private const val NUM_OTHER_CHARS = "+-_." private const val EXP_CHARS = "eE" @JvmStatic fun createTokenType(debugName: String): RustLiteralTokenType = RustLiteralTokenType(debugName, ::RustNumericLiteralImpl) } }
mit
7b3ea46c042237a424eb034e3c79d7c9
36.99
123
0.560937
4.391908
false
false
false
false
mrtnzlml/native
android/react-native-native-modules/src/main/java/com/skypicker/reactnative/nativemodules/logging/RNLoggingModule.kt
1
5004
package com.skypicker.reactnative.nativemodules.logging import com.facebook.react.bridge.* import com.trinerdis.skypicker.logging.event.model.* import com.trinerdis.skypicker.logging.sender.* import java.util.HashMap class RNLoggingModule(reactContext: ReactApplicationContext, activeBooking: Boolean) : ReactContextBaseJavaModule(reactContext) { // region Public Types private object AncillaryTypeKey { const val HOTEL = "HOTEL" } private object AncillaryType { const val HOTEL = "hotel" } private object AncillaryStepKey { const val SEARCH_FORM = "ANCILLARY_STEP_SEARCH_FORM" const val RESULTS = "ANCILLARY_STEP_RESULTS" const val DETAILS = "ANCILLARY_STEP_DETAILS" const val PAYMENT = "ANCILLARY_STEP_PAYMENT" } private object AncillaryStep { const val SEARCH_FORM = "searchForm" const val RESULTS = "results" const val DETAILS = "details" const val PAYMENT = "payment" } private object Implementation { const val REACT = "react" } private object AncillaryProviderKey { const val BOOKINGCOM = "ANCILLARY_PROVIDER_BOOKINGCOM" const val STAY22 = "ANCILLARY_PROVIDER_STAY22" } private object AncillaryProvider { const val BOOKINGCOM = "booking.com" const val STAY22 = "stay22" } private object HotelsGalleryTypeKey { const val HOTEL = "HOTELS_GALLERY_TYPE_HOTEL" const val ROOM = "HOTELS_GALLERY_TYPE_ROOM" } private object HotelsGalleryType { const val HOTEL = "HOTEL" const val ROOM = "ROOM" } // endregion Public Types // region Private Constants private object Constants { const val TAG = "RNLoggingModule" } // endregion Private Constants // region Public Attributes private val hasActiveBooking = activeBooking // endregion Public Attributes // region Private Attributes private val eventSenders: EventSender = EventSender.getInstance() // endregion Private Attributes // region Public Methods override fun getName() = Constants.TAG override fun getConstants(): Map<String, Any>? { val constants = HashMap<String, Any>() constants[AncillaryStepKey.SEARCH_FORM] = AncillaryStep.SEARCH_FORM constants[AncillaryStepKey.RESULTS] = AncillaryStep.RESULTS constants[AncillaryStepKey.DETAILS] = AncillaryStep.DETAILS constants[AncillaryStepKey.PAYMENT] = AncillaryStep.PAYMENT constants[AncillaryTypeKey.HOTEL] = AncillaryType.HOTEL constants[AncillaryProviderKey.BOOKINGCOM] = AncillaryProvider.BOOKINGCOM constants[AncillaryProviderKey.STAY22] = AncillaryProvider.STAY22 constants[HotelsGalleryTypeKey.HOTEL] = HotelsGalleryType.HOTEL constants[HotelsGalleryTypeKey.ROOM] = HotelsGalleryType.ROOM return constants } @ReactMethod fun ancillaryDisplayed(type: String, provider: String) { eventSenders.sendEvent( AncillaryDisplayed(type, provider, null, null, null, hasActiveBooking, Implementation.REACT) ) } @ReactMethod fun ancillaryPurchased(type: String, provider: String) { eventSenders.sendEvent( AncillaryPurchased(type, provider, hasActiveBooking, Implementation.REACT) ) } @ReactMethod fun hotelsResultsDisplayed(searchQuery: String?, params: String?) { eventSenders.sendEvent( HotelsResultsDisplayed(searchQuery, params) ) } @ReactMethod fun hotelsSelectedFilterTag(filterTag: String) { eventSenders.sendEvent( HotelsFilterTagSet(filterTag) ) } @ReactMethod fun hotelsDetailOpened() { eventSenders.sendEvent( HotelsDetailOpened() ) } @ReactMethod fun hotelsDetailAbandoned() { eventSenders.sendEvent( HotelsDetailAbandoned() ) } @ReactMethod fun hotelsDetailDescriptionExpanded() { eventSenders.sendEvent( HotelsDetailDescriptionExpanded() ) } @ReactMethod fun hotelsDetailMapOpened() { eventSenders.sendEvent( HotelsDetailMapOpened() ) } @ReactMethod fun hotelsDetailRoomSelected(hotelId: String, roomType: String) { eventSenders.sendEvent( HotelsDetailRoomSelected(hotelId, roomType) ) } @ReactMethod fun hotelsGalleryOpened(type: String) { eventSenders.sendEvent( HotelsGalleryOpened(HotelsGalleryOpened.Type.valueOf(type)) ) } @ReactMethod fun hotelsBookNowPressed(hotelId: String, rooms: Int, guests: Int, price: Float, formattedPrice: String) { eventSenders.sendEvent( HotelsBookNowPressed(hotelId, rooms, guests, price, formattedPrice) ) } // endregion Public Methods }
mit
cea1da7ee9cf2dc6af96b33a37e6ebad
26.8
110
0.661271
4.251487
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/github/tablayout/ScaleAnimImageView.kt
1
1449
package com.angcyo.uiview.github.tablayout import android.content.Context import android.support.v4.view.MotionEventCompat import android.support.v4.view.ViewCompat import android.support.v7.widget.AppCompatImageView import android.util.AttributeSet import android.view.MotionEvent import android.view.animation.BounceInterpolator /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述: * 创建人员:Robi * 创建时间:2017/08/04 15:55 * 修改人员:Robi * 修改时间:2017/08/04 15:55 * 修改备注: * Version: 1.0.0 */ open class ScaleAnimImageView(context: Context, attributeSet: AttributeSet? = null) : AppCompatImageView(context, attributeSet) { var enableScaleAnim = false override fun onTouchEvent(event: MotionEvent?): Boolean { if (enableScaleAnim) { val masked = MotionEventCompat.getActionMasked(event) if (masked == MotionEvent.ACTION_DOWN) { ViewCompat.setScaleX(this, 0.5f) ViewCompat.setScaleY(this, 0.5f) this.animate() .scaleX(1f) .scaleY(1f) .setInterpolator(BounceInterpolator()) .setDuration(300) .start() } } return super.onTouchEvent(event) } }
apache-2.0
9bd6a6bf03552b1e21f71c0fd4bff4b9
30.166667
129
0.616753
4.309904
false
false
false
false
raniejade/kspec
kspec-core/src/test/kotlin/io/polymorphicpanda/kspec/helpers/MemoizedHelperTest.kt
1
940
package io.polymorphicpanda.kspec.helpers import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.sameInstance import com.natpryce.hamkrest.throws import org.junit.Test /** * @author Ranie Jade Ramiso */ class MemoizedHelperTest { @Test fun testLazy() { val memoized = MemoizedHelper<String>({ throw UnsupportedOperationException() }) assertThat({ memoized.get() }, throws<UnsupportedOperationException>()) } @Test fun testCached() { val memoized = MemoizedHelper({ Any() }) val first = memoized.get() assertThat(first, sameInstance(memoized.get())) } @Test fun testForget() { val memoized = MemoizedHelper({ Any() }) val first = memoized.get() memoized.forget() assertThat(first, !sameInstance(memoized.get())) } }
mit
e12a15bcd24f41f40ea7d9100400b5cb
19
56
0.601064
4.723618
false
true
false
false
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/projects/list/RepoProjectPresenter.kt
1
10434
package com.fastaccess.ui.modules.repos.projects.list import android.os.Bundle import android.view.View import com.apollographql.apollo.rx2.Rx2Apollo import com.fastaccess.data.dao.types.IssueState import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Logger import com.fastaccess.provider.rest.ApolloProdivder import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.fastaccess.ui.modules.repos.projects.details.ProjectPagerActivity import github.OrgProjectsClosedQuery import github.OrgProjectsOpenQuery import github.RepoProjectsClosedQuery import github.RepoProjectsOpenQuery import io.reactivex.Observable /** * Created by kosh on 09/09/2017. */ class RepoProjectPresenter : BasePresenter<RepoProjectMvp.View>(), RepoProjectMvp.Presenter { private val projects = arrayListOf<RepoProjectsOpenQuery.Node>() private var page: Int = 0 private var previousTotal: Int = 0 private var lastPage = Integer.MAX_VALUE @com.evernote.android.state.State var login: String = "" @com.evernote.android.state.State var repoId: String? = null var count: Int = 0 val pages = arrayListOf<String>() override fun onItemClick(position: Int, v: View, item: RepoProjectsOpenQuery.Node) { item.databaseId()?.let { ProjectPagerActivity.startActivity(v.context, login, repoId, it.toLong(), isEnterprise) } } override fun onItemLongClick(position: Int, v: View?, item: RepoProjectsOpenQuery.Node?) {} override fun onFragmentCreate(bundle: Bundle?) { bundle?.let { repoId = it.getString(BundleConstant.ID) login = it.getString(BundleConstant.EXTRA) ?: "" } } override fun getProjects(): ArrayList<RepoProjectsOpenQuery.Node> = projects override fun getCurrentPage(): Int = page override fun getPreviousTotal(): Int = previousTotal override fun setCurrentPage(page: Int) { this.page = page } override fun setPreviousTotal(previousTotal: Int) { this.previousTotal = previousTotal } override fun onCallApi(page: Int, parameter: IssueState?): Boolean { if (page == 1) { lastPage = Integer.MAX_VALUE sendToView { view -> view.getLoadMore().reset() } } if (page > lastPage || lastPage == 0 || parameter == null) { sendToView({ it.hideProgress() }) return false } currentPage = page Logger.e(login) val repoId = repoId val apollo = ApolloProdivder.getApollo(isEnterprise) if (repoId != null && !repoId.isNullOrBlank()) { if (parameter == IssueState.open) { val query = RepoProjectsOpenQuery.builder() .name(repoId) .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { response -> val list = arrayListOf<RepoProjectsOpenQuery.Node>() response.data()?.repository()?.let { repos -> repos.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { list.addAll(it) } } } return@flatMap Observable.just(list) } ) { sendToView { v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) } } } else { val query = RepoProjectsClosedQuery.builder() .name(repoId) .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { response -> val list = arrayListOf<RepoProjectsOpenQuery.Node>() response.data()?.repository()?.let { repository -> repository.projects().let { projects1 -> lastPage = if (projects1.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = projects1.totalCount() projects1.edges()?.let { edges -> pages.addAll(edges.map { it.cursor() }) } projects1.nodes()?.let { nodesList -> val toConvert = arrayListOf<RepoProjectsOpenQuery.Node>() nodesList.onEach { val columns = RepoProjectsOpenQuery.Columns(it.columns().__typename(), it.columns().totalCount()) val node = RepoProjectsOpenQuery.Node( it.__typename(), it.name(), it.number(), it.body(), it.createdAt(), it.id(), it.viewerCanUpdate(), columns, it.databaseId() ) toConvert.add(node) } list.addAll(toConvert) } } } return@flatMap Observable.just(list) } ) { sendToView { v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) } } } } else { if (parameter == IssueState.open) { val query = OrgProjectsOpenQuery.builder() .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { val list = arrayListOf<RepoProjectsOpenQuery.Node>() it.data()?.organization()?.let { it.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { val toConvert = arrayListOf<RepoProjectsOpenQuery.Node>() it.onEach { val columns = RepoProjectsOpenQuery.Columns(it.columns().__typename(), it.columns().totalCount()) val node = RepoProjectsOpenQuery.Node( it.__typename(), it.name(), it.number(), it.body(), it.createdAt(), it.id(), it.viewerCanUpdate(), columns, it.databaseId() ) toConvert.add(node) } list.addAll(toConvert) } } } return@flatMap Observable.just(list) } ) { sendToView { v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) } } } else { val query = OrgProjectsClosedQuery.builder() .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { val list = arrayListOf<RepoProjectsOpenQuery.Node>() it.data()?.organization()?.let { it.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { val toConvert = arrayListOf<RepoProjectsOpenQuery.Node>() it.onEach { val columns = RepoProjectsOpenQuery.Columns(it.columns().__typename(), it.columns().totalCount()) val node = RepoProjectsOpenQuery.Node( it.__typename(), it.name(), it.number(), it.body(), it.createdAt(), it.id(), it.viewerCanUpdate(), columns, it.databaseId() ) toConvert.add(node) } list.addAll(toConvert) } } } return@flatMap Observable.just(list) } ) { sendToView { v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) } } } } return true } private fun getPage(): String? = if (pages.isNotEmpty()) pages.last() else null }
gpl-3.0
d1fa77be190af82e5dd5f7a23accc7d1
44.767544
137
0.434828
5.739274
false
false
false
false
f-droid/fdroidclient
libs/index/src/commonMain/kotlin/org/fdroid/index/v2/IndexV2.kt
1
2560
package org.fdroid.index.v2 import kotlinx.serialization.Serializable @Serializable public data class EntryV2( val timestamp: Long, val version: Long, val maxAge: Int? = null, val index: EntryFileV2, val diffs: Map<String, EntryFileV2> = emptyMap(), ) { /** * @return the diff for the given [timestamp] or null if none exists * in which case the full [index] should be used. */ public fun getDiff(timestamp: Long): EntryFileV2? { return diffs[timestamp.toString()] } } @Serializable public data class EntryFileV2( val name: String, val sha256: String, val size: Long, val numPackages: Int, ) @Serializable public data class FileV2( val name: String, val sha256: String? = null, val size: Long? = null, ) @Serializable public data class IndexV2( val repo: RepoV2, val packages: Map<String, PackageV2> = emptyMap(), ) { public fun walkFiles(fileConsumer: (FileV2?) -> Unit) { repo.walkFiles(fileConsumer) packages.values.forEach { it.walkFiles(fileConsumer) } } } @Serializable public data class RepoV2( val name: LocalizedTextV2 = emptyMap(), val icon: LocalizedFileV2 = emptyMap(), val address: String, val webBaseUrl: String? = null, val description: LocalizedTextV2 = emptyMap(), val mirrors: List<MirrorV2> = emptyList(), val timestamp: Long, val antiFeatures: Map<String, AntiFeatureV2> = emptyMap(), val categories: Map<String, CategoryV2> = emptyMap(), val releaseChannels: Map<String, ReleaseChannelV2> = emptyMap(), ) { public fun walkFiles(fileConsumer: (FileV2?) -> Unit) { icon.values.forEach { fileConsumer(it) } antiFeatures.values.forEach { fileConsumer(it.icon) } categories.values.forEach { fileConsumer(it.icon) } } } public typealias LocalizedTextV2 = Map<String, String> public typealias LocalizedFileV2 = Map<String, FileV2> public typealias LocalizedFileListV2 = Map<String, List<FileV2>> @Serializable public data class MirrorV2( val url: String, val location: String? = null, ) @Serializable public data class AntiFeatureV2( val icon: FileV2? = null, val name: LocalizedTextV2, val description: LocalizedTextV2 = emptyMap(), ) @Serializable public data class CategoryV2( val icon: FileV2? = null, val name: LocalizedTextV2, val description: LocalizedTextV2 = emptyMap(), ) @Serializable public data class ReleaseChannelV2( val name: LocalizedTextV2, val description: LocalizedTextV2 = emptyMap(), )
gpl-3.0
e3929b94984c53aaf675c3bb7e47d0ad
25.666667
72
0.689844
3.79822
false
false
false
false
konachan700/Mew
software/MeWSync/app/src/main/java/com/mewhpm/mewsync/ui/fragmentpages/FragmentBook.kt
1
1466
package com.mewhpm.mewsync.ui.fragmentpages import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager class FragmentBook private constructor() { companion object { private val fb: HashMap<Int, FragmentBook> = HashMap() fun getInstance(classId: Int) : FragmentBook { if (!fb.containsKey(classId)) fb[classId] = FragmentBook() return fb[classId]!! } } var hostViewResId: Int? = null var fragmentManager: FragmentManager? = null var groupTopFragmentRequest: (group: String) -> Fragment = { throw NotImplementedError("groupTopFragmentRequest not implemented now") } var currentFragment: Fragment? = null fun showTopInGroup(group: String) { currentFragment = groupTopFragmentRequest(group) val transaction = fragmentManager!!.beginTransaction() transaction.replace(hostViewResId!!, currentFragment!!) transaction.commit() } } fun androidx.appcompat.app.AppCompatActivity.getFragmentBook(hostViewResId: Int) : FragmentBook { val fb = FragmentBook.getInstance(this.hashCode()) fb.fragmentManager = supportFragmentManager fb.hostViewResId = hostViewResId return fb } fun androidx.fragment.app.Fragment.getFragmentBook(hostViewResId: Int) : FragmentBook { val fb = FragmentBook.getInstance(this.hashCode()) fb.fragmentManager = fragmentManager fb.hostViewResId = hostViewResId return fb }
gpl-3.0
14c61d32f3a4d0971c44520c13dd94b6
33.928571
97
0.718281
4.729032
false
false
false
false
diyaakanakry/Diyaa
functionOverload.kt
1
391
fun sum(n1:Int,n2:Int):Int{ return n1+n2 } fun sum(n1:Int,n2:Int,n3:Int):Int{ return n1+n2+n3 } fun sum(n1:Int,n2:Int,n3:Int,n4:Int):Int{ return n1+n2+n3+n4 } fun main(args:Array<String>){ var sumNumber=sum(10,11) println("sum="+sumNumber) sumNumber=sum(10,11,15) println("sum="+sumNumber) sumNumber=sum(10,11,15,14) println("sum="+sumNumber) }
unlicense
a81463179f1ca684e93b934d1c6f336d
13
41
0.624041
2.234286
false
false
false
false
Ekito/koin
koin-projects/koin-android-viewmodel/src/main/java/org/koin/android/viewmodel/ext/android/FragmentExt.kt
1
2374
/* * Copyright 2017-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 org.koin.android.viewmodel.ext.android import android.arch.lifecycle.ViewModel import android.support.v4.app.Fragment import org.koin.android.ext.android.getKoin import org.koin.android.viewmodel.ViewModelOwner.Companion.from import org.koin.android.viewmodel.ViewModelOwnerDefinition import org.koin.android.viewmodel.koin.getViewModel import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import kotlin.reflect.KClass /** * LifecycleOwner extensions to help for ViewModel * * @author Arnaud Giuliani */ inline fun <reified T : ViewModel> Fragment.viewModel( qualifier: Qualifier? = null, noinline owner: ViewModelOwnerDefinition = { from(this) }, noinline parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getViewModel<T>(qualifier, owner, parameters) } } fun <T : ViewModel> Fragment.viewModel( qualifier: Qualifier? = null, owner: ViewModelOwnerDefinition = { from(this) }, clazz: KClass<T>, parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getViewModel(qualifier, owner, clazz, parameters) } } inline fun <reified T : ViewModel> Fragment.getViewModel( qualifier: Qualifier? = null, noinline owner: ViewModelOwnerDefinition = { from(this) }, noinline parameters: ParametersDefinition? = null ): T { return getViewModel(qualifier, owner, T::class, parameters) } fun <T : ViewModel> Fragment.getViewModel( qualifier: Qualifier? = null, owner: ViewModelOwnerDefinition = { from(this) }, clazz: KClass<T>, parameters: ParametersDefinition? = null ): T { return getKoin().getViewModel(qualifier, owner, clazz, parameters) }
apache-2.0
56ea5c7d87e189dbc5aa4b3c9acf6a71
34.447761
96
0.743892
4.246869
false
false
false
false
exteso/alf.io-PI
backend/src/main/kotlin/alfio/pi/controller/PrintApi.kt
1
5366
/* * This file is part of alf.io. * * alf.io 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. * * alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>. */ package alfio.pi.controller import alfio.pi.manager.* import alfio.pi.model.* import alfio.pi.repository.PrinterRepository import alfio.pi.repository.UserPrinterRepository import alfio.pi.wrapper.tryOrDefault import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.context.ApplicationEventPublisher import org.springframework.context.annotation.Profile import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.transaction.PlatformTransactionManager import org.springframework.web.bind.annotation.* import javax.servlet.http.HttpServletRequest val logger: Logger = LoggerFactory.getLogger("PrintApi") @RestController @RequestMapping("/api/internal/user-printer") @Profile("server", "full") open class UserPrinterApi(private val transactionManager: PlatformTransactionManager, private val userPrinterRepository: UserPrinterRepository) { @RequestMapping(value = ["/"], method = [(RequestMethod.POST)]) open fun linkUserToPrinter(@RequestBody userPrinterForm: UserPrinterForm, method: HttpMethod): ResponseEntity<Boolean> { val userId = userPrinterForm.userId val printerId = userPrinterForm.printerId return if(userId != null && printerId != null) { val result = alfio.pi.manager.linkUserToPrinter(userId, printerId).invoke(transactionManager, userPrinterRepository) if(result) { ResponseEntity.ok(true) } else { ResponseEntity(HttpStatus.CONFLICT) } } else { ResponseEntity(HttpStatus.BAD_REQUEST) } } @RequestMapping(value = ["/{userId}"], method = [(RequestMethod.DELETE)]) open fun removeUserPrinterLink(@PathVariable("userId") userId: Int): ResponseEntity<Boolean> { val result = alfio.pi.manager.removeUserPrinterLink(userId).invoke(transactionManager, userPrinterRepository) return if(result) { ResponseEntity.ok(true) } else { ResponseEntity(HttpStatus.CONFLICT) } } } class UserPrinterForm { var userId: Int? = null var printerId: Int? = null } @RestController @RequestMapping("/api/internal/printers") @Profile("server", "full") open class PrinterApi (private val transactionManager: PlatformTransactionManager, private val printerRepository: PrinterRepository, private val userPrinterRepository: UserPrinterRepository, private val printManager: PrintManager) { @RequestMapping(value = [""], method = [(RequestMethod.GET)]) open fun loadAllPrinters(): List<Printer> = findAllRegisteredPrinters().invoke(printerRepository) @RequestMapping(value = ["/{printerId}/active"], method = [(RequestMethod.PUT), (RequestMethod.DELETE)]) open fun toggleActiveState(@PathVariable("printerId") printerId: Int, method: HttpMethod): Boolean = togglePrinterActivation(printerId, method == HttpMethod.PUT).invoke(transactionManager, printerRepository) @RequestMapping(value = ["/with-users"], method = [(RequestMethod.GET)]) open fun loadPrintConfiguration() = loadPrinterConfiguration().invoke(userPrinterRepository, printerRepository) @RequestMapping(value = ["/{printerId}/test"], method = [(RequestMethod.PUT)]) open fun printTestPage(@PathVariable("printerId") printerId: Int) = printTestBadge(printerId).invoke(printManager, printerRepository) } @RestController @RequestMapping("/api/printers") @Profile("printer") open class LocalPrinterApi(private val printManager: PrintManager) { @RequestMapping(value= ["/{printerName}/print"], method = [(RequestMethod.POST)]) open fun print(@PathVariable("printerName") printerName: String, @RequestBody ticket: Ticket) = printOnLocalPrinter(printerName, ticket, null).invoke(printManager) } @RestController @RequestMapping("/api/printers") @Profile("server", "full") open class RemotePrinterApi(private val applicationEventPublisher: ApplicationEventPublisher) { @RequestMapping(value = ["/register"], method = [(RequestMethod.POST)]) open fun registerPrinters(@RequestBody printers: List<SystemPrinter>, request: HttpServletRequest) = tryOrDefault<ResponseEntity<Unit>>().invoke({ val remoteAddress = request.remoteAddr logger.trace("registering $printers for $remoteAddress") applicationEventPublisher.publishEvent(PrintersRegistered(printers.map { RemotePrinter(it.name, remoteAddress) }, remoteAddress)) ResponseEntity.ok(null) }, { logger.error("cannot register printers", it) ResponseEntity(HttpStatus.BAD_REQUEST) }) }
gpl-3.0
08c2ac84205120b2dd3a2a3608a895cb
45.267241
211
0.735744
4.578498
false
false
false
false
team401/2017-Robot-Code
src/main/java/org/team401/lib/MotionProfile.kt
1
951
package org.team401.lib import com.ctre.CANTalon class MotionProfile internal constructor(val name: String, private val positions: DoubleArray, private val speeds: DoubleArray, private val durations: IntArray) { var currentIndex = 0 var totalPoints = positions.size fun getNextTrajectoryPoint(): CANTalon.TrajectoryPoint { val point = CANTalon.TrajectoryPoint() if (currentIndex >= totalPoints) { println("Trying to access index $currentIndex of profile $name with a max index of $totalPoints") point.isLastPoint = true return point } point.position = positions[currentIndex] point.velocity = speeds[currentIndex] point.timeDurMs = durations[currentIndex] point.isLastPoint = false if (currentIndex+1 == totalPoints) point.isLastPoint = true currentIndex++ return point } }
gpl-3.0
51c68a15b1c62d509283254485b6aa9c
33
109
0.651945
4.707921
false
false
false
false
team401/2017-Robot-Code
src/main/java/org/team401/robot/subsystems/Tower.kt
1
1673
package org.team401.robot.subsystems import com.ctre.CANTalon import edu.wpi.first.wpilibj.Solenoid import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard import org.team401.robot.Constants import org.team401.lib.Loop object Tower : Subsystem("tower") { enum class TowerState { TOWER_IN, TOWER_OUT, KICKER_ON, KICKER_INVERTED } private var state = TowerState.TOWER_IN private val shift = Solenoid(Constants.TOWER_SHIFTER) private val motor = CANTalon(Constants.TURRET_FEEDER) init { motor.enableLimitSwitch(true, false) motor.set(0.0) } private val loop = object : Loop { override fun onStart() { } override fun onLoop() { if (Flywheel.isWithinTolerance()) setWantedState(TowerState.KICKER_ON) if (Flywheel.getCurrentState() == Flywheel.FlywheelState.STOPPED && state == TowerState.KICKER_ON) setWantedState(TowerState.TOWER_OUT) when (state) { TowerState.TOWER_IN -> { shift.set(false) motor.set(0.0) } TowerState.TOWER_OUT -> { shift.set(true) motor.set(0.0) } TowerState.KICKER_ON -> { shift.set(true) motor.set(1.0) } TowerState.KICKER_INVERTED -> { shift.set(true) motor.set(-1.0) } } } override fun onStop() { } } init { dataLogger.register("tower_extended", { state != TowerState.TOWER_IN }) dataLogger.register("kicker_throttle", { motor.get() }) } fun isTurretLimitSwitchTriggered() = motor.isRevLimitSwitchClosed fun setWantedState(state: TowerState) { this.state = state } fun getCurrentState() = state override fun getSubsystemLoop(): Loop = loop }
gpl-3.0
e36356e9f0a662feb25d92b9ecf753cc
21.32
110
0.665272
3.081031
false
false
false
false
toastkidjp/Yobidashi_kt
todo/src/main/java/jp/toastkid/todo/view/board/TaskBoardUi.kt
1
9792
/* * Copyright (c) 2022 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.todo.view.board import android.text.format.DateFormat import androidx.activity.ComponentActivity import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Checkbox import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModelProvider import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.cachedIn import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.items import coil.compose.AsyncImage import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.todo.R import jp.toastkid.todo.data.TodoTaskDataAccessor import jp.toastkid.todo.data.TodoTaskDatabase import jp.toastkid.todo.model.TodoTask import jp.toastkid.todo.view.addition.TaskAdditionDialogFragmentViewModel import jp.toastkid.todo.view.addition.TaskEditorUi import jp.toastkid.todo.view.appbar.AppBarUi import jp.toastkid.todo.view.item.menu.ItemMenuPopupActionUseCase import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.math.roundToInt @OptIn(ExperimentalMaterialApi::class) @Composable fun TaskBoardUi() { val context = LocalContext.current as? ComponentActivity ?: return val taskAdditionDialogFragmentViewModel = ViewModelProvider(context).get(TaskAdditionDialogFragmentViewModel::class.java) val repository = TodoTaskDatabase.find(context).repository() val preferenceApplier = PreferenceApplier(context) val bottomSheetScaffoldState = rememberModalBottomSheetState( ModalBottomSheetValue.Hidden ) val menuUseCase = ItemMenuPopupActionUseCase( { taskAdditionDialogFragmentViewModel?.setTask(it) }, { CoroutineScope(Dispatchers.Main).launch { withContext(Dispatchers.IO) { repository.delete(it) } } } ) val coroutineScope = rememberCoroutineScope() val tasks = remember { mutableStateOf<Flow<PagingData<TodoTask>>?>(null) } LaunchedEffect(key1 = "init", block = { val flow = withContext(Dispatchers.IO) { Pager( PagingConfig(pageSize = 10, enablePlaceholders = true), pagingSourceFactory = { repository.allTasks() } ) .flow .cachedIn(coroutineScope) } tasks.value = flow taskAdditionDialogFragmentViewModel?.task?.observe(context, { coroutineScope.launch { bottomSheetScaffoldState.show() } }) }) ViewModelProvider(context).get(ContentViewModel::class.java) .replaceAppBarContent { AppBarUi { taskAdditionDialogFragmentViewModel?.setTask(null) } } TaskEditorUi( { TaskBoard(tasks.value, menuUseCase) }, taskAdditionDialogFragmentViewModel, bottomSheetScaffoldState, { CoroutineScope(Dispatchers.IO).launch { repository.insert(it) } }, preferenceApplier.colorPair() ) } @OptIn(ExperimentalFoundationApi::class) @Composable fun TaskBoard(flow: Flow<PagingData<TodoTask>>?, menuUseCase: ItemMenuPopupActionUseCase) { val context = LocalContext.current val repository = TodoTaskDatabase.find(context).repository() val color = PreferenceApplier(context).color val tasks = flow?.collectAsLazyPagingItems() ?: return LazyColumn(modifier = Modifier.fillMaxWidth()) { items(tasks, { it.id }) { task -> task ?: return@items BoardItem( task, repository, color, menuUseCase, Modifier.animateItemPlacement() ) } } } @Composable private fun BoardItem( task: TodoTask, repository: TodoTaskDataAccessor, color: Int, menuUseCase: ItemMenuPopupActionUseCase, modifier: Modifier = Modifier ) { var expanded by remember { mutableStateOf(false) } val items = listOf( stringResource(id = R.string.modify), stringResource(id = R.string.delete) ) var offsetX by remember { mutableStateOf(task.x) } var offsetY by remember { mutableStateOf(task.y) } Surface( elevation = 4.dp, modifier = modifier .padding(start = 16.dp, end = 16.dp, top = 2.dp, bottom = 2.dp) .width(140.dp) .height(140.dp) .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) } .pointerInput(Unit) { detectDragGestures( onDragEnd = { task.x = offsetX task.y = offsetY CoroutineScope(Dispatchers.IO).launch { repository.insert(task) } }, onDrag = { change, dragAmount -> change.consume() offsetX += dragAmount.x offsetY += dragAmount.y } ) } ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) { Checkbox( checked = task.done, onCheckedChange = { task.done = task.done.not() CoroutineScope(Dispatchers.IO).launch { repository.insert(task) } }, modifier = Modifier .width(32.dp) .fillMaxHeight() ) Column( modifier = Modifier.weight(1f) ) { Text( text = task.description, fontSize = 16.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.fillMaxWidth() ) Text( text = DateFormat.format("yyyy/MM/dd(E)", task.dueDate).toString(), fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.fillMaxWidth() ) } AsyncImage( R.drawable.ic_more, contentDescription = stringResource(R.string.menu), colorFilter = ColorFilter.tint( Color(color), BlendMode.SrcIn ), modifier = Modifier .width(32.dp) .fillMaxHeight() .clickable { expanded = true } .background(color = Color(task.color)) ) DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, modifier = Modifier.fillMaxWidth() ) { items.forEachIndexed { index, s -> DropdownMenuItem(onClick = { when (index) { 0 -> menuUseCase.modify(task) 1 -> menuUseCase.delete(task) } expanded = false }) { Text(text = s) } } } } } }
epl-1.0
a0d24add0c5874fb1d4194c9af579cd6
34.740876
91
0.625102
5.33624
false
false
false
false
opeykin/vkspy
backend/src/main/kotlin/org/vkspy/main.kt
1
828
package org.vkspy import org.vkspy.util.Config import org.vkspy.util.Logger fun main(args: Array<String>) { try { val accessor = VkAccessor() val parser = VkParser() val db = newVkSpyDb(Config.DbUrl, Config.DbUserName, Config.DbPassword) kotlin.concurrent.timer("MyTimer", false, 0, Config.TimerSpan, { try { val ids = db.getUserIds() val json = accessor.checkOnline(ids) val statuses = parser.parseOnline(json) db.writeStatuses(statuses) Logger.get().trace("Got ${statuses.size} statuses") } catch (e: Exception) { Logger.logException(e) } }); } catch (e: Exception) { Logger.logException(e, "Initialization") throw e } }
gpl-2.0
3c85d3f237b253f62017ac6fd5ea5060
27.551724
79
0.559179
4.078818
false
true
false
false
h2andp/vesta
src/main/kotlin/net/h2andp/core/domain/ImageAttribute.kt
1
789
package net.h2andp.core.domain import javax.persistence.* import javax.persistence.GenerationType.AUTO /** * Contains all variables tied to the image attributes collection in database. */ @Entity @Table( name = "image_attribute" ) data class ImageAttribute ( /** * Id of the record in database. */ @Id @GeneratedValue( strategy = AUTO ) var id: Long? = null, /** * Name of the attribute. */ var name: String? = null, /** * Value of the attribute. */ var value: String? = null, /** * Instance of {@link Image} for which attribute attached. */ @ManyToOne @JoinColumn( name = "image_id" ) var image: Image? = null )
mit
74178dc8aa848b5dd306e34822741dfe
20.351351
78
0.546261
4.311475
false
false
false
false
camdenorrb/KPortals
src/main/kotlin/me/camdenorrb/kportals/listeners/PlayerListener.kt
1
2403
package me.camdenorrb.kportals.listeners import me.camdenorrb.kportals.KPortals import me.camdenorrb.kportals.events.PlayerKPortalEnterEvent import me.camdenorrb.kportals.events.PlayerMoveBlockEvent import me.camdenorrb.kportals.ext.teleportToRandomLoc import me.camdenorrb.kportals.portal.Portal import me.camdenorrb.minibus.event.EventWatcher import me.camdenorrb.minibus.listener.ListenerPriority.LAST import me.camdenorrb.minibus.listener.MiniListener import org.bukkit.Bukkit import org.bukkit.ChatColor.RED import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerMoveEvent /** * Created by camdenorrb on 3/20/17. */ class PlayerListener(val plugin: KPortals) : Listener, MiniListener { @EventHandler(ignoreCancelled = true) fun onMove(event: PlayerMoveEvent) { val from = event.from val to = event.to ?: return val fromBlock = from.block val toBlock = to.block if (fromBlock == toBlock) return val moveBlockEvent = PlayerMoveBlockEvent(event.player, fromBlock, toBlock, from, to) event.isCancelled = plugin.miniBus(moveBlockEvent).isCancelled } @EventWatcher(priority = LAST) fun onMoveBlock(event: PlayerMoveBlockEvent) { if (event.isCancelled) return val player = event.player val toVec = event.toBlock.location.toVector() val portal = plugin.portals.find { portal -> val center = portal.selection.center() ?: return@find false if (toVec.distance(center) > portal.maxRadius) { return@find false } portal.positions.any { it == toVec } } ?: return if (plugin.miniBus(PlayerKPortalEnterEvent(player, portal)).isCancelled) return when (portal.type) { Portal.Type.World -> player.teleport(Bukkit.getWorld(portal.toArgs)?.spawnLocation ?: return player.sendMessage(portalNotCorrectMsg)) Portal.Type.Bungee -> plugin.sendPlayerToServer(player, portal.toArgs) Portal.Type.Random -> player.teleportToRandomLoc(portal.toArgs.toIntOrNull() ?: return player.sendMessage(portalNotCorrectMsg)) Portal.Type.PlayerCommand -> player.chat("/${portal.toArgs.replace("%player%", player.name)}") Portal.Type.ConsoleCommand -> Bukkit.dispatchCommand(plugin.server.consoleSender, portal.toArgs.replace("%player%", player.name)) else -> return } } companion object { val portalNotCorrectMsg = "${RED}The portal you have walked into is not setup correctly." } }
mit
591db7f6dd22bdc1613508609f0d919f
30.618421
136
0.765293
3.714065
false
false
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/mapper/MapperJavaProxy.kt
1
4570
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sdibt.korm.core.mapper import com.sdibt.korm.core.db.KormSqlSession import java.lang.invoke.MethodHandles import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType import java.util.concurrent.ConcurrentHashMap class MapperJavaProxy : InvocationHandler { internal var builder: DefaultMapperBuilder private var db: KormSqlSession private var entityClass: Class<*>? = null private val methodCache = ConcurrentHashMap<Method, MapperMethod>() private val mapperInterface: Class<*> constructor(builder: DefaultMapperBuilder, db: KormSqlSession, mapperInterface: Class<*>) : super() { this.db = db this.builder = builder this.mapperInterface(mapperInterface) this.mapperInterface = mapperInterface } fun mapperInterface(mapperInterface: Class<*>): MapperJavaProxy { if (mapperInterface.isInterface) { val faces = mapperInterface.genericInterfaces if (faces.isNotEmpty() && faces[0] is ParameterizedType) { val pt = faces[0] as ParameterizedType if (pt.actualTypeArguments.isNotEmpty()) { this.entityClass = pt.actualTypeArguments[0] as Class<*> } } } else { throw IllegalArgumentException("mapperInterface is not interface.") } return this } fun entityClass(entityClass: Class<*>): MapperJavaProxy { this.entityClass = entityClass return this } override fun invoke(proxy: Any, method: Method, args: Array<Any>?): Any? { if (entityClass == null) throw RuntimeException("entityClass can't be null ") if (Any::class.java == method.declaringClass) run { return method.invoke(this, args) } if (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args) } // val c = method.declaringClass // println("method.name = ${method.name}") // println("method.declaringClass = ${method.declaringClass}") // println("method.genericReturnType = ${method.genericReturnType.typeName}") // println("method.genericParameterTypes.forEach { soutv } = ${method.genericParameterTypes.forEach { println("it.typeName = ${it.typeName}") }}") // val mapperMethod = cachedMapperMethod(method) return mapperMethod.execute(db, args, entityClass!!) } private fun invokeDefaultMethod(proxy: Any, method: Method, args: Array<Any>?): Any { val constructor = MethodHandles.Lookup::class.java .getDeclaredConstructor(Class::class.java, Int::class.javaPrimitiveType) if (!constructor.isAccessible) { constructor.isAccessible = true } val declaringClass = method.declaringClass return constructor .newInstance(declaringClass, MethodHandles.Lookup.PRIVATE or MethodHandles.Lookup.PROTECTED or MethodHandles.Lookup.PACKAGE or MethodHandles.Lookup.PUBLIC) .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args) } private fun cachedMapperMethod(method: Method): MapperMethod { var mapperMethod: MapperMethod? = methodCache[method] if (mapperMethod == null) { mapperMethod = MapperMethod(mapperInterface, method) methodCache.put(method, mapperMethod) } return mapperMethod } private fun isDefaultMethod(method: Method): Boolean { return method.modifiers and (Modifier.ABSTRACT or Modifier.PUBLIC or Modifier.STATIC) == Modifier.PUBLIC && method.declaringClass.isInterface } }
apache-2.0
a05b06a5cf9c181295180680dea2c984
38.396552
153
0.684026
4.825766
false
false
false
false
jtransc/jtransc
jtransc-gen-js/src/com/jtransc/gen/js/JsTarget.kt
1
22860
package com.jtransc.gen.js import com.jtransc.ConfigOutputFile import com.jtransc.ConfigTargetDirectory import com.jtransc.annotation.JTranscCustomMainList import com.jtransc.ast.* import com.jtransc.ast.feature.method.SwitchFeature import com.jtransc.ds.Allocator import com.jtransc.ds.getOrPut2 import com.jtransc.error.InvalidOperationException import com.jtransc.error.invalidOp import com.jtransc.gen.GenTargetDescriptor import com.jtransc.gen.TargetBuildTarget import com.jtransc.gen.common.* import com.jtransc.injector.Injector import com.jtransc.injector.Singleton import com.jtransc.io.ProcessResult2 import com.jtransc.log.log import com.jtransc.sourcemaps.Sourcemaps import com.jtransc.text.Indenter import com.jtransc.text.isLetterDigitOrUnderscore import com.jtransc.text.quote import com.jtransc.vfs.ExecOptions import com.jtransc.vfs.LocalVfs import com.jtransc.vfs.LocalVfsEnsureDirs import com.jtransc.vfs.SyncVfsFile import java.io.File import java.util.* class JsTarget : GenTargetDescriptor() { override val priority = 500 override val name = "js" override val longName = "Javascript" override val outputExtension = "js" override val extraLibraries = listOf<String>() override val extraClasses = listOf<String>() override val runningAvailable: Boolean = true override val buildTargets: List<TargetBuildTarget> = listOf( TargetBuildTarget("js", "js", "program.js", minimizeNames = true), TargetBuildTarget("plainJs", "js", "program.js", minimizeNames = true) ) override fun getGenerator(injector: Injector): CommonGenerator { val settings = injector.get<AstBuildSettings>() val configTargetDirectory = injector.get<ConfigTargetDirectory>() val configOutputFile = injector.get<ConfigOutputFile>() val targetFolder = LocalVfsEnsureDirs(File("${configTargetDirectory.targetDirectory}/jtransc-js")) injector.mapInstance(CommonGenFolders(settings.assets.map { LocalVfs(it) })) injector.mapInstance(ConfigTargetFolder(targetFolder)) injector.mapInstance(ConfigSrcFolder(targetFolder)) injector.mapInstance(ConfigOutputFile2(targetFolder[configOutputFile.outputFileBaseName].realfile)) injector.mapImpl<IProgramTemplate, IProgramTemplate>() return injector.get<JsGenerator>() } override fun getTargetByExtension(ext: String): String? = when (ext) { "js" -> "js" else -> null } } data class ConfigJavascriptOutput(val javascriptOutput: SyncVfsFile) fun hasSpecialChars(name: String): Boolean = !name.all(Char::isLetterDigitOrUnderscore) @Suppress("ConvertLambdaToReference") @Singleton class JsGenerator(injector: Injector) : CommonGenerator(injector) { override val TARGET_NAME: String = "JS" override val SINGLE_FILE: Boolean = true override val ADD_UTF8_BOM = true override val GENERATE_LINE_NUMBERS = false override val methodFeatures = super.methodFeatures + setOf(SwitchFeature::class.java) override val keywords = super.keywords + setOf("name", "constructor", "prototype", "__proto__", "G", "N", "S", "SS", "IO") override val stringPoolType = StringPool.Type.GLOBAL override val floatHasFSuffix: Boolean = false override val optionalDoubleDummyDecimals = true override val targetExtraParams = mapOf<String, Any?>( ) override fun compileAndRun(redirect: Boolean, args: List<String>): ProcessResult2 = _compileRun(run = true, redirect = redirect, args = args) override fun compile(): ProcessResult2 = _compileRun(run = false, redirect = false) private fun commonAccessBase(name: String, field: Boolean): String = if (hasSpecialChars(name)) name.quote() else name private fun commonAccess(name: String, field: Boolean): String = if (hasSpecialChars(name)) "[${name.quote()}]" else ".$name" override fun staticAccess(name: String, field: Boolean): String = commonAccess(name, field) override fun instanceAccess(name: String, field: Boolean): String = commonAccess(name, field) val jsOutputFile by lazy { injector.get<ConfigJavascriptOutput>().javascriptOutput } fun _compileRun(run: Boolean, redirect: Boolean, args: List<String> = listOf()): ProcessResult2 { log.info("Generated javascript at..." + jsOutputFile.realpathOS) if (run) { val result = CommonGenCliCommands.runProgramCmd( program, target = "js", default = listOf("node", "{{ outputFile }}") + args, template = this, options = ExecOptions(passthru = redirect) ) return ProcessResult2(result) } else { return ProcessResult2(0) } } override fun run(redirect: Boolean, args: List<String>): ProcessResult2 = ProcessResult2(0) @Suppress("UNCHECKED_CAST") override fun writeClasses(output: SyncVfsFile) { val concatFilesTrans = copyFiles(output) val classesIndenter = arrayListOf<Indenter>() classesIndenter += genSingleFileClassesWithoutAppends(output) val SHOW_SIZE_REPORT = true if (SHOW_SIZE_REPORT) { for ((clazz, text) in indenterPerClass.toList().map { it.first to it.second.toString() }.sortedBy { it.second.length }) { log.info("CLASS SIZE: ${clazz.fqname} : ${text.length}") } } val mainClassFq = program.entrypoint val mainClass = mainClassFq.targetClassFqName //val mainMethod = program[mainClassFq].getMethod("main", AstType.build { METHOD(VOID, ARRAY(STRING)) }.desc)!!.jsName val mainMethod = "main" entryPointClass = FqName(mainClassFq.fqname + "_EntryPoint") entryPointFilePath = entryPointClass.targetFilePath val entryPointFqName = entryPointClass.targetGeneratedFqName val entryPointSimpleName = entryPointClass.targetSimpleName val entryPointPackage = entryPointFqName.packagePath val customMain = program.allAnnotationsList.getTypedList(JTranscCustomMainList::value).firstOrNull { it.target == "js" }?.value log("Using ... " + if (customMain != null) "customMain" else "plainMain") setExtraData(mapOf( "entryPointPackage" to entryPointPackage, "entryPointSimpleName" to entryPointSimpleName, "mainClass" to mainClass, "mainClass2" to mainClassFq.fqname, "mainMethod" to mainMethod )) val strs = Indenter { //val strs = getGlobalStrings() //val maxId = strs.maxBy { it.id }?.id ?: 0 //line("SS = new Array($maxId);") //for (e in strs) line("SS[${e.id}] = ${e.str.quote()};") } val out = Indenter { if (settings.debug) line("//# sourceMappingURL=$outputFileBaseName.map") line(concatFilesTrans.prepend) line(strs.toString()) for (indent in classesIndenter) line(indent) val mainClassClass = program[mainClassFq] line("function __main()") { line("__createJavaArrays();") //line("__buildStrings();") line("N.preInit();") line(genStaticConstructorsSorted()) //line(buildStaticInit(mainClassFq)) val mainMethod2 = mainClassClass[AstMethodRef(mainClassFq, "main", AstType.METHOD(AstType.VOID, listOf(ARRAY(AstType.STRING))))] val mainCall = buildMethod(mainMethod2, static = true) line("try {") indent { line("N.afterInit();") line("$mainCall(N.strArray(N.args()));") } line("} catch (e) {") indent { line("console.error(e);") line("console.error(e.stack);") } line("}") } line("let result = __main();") line(concatFilesTrans.append) } val sources = Allocator<String>() val mappings = hashMapOf<Int, Sourcemaps.MappingItem>() val source = out.toString { sb, line, data -> if (settings.debug && data is AstStm.LINE) { //println("MARKER: ${sb.length}, $line, $data, ${clazz.source}") mappings[line] = Sourcemaps.MappingItem( sourceIndex = sources.allocateOnce(data.file), sourceLine = data.line, sourceColumn = 0, targetColumn = 0 ) //clazzName.internalFqname + ".java" } } val sourceMap = if (settings.debug) Sourcemaps.encodeFile(sources.array, mappings) else null // Generate source //println("outputFileBaseName:$outputFileBaseName") output[outputFileBaseName] = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + source.toByteArray(Charsets.UTF_8) if (sourceMap != null) output[outputFileBaseName + ".map"] = sourceMap injector.mapInstance(ConfigJavascriptOutput(output[outputFile])) } override fun genSICall(it: AstClass): String { return it.name.targetNameForStatic + access("SI", static = true, field = false) + "();" } override fun genStmTryCatch(stm: AstStm.TRY_CATCH) = indent { line("try") { line(stm.trystm.genStm()) } line("catch (J__i__exception__)") { //line("J__exception__ = J__i__exception__.native || J__i__exception__;") line("J__exception__ = J__i__exception__.javaThrowable || J__i__exception__;") line(stm.catch.genStm()) } } override fun genStmRethrow(stm: AstStm.RETHROW, last: Boolean) = indent { line("throw J__i__exception__;") } override fun genBodyLocals(locals: List<AstLocal>) = indent { if (locals.isNotEmpty()) { val vars = locals.map { local -> "${local.targetName} = ${local.type.nativeDefaultString}" }.joinToString(", ") line("var $vars;") } } override val AstLocal.decl: String get() = "var ${this.targetName} = ${this.type.nativeDefaultString};" override fun genBodyTrapsPrefix() = indent { line("var J__exception__ = null;") } override fun genBodyStaticInitPrefix(clazzRef: AstType.REF, reasons: ArrayList<String>) = indent { line(buildStaticInit(clazzRef.name)) } override fun N_AGET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String): String { return if (debugVersion) { "($array.get($index))" } else { "($array.data[$index])" } } override fun N_ASET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String, value: String): String { return if (debugVersion) { "$array.set($index, $value);" } else { "$array.data[$index] = $value;" } } override fun N_func(name: String, args: String): String { val base = "N$staticAccessOperator$name($args)" return when (name) { "resolveClass", "box", "boxVoid", "boxBool", "boxByte", "boxShort", "boxChar", "boxInt", "boxLong", "boxFloat", "boxDouble", "boxString", "boxWrapped" -> "N.$name($args)" //"resolveClass", "iteratorToArray", "imap" -> "(await($base))" "iteratorToArray", "imap" -> "($base)" else -> base } } override fun N_isObj(a: String, b: AstClass): String = "N.isObj($a, ${b.ref.targetName})" override fun N_isIfc(a: String, b: AstClass): String = "N.isClassId($a, ${b.classId})" override fun N_is(a: String, b: String) = "N.is($a, $b)" override fun N_z2i(str: String) = "N.z2i($str)" override fun N_i(str: String) = "(($str)|0)" override fun N_i2z(str: String) = "(($str)!=0)" override fun N_i2b(str: String) = "(($str)<<24>>24)" // shifts use 32-bit integers override fun N_i2c(str: String) = "(($str)&0xFFFF)" override fun N_i2s(str: String) = "(($str)<<16>>16)" // shifts use 32-bit integers override fun N_f2i(str: String) = "N.f2i($str)" override fun N_i2i(str: String) = N_i(str) override fun N_i2j(str: String) = "N.i2j($str)" override fun N_i2f(str: String) = "N.d2f(+($str))" override fun N_i2d(str: String) = "+($str)" override fun N_f2f(str: String) = "N.d2f($str)" override fun N_f2d(str: String) = "($str)" override fun N_d2f(str: String) = "N.d2f(+($str))" override fun N_d2i(str: String) = "N.d2i($str)" override fun N_d2d(str: String) = "+($str)" override fun N_j2i(str: String) = "N.j2i($str)" override fun N_j2j(str: String) = str override fun N_j2f(str: String) = "N.d2f(N.j2d($str))" override fun N_j2d(str: String) = "N.j2d($str)" override fun N_getFunction(str: String) = "N.getFunction($str)" override fun N_c(str: String, from: AstType, to: AstType) = "($str)" override fun N_ineg(str: String) = "-($str)" override fun N_iinv(str: String) = "~($str)" override fun N_fneg(str: String) = "-($str)" override fun N_dneg(str: String) = "-($str)" override fun N_znot(str: String) = "!($str)" override fun N_imul(l: String, r: String): String = "Math.imul($l, $r)" //override val String.escapeString: String get() = "S[" + allocString(context.clazz.name, this) + "]" override val String.escapeString: String get() = this.quote() //val String.escapeStringJs: String get() = "SS[" + allocString(context.clazz.name, this) + "]" override fun genCallWrap(e: AstExpr.CALL_BASE, str: String): String { return str } override fun generateDeclArgString(args: List<String>): String { return (args).joinToString(", ") } override fun generateCallArgString(args: List<String>, isNativeCall: Boolean): String { return ((if (isNativeCall) listOf<String>() else listOf<String>()) + args).joinToString(", ") } override fun genExprCallBaseSuper(e2: AstExpr.CALL_SUPER, clazz: AstType.REF, refMethodClass: AstClass, method: AstMethodRef, methodAccess: String, args: List<String>, isNativeCall: Boolean): String { val superMethod = refMethodClass[method.withoutClass] ?: invalidOp("Can't find super for method : $method") val base = superMethod.containingClass.name.targetName + ".prototype" val argsString = (listOf(e2.obj.genExpr()) + (if (isNativeCall) listOf<String>() else listOf<String>()) + args).joinToString(", ") return genCallWrap(e2, "$base$methodAccess.call($argsString)") } private fun AstMethod.getJsNativeBodies(): Map<String, Indenter> = this.getNativeBodies(target = "js") override fun genClass(clazz: AstClass): List<ClassResult> { setCurrentClass(clazz) val isAbstract = (clazz.classType == AstClassType.ABSTRACT) refs._usedDependencies.clear() if (!clazz.extending?.fqname.isNullOrEmpty()) refs.add(AstType.REF(clazz.extending!!)) for (impl in clazz.implementing) refs.add(AstType.REF(impl)) val classCodeIndenter = Indenter { if (isAbstract) line("// ABSTRACT") val classBase = clazz.name.targetName //val memberBaseStatic = classBase //val memberBaseInstance = "$classBase.prototype" fun getMemberBase(isStatic: Boolean) = if (isStatic) "static " else "" val parentClassBase = if (clazz.extending != null) clazz.extending!!.targetName else "java_lang_Object_base"; val staticFields = clazz.fields.filter { it.isStatic } //val instanceFields = clazz.fields.filter { !it.isStatic } val allInstanceFields = (listOf(clazz) + clazz.parentClassList).flatMap { it.fields }.filter { !it.isStatic } fun lateInitField(a: Any?) = (a is String) val allInstanceFieldsThis = allInstanceFields.filter { lateInitField(it) } val allInstanceFieldsProto = allInstanceFields.filter { !lateInitField(it) } line("class $classBase extends $parentClassBase") { line("constructor()") { line("super();") for (field in allInstanceFieldsThis) { val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName line("this${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};") } } if (staticFields.isNotEmpty() || clazz.staticConstructor != null) { line("static SI()") { //line("$classBase.SI = N.EMPTY_FUNCTION;") for (field in staticFields) { val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName line("$classBase${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};") } if (clazz.staticConstructor != null) { line("($classBase${getTargetMethodAccess(clazz.staticConstructor!!, true)}());") } } } else { line("static SI()") { } } //renderFields(clazz.fields); fun writeMethod(method: AstMethod): Indenter { setCurrentMethod(method) return Indenter { refs.add(method.methodType) val margs = method.methodType.args.map { it.name } //val defaultMethodName = if (method.isInstanceInit) "${method.ref.classRef.fqname}${method.name}${method.desc}" else "${method.name}${method.desc}" //val methodName = if (method.targetName == defaultMethodName) null else method.targetName val nativeMemberName = buildMethod(method, false, includeDot = false) //val prefix = "${getMemberBase(method.isStatic)}${instanceAccess(nativeMemberName, field = false)}" val prefix = "${getMemberBase(method.isStatic)}${commonAccessBase(nativeMemberName, field = false)}" val rbody = if (method.body != null) method.body else if (method.bodyRef != null) program[method.bodyRef!!]?.body else null fun renderBranch(actualBody: Indenter?) = Indenter { //if (actualBody != null) { // line("$prefix(${margs.joinToString(", ")})") { // line(actualBody) // if (method.methodVoidReturnThis) line("return this;") // } //} else { // line("$prefix() { N.methodWithoutBody('${clazz.name}.${method.name}') }") //} if (actualBody != null) { line(actualBody) if (method.methodVoidReturnThis) line("return this;") } else { line("N.methodWithoutBody('${clazz.name}.${method.name}');") } } fun renderBranches() = Indenter { line("$prefix(${generateDeclArgString(margs)})") { try { val nativeBodies = method.getJsNativeBodies() var javaBodyCacheDone: Boolean = false var javaBodyCache: Indenter? = null fun javaBody(): Indenter? { if (!javaBodyCacheDone) { javaBodyCacheDone = true javaBodyCache = rbody?.genBodyWithFeatures(method) } return javaBodyCache } //val javaBody by lazy { } // @TODO: Do not hardcode this! if (nativeBodies.isEmpty() && javaBody() == null) { line(renderBranch(null)) } else { if (nativeBodies.isNotEmpty()) { val default = if ("" in nativeBodies) nativeBodies[""]!! else javaBody() ?: Indenter.EMPTY val options = nativeBodies.filter { it.key != "" }.map { it.key to it.value } + listOf("" to default) if (options.size == 1) { line(renderBranch(default)) } else { for (opt in options.withIndex()) { if (opt.index != options.size - 1) { val iftype = if (opt.index == 0) "if" else "else if" line("$iftype (${opt.value.first})") { line(renderBranch(opt.value.second)) } } else { line("else") { line(renderBranch(opt.value.second)) } } } } //line(nativeBodies ?: javaBody ?: Indenter.EMPTY) } else { line(renderBranch(javaBody())) } } } catch (e: Throwable) { log.printStackTrace(e) log.warn("WARNING GenJsGen.writeMethod:" + e.message) line("// Errored method: ${clazz.name}.${method.name} :: ${method.desc} :: ${e.message};") line(renderBranch(null)) } } } line(renderBranches()) } } for (method in clazz.methods.filter { it.isClassOrInstanceInit }) line(writeMethod(method)) for (method in clazz.methods.filter { !it.isClassOrInstanceInit }) line(writeMethod(method)) } val nativeWrapper = clazz.getNativeWrapper() val relatedTypesIds = (clazz.getAllRelatedTypes() + listOf(JAVA_LANG_OBJECT_CLASS)).toSet().map { it.classId } fun writeStore(classBase: String) { for (field in allInstanceFieldsProto) { val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName line("$classBase.prototype${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};") } line("$classBase.prototype.__JT__CLASS_ID = $classBase.__JT__CLASS_ID = ${clazz.classId};") line("$classBase.prototype.__JT__CLASS_IDS = $classBase.__JT__CLASS_IDS = [${relatedTypesIds.joinToString(",")}];") } writeStore(classBase) if (nativeWrapper != null) { writeStore(nativeWrapper) line("$nativeWrapper.SI = $classBase.SI;") for (method in clazz.methods) { if (method.isStatic) { line("$nativeWrapper${commonAccess(method.targetName, false)} = $classBase${commonAccess(method.targetName, false)};") } else { line("$nativeWrapper.prototype${commonAccess(method.targetName, false)} = $classBase.prototype${commonAccess(method.targetName, false)};") } } line("$classBase = $nativeWrapper;") } line("") } return listOf(ClassResult(SubClass(clazz, MemberTypes.ALL), classCodeIndenter)) } override fun genStmSetArrayLiterals(stm: AstStm.SET_ARRAY_LITERALS) = Indenter { line("${stm.array.genExpr()}.setArraySlice(${stm.startIndex}, [${stm.values.map { it.genExpr() }.joinToString(", ")}]);") } override fun buildStaticInit(clazzName: FqName): String? = null override val FqName.targetName: String get() = classNames.getOrPut2(this) { if (minimize) allocClassName() else this.fqname.replace('.', '_') } override fun cleanMethodName(name: String): String = name override val AstType.localDeclType: String get() = "var" override fun genStmThrow(stm: AstStm.THROW, last: Boolean) = Indenter("throw NewWrappedError(${stm.exception.genExpr()});") override fun genExprCastChecked(e: String, from: AstType.Reference, to: AstType.Reference): String { return "N.checkCast($e, ${to.targetNameRef})" } override fun genExprLiteral(e: AstExpr.LITERAL): String { val value = e.value if (value is Float) return "N.d2f(${value})" return super.genExprLiteral(e) } override fun genConcatString(e: AstExpr.CONCAT_STRING): String { try { val params = e.args.map { if (it is AstExpr.LITERAL) { val value = it.value when (it.type) { AstType.STRING -> (value as String).quote() AstType.BYTE -> ("" + (value as Byte)).quote() AstType.CHAR -> ("" + (value as Char)).quote() AstType.INT -> ("" + (value as Int)).quote() AstType.LONG -> ("" + (value as Long)).quote() AstType.FLOAT -> ("" + (value as Float)).quote() AstType.DOUBLE -> ("" + (value as Double)).quote() AstType.OBJECT -> genExpr2(it) else -> invalidOp("genConcatString[1]: ${it.type}") } } else { when (it.type) { AstType.STRING, AstType.OBJECT -> genExpr2(it) AstType.BOOL -> "N.boxBool(" + genExpr2(it) + ")" AstType.BYTE -> genExpr2(it) AstType.CHAR -> "N.boxChar(" + genExpr2(it) + ")" AstType.SHORT -> genExpr2(it) AstType.INT -> genExpr2(it) AstType.FLOAT -> "N.boxFloat(" + genExpr2(it) + ")" AstType.DOUBLE -> "N.boxDouble(" + genExpr2(it) + ")" AstType.LONG -> "N.boxLong(" + genExpr2(it) + ")" else -> invalidOp("genConcatString[2]: ${it.type}") } } }.joinToString(" + ") return "N.str('' + $params)" } catch (t: InvalidOperationException) { t.printStackTrace() return genExpr2(e.original) } } override fun genStmMonitorEnter(stm: AstStm.MONITOR_ENTER) = indent { line("N.monitorEnter(${stm.expr.genExpr()});") } override fun genStmMonitorExit(stm: AstStm.MONITOR_EXIT) = indent { line("N.monitorExit(${stm.expr.genExpr()});") } }
apache-2.0
49c7b5d06d2b497688d21f3fbd334968
38.483592
201
0.674628
3.497017
false
false
false
false
fonoster/sipio
src/main/kotlin/io/routr/core/LogsHandler.kt
1
1745
package io.routr.core import org.eclipse.jetty.websocket.api.Session import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage import org.eclipse.jetty.websocket.api.annotations.WebSocket import java.io.BufferedReader import java.io.File import java.io.FileReader import java.io.IOException import java.util.* import java.util.concurrent.ConcurrentLinkedQueue /** * @author Pedro Sanders * @since v1 */ @WebSocket class LogsHandler { @OnWebSocketConnect fun connected(session: Session) { sessions.add(session) } @OnWebSocketClose fun closed(session: Session, statusCode: Int, reason: String) { sessions.remove(session) } @OnWebSocketMessage @Throws(IOException::class, InterruptedException::class) fun message(session: Session, message: String) { var br: BufferedReader? = null try { val base = if (System.getenv("DATA") != null) System.getenv("DATA") else "." val file = File("$base/logs/routr.log") br = BufferedReader(FileReader(file)) while (true) { val line = br.readLine() if (line == null) { // end of file, start polling Thread.sleep(5 * 1000.toLong()) } else { session.remote.sendString(line) } } } finally { br?.close() } } companion object { // Store sessions if you want to, for example, broadcast a message to all users private val sessions: Queue<Session> = ConcurrentLinkedQueue() } }
mit
8060dd523045eb32dc7c6ad13b246d65
30.178571
88
0.643553
4.287469
false
false
false
false
http4k/http4k
http4k-opentelemetry/src/main/kotlin/org/http4k/filter/tracingFiltersOpenTelemetryExtensions.kt
1
4795
package org.http4k.filter import io.opentelemetry.api.GlobalOpenTelemetry import io.opentelemetry.api.OpenTelemetry import io.opentelemetry.api.trace.Span import io.opentelemetry.api.trace.SpanBuilder import io.opentelemetry.api.trace.SpanKind.CLIENT import io.opentelemetry.api.trace.SpanKind.SERVER import io.opentelemetry.api.trace.StatusCode.ERROR import io.opentelemetry.context.Context import io.opentelemetry.context.propagation.TextMapGetter import io.opentelemetry.context.propagation.TextMapPropagator import io.opentelemetry.context.propagation.TextMapSetter import org.http4k.core.Filter import org.http4k.core.HttpMessage import org.http4k.core.Request import org.http4k.core.Response import org.http4k.metrics.Http4kOpenTelemetry.INSTRUMENTATION_NAME import org.http4k.routing.RoutedRequest import java.util.concurrent.atomic.AtomicReference fun ClientFilters.OpenTelemetryTracing( openTelemetry: OpenTelemetry = GlobalOpenTelemetry.get(), spanNamer: (Request) -> String = { it.uri.toString() }, error: (Request, Throwable) -> String = { _, t -> t.message ?: "no message" }, spanCreationMutator: (SpanBuilder) -> SpanBuilder = { it }, spanCompletionMutator: (Span, Request, Response) -> Unit = { _, _, _ -> }, ): Filter { val tracer = openTelemetry.tracerProvider.get(INSTRUMENTATION_NAME) val textMapPropagator = openTelemetry.propagators.textMapPropagator val setter = setter<Request>() return Filter { next -> { req -> with(tracer.spanBuilder(spanNamer(req)) .setSpanKind(CLIENT) .let { spanCreationMutator(it) } .startSpan()) { try { setAttribute("http.method", req.method.name) setAttribute("http.url", req.uri.toString()) makeCurrent().use { val ref = AtomicReference(req) textMapPropagator.inject(Context.current(), ref, setter) next(ref.get()).apply { setAttribute("http.status_code", status.code.toString()) spanCompletionMutator(this@with, req, this) } } } catch (t: Throwable) { setStatus(ERROR, error(req, t)) throw t } finally { end() } } } } } fun ServerFilters.OpenTelemetryTracing( openTelemetry: OpenTelemetry = GlobalOpenTelemetry.get(), spanNamer: (Request) -> String = { it.uri.toString() }, error: (Request, Throwable) -> String = { _, t -> t.message ?: "no message" }, spanCreationMutator: (SpanBuilder, Request) -> SpanBuilder = { spanBuilder, _ -> spanBuilder }, spanCompletionMutator: (Span, Request, Response) -> Unit = { _, _, _ -> }, ): Filter { val tracer = openTelemetry.tracerProvider.get(INSTRUMENTATION_NAME) val textMapPropagator = openTelemetry.propagators.textMapPropagator val getter = getter<Request>(textMapPropagator) val setter = setter<Response>() return Filter { next -> { req -> with(tracer.spanBuilder(spanNamer(req)) .setParent(textMapPropagator.extract(Context.current(), req, getter)) .setSpanKind(SERVER) .let { spanCreationMutator(it, req) } .startSpan()) { makeCurrent().use { try { if (req is RoutedRequest) setAttribute("http.route", req.xUriTemplate.toString()) setAttribute("http.method", req.method.name) setAttribute("http.url", req.uri.toString()) val ref = AtomicReference(next(req)) textMapPropagator.inject(Context.current(), ref, setter) ref.get().also { spanCompletionMutator(this, req, it) setAttribute("http.status_code", it.status.code.toString()) } } catch (t: Throwable) { setStatus(ERROR, error(req, t)) throw t } finally { end() } } } } } } @Suppress("UNCHECKED_CAST") internal fun <T : HttpMessage> setter() = TextMapSetter<AtomicReference<T>> { ref, name, value -> ref?.run { set(get().header(name, value) as T) } } internal fun <T : HttpMessage> getter(textMapPropagator: TextMapPropagator) = object : TextMapGetter<T> { override fun keys(carrier: T) = textMapPropagator.fields() override fun get(carrier: T?, key: String) = carrier?.header(key) }
apache-2.0
12e50298556fcbf201d01ad7cb80eed6
41.8125
105
0.591867
4.527856
false
false
false
false
alashow/music-android
modules/base/src/main/java/tm/alashow/base/util/date/LocalDateRange.kt
1
846
/* * Copyright (C) 2019, Alashov Berkeli * All rights reserved. */ package tm.alashow.base.util.date import org.threeten.bp.LocalDate class LocalDateRange(override val start: LocalDate, override val endInclusive: LocalDate) : ClosedRange<LocalDate>, Iterable<LocalDate> { override fun iterator(): Iterator<LocalDate> { return LocalDateIterator(start, endInclusive) } } open class LocalDateIterator(start: LocalDate, private val endInclusive: LocalDate) : Iterator<LocalDate> { private var current = start override fun hasNext(): Boolean { return current <= endInclusive } override fun next(): LocalDate { val current = current this.current = current.plusDays(1) return current } } infix operator fun LocalDate.rangeTo(that: LocalDate) = LocalDateRange(this, that)
apache-2.0
380a21b798a906edc1de7cfb20087146
26.290323
107
0.706856
4.524064
false
false
false
false
OdysseusLevy/kale
src/main/kotlin/org/kale/mail/AddressHelper.kt
1
1171
package org.kale.mail import javax.mail.Address import javax.mail.internet.InternetAddress /** * @author Odysseus Levy ([email protected]) */ class AddressHelper(val email: String, val name: String) { companion object { fun create(a: Address): AddressHelper { val ia: InternetAddress = a as InternetAddress val email = if (ia.address != null) ia.address else "" val name: String = if (ia.personal != null) ia.personal else "" return AddressHelper(email, name) } val NoOne = AddressHelper("None", "None") fun getFirst (addressArray: Array<Address>?): AddressHelper { return if (addressArray == null || addressArray.count() == 0) { NoOne } else { create(addressArray[0] as InternetAddress) } } fun getAll (addressArray: Array<Address>?): List<AddressHelper> { return if (addressArray == null || addressArray.count() == 0) { listOf(NoOne) } else { addressArray.map {create(it)} } } } }
apache-2.0
21f51c4241017dd8eb72b3391e032309
26.904762
75
0.551665
4.305147
false
false
false
false
NooAn/bytheway
app/src/main/java/ru/a1024bits/bytheway/model/User.kt
1
3024
package ru.a1024bits.bytheway.model import com.google.firebase.firestore.GeoPoint import com.google.firebase.firestore.ServerTimestamp import java.io.Serializable import java.util.* enum class Method(var link: String) { TRAIN("train"), BUS("bus"), CAR("car"), PLANE("plane"), HITCHHIKING("hitchhiking") //BOAT("boat") } enum class SocialNetwork(var link: String) { VK("VK"), WHATSAPP("WHATSAPP"), CS("CS"), FB("FB"), TG("TG") } const val URL_PHOTO = "https://www.ischool.berkeley.edu/sites/default/files/default_images/avatar.jpeg" class SocialResponse(var link: String = "", var value: String = "") class FireBaseNotification(var title: String = "", var body: String = "", var cmd: String = "", var value: String? = "") data class User(var name: String = "", var lastName: String = "", var age: Int = 0, var id: String = "0", var email: String = "", var phone: String = "", var countTrip: Int = 0, var flightHours: Long = 0, var cityFromLatLng: GeoPoint = GeoPoint(0.0, 0.0), var cityToLatLng: GeoPoint = GeoPoint(0.0, 0.0), var cityTwoLatLng: GeoPoint = GeoPoint(0.0, 0.0), var countries: Long = 0, var kilometers: Long = 0, var route: String = "", var cities: HashMap<String, String> = hashMapOf(), var method: HashMap<String, Boolean> = hashMapOf(Method.BUS.link to false, Method.TRAIN.link to false, Method.PLANE.link to false, Method.CAR.link to false, Method.HITCHHIKING.link to false), var dates: HashMap<String, Long> = hashMapOf(), var budget: Long = 0, var budgetPosition: Int = 0, var city: String = "", var percentsSimilarTravel: Int = 0, var addInformation: String = "", var sex: Int = 0, var socialNetwork: HashMap<String, String> = hashMapOf(), var data: Long = 0, var token: String = "", var urlPhoto: String = URL_PHOTO, @ServerTimestamp var timestamp: Date? = Date()) : Serializable fun User.contains(query: String): Boolean = this.cities.filterValues { city -> city.contains(query, true) }.isNotEmpty() || this.name.contains(query, true) || this.lastName.contains(query, true) || this.city.contains(query, true) || this.age.toString().contains(query) || this.budget.toString().contains(query) || this.lastName.contains(query, true) || this.phone.contains(query) || this.addInformation.contains(query, true)
mit
fb8e1f9dbac9ccde54d88681da7dcc31
38.285714
103
0.525794
4.332378
false
false
false
false
rock3r/detekt
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/ReportLocator.kt
1
2023
package io.gitlab.arturbosch.detekt.cli import io.gitlab.arturbosch.detekt.api.ConsoleReport import io.gitlab.arturbosch.detekt.api.Extension import io.gitlab.arturbosch.detekt.api.OutputReport import io.gitlab.arturbosch.detekt.core.ProcessingSettings import java.net.URLClassLoader import java.util.ServiceLoader class ReportLocator(private val settings: ProcessingSettings) { private val consoleSubConfig = settings.config.subConfig("console-reports") private val consoleActive = consoleSubConfig.valueOrDefault(ACTIVE, true) private val consoleExcludes = consoleSubConfig.valueOrDefault(EXCLUDE, emptyList<String>()).toSet() private val outputSubConfig = settings.config.subConfig("output-reports") private val outputActive = outputSubConfig.valueOrDefault(ACTIVE, true) private val outputExcludes = outputSubConfig.valueOrDefault(EXCLUDE, emptyList<String>()).toSet() fun load(): List<Extension> { val consoleReports = loadConsoleReports(settings.pluginLoader) settings.debug { "Registered console reports: $consoleReports" } val outputReports = loadOutputReports(settings.pluginLoader) settings.debug { "Registered output reports: $outputReports" } return consoleReports.plus(outputReports) } private fun loadOutputReports(detektLoader: URLClassLoader) = if (outputActive) { ServiceLoader.load(OutputReport::class.java, detektLoader) .filter { it.id !in outputExcludes } .toList() } else { emptyList<OutputReport>() } private fun loadConsoleReports(detektLoader: URLClassLoader) = if (consoleActive) { ServiceLoader.load(ConsoleReport::class.java, detektLoader) .filter { it.id !in consoleExcludes } .toList() } else { emptyList<ConsoleReport>() } companion object { private const val ACTIVE = "active" private const val EXCLUDE = "exclude" } }
apache-2.0
89886e8097f045de51c4eefc7d1a8ed8
39.46
103
0.704894
4.693735
false
true
false
false
alex-tavella/MooV
core-android/src/main/java/br/com/core/android/views/AutofitRecyclerView.kt
1
1996
/* * Copyright 2020 Alex Almeida Tavella * * 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 br.com.core.android.views import android.content.Context import android.util.AttributeSet import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView class AutofitRecyclerView : RecyclerView { private lateinit var manager: GridLayoutManager private var columnWidth = -1 constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(context, attrs) } private fun init(context: Context, attrs: AttributeSet? = null) { if (attrs != null) { val attrsArray = intArrayOf(android.R.attr.columnWidth) val ta = context.obtainStyledAttributes(attrs, attrsArray) columnWidth = ta.getDimensionPixelSize(0, -1) ta.recycle() } manager = GridLayoutManager(context, 1) layoutManager = manager } override fun onMeasure(widthSpec: Int, heightSpec: Int) { super.onMeasure(widthSpec, heightSpec) if (columnWidth > 0) { val spanCount = Math.max(1, measuredWidth / columnWidth) manager.spanCount = spanCount } } }
apache-2.0
99176b6ea0f6227259cff08581000910
31.193548
82
0.682365
4.546697
false
false
false
false
aleksey-zhidkov/jeb-k
src/test/kotlin/jeb/StorageSpeck.kt
1
4507
package jeb import jeb.ddsl.dir import org.jetbrains.spek.api.* import java.io.File class StorageSpeck : Spek() {init { val jebDir = File("/tmp/jeb") given("Two nested directories with file within each") { val outerDir = File(jebDir, "outerDir") val outerDirCopy = File(jebDir, "outerDirCopy") outerDir.deleteRecursively() outerDirCopy.deleteRecursively() val dir = dir(outerDir) { file("outerFile") { "content" } dir("nestedDir") { file("nestedFile") { "content2" } } } dir.create() val storage = Storage() on("copy outer dir") { storage.fullBackup(listOf(Source(outerDir.absolutePath + "/")), null, outerDirCopy) it("copy should be equal") { shouldBeTrue(dir.contentEqualTo(outerDirCopy)) } it("copy should be separate files") { shouldNotEqual(File(outerDir, "outerFile").inode, File(outerDirCopy, "outerFile").inode) }}} given("Directory with a file") { val from = File(jebDir, "mvFrom") val to = File(jebDir, "mvTo") from.deleteRecursively() to.deleteRecursively() val dir = dir(from) { file("file") { "content" } } dir.create() val storage = Storage() on("move dir") { storage.move(from, to) it("should be moved") { shouldBeFalse(from.exists()) shouldBeTrue(dir.contentEqualTo(to)) }}} given("""Origin directory with new, same and changed files Base directory with same, changed and deleted files Backup directory without files""") { val origin = File(jebDir, "origin") val base = File(jebDir, "base") val backup = File(jebDir, "backup") origin.deleteRecursively() base.deleteRecursively() backup.deleteRecursively() val originDir = dir(origin) { file("same") { "sameContent" } file("new") { "newContent" } file("changed") { "changedContent" } } originDir.create() dir(base) { file("same") { "sameContent" } file("changed") { "originContent" } file("deleted") { "deletedContent" } }.create() val storage = Storage() on("sync dir") { storage.incBackup(listOf(Source(origin.absolutePath + "/")), null, base, backup) it("backup dir should be equal to origin") { shouldBeTrue(originDir.contentEqualTo(backup)) } it("same should be hardlink and new should not be hardlink") { val originNew = File(origin, "new") val originSame = File(base, "same") val backupNew = File(backup, "new") val backupSame = File(backup, "same") shouldEqual(originSame.inode, backupSame.inode) shouldNotEqual(originNew.inode, backupNew.inode) }}} given("""Directories a and b with files (a1, a2) and (b1, b2) correspondly and Sources for that directories with type content and directory""") { val a = File(jebDir, "a") val b = File(jebDir, "b") val backup = File(jebDir, "backup2") a.deleteRecursively() b.deleteRecursively() backup.deleteRecursively() val aDir = dir(a) { file("a1") { "a1Content" } file("a2") { "a2Content" } } aDir.create() val bDir = dir(b) { file("b1") { "b1Content" } file("b2") { "b2Content" } } bDir.create() val aSource = Source(a, BackupType.CONTENT) val bSoource = Source(b, BackupType.DIRECTORY) val storage = Storage() on("sync dirs") { storage.fullBackup(listOf(aSource, bSoource), null, backup) it("backup directory should contain a1 and a2 files and b dir") { val res = dir(backup) { dir("a") { file("a1") { "a1Content" } file("a2") { "a2Content" } } dir("b") { file("b1") { "b1Content" } file("b2") { "b2Content" } } } res.contentEqualTo(backup) }}} } }
apache-2.0
0448de2a9c10e48ad17c4b119eb716b8
30.739437
104
0.512536
4.173148
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/models/Credentials.kt
1
485
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonProperty class Credentials { @JsonProperty("access_token") var accessToken: String? = null @JsonProperty("token_type") var tokenType: String? = null @JsonProperty("expires_in") var expiresIn: String? = null @JsonProperty("refresh_token") var refreshToken: String? = null var scope: String? = null @JsonProperty("created_at") var createdAt: String? = null }
gpl-3.0
2530ad071ae09c1c036a4ca75597ca4d
19.208333
52
0.684536
4.145299
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/store/stats/insights/PublicizeStore.kt
2
2216
package org.wordpress.android.fluxc.store.stats.insights import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.InsightsMapper import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.network.rest.wpcom.stats.insights.PublicizeRestClient import org.wordpress.android.fluxc.persistence.InsightsSqlUtils.PublicizeSqlUtils import org.wordpress.android.fluxc.store.StatsStore.OnStatsFetched import org.wordpress.android.fluxc.store.StatsStore.StatsError import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.INVALID_RESPONSE import org.wordpress.android.fluxc.tools.CoroutineEngine import org.wordpress.android.util.AppLog.T.STATS import javax.inject.Inject import javax.inject.Singleton @Singleton class PublicizeStore @Inject constructor( private val restClient: PublicizeRestClient, private val sqlUtils: PublicizeSqlUtils, private val insightsMapper: InsightsMapper, private val coroutineEngine: CoroutineEngine ) { suspend fun fetchPublicizeData(siteModel: SiteModel, limitMode: LimitMode, forced: Boolean = false) = coroutineEngine.withDefaultContext(STATS, this, "fetchPublicizeData") { if (!forced && sqlUtils.hasFreshRequest(siteModel)) { return@withDefaultContext OnStatsFetched(getPublicizeData(siteModel, limitMode), cached = true) } val response = restClient.fetchPublicizeData(siteModel, forced = forced) return@withDefaultContext when { response.isError -> { OnStatsFetched(response.error) } response.response != null -> { sqlUtils.insert(siteModel, response.response) OnStatsFetched(insightsMapper.map(response.response, limitMode)) } else -> OnStatsFetched(StatsError(INVALID_RESPONSE)) } } fun getPublicizeData(site: SiteModel, limitMode: LimitMode) = coroutineEngine.run(STATS, this, "getPublicizeData") { sqlUtils.select(site)?.let { insightsMapper.map(it, limitMode) } } }
gpl-2.0
c2df258ddab00a48ead52524ec6825bd
48.244444
120
0.70713
4.796537
false
false
false
false
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/modules/PolymorphicModuleBuilder.kt
1
5829
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.modules import kotlinx.serialization.* import kotlinx.serialization.internal.* import kotlin.reflect.* /** * A builder which registers all its content for polymorphic serialization in the scope of the [base class][baseClass]. * If [baseSerializer] is present, registers it as a serializer for [baseClass] (which will be used if base class is serializable). * Subclasses and its serializers can be added with [subclass] builder function. * * To obtain an instance of this builder, use [SerializersModuleBuilder.polymorphic] DSL function. */ public class PolymorphicModuleBuilder<in Base : Any> @PublishedApi internal constructor( private val baseClass: KClass<Base>, private val baseSerializer: KSerializer<Base>? = null ) { private val subclasses: MutableList<Pair<KClass<out Base>, KSerializer<out Base>>> = mutableListOf() private var defaultSerializerProvider: ((Base) -> SerializationStrategy<Base>?)? = null private var defaultDeserializerProvider: ((String?) -> DeserializationStrategy<out Base>?)? = null /** * Registers a [subclass] [serializer] in the resulting module under the [base class][Base]. */ public fun <T : Base> subclass(subclass: KClass<T>, serializer: KSerializer<T>) { subclasses.add(subclass to serializer) } /** * Adds a default serializers provider associated with the given [baseClass] to the resulting module. * [defaultDeserializerProvider] is invoked when no polymorphic serializers associated with the `className` * were found. `className` could be `null` for formats that support nullable class discriminators * (currently only [Json] with [useArrayPolymorphism][JsonBuilder.useArrayPolymorphism] set to `false`) * * [defaultDeserializerProvider] can be stateful and lookup a serializer for the missing type dynamically. * * Typically, if the class is not registered in advance, it is not possible to know the structure of the unknown * type and have a precise serializer, so the default serializer has limited capabilities. * To have a structural access to the unknown data, it is recommended to use [JsonTransformingSerializer] * or [JsonContentPolymorphicSerializer] classes. * * Default deserializers provider affects only deserialization process. */ @ExperimentalSerializationApi public fun defaultDeserializer(defaultDeserializerProvider: (className: String?) -> DeserializationStrategy<out Base>?) { require(this.defaultDeserializerProvider == null) { "Default deserializer provider is already registered for class $baseClass: ${this.defaultDeserializerProvider}" } this.defaultDeserializerProvider = defaultDeserializerProvider } /** * Adds a default deserializers provider associated with the given [baseClass] to the resulting module. * [defaultSerializerProvider] is invoked when no polymorphic serializers associated with the `className` * were found. `className` could be `null` for formats that support nullable class discriminators * (currently only [Json] with [useArrayPolymorphism][JsonBuilder.useArrayPolymorphism] set to `false`) * * [defaultSerializerProvider] can be stateful and lookup a serializer for the missing type dynamically. * * [defaultSerializerProvider] is named as such for backwards compatibility reasons; it provides deserializers. * * Typically, if the class is not registered in advance, it is not possible to know the structure of the unknown * type and have a precise serializer, so the default serializer has limited capabilities. * To have a structural access to the unknown data, it is recommended to use [JsonTransformingSerializer] * or [JsonContentPolymorphicSerializer] classes. * * Default deserializers provider affects only deserialization process. To affect serialization process, use * [SerializersModuleBuilder.polymorphicDefaultSerializer]. * * @see defaultDeserializer */ @OptIn(ExperimentalSerializationApi::class) // TODO: deprecate in 1.4 public fun default(defaultSerializerProvider: (className: String?) -> DeserializationStrategy<out Base>?) { defaultDeserializer(defaultSerializerProvider) } @Suppress("UNCHECKED_CAST") @PublishedApi internal fun buildTo(builder: SerializersModuleBuilder) { if (baseSerializer != null) builder.registerPolymorphicSerializer(baseClass, baseClass, baseSerializer) subclasses.forEach { (kclass, serializer) -> builder.registerPolymorphicSerializer( baseClass, kclass as KClass<Base>, serializer.cast() ) } val defaultSerializer = defaultSerializerProvider if (defaultSerializer != null) { builder.registerDefaultPolymorphicSerializer(baseClass, defaultSerializer, false) } val defaultDeserializer = defaultDeserializerProvider if (defaultDeserializer != null) { builder.registerDefaultPolymorphicDeserializer(baseClass, defaultDeserializer, false) } } } /** * Registers a [subclass] [serializer] in the resulting module under the [base class][Base]. */ public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclass(serializer: KSerializer<T>): Unit = subclass(T::class, serializer) /** * Registers a serializer for class [T] in the resulting module under the [base class][Base]. */ public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclass(clazz: KClass<T>): Unit = subclass(clazz, serializer())
apache-2.0
f9318d01c82172a3af97f2e7d24d0be1
49.25
131
0.727741
5.068696
false
false
false
false
lllllT/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/navigation_drawer/NavigationDrawerViewHolder.kt
2
1283
package com.bl_lia.kirakiratter.presentation.adapter.navigation_drawer import android.support.annotation.LayoutRes import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.bl_lia.kirakiratter.R import io.reactivex.Observable class NavigationDrawerViewHolder(val parent: View) : RecyclerView.ViewHolder(parent) { companion object { @LayoutRes val LAYOUT = R.layout.list_item_navigation_drawer fun newInstance(parent: View): NavigationDrawerViewHolder = NavigationDrawerViewHolder(parent) } val onClickItem = Observable.create<NavigationDrawerAdapter.Menu> { subscriber -> itemView.setOnClickListener { subscriber.onNext(menu) } } private val menuText:TextView by lazy { itemView.findViewById(R.id.menu_text) as TextView } private lateinit var menu: NavigationDrawerAdapter.Menu fun bind(menu: NavigationDrawerAdapter.Menu) { this.menu = menu when (menu) { NavigationDrawerAdapter.Menu.License -> { menuText.text = "Open Source License" } NavigationDrawerAdapter.Menu.Thanks -> { menuText.text = "Special Thanks" } } } }
mit
0c6f311dc0f4f6ac28d9b63acc91b576
28.860465
102
0.681995
4.716912
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/packable/PackableLauncher.kt
1
5192
// Copyright 2021 [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 cfig.packable import cfig.utils.SparseImgParser import org.slf4j.LoggerFactory import java.io.File import java.util.regex.Pattern import kotlin.reflect.KClass import kotlin.reflect.full.createInstance import kotlin.reflect.full.declaredFunctions import kotlin.system.exitProcess class PackableLauncher fun main(args: Array<String>) { val log = LoggerFactory.getLogger(PackableLauncher::class.java) val packablePool = mutableMapOf<List<String>, KClass<IPackable>>() listOf( DtboParser(), VBMetaParser(), BootImgParser(), SparseImgParser(), VendorBootParser(), PayloadBinParser(), MiscImgParser() ).forEach { @Suppress("UNCHECKED_CAST") packablePool.put(it.capabilities(), it::class as KClass<IPackable>) } packablePool.forEach { log.debug("" + it.key + "/" + it.value) } var targetFile: String? = null var targetHandler: KClass<IPackable>? = null run found@{ for (currentLoopNo in 0..1) { //currently we have only 2 loops File(".").listFiles()!!.forEach { file -> packablePool .filter { it.value.createInstance().loopNo == currentLoopNo } .forEach { p -> for (item in p.key) { if (Pattern.compile(item).matcher(file.name).matches()) { log.debug("Found: " + file.name + ", " + item) targetFile = file.name targetHandler = p.value return@found } } } }//end-of-file-traversing }//end-of-range-loop }//end-of-found@ // /* 1 */ no-args & no-handler: help for IPackable // /* 2 */ no-args & handler : help for Handler // /* 3 */ args & no-handler: do nothing // /* 4 */ args & handler : work when (listOf(args.isEmpty(), targetHandler == null)) { listOf(true, true) -> { /* 1 */ log.info("help:") log.info("available IPackable subcommands are:") IPackable::class.declaredFunctions.forEach { log.info("\t" + it.name) } exitProcess(1) } listOf(true, false) -> {/* 2 */ log.info("available ${targetHandler!!.simpleName} subcommands are:") targetHandler!!.declaredFunctions.forEach { log.info("\t" + it.name) } exitProcess(1) } listOf(false, true) -> {/* 3 */ log.warn("No handler is activated, DO NOTHING!") exitProcess(2) } listOf(false, false) -> {/* 4 */ log.debug("continue ...") } } targetHandler?.let { log.warn("[$targetFile] will be handled by [${it.simpleName}]") val functions = it.declaredFunctions.filter { funcItem -> funcItem.name == args[0] } if (functions.size != 1) { log.error("command '${args[0]}' can not be recognized") log.info("available ${it.simpleName} subcommands are:") it.declaredFunctions.forEach { theFunc -> log.info("\t" + theFunc.name) } exitProcess(3) } log.warn("'${args[0]}' sequence initialized") val reflectRet = when (functions[0].parameters.size) { 1 -> { functions[0].call(it.createInstance()) } 2 -> { functions[0].call(it.createInstance(), targetFile!!) } 3 -> { if (args.size != 2) { log.info("invoke: ${it.qualifiedName}, $targetFile, " + targetFile!!.removeSuffix(".img")) functions[0].call(it.createInstance(), targetFile!!, targetFile!!.removeSuffix(".img")) } else { log.info("invoke: ${it.qualifiedName}, $targetFile, " + args[1]) functions[0].call(it.createInstance(), targetFile!!, args[1]) } } else -> { functions[0].parameters.forEach { kp -> println("Param: " + kp.index + " " + kp.type + " " + kp.name) } log.error("I am confused by so many parameters") exitProcess(4) } } if (functions[0].returnType.toString() != Unit.toString()) { log.info("ret: $reflectRet") } log.warn("'${args[0]}' sequence completed") } }
apache-2.0
63e299af1556a82d771062824285a3ee
38.333333
113
0.537943
4.392555
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/feed/FeedService.kt
1
6824
package com.pr0gramm.app.feed import com.pr0gramm.app.* import com.pr0gramm.app.api.pr0gramm.Api import com.pr0gramm.app.db.FeedItemInfoQueries import com.pr0gramm.app.services.UserService import com.pr0gramm.app.ui.base.AsyncScope import com.pr0gramm.app.ui.base.launchIgnoreErrors import com.pr0gramm.app.util.equalsIgnoreCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runInterruptible import java.util.* /** * Performs the actual request to get the items for a feed. */ interface FeedService { suspend fun load(query: FeedQuery): Api.Feed suspend fun post(id: Long, bust: Boolean = false): Api.Post suspend fun item(itemId: Long): Api.Feed.Item { val query = FeedQuery( filter = FeedFilter().withFeedType(FeedType.NEW), contentTypes = ContentType.AllSet, around = itemId, ) return load(query).items.single { item -> item.id == itemId } } /** * Streams feed items - giving one page after the next until * the end of the stream. */ fun stream(startQuery: FeedQuery): Flow<Api.Feed> data class FeedQuery(val filter: FeedFilter, val contentTypes: Set<ContentType>, val newer: Long? = null, val older: Long? = null, val around: Long? = null) } class FeedServiceImpl(private val api: Api, private val userService: UserService, private val itemQueries: FeedItemInfoQueries) : FeedService { private val logger = Logger("FeedService") override suspend fun load(query: FeedService.FeedQuery): Api.Feed { val feedFilter = query.filter // filter by feed-type val promoted = if (feedFilter.feedType === FeedType.PROMOTED) 1 else null val following = if (feedFilter.feedType === FeedType.STALK) 1 else null val flags = ContentType.combine(query.contentTypes) val feedType = feedFilter.feedType // statistics Stats().incrementCounter( "feed.loaded", "type:" + feedType.name.lowercase(Locale.ROOT)) val tags = feedFilter.tags?.replaceFirst("^\\s*\\?\\s*".toRegex(), "!") return when (feedType) { FeedType.RANDOM -> { // convert to a query including the x:random flag. val bust = Instant.now().millis / 1000L val tagsQuery = Tags.joinAnd("!-(x:random | x:$bust)", feedFilter.tags) // and load it directly on 'new' val feed = load( query.copy( newer = null, older = null, around = null, filter = feedFilter.withFeedType(FeedType.NEW).basicWithTags(tagsQuery) ) ) // then shuffle the result feed.copy(_items = feed._items?.shuffled()) } FeedType.BESTOF -> { // add add s:1000 tag to the query. // and add s:700 to nsfw posts. val tagsQuery = Tags.joinOr( Tags.joinAnd("s:2000", feedFilter.tags), Tags.joinAnd("s:700 f:nsfw", feedFilter.tags), ) load(query.copy(filter = feedFilter.withFeedType(FeedType.NEW).basicWithTags(tagsQuery))) } FeedType.CONTROVERSIAL -> { // just add the f:controversial flag to the query val tagsQuery = Tags.joinAnd("!f:controversial", feedFilter.tags) load(query.copy(filter = feedFilter.withFeedType(FeedType.NEW).basicWithTags(tagsQuery))) } else -> { val collection = feedFilter.collection val user = feedFilter.username val self = userService.loginState .let { loginState -> // we have a user and it is the same as in the query. loginState.name != null && loginState.name.equalsIgnoreCase(user) } .takeIf { self -> self } // do the normal query as is. val result = api.itemsGet(promoted, following, query.older, query.newer, query.around, flags, tags, collection, self, user) result.also { AsyncScope.launchIgnoreErrors { logger.time("Cache items from result") { cacheItems(result) } } } } } } private suspend fun cacheItems(feed: Api.Feed) { runInterruptible(Dispatchers.IO) { itemQueries.transaction { for (item in feed.items) { itemQueries.cache( id = item.id, promotedId = item.promoted, userId = item.userId, image = item.image, thumbnail = item.thumb, fullsize = item.fullsize, user = item.user, up = item.up, down = item.down, mark = item.mark, flags = item.flags, width = item.width, height = item.height, created = item.created.epochSeconds, audio = item.audio, deleted = item.deleted, ) } } } } override suspend fun post(id: Long, bust: Boolean): Api.Post { val buster = if (bust) TimeFactory.currentTimeMillis() else null return api.info(id, bust = buster) } override fun stream(startQuery: FeedService.FeedQuery): Flow<Api.Feed> { // move from low to higher numbers if newer is set. val upwards = startQuery.newer != null return flow { var query: FeedService.FeedQuery? = startQuery while (true) { val currentQuery = query ?: break val feed = load(currentQuery) emit(feed) // get the previous (or next) page from the current set of items. query = when { upwards && !feed.isAtStart -> feed.items.maxByOrNull { it.id }?.let { currentQuery.copy(newer = it.id) } !upwards && !feed.isAtEnd -> feed.items.minByOrNull { it.id }?.let { currentQuery.copy(older = it.id) } else -> null } } } } }
mit
da7398c04488a2808398900b7d965325
36.289617
143
0.524912
4.7356
false
false
false
false
google/modernstorage
sample/src/main/java/com/google/modernstorage/sample/permissions/CheckPermissionScreen.kt
1
14190
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.modernstorage.sample.permissions import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Divider import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.ListItem import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Article import androidx.compose.material.icons.filled.Image import androidx.compose.material.icons.filled.Movie import androidx.compose.material.icons.filled.MusicNote import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.google.modernstorage.permissions.StoragePermissions import com.google.modernstorage.permissions.StoragePermissions.Action import com.google.modernstorage.permissions.StoragePermissions.CreatedBy import com.google.modernstorage.permissions.StoragePermissions.FileType import com.google.modernstorage.sample.Demos import com.google.modernstorage.sample.HomeRoute import com.google.modernstorage.sample.R @ExperimentalMaterialApi @ExperimentalFoundationApi @Composable fun CheckPermissionScreen(navController: NavController) { val check = StoragePermissions(LocalContext.current) Scaffold( topBar = { TopAppBar( title = { Text(stringResource(Demos.CheckPermission.name)) }, navigationIcon = { IconButton(onClick = { navController.popBackStack(HomeRoute, false) }) { Icon( Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button_label) ) } } ) }, content = { paddingValues -> LazyColumn(modifier = Modifier.padding(paddingValues)) { item { ListItem( icon = { Icon(Icons.Filled.Image, contentDescription = null) }, text = { Text(stringResource(R.string.demo_check_permission_image_type)) }, secondaryText = { Column(Modifier.padding(bottom = 10.dp)) { CreatedByLabel( action = Action.READ, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ, listOf(FileType.Image), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ, listOf(FileType.Image), CreatedBy.AllApps ) ) Spacer(Modifier.height(10.dp)) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Image), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Image), CreatedBy.AllApps ) ) } }, ) Divider() ListItem( icon = { Icon(Icons.Filled.Movie, contentDescription = null) }, text = { Text(stringResource(R.string.demo_check_permission_video_type)) }, secondaryText = { Column(Modifier.padding(bottom = 10.dp)) { CreatedByLabel( action = Action.READ, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ, listOf(FileType.Video), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ, listOf(FileType.Video), CreatedBy.AllApps ) ) Spacer(Modifier.height(10.dp)) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Video), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Video), CreatedBy.AllApps ) ) } }, ) Divider() ListItem( icon = { Icon(Icons.Filled.MusicNote, contentDescription = null) }, text = { Text(stringResource(R.string.demo_check_permission_audio_type)) }, secondaryText = { Column(Modifier.padding(bottom = 10.dp)) { CreatedByLabel( action = Action.READ, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ, listOf(FileType.Audio), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ, listOf(FileType.Audio), CreatedBy.AllApps ) ) Spacer(Modifier.height(10.dp)) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Audio), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Audio), CreatedBy.AllApps ) ) } }, ) Divider() ListItem( icon = { Icon(Icons.Filled.Article, contentDescription = null) }, text = { Text(stringResource(R.string.demo_check_permission_document_type)) }, secondaryText = { Column(Modifier.padding(bottom = 10.dp)) { CreatedByLabel( action = Action.READ, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ, listOf(FileType.Document), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ, listOf(FileType.Document), CreatedBy.AllApps ) ) Spacer(Modifier.height(10.dp)) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.Self, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Document), CreatedBy.Self ) ) CreatedByLabel( action = Action.READ_AND_WRITE, createdBy = CreatedBy.AllApps, enabled = check.hasAccess( Action.READ_AND_WRITE, listOf(FileType.Document), CreatedBy.AllApps ) ) } }, ) Divider() } } } ) } @Composable fun CreatedByLabel(action: Action, createdBy: CreatedBy, enabled: Boolean) { Text( buildAnnotatedString { append(if (enabled) "✅ " else "❌ ") when (action) { Action.READ -> append(stringResource(R.string.demo_check_permission_read_label)) Action.READ_AND_WRITE -> append(stringResource(R.string.demo_check_permission_read_and_write_label)) } append(" ") append(stringResource(R.string.demo_check_permission_created_by_label)) append(" ") withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) { when (createdBy) { CreatedBy.Self -> append(stringResource(R.string.demo_check_permission_created_by_self_label)) CreatedBy.AllApps -> append(stringResource(R.string.demo_check_permission_created_by_all_apps_label)) } } } ) }
apache-2.0
1172bba25e7aa286987d7bfc57533c2a
47.749141
121
0.413577
6.774594
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/internal/platform/AndroidPlatform.kt
3
6358
/* * Copyright (C) 2016 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 okhttp3.internal.platform import android.os.Build import android.security.NetworkSecurityPolicy import java.io.IOException import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.net.InetSocketAddress import java.net.Socket import java.security.cert.TrustAnchor import java.security.cert.X509Certificate import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import javax.net.ssl.X509TrustManager import okhttp3.Protocol import okhttp3.internal.SuppressSignatureCheck import okhttp3.internal.platform.android.AndroidCertificateChainCleaner import okhttp3.internal.platform.android.AndroidSocketAdapter import okhttp3.internal.platform.android.BouncyCastleSocketAdapter import okhttp3.internal.platform.android.CloseGuard import okhttp3.internal.platform.android.ConscryptSocketAdapter import okhttp3.internal.platform.android.DeferredSocketAdapter import okhttp3.internal.platform.android.StandardAndroidSocketAdapter import okhttp3.internal.tls.BasicTrustRootIndex import okhttp3.internal.tls.CertificateChainCleaner import okhttp3.internal.tls.TrustRootIndex /** Android 5+. */ @SuppressSignatureCheck class AndroidPlatform : Platform() { private val socketAdapters = listOfNotNull( StandardAndroidSocketAdapter.buildIfSupported(), DeferredSocketAdapter(AndroidSocketAdapter.playProviderFactory), // Delay and Defer any initialisation of Conscrypt and BouncyCastle DeferredSocketAdapter(ConscryptSocketAdapter.factory), DeferredSocketAdapter(BouncyCastleSocketAdapter.factory) ).filter { it.isSupported() } private val closeGuard = CloseGuard.get() @Throws(IOException::class) override fun connectSocket( socket: Socket, address: InetSocketAddress, connectTimeout: Int ) { try { socket.connect(address, connectTimeout) } catch (e: ClassCastException) { // On android 8.0, socket.connect throws a ClassCastException due to a bug // see https://issuetracker.google.com/issues/63649622 if (Build.VERSION.SDK_INT == 26) { throw IOException("Exception in connect", e) } else { throw e } } } override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? = socketAdapters.find { it.matchesSocketFactory(sslSocketFactory) } ?.trustManager(sslSocketFactory) override fun configureTlsExtensions( sslSocket: SSLSocket, hostname: String?, protocols: List<@JvmSuppressWildcards Protocol> ) { // No TLS extensions if the socket class is custom. socketAdapters.find { it.matchesSocket(sslSocket) } ?.configureTlsExtensions(sslSocket, hostname, protocols) } override fun getSelectedProtocol(sslSocket: SSLSocket) = // No TLS extensions if the socket class is custom. socketAdapters.find { it.matchesSocket(sslSocket) }?.getSelectedProtocol(sslSocket) override fun getStackTraceForCloseable(closer: String): Any? = closeGuard.createAndOpen(closer) override fun logCloseableLeak(message: String, stackTrace: Any?) { val reported = closeGuard.warnIfOpen(stackTrace) if (!reported) { // Unable to report via CloseGuard. As a last-ditch effort, send it to the logger. log(message, WARN) } } override fun isCleartextTrafficPermitted(hostname: String): Boolean = when { Build.VERSION.SDK_INT >= 24 -> NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(hostname) Build.VERSION.SDK_INT >= 23 -> NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted else -> true } override fun buildCertificateChainCleaner(trustManager: X509TrustManager): CertificateChainCleaner = AndroidCertificateChainCleaner.buildIfSupported(trustManager) ?: super.buildCertificateChainCleaner(trustManager) override fun buildTrustRootIndex(trustManager: X509TrustManager): TrustRootIndex = try { // From org.conscrypt.TrustManagerImpl, we want the method with this signature: // private TrustAnchor findTrustAnchorByIssuerAndSignature(X509Certificate lastCert); val method = trustManager.javaClass.getDeclaredMethod( "findTrustAnchorByIssuerAndSignature", X509Certificate::class.java) method.isAccessible = true CustomTrustRootIndex(trustManager, method) } catch (e: NoSuchMethodException) { super.buildTrustRootIndex(trustManager) } /** * A trust manager for Android applications that customize the trust manager. * * This class exploits knowledge of Android implementation details. This class is potentially * much faster to initialize than [BasicTrustRootIndex] because it doesn't need to load and * index trusted CA certificates. */ internal data class CustomTrustRootIndex( private val trustManager: X509TrustManager, private val findByIssuerAndSignatureMethod: Method ) : TrustRootIndex { override fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate? { return try { val trustAnchor = findByIssuerAndSignatureMethod.invoke( trustManager, cert) as TrustAnchor trustAnchor.trustedCert } catch (e: IllegalAccessException) { throw AssertionError("unable to get issues and signature", e) } catch (_: InvocationTargetException) { null } } } companion object { val isSupported: Boolean = when { !isAndroid -> false Build.VERSION.SDK_INT >= 30 -> false // graylisted methods are banned else -> { // Fail Fast check( Build.VERSION.SDK_INT >= 21) { "Expected Android API level 21+ but was ${Build.VERSION.SDK_INT}" } true } } fun buildIfSupported(): Platform? = if (isSupported) AndroidPlatform() else null } }
apache-2.0
408dd4b236e813ac97f75a8e0254366b
38.246914
121
0.751809
4.580692
false
false
false
false
umren/Watcher
app/src/main/java/io/github/umren/watcher/Views/Activities/MainActivity.kt
1
7516
package io.github.umren.watcher.Views.Activities import android.R.attr.duration import android.content.Intent import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.view.animation.AnimationUtils import android.widget.TextView import android.widget.Toast import com.squareup.picasso.Picasso import io.github.umren.watcher.Views.Fragments.AboutFragment import io.github.umren.watcher.Entities.Movie import io.github.umren.watcher.Interactors.Db.WatcherDatabaseHelper import io.github.umren.watcher.R import io.github.umren.watcher.Views.Presenters.MainActivityPresenter import io.github.umren.watcher.Views.View.MainView import kotlinx.android.synthetic.main.content_main.* class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, MainView { lateinit internal var Presenter: MainActivityPresenter var loadedMovie: Movie? = null var isLoading: Boolean = false var menuFavBtn: MenuItem? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // set toolbar val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) // set drawer val drawer = findViewById(R.id.drawer_layout) as DrawerLayout val toggle = ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.addDrawerListener(toggle) toggle.syncState() val navigationView = findViewById(R.id.nav_view) as NavigationView navigationView.setNavigationItemSelectedListener(this) navigationView.menu.getItem(0).isChecked = true // initialize presenter attachPresenter() // load movie if (!isLoading) { Presenter.loadMovie() } else { isLoading = false } } fun attachPresenter() { Presenter = MainActivityPresenter() if (lastCustomNonConfigurationInstance != null) { val that = lastCustomNonConfigurationInstance as MainActivity loadView(that.loadedMovie!!) isLoading = true } Presenter.attachView(this) } override fun onRetainCustomNonConfigurationInstance(): Any { return this } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val movieId = intent?.getStringExtra("movie_id")?.toInt() ?: return val db = WatcherDatabaseHelper.getInstance(this) val movie = db.getFavorite(movieId) ?: return loadView(movie) setBtnFavoriteIcon(movie) } override fun onResume() { super.onResume() val navigationView = findViewById(R.id.nav_view) as NavigationView navigationView.menu.getItem(0).isChecked = true } override fun onBackPressed() { val drawer = findViewById(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { moveTaskToBack(true) //super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menu.clear() menuInflater.inflate(R.menu.main, menu) menuFavBtn = menu.findItem(R.id.action_favorite) if (loadedMovie != null) { setBtnFavoriteIcon(loadedMovie!!) // TODO UGLY } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (isLoading) return false when (item.itemId) { R.id.action_favorite -> { if (movie_error.visibility != View.VISIBLE) { clickBtnFavorite(item) } return true } R.id.action_refresh -> { val view = findViewById(R.id.action_refresh) val rotation = AnimationUtils.loadAnimation(this, R.anim.rotation) view.startAnimation(rotation) Presenter.loadMovie() return true } else -> return super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.get_movie -> { } R.id.favorites -> { val i = Intent(this, FavoritesActivity::class.java) startActivity(i) } R.id.about -> { val dialog = AboutFragment() dialog.show(this.supportFragmentManager, "About") } } val drawer = findViewById(R.id.drawer_layout) as DrawerLayout drawer.closeDrawer(GravityCompat.START) return true } override fun getActivity(): MainActivity { return this } fun clickBtnFavorite(item: MenuItem) { val movie = loadedMovie as Movie val db = WatcherDatabaseHelper.getInstance(this) if (db.isFavorite(movie.id)) { db.removeFavorite(movie.id) item.setIcon(R.drawable.ic_favorite_border_white_24dp) Toast.makeText(this, "Movie removed from favorites", duration).show() } else { db.addFavorite(movie) item.setIcon(R.drawable.ic_favorite_white_24dp) Toast.makeText(this, "Movie added to favorites", duration).show() } } fun loadView(movie: Movie) { movie_actors_list.removeAllViews() movie_title.text = movie.title movie_genre.text = movie.genres movie_year.text = movie.release_date movie_desc.text = movie.overview movie_director.text = movie.director movie.cast.forEach { val tv = TextView(this) tv.text = it movie_actors_list.addView(tv) } Picasso.with(this).load(movie.poster_path).into(movie_preview_image) showView() loadedMovie = movie } fun setBtnFavoriteIcon(movie: Movie) { val db = WatcherDatabaseHelper.getInstance(this) if (db.isFavorite(movie.id)) { menuFavBtn?.setIcon(R.drawable.ic_favorite_white_24dp) } else { menuFavBtn?.setIcon(R.drawable.ic_favorite_border_white_24dp) } } fun hideView() { movie_error.visibility = View.INVISIBLE movie_layout.visibility = View.INVISIBLE movie_progress.visibility = View.VISIBLE isLoading = true } fun showView() { movie_error.visibility = View.INVISIBLE movie_layout.visibility = View.VISIBLE movie_progress.visibility = View.INVISIBLE isLoading = false } fun showError() { movie_error.visibility = View.VISIBLE movie_layout.visibility = View.INVISIBLE movie_progress.visibility = View.INVISIBLE isLoading = false } fun cleanView() { movie_genre.text = getString(R.string.default_value) movie_desc.text = resources.getString(R.string.default_movie_desc) movie_actors_list.removeAllViews() } }
gpl-3.0
f8ce238a6c3ab9580370c22a4f735150
30.579832
105
0.63917
4.557914
false
false
false
false
AoEiuV020/PaNovel
app/src/test/java/cc/aoeiuv020/panovel/backup/BackupManagerTest.kt
1
1226
package cc.aoeiuv020.panovel.backup import net.lingala.zip4j.core.ZipFile import net.lingala.zip4j.model.FileHeader import net.lingala.zip4j.model.ZipParameters import org.junit.Assert.assertEquals import org.junit.Before import org.junit.FixMethodOrder import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runners.MethodSorters /** * Created by AoEiuV020 on 2018.05.11-18:09:14. */ @FixMethodOrder(value = MethodSorters.NAME_ASCENDING) class BackupManagerTest { @Rule @JvmField val folder = TemporaryFolder() @Before fun setUp() { } @Test fun a1_addVersion() { val zipFile: ZipFile = folder.newFile().let { it.delete() ZipFile(it) } val p = ZipParameters() zipFile.addStream("1".byteInputStream(), p.apply { isSourceExternalStream = true fileNameInZip = "version" }) val headers: List<FileHeader> = zipFile.fileHeaders.map { it as FileHeader } val header = headers[0] assertEquals("version", header.fileName) zipFile.getInputStream(header).reader().readText().let { assertEquals("1", it) } } }
gpl-3.0
920cc624f937a0fb1c58b9efe9ea6a33
24.5625
84
0.661501
4.032895
false
true
false
false
rickshory/VegNab
app/src/main/java/com/rickshory/vegnab/viewmodels/VNRoomViewModel.kt
1
1182
package com.rickshory.vegnab.viewmodels import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import com.rickshory.vegnab.repositories.VNRoomRepository import com.rickshory.vegnab.roomdb.VNRoomDatabase import com.rickshory.vegnab.roomdb.entities.Visit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext class VNRoomViewModel (app: Application) : AndroidViewModel(app) { private var parentJob = Job() private val coroutineContext: CoroutineContext get() = parentJob + Dispatchers.Main private val scope = CoroutineScope(coroutineContext) private val repo: VNRoomRepository val allVis: LiveData<List<Visit>> init { val visitsDao = VNRoomDatabase.getDatabase(app, scope).visitDao() repo = VNRoomRepository(visitsDao) allVis = repo.allVisits } fun insert(visit: Visit) = scope.launch(Dispatchers.IO) { repo.insert(visit) } override fun onCleared() { super.onCleared() parentJob.cancel() } }
gpl-3.0
09d69b77df6512491c99184e53094d59
29.333333
73
0.754653
4.494297
false
false
false
false
jereksel/LibreSubstratum
app/src/test/kotlin/com/jereksel/libresubstratum/activities/detailed/DetailedReducerTest.kt
1
13687
/* * Copyright (C) 2018 Andrzej Ressel ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.activities.detailed import arrow.core.hashCodeForNullable import com.jereksel.libresubstratum.activities.detailed.DetailedReducer.oneTimeFunction import com.jereksel.libresubstratumlib.Type1Extension import com.jereksel.libresubstratumlib.Type2Extension import com.jereksel.libresubstratumlib.Type3Extension import io.kotlintest.properties.Gen import io.kotlintest.specs.FreeSpec import org.assertj.core.api.Assertions.assertThat class DetailedReducerTest: FreeSpec() { private val reducer = DetailedReducer init { "ListLoaded" - { "Type3 is copied properly" { val type3Extensions = listOf( Type3Extension("a", true), Type3Extension("b", false), Type3Extension("c", false) ) val t = DetailedResult.ListLoaded("", "", listOf(), DetailedResult.ListLoaded.Type3(type3Extensions)) val (result, list) = reducer.apply(DetailedViewState.INITIAL, t) assertThat(list).isEmpty() assertThat(result.themePack!!.type3!!.data).isEqualTo(type3Extensions) } } "ChangeSpinnerSelection" - { val t = table( headers("Type", "Selection generator", "Type getter"), row("Type1a", {listPosition: Int, position: Int -> DetailedResult.ChangeSpinnerSelection.ChangeType1aSpinnerSelection(listPosition, position) as DetailedResult.ChangeSpinnerSelection }, { theme: DetailedViewState.Theme -> theme.type1a!! as DetailedViewState.Type } ), row("Type1b", {listPosition: Int, position: Int -> DetailedResult.ChangeSpinnerSelection.ChangeType1bSpinnerSelection(listPosition, position) as DetailedResult.ChangeSpinnerSelection }, { theme: DetailedViewState.Theme -> theme.type1b!! as DetailedViewState.Type } ), row("Type1c", {listPosition: Int, position: Int -> DetailedResult.ChangeSpinnerSelection.ChangeType1cSpinnerSelection(listPosition, position) as DetailedResult.ChangeSpinnerSelection }, { theme: DetailedViewState.Theme -> theme.type1c!! as DetailedViewState.Type } ), row("Type2", {listPosition: Int, position: Int -> DetailedResult.ChangeSpinnerSelection.ChangeType2SpinnerSelection(listPosition, position) as DetailedResult.ChangeSpinnerSelection }, { theme: DetailedViewState.Theme -> theme.type2!! as DetailedViewState.Type } ) ) forAll(t, { s: String, gen: (Int, Int) -> DetailedResult.ChangeSpinnerSelection, get: (DetailedViewState.Theme) -> DetailedViewState.Type -> "$s is changed properly" - { "When recyclerView position is too large larger than list size nothing happens" { val (newState, list) = reducer.apply(state, gen(1000, 1)) // assertThat(list).isEmpty() assertThat(newState).isEqualTo(state) } "When position is larger than list size nothing happens" { val (newState, list) = reducer.apply(state, gen(1, 100)) // assertThat(list).isEmpty() assertThat(newState).isEqualTo(state) } "When position is proper, position is changed" { val (newState, list) = reducer.apply(state, gen(0, 1)) // assertThat(list).isEmpty() assertThat(get(newState.themePack!!.themes[0]).getListPosition()).isEqualTo(1) } } }) } "InstalledStateResult" - { "Result" { val result = DetailedResult.InstalledStateResult.Result( targetApp = "app1", targetOverlayId = "newOverlay", installedResult = DetailedViewState.InstalledState.Installed("123", 123), enabledState = DetailedViewState.EnabledState.ENABLED ) val (newState, list) = reducer.apply(state, result) assertThat(list).isEmpty() val newTheme = newState.themePack!!.themes[0] assertThat(newTheme.installedState).isEqualTo(DetailedViewState.InstalledState.Installed("123", 123)) assertThat(newTheme.enabledState).isEqualTo(DetailedViewState.EnabledState.ENABLED) assertThat(newTheme.overlayId).isEqualTo("newOverlay") } } "ChangeType3SpinnerSelection" - { "When position is the same nothing changes" { val selection = DetailedResult.ChangeType3SpinnerSelection(0) val (newState, list) = reducer.apply(state, selection) assertThat(list).isEmpty() assertThat(newState).isEqualTo(state) } "When position is not the same position changes" { val selection = DetailedResult.ChangeType3SpinnerSelection(1) val (newState, list) = reducer.apply(state, selection) assertThat(list).hasSize(1) assertThat(list[0]).isOfAnyClassIn(DetailedAction.GetInfoBasicAction::class.java) assertThat(newState.themePack!!.type3!!.position).isEqualTo(1) } } "ToggleCheckbox" { assertThat(state.themePack!!.themes[0].checked).isFalse() val action = DetailedResult.ToggleCheckbox(0, true) val (newState, list) = reducer.apply(state, action) assertThat(newState.themePack!!.themes[0].checked).isTrue() assertThat(list).isEmpty() } "PositionResult" { val action = DetailedResult.InstalledStateResult.PositionResult(0) val (newState, list) = reducer.apply(state, action) assertThat(newState).isEqualTo(state) assertThat(list).hasSize(1) assertThat(list[0]).isEqualTo(DetailedAction.GetInfoAction( appId = "appId", targetAppId = "app1", type1a = Type1Extension("a", true), type1b = Type1Extension("a", true), type1c = Type1Extension("a", true), type2 = Type2Extension("a", true), type3 = Type3Extension("a", true) )) } "AppIdResult" - { "App cannot be found" { val action = DetailedResult.InstalledStateResult.AppIdResult("idontexist") val (newState, list) = reducer.apply(state, action) assertThat(newState).isEqualTo(state) assertThat(list).isEmpty() } "App is found" { val action = DetailedResult.InstalledStateResult.AppIdResult("app1") val (newState, list) = reducer.apply(state, action) assertThat(newState).isEqualTo(state) assertThat(list).hasSize(1) assertThat(list[0]).isEqualTo(DetailedAction.GetInfoBasicAction(0)) } } "CompilationStatusResult" - { "Start Flow" { val action = DetailedResult.CompilationStatusResult.StartFlow("app1") val (newState, list) = reducer.apply(state, action) assertThat(list).isEmpty() assertThat(newState.numberOfAllCompilations).isEqualTo(1) } "Start compilation" { val action = DetailedResult.CompilationStatusResult.StartCompilation("app1") val (newState, list) = reducer.apply(state, action) assertThat(list).isEmpty() assertThat(newState.themePack!!.themes[0].compilationState).isEqualTo(DetailedViewState.CompilationState.COMPILING) } "Start installation" { val action = DetailedResult.CompilationStatusResult.StartInstallation("app1") val (newState, list) = reducer.apply(state, action) assertThat(list).isEmpty() assertThat(newState.themePack!!.themes[0].compilationState).isEqualTo(DetailedViewState.CompilationState.INSTALLING) } "Failed compilation" { val exception = RuntimeException("My awesome error message") val action = DetailedResult.CompilationStatusResult.FailedCompilation("app1", exception) val (newState, list) = reducer.apply(state, action) assertThat(list).isEmpty() assertThat(newState.themePack!!.themes[0].compilationError).isSameAs(exception) assertThat(newState.toast()).isEqualTo("Compilation failed for app1") } } "oneTimeFunction test" { forAll(Gen.string()) { s -> val f = oneTimeFunction(s) f() shouldBe s f() shouldBe null true } } } private val state = DetailedViewState( themePack = DetailedViewState.ThemePack( appId = "appId", themeName = "Theme", type3 = DetailedViewState.Type3( position = 0, data = listOf( Type3Extension("a", true), Type3Extension("b", false), Type3Extension("c", false) ) ), themes = listOf( DetailedViewState.Theme( appId = "app1", name = "name", overlayId = "overlayId", type1a = DetailedViewState.Type1( position = 0, data = listOf( Type1Extension("a", true), Type1Extension("b", false), Type1Extension("c", false) ) ), type1b = DetailedViewState.Type1( position = 0, data = listOf( Type1Extension("a", true), Type1Extension("b", false), Type1Extension("c", false) ) ), type1c = DetailedViewState.Type1( position = 0, data = listOf( Type1Extension("a", true), Type1Extension("b", false), Type1Extension("c", false) ) ), type2 = DetailedViewState.Type2( position = 0, data = listOf( Type2Extension("a", true), Type2Extension("b", false), Type2Extension("c", false) ) ), checked = false, compilationError = null, compilationState = DetailedViewState.CompilationState.DEFAULT, enabledState = DetailedViewState.EnabledState.DISABLED, installedState = DetailedViewState.InstalledState.Unknown ) ) ), compilationError = null, numberOfAllCompilations = 0, numberOfFinishedCompilations = 0, toast = { null } ) }
mit
4a9a464f94870f50ac14c2b13087d07a
41.377709
155
0.502959
5.966434
false
false
false
false
mobilejazz/Colloc
server/src/main/kotlin/com/mobilejazz/colloc/di/ApplicationProvider.kt
1
2268
package com.mobilejazz.colloc.di import com.mobilejazz.colloc.domain.interactor.CollocInteractor import com.mobilejazz.colloc.domain.interactor.DownloadFileInteractor import com.mobilejazz.colloc.domain.model.Platform import com.mobilejazz.colloc.feature.decoder.CsvLocalizationDecoder import com.mobilejazz.colloc.feature.decoder.LocalizationDecoder import com.mobilejazz.colloc.feature.encoder.domain.interactor.AndroidEncodeInteractor import com.mobilejazz.colloc.feature.encoder.domain.interactor.AngularEncodeInteractor import com.mobilejazz.colloc.feature.encoder.domain.interactor.EncodeInteractor import com.mobilejazz.colloc.feature.encoder.domain.interactor.IosEncodeInteractor import com.mobilejazz.colloc.feature.encoder.domain.interactor.JsonEncodeInteractor import com.mobilejazz.colloc.feature.encoder.domain.interactor.angular.AngularEncoderV1Interactor import io.ktor.client.HttpClient import io.ktor.client.engine.okhttp.OkHttp import io.ktor.client.plugins.HttpTimeout import kotlinx.serialization.json.Json import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class ApplicationModule { @Bean fun provideCollocInteractor( downloadFileInteractor: DownloadFileInteractor, localizationDecoder: LocalizationDecoder, platformCollocInteractorMap: Map<Platform, Map<Int, EncodeInteractor>> ) = CollocInteractor( downloadFileInteractor, localizationDecoder, platformCollocInteractorMap ) @Bean fun provideDownloadFileInteractor(httpClient: HttpClient) = DownloadFileInteractor(httpClient) @Bean fun provideHttpClient() = HttpClient(OkHttp) { install(HttpTimeout) { requestTimeoutMillis = 60_000 } } @Bean fun provideLocalizationDecoder() = CsvLocalizationDecoder() @Bean fun providePlatformEncodeInteractorMap(json: Json) = mapOf( Platform.ANDROID to mapOf(1 to AndroidEncodeInteractor()), Platform.IOS to mapOf(1 to IosEncodeInteractor()), Platform.ANGULAR to mapOf( 1 to AngularEncoderV1Interactor(json), 2 to AngularEncodeInteractor(json) ), Platform.JSON to mapOf(1 to JsonEncodeInteractor(json)) ) @Bean fun provideJson() = Json { prettyPrint = true } }
apache-2.0
c8c1e90495625c82b7f839e649e594d2
33.892308
97
0.809083
4.455796
false
false
false
false
DemonWav/IntelliJBukkitSupport
buildSrc/src/main/kotlin/util.kt
1
2124
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.tasks.JavaExec import org.gradle.kotlin.dsl.getValue import org.gradle.kotlin.dsl.provideDelegate import org.gradle.kotlin.dsl.registering fun Project.lexer(flex: String, pack: String) = tasks.registering(JavaExec::class) { val src = layout.projectDirectory.file("src/main/grammars/$flex.flex") val dst = layout.buildDirectory.dir("gen/$pack") val output = layout.buildDirectory.file("gen/$pack/$flex.java") val jflex by project.configurations val jflexSkeleton by project.configurations classpath = jflex mainClass.set("jflex.Main") doFirst { args( "--skel", jflexSkeleton.singleFile.absolutePath, "-d", dst.get().asFile.absolutePath, src.asFile.absolutePath ) // Delete current lexer project.delete(output) } inputs.files(src, jflexSkeleton) outputs.file(output) } fun Project.parser(bnf: String, pack: String) = tasks.registering(JavaExec::class) { val src = project.layout.projectDirectory.file("src/main/grammars/$bnf.bnf") val dstRoot = project.layout.buildDirectory.dir("gen") val dst = dstRoot.map { it.dir(pack) } val psiDir = dst.map { it.dir("psi") } val parserDir = dst.map { it.dir("parser") } val grammarKit by project.configurations doFirst { project.delete(psiDir, parserDir) } classpath = grammarKit mainClass.set("org.intellij.grammar.Main") if (JavaVersion.current().isJava9Compatible) { jvmArgs( "--add-opens", "java.base/java.lang=ALL-UNNAMED", "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED", "--add-opens", "java.base/java.util=ALL-UNNAMED" ) } doFirst { args(dstRoot.get().asFile, src.asFile) } inputs.file(src) outputs.dirs( mapOf( "psi" to psiDir, "parser" to parserDir ) ) }
mit
2c5d5bab862d5d8aea3017d4751cecf7
25.886076
84
0.644539
3.726316
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/dialogs/HelpdeskTopicAdapter.kt
1
3751
package de.xikolo.controllers.dialogs import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import butterknife.BindView import butterknife.ButterKnife import de.xikolo.R import de.xikolo.controllers.base.BaseMetaRecyclerViewAdapter import de.xikolo.models.TicketTopic import de.xikolo.models.dao.CourseDao import de.xikolo.utils.MetaSectionList import de.xikolo.utils.extensions.calendarYear typealias HelpdeskTopic = Pair<TicketTopic, String?> typealias HelpdeskTopicList = MetaSectionList<String, Any, List<HelpdeskTopic>> class HelpdeskTopicAdapter(private val onTopicClickedListener: OnTopicClickedListener?) : BaseMetaRecyclerViewAdapter<Any, HelpdeskTopic>() { companion object { val TAG: String = HelpdeskTopicAdapter::class.java.simpleName } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { ITEM_VIEW_TYPE_HEADER -> createHeaderViewHolder(parent, viewType) else -> createTopicViewHolder(parent) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is HeaderViewHolder -> bindHeaderViewHolder(holder, position) is CourseTitleViewHolder -> bindTopicViewHolder(holder, position) } } interface OnTopicClickedListener { fun onTopicClicked(title: String?, topic: TicketTopic, courseId: String?) } class CourseTitleViewHolder(view: View) : RecyclerView.ViewHolder(view) { @BindView(R.id.helpdeskTopic) lateinit var topicTitle: TextView @BindView(R.id.container) lateinit var layout: ViewGroup @BindView(R.id.smallerContainer) lateinit var optionalViewGroup: ViewGroup @BindView(R.id.courseYear) lateinit var topicYear: TextView @BindView(R.id.courseSlug) lateinit var topicSlug: TextView init { ButterKnife.bind(this, view) } } private fun createTopicViewHolder(parent: ViewGroup): RecyclerView.ViewHolder { return CourseTitleViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.item_helpdesk_topic_list, parent, false) ) } private fun bindTopicViewHolder(holder: CourseTitleViewHolder, position: Int) { val topic = contentList.get(position) as HelpdeskTopic val title: String? if (topic.first == TicketTopic.COURSE) { val course = CourseDao.Unmanaged.find(topic.second) title = course?.title holder.topicSlug.text = course?.slug holder.topicYear.text = course?.startDate?.calendarYear.toString() holder.optionalViewGroup.visibility = View.VISIBLE } else { title = topic.first.toString() holder.optionalViewGroup.visibility = View.GONE } holder.topicTitle.text = title holder.layout.setOnClickListener { onTopicClickedListener?.onTopicClicked(title, topic.first, topic.second) } } override fun createHeaderViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return HeaderViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.item_header_secondary, parent, false).apply { findViewById<TextView>(R.id.textHeader).apply { //additional left padding to match the rest of layout setPadding((paddingLeft * 1.5f).toInt(), paddingTop, paddingRight, paddingBottom) } } ) } }
bsd-3-clause
c09a83e392db31ac8a73cefed42c3ed3
35.067308
141
0.684617
4.748101
false
false
false
false
REBOOTERS/AndroidAnimationExercise
buildSrc/src/main/kotlin/com/engineer/plugin/extensions/model/Info.kt
1
255
package com.engineer.plugin.extensions.model /** * @author rookie * @since 12-04-2019 */ data class Info( var path: String = "", var size: Long = 0, var time: String = "", var commitBranch: String = "", var commitId: String = "" )
apache-2.0
47a108ec497395023d6145e39d3539f2
17.285714
44
0.6
3.445946
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/Messages.kt
1
3383
package tornadofx import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.nio.charset.StandardCharsets import java.security.AccessController import java.security.PrivilegedActionException import java.security.PrivilegedExceptionAction import java.text.MessageFormat import java.util.* private fun <EXCEPTION: Throwable, RETURN> doPrivileged(privilegedAction: ()->RETURN) : RETURN = try { AccessController.doPrivileged( PrivilegedExceptionAction<RETURN> { privilegedAction() } ) } catch (e: PrivilegedActionException) { @Suppress("UNCHECKED_CAST") throw e.exception as EXCEPTION } object FXResourceBundleControl : ResourceBundle.Control() { override fun newBundle(baseName: String, locale: Locale, format: String, loader: ClassLoader, reload: Boolean): ResourceBundle? { val bundleName = toBundleName(baseName, locale) return when (format) { "java.class" -> try { @Suppress("UNCHECKED_CAST") val bundleClass = loader.loadClass(bundleName) as Class<out ResourceBundle> // If the class isn't a ResourceBundle subclass, throw a ClassCastException. if (ResourceBundle::class.java.isAssignableFrom(bundleClass)) bundleClass.newInstance() else throw ClassCastException(bundleClass.name + " cannot be cast to ResourceBundle") } catch (e: ClassNotFoundException) { null } "java.properties" -> { val resourceName: String = toResourceName(bundleName, "properties") doPrivileged<IOException, InputStream?> { if (!reload) loader.getResourceAsStream(resourceName) else loader.getResource(resourceName)?.openConnection()?.apply { useCaches = false // Disable caches to get fresh data for reloading. } ?.inputStream }?.use { FXPropertyResourceBundle(InputStreamReader(it, StandardCharsets.UTF_8)) } } else -> throw IllegalArgumentException("unknown format: $format") }!! } } /** * Convenience function to support lookup via messages["key"] */ operator fun ResourceBundle.get(key: String) = getString(key) /** * Convenience function to retrieve a translation and format it with values. */ fun ResourceBundle.format(key: String, vararg fields: Any) = MessageFormat(this[key], locale).format(fields) class FXPropertyResourceBundle(input: InputStreamReader): PropertyResourceBundle(input) { fun inheritFromGlobal() { parent = FX.messages.takeUnless(::equals) } /** * Lookup resource in this bundle. If no value, lookup in parent bundle if defined. * If we still have no value, return "[key]" instead of null. */ override fun handleGetObject(key: String?) = super.handleGetObject(key) ?: parent?.getObject(key) ?: "[$key]" /** * Always return true, since we want to supply a default text message instead of throwing exception */ override fun containsKey(key: String) = true } internal object EmptyResourceBundle : ResourceBundle() { override fun getKeys(): Enumeration<String> = Collections.emptyEnumeration() override fun handleGetObject(key: String) = "[$key]" override fun containsKey(p0: String) = true }
apache-2.0
1767fc814020f7bbb983771c1c5b6e85
38.337209
133
0.678392
4.867626
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/SupportAdapter.kt
1
1893
package com.pennapps.labs.pennmobile.adapters import android.content.Context import android.content.Intent import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import com.pennapps.labs.pennmobile.R import com.pennapps.labs.pennmobile.classes.Contact import kotlinx.android.synthetic.main.support_list_item.view.* class SupportAdapter(context: Context, contacts: List<Contact?>) : ArrayAdapter<Contact?>(context, R.layout.support_list_item, contacts) { private val inflater: LayoutInflater = LayoutInflater.from(context) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val currentPerson = getItem(position) val view = convertView ?: inflater.inflate(R.layout.support_list_item, parent, false) view.support_name?.text = currentPerson?.name if (currentPerson?.phoneWords == "") { view.support_phone?.text = currentPerson.phone } else { view.support_phone?.text = currentPerson?.phoneWords + " (" + currentPerson?.phone + ")" } if (currentPerson?.isURL == true) { view.support_phone_icon?.visibility = View.GONE } else { view.support_phone_icon?.visibility = View.GONE } view.setOnClickListener { v -> val intent: Intent if (currentPerson?.isURL == true) { intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(currentPerson.phone) } else { val uri = "tel:" + currentPerson?.phone intent = Intent(Intent.ACTION_DIAL) intent.data = Uri.parse(uri) } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) v.context.startActivity(intent) } return view } }
mit
8e0350450091f2cc0660fc37134cb809
35.423077
138
0.647121
4.312073
false
false
false
false
congwiny/KotlinBasic
src/main/kotlin/operator/overloading/equals.kt
1
204
package operator.overloading fun main(args: Array<String>) { println(Point(10, 20) == Point(10, 20)) //true println(Point(10, 20) != Point(5, 5)) //true println(null == Point(1, 2)) //false }
apache-2.0
f826a970f4bda53ef2aa0b7b4f0e9b7e
28.285714
50
0.622549
3
false
false
false
false
AndroidX/androidx
window/window/src/main/java/androidx/window/layout/WindowInfoTracker.kt
3
4770
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.layout import android.app.Activity import android.content.Context import android.util.Log import androidx.annotation.RestrictTo import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP import androidx.window.core.ConsumerAdapter import androidx.window.layout.adapter.WindowBackend import androidx.window.layout.adapter.extensions.ExtensionWindowLayoutInfoBackend import androidx.window.layout.adapter.sidecar.SidecarWindowBackend import kotlinx.coroutines.flow.Flow /** * An interface to provide all the relevant info about a [android.view.Window]. * @see WindowInfoTracker.getOrCreate to get an instance. */ interface WindowInfoTracker { /** * A [Flow] of [WindowLayoutInfo] that contains all the available features. A [WindowLayoutInfo] * contains a [List] of [DisplayFeature] that intersect the associated [android.view.Window]. * * The first [WindowLayoutInfo] will not be emitted until [Activity.onStart] has been called. * which values you receive and when is device dependent. It is recommended to test scenarios * where there is a long delay between subscribing and receiving the first value or never * receiving a value, since it may differ between hardware implementations. * * Since the information is associated to the [Activity] you should not retain the [Flow] across * [Activity] recreations. Doing so can result in unpredictable behavior such as a memory leak * or incorrect values for [WindowLayoutInfo]. * * @param activity an [Activity] that has not been destroyed. * @see WindowLayoutInfo * @see DisplayFeature */ fun windowLayoutInfo(activity: Activity): Flow<WindowLayoutInfo> companion object { private val DEBUG = false private val TAG = WindowInfoTracker::class.simpleName @Suppress("MemberVisibilityCanBePrivate") // Avoid synthetic accessor internal val extensionBackend: WindowBackend? by lazy { try { val loader = WindowInfoTracker::class.java.classLoader val provider = loader?.let { SafeWindowLayoutComponentProvider(loader, ConsumerAdapter(loader)) } provider?.windowLayoutComponent?.let { component -> ExtensionWindowLayoutInfoBackend(component, ConsumerAdapter(loader)) } } catch (t: Throwable) { if (DEBUG) { Log.d(TAG, "Failed to load WindowExtensions") } null } } private var decorator: WindowInfoTrackerDecorator = EmptyDecorator /** * Provide an instance of [WindowInfoTracker] that is associated to the given [Context]. * The instance created should be safe to retain globally. The actual data is provided by * [WindowInfoTracker.windowLayoutInfo] and requires an [Activity]. * @param context Any valid [Context]. * @see WindowInfoTracker.windowLayoutInfo */ @JvmName("getOrCreate") @JvmStatic fun getOrCreate(context: Context): WindowInfoTracker { val backend = extensionBackend ?: SidecarWindowBackend.getInstance(context) val repo = WindowInfoTrackerImpl(WindowMetricsCalculatorCompat, backend) return decorator.decorate(repo) } @JvmStatic @RestrictTo(LIBRARY_GROUP) fun overrideDecorator(overridingDecorator: WindowInfoTrackerDecorator) { decorator = overridingDecorator } @JvmStatic @RestrictTo(LIBRARY_GROUP) fun reset() { decorator = EmptyDecorator } } } @RestrictTo(LIBRARY_GROUP) interface WindowInfoTrackerDecorator { /** * Returns an instance of [WindowInfoTracker] associated to the [Activity] */ @RestrictTo(LIBRARY_GROUP) fun decorate(tracker: WindowInfoTracker): WindowInfoTracker } private object EmptyDecorator : WindowInfoTrackerDecorator { override fun decorate(tracker: WindowInfoTracker): WindowInfoTracker { return tracker } }
apache-2.0
a4763454742a862e943bfe307bfd745c
38.098361
100
0.690985
5.052966
false
false
false
false
Xenoage/Zong
core/src/com/xenoage/zong/core/music/direction/DynamicValue.kt
1
1729
package com.xenoage.zong.core.music.direction import com.xenoage.zong.core.music.direction.WedgeType.Crescendo /** * Dynamic values: forte, piano, sforzando and so on. * * These are the same dynamics as supported in MusicXML. */ enum class DynamicValue { p, pp, ppp, pppp, ppppp, pppppp, f, ff, fff, ffff, fffff, ffffff, mp, mf, sf, sfp, sfpp, fp, rf, rfz, sfz, sffz, fz; /** * When this is the start dynamic value of a diminuendo, * the diminuendo ends by default at the returned value. */ val diminuendoEndValue: DynamicValue get() = getWedgeEndValue(-1) /** * When this is the start dynamic value of a wedge (crescendo/diminuendo), * the wedge ends by default at the returned value. */ fun getWedgeEndValue(type: WedgeType): DynamicValue { return getWedgeEndValue(if (type == Crescendo) 1 else -1) } /** * Gets the end dynamic of a crescendo (dir = 1) or * diminuendo (dir = -1), when this is the start value. */ private fun getWedgeEndValue(dir: Int): DynamicValue { val wedgeProgress = arrayOf(pp, p, mf, f, ff) val index = wedgeProgress.indexOf(rounded) + dir return when { index < 0 -> pp index >= wedgeProgress.size -> ff else -> wedgeProgress[index] } } /** * Returns the nearest commonly used dynamic value (pp, p, mf, f, ff) * to this value. */ private val rounded: DynamicValue get() = when (this) { pp, p, mf, f, ff -> this //everything lower than pp is treated as pp, //everything higher than ff as ff ppp, pppp, ppppp, pppppp -> pp fff, ffff, fffff, ffffff -> ff //mp is like mf mp -> mf //sXY-values are treated as Y sf, rf, rfz, sfz, fz -> f sfp, fp -> p sfpp -> pp sffz -> ff } }
agpl-3.0
15314fd42e2fc5d4fedaac8d92cd5489
19.104651
75
0.648352
2.66821
false
false
false
false