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
JetBrains/intellij-community
plugins/kotlin/completion/tests-shared/test/org/jetbrains/kotlin/idea/completion/test/ExpectedCompletionUtils.kt
1
16745
// 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.completion.test import com.google.common.collect.ImmutableList import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import com.google.gson.JsonParser import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.ui.JBColor import com.intellij.ui.icons.RowIcon import com.intellij.util.ArrayUtil import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.completion.KOTLIN_CAST_REQUIRED_COLOR import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject import org.jetbrains.kotlin.idea.test.AstAccessControl import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isJs import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.test.utils.IgnoreTests import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.junit.Assert import javax.swing.Icon /** * Extract a number of statements about completion from the given text. Those statements * should be asserted during test execution. */ object ExpectedCompletionUtils { class CompletionProposal { private val map: Map<String, String?> constructor(source: CompletionProposal, filter: (String, String?) -> Boolean) { map = source.map.filter { filter(it.key, it.value) } } constructor(lookupString: String) { map = mapOf(LOOKUP_STRING to lookupString) } constructor(map: MutableMap<String, String?>) { this.map = map for (key in map.keys) { if (key !in validKeys) { throw RuntimeException("Invalid key '$key'") } } } constructor(json: JsonObject) { map = HashMap<String, String?>() for (entry in json.entrySet()) { val key = entry.key if (key !in validKeys) { throw RuntimeException("Invalid json property '$key'") } val value = entry.value map.put(key, if (value !is JsonNull) value.asString else null) } } operator fun get(key: String): String? = map[key] fun matches(expectedProposal: CompletionProposal, ignoreProperties: Collection<String>): Boolean { return expectedProposal.map.entries.none { expected -> val actualValues = when (expected.key) { in ignoreProperties -> return@none false "lookupString" -> { // FIR IDE adds `.` after package names in completion listOf(map[expected.key]?.removeSuffix("."), map[expected.key]) } else -> listOf(map[expected.key]) } expected.value !in actualValues } } override fun toString(): String { val jsonObject = JsonObject() for ((key, value) in map) { jsonObject.addProperty(key, value) } return jsonObject.toString() } companion object { const val LOOKUP_STRING: String = "lookupString" const val ALL_LOOKUP_STRINGS: String = "allLookupStrings" const val PRESENTATION_ITEM_TEXT: String = "itemText" const val PRESENTATION_ICON: String = "icon" const val PRESENTATION_TYPE_TEXT: String = "typeText" const val PRESENTATION_TAIL_TEXT: String = "tailText" const val PRESENTATION_TEXT_ATTRIBUTES: String = "attributes" const val MODULE_NAME: String = "module" val validKeys: Set<String> = setOf( LOOKUP_STRING, ALL_LOOKUP_STRINGS, PRESENTATION_ITEM_TEXT, PRESENTATION_ICON, PRESENTATION_TYPE_TEXT, PRESENTATION_TAIL_TEXT, PRESENTATION_TEXT_ATTRIBUTES, MODULE_NAME ) } } private val UNSUPPORTED_PLATFORM_MESSAGE = "Only ${JvmPlatforms.unspecifiedJvmPlatform} and ${JsPlatforms.defaultJsPlatform} platforms are supported" private const val EXIST_LINE_PREFIX = "EXIST:" private const val ABSENT_LINE_PREFIX = "ABSENT:" private const val ABSENT_JS_LINE_PREFIX = "ABSENT_JS:" private const val ABSENT_JAVA_LINE_PREFIX = "ABSENT_JAVA:" private const val EXIST_JAVA_ONLY_LINE_PREFIX = "EXIST_JAVA_ONLY:" private const val EXIST_JS_ONLY_LINE_PREFIX = "EXIST_JS_ONLY:" private const val NUMBER_LINE_PREFIX = "NUMBER:" private const val NUMBER_JS_LINE_PREFIX = "NUMBER_JS:" private const val NUMBER_JAVA_LINE_PREFIX = "NUMBER_JAVA:" private const val NOTHING_ELSE_PREFIX = "NOTHING_ELSE" private const val RUN_HIGHLIGHTING_BEFORE_PREFIX = "RUN_HIGHLIGHTING_BEFORE" private const val INVOCATION_COUNT_PREFIX = "INVOCATION_COUNT:" private const val WITH_ORDER_PREFIX = "WITH_ORDER" private const val AUTOCOMPLETE_SETTING_PREFIX = "AUTOCOMPLETE_SETTING:" const val RUNTIME_TYPE: String = "RUNTIME_TYPE:" const val BLOCK_CODE_FRAGMENT = "BLOCK_CODE_FRAGMENT" private const val COMPLETION_TYPE_PREFIX = "COMPLETION_TYPE:" val KNOWN_PREFIXES: List<String> = ImmutableList.of( "LANGUAGE_VERSION:", EXIST_LINE_PREFIX, ABSENT_LINE_PREFIX, ABSENT_JS_LINE_PREFIX, ABSENT_JAVA_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX, NUMBER_LINE_PREFIX, NUMBER_JS_LINE_PREFIX, NUMBER_JAVA_LINE_PREFIX, INVOCATION_COUNT_PREFIX, WITH_ORDER_PREFIX, AUTOCOMPLETE_SETTING_PREFIX, NOTHING_ELSE_PREFIX, RUN_HIGHLIGHTING_BEFORE_PREFIX, RUNTIME_TYPE, COMPLETION_TYPE_PREFIX, BLOCK_CODE_FRAGMENT, AstAccessControl.ALLOW_AST_ACCESS_DIRECTIVE, IgnoreTests.DIRECTIVES.FIR_COMPARISON, IgnoreTests.DIRECTIVES.FIR_IDENTICAL, IgnoreTests.DIRECTIVES.FIR_COMPARISON_MULTILINE_COMMENT, ) fun itemsShouldExist(fileText: String, platform: TargetPlatform?): Array<CompletionProposal> = when { platform.isJvm() -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX) platform.isJs() -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX) platform == null -> processProposalAssertions(fileText, EXIST_LINE_PREFIX) else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) } fun itemsShouldAbsent(fileText: String, platform: TargetPlatform?): Array<CompletionProposal> = when { platform.isJvm() -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JAVA_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX) platform.isJs() -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JS_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX) platform == null -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX) else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) } fun processProposalAssertions(fileText: String, vararg prefixes: String): Array<CompletionProposal> { val proposals = ArrayList<CompletionProposal>() for (proposalStr in InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, *prefixes)) { if (proposalStr.startsWith("{")) { val parser = JsonParser() val json: JsonElement? = try { parser.parse(proposalStr) } catch (t: Throwable) { throw RuntimeException("Error parsing '$proposalStr'", t) } proposals.add(CompletionProposal(json as JsonObject)) } else if (proposalStr.startsWith("\"") && proposalStr.endsWith("\"")) { proposals.add(CompletionProposal(proposalStr.substring(1, proposalStr.length - 1))) } else { for (item in proposalStr.split(",")) { proposals.add(CompletionProposal(item.trim())) } } } return ArrayUtil.toObjectArray(proposals, CompletionProposal::class.java) } fun getExpectedNumber(fileText: String, platform: TargetPlatform?): Int? = when { platform == null -> InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX) platform.isJvm() -> getPlatformExpectedNumber(fileText, NUMBER_JAVA_LINE_PREFIX) platform.isJs() -> getPlatformExpectedNumber(fileText, NUMBER_JS_LINE_PREFIX) else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) } fun isNothingElseExpected(fileText: String): Boolean = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, NOTHING_ELSE_PREFIX).isNotEmpty() fun shouldRunHighlightingBeforeCompletion(fileText: String): Boolean = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, RUN_HIGHLIGHTING_BEFORE_PREFIX).isNotEmpty() fun getInvocationCount(fileText: String): Int? = InTextDirectivesUtils.getPrefixedInt(fileText, INVOCATION_COUNT_PREFIX) fun getCompletionType(fileText: String): CompletionType? = when (val completionTypeString = InTextDirectivesUtils.findStringWithPrefixes(fileText, COMPLETION_TYPE_PREFIX)) { "BASIC" -> CompletionType.BASIC "SMART" -> CompletionType.SMART null -> null else -> error("Unknown completion type: $completionTypeString") } fun getAutocompleteSetting(fileText: String): Boolean? = InTextDirectivesUtils.getPrefixedBoolean(fileText, AUTOCOMPLETE_SETTING_PREFIX) fun isWithOrder(fileText: String): Boolean = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, WITH_ORDER_PREFIX).isNotEmpty() fun assertDirectivesValid(fileText: String, additionalValidDirectives: Collection<String> = emptyList()) { InTextDirectivesUtils.assertHasUnknownPrefixes(fileText, KNOWN_PREFIXES + additionalValidDirectives) } fun assertContainsRenderedItems( expected: Array<CompletionProposal>, items: Array<LookupElement>, checkOrder: Boolean, nothingElse: Boolean, ignoreProperties: Collection<String>, ) { val itemsInformation = getItemsInformation(items) val allItemsString = listToString(itemsInformation) val leftItems = if (nothingElse) LinkedHashSet(itemsInformation) else null var indexOfPrevious = Integer.MIN_VALUE for (expectedProposal in expected) { var isFound = false for (index in itemsInformation.indices) { val proposal = itemsInformation[index] if (proposal.matches(expectedProposal, ignoreProperties)) { isFound = true Assert.assertTrue( "Invalid order of existent elements in $allItemsString", !checkOrder || index > indexOfPrevious ) indexOfPrevious = index leftItems?.remove(proposal) break } } if (!isFound) { if (allItemsString.isEmpty()) { Assert.fail("Completion is empty but $expectedProposal is expected") } else { var closeMatchWithoutIcon: CompletionProposal? = null for (index in itemsInformation.indices) { val proposal = itemsInformation[index] val candidate = CompletionProposal(expectedProposal) { k, _ -> k != CompletionProposal.PRESENTATION_ICON } if (proposal.matches(candidate, ignoreProperties)) { closeMatchWithoutIcon = proposal break } } if (closeMatchWithoutIcon == null) { Assert.fail("Expected $expectedProposal not found in:\n$allItemsString") } else { Assert.fail("Missed ${CompletionProposal.PRESENTATION_ICON}:\"${closeMatchWithoutIcon[CompletionProposal.PRESENTATION_ICON]}\" in $expectedProposal") } } } } if (!leftItems.isNullOrEmpty()) { Assert.fail("No items not mentioned in EXIST directives expected but some found:\n" + listToString(leftItems)) } } private fun getPlatformExpectedNumber(fileText: String, platformNumberPrefix: String): Int? { val prefixedInt = InTextDirectivesUtils.getPrefixedInt(fileText, platformNumberPrefix) if (prefixedInt != null) { Assert.assertNull( "There shouldn't be $NUMBER_LINE_PREFIX and $platformNumberPrefix prefixes set in same time", InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX) ) return prefixedInt } return InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX) } fun assertNotContainsRenderedItems(unexpected: Array<CompletionProposal>, items: Array<LookupElement>, ignoreProperties: Collection<String>) { val itemsInformation = getItemsInformation(items) val allItemsString = listToString(itemsInformation) for (unexpectedProposal in unexpected) { for (proposal in itemsInformation) { Assert.assertFalse( "Unexpected '$unexpectedProposal' presented in\n$allItemsString", proposal.matches(unexpectedProposal, ignoreProperties) ) } } } fun getItemsInformation(items: Array<LookupElement>): List<CompletionProposal> { val presentation = LookupElementPresentation() val result = ArrayList<CompletionProposal>(items.size) for (item in items) { item.renderElement(presentation) val map = HashMap<String, String?>() map[CompletionProposal.LOOKUP_STRING] = item.lookupString map[CompletionProposal.ALL_LOOKUP_STRINGS] = item.allLookupStrings.sorted().joinToString() presentation.itemText?.let { map[CompletionProposal.PRESENTATION_ITEM_TEXT] = it map[CompletionProposal.PRESENTATION_TEXT_ATTRIBUTES] = textAttributes(presentation) } presentation.typeText?.let { map[CompletionProposal.PRESENTATION_TYPE_TEXT] = it } presentation.icon?.let { map[CompletionProposal.PRESENTATION_ICON] = iconToString(it) } presentation.tailText?.let { map[CompletionProposal.PRESENTATION_TAIL_TEXT] = it } item.moduleName?.let { map.put(CompletionProposal.MODULE_NAME, it) } result.add(CompletionProposal(map)) } return result } private fun iconToString(it: Icon): String { return (it.safeAs<RowIcon>()?.allIcons?.firstOrNull() ?: it).toString() //todo check how do we get not a dummy icon? .replace("nodes/property.svg", "Property") } private val LookupElement.moduleName: String? get() { return psiElement?.module?.name } private fun textAttributes(presentation: LookupElementPresentation): String { fun StringBuilder.appendAttribute(text: String) { if (this.isNotEmpty()) { append(' ') } append(text) } return buildString { if (presentation.isItemTextBold) { appendAttribute("bold") } if (presentation.isItemTextUnderlined) { appendAttribute("underlined") } when (val foreground = presentation.itemTextForeground) { JBColor.RED -> appendAttribute("red") JBColor.foreground() -> {} else -> { assert(foreground == KOTLIN_CAST_REQUIRED_COLOR) appendAttribute("grayed") } } if (presentation.isStrikeout) { appendAttribute("strikeout") } } } fun listToString(items: Collection<CompletionProposal>): String = items.joinToString("\n") }
apache-2.0
60aa756e736b801544fb308fd0d3668e
41.392405
173
0.637623
4.958543
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/app/src/main/java/com/neatorobotics/sdk/android/example/robots/RobotCommandsActivityFragment.kt
1
13171
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.example.robots import androidx.fragment.app.Fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.Toast import com.bumptech.glide.Glide import com.neatorobotics.sdk.android.clients.Resource import com.neatorobotics.sdk.android.clients.nucleo.Nucleo import com.neatorobotics.sdk.android.example.R import com.neatorobotics.sdk.android.models.* import com.neatorobotics.sdk.android.robotservices.cleaning.CleaningParams import com.neatorobotics.sdk.android.robotservices.cleaning.cleaningService import com.neatorobotics.sdk.android.robotservices.findme.findMeService import com.neatorobotics.sdk.android.robotservices.housecleaning.houseCleaningService import com.neatorobotics.sdk.android.robotservices.maps.mapService import com.neatorobotics.sdk.android.robotservices.scheduling.schedulingService import com.neatorobotics.sdk.android.robotservices.spotcleaning.spotCleaningService import kotlinx.android.synthetic.main.fragment_robot_commands.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch class RobotCommandsActivityFragment : Fragment() { // coroutines private var myJob: Job = Job() private var uiScope: CoroutineScope = CoroutineScope(Dispatchers.Main + myJob) private var robot: Robot? = null override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable("ROBOT", robot) } private fun restoreState(inState: Bundle) { robot = inState.getParcelable("ROBOT") updateUIButtons() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_robot_commands, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) spotCleaning.setOnClickListener { executeSpotCleaning() } houseCleaning.setOnClickListener { executeHouseCleaning() } mapCleaning.setOnClickListener { executeMapCleaning() } pauseCleaning.setOnClickListener { executePause() } stopCleaning.setOnClickListener { executeStop() } returnToBaseCleaning.setOnClickListener { executeReturnToBase() } resumeCleaning.setOnClickListener { executeResumeCleaning() } findMe.setOnClickListener { executeFindMe() } enableDisableScheduling.setOnClickListener { enableDisableScheduling() } wednesdayScheduling.setOnClickListener { scheduleEveryWednesday() } getScheduling!!.setOnClickListener { getScheduling() } maps.setOnClickListener { getMaps() } } private fun updateUIButtons() { if (robot != null && robot?.state != null) { houseCleaning.isEnabled = robot?.state?.isStartAvailable?:false spotCleaning.isEnabled = robot?.state?.isStartAvailable?:false pauseCleaning.isEnabled = robot?.state?.isPauseAvailable?:false stopCleaning.isEnabled = robot?.state?.isStopAvailable?:false resumeCleaning.isEnabled = robot?.state?.isResumeAvailable?:false returnToBaseCleaning.isEnabled = robot?.state?.isGoToBaseAvailable?:false } else { houseCleaning.isEnabled = false spotCleaning.isEnabled = false pauseCleaning.isEnabled = false stopCleaning.isEnabled = false resumeCleaning.isEnabled = false returnToBaseCleaning.isEnabled = false } } private fun executePause() { uiScope.launch { val result = robot?.cleaningService?.pauseCleaning(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } } private fun executeResumeCleaning() { uiScope.launch { val result = robot?.cleaningService?.resumeCleaning(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } } private fun executeHouseCleaning() { uiScope.launch { val params = CleaningParams(category = CleaningCategory.HOUSE, mode = CleaningMode.TURBO) val result = robot?.houseCleaningService?.startCleaning(robot!!, params) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } } private fun executeMapCleaning() { // first check if the robot support map cleaning service if (robot?.mapService?.isFloorPlanSupported == true) { uiScope.launch { val params = CleaningParams(category = CleaningCategory.MAP, mode = CleaningMode.TURBO) val result = robot?.houseCleaningService?.startCleaning(robot!!, params) when (result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } }else showNotSupportedService() } private fun executeReturnToBase() { uiScope.launch { val result = robot?.cleaningService?.returnToBase(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } } private fun executeFindMe() { uiScope.launch { val result = robot?.findMeService?.findMe(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() null -> showNotSupportedService() } } } private fun enableDisableScheduling() { if (robot != null) { if (robot?.state?.isScheduleEnabled == true) { uiScope.launch { val result = robot?.schedulingService?.disableSchedule(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.SUCCESS -> Toast.makeText(context, "Successfully enabled/disabled schedule", Toast.LENGTH_SHORT).show() else -> Toast.makeText(context, result?.message, Toast.LENGTH_SHORT).show() } } } else { uiScope.launch { val result = robot?.schedulingService?.enableSchedule(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.SUCCESS -> Toast.makeText(context, "Successfully enabled/disabled schedule", Toast.LENGTH_SHORT).show() else -> Toast.makeText(context, result?.message, Toast.LENGTH_SHORT).show() } } } } } private fun scheduleEveryWednesday() { uiScope.launch { val everyWednesday = ScheduleEvent().apply { mode = CleaningMode.TURBO day = 3//0 is Sunday, 1 Monday and so on startTime = "15:00" } val robotSchedule = RobotSchedule(true, arrayListOf(everyWednesday)) val result = robot?.schedulingService?.setSchedule(robot!!, robotSchedule) if(!isAdded) return@launch when(result?.status) { Resource.Status.SUCCESS -> { Toast.makeText(context, "Yay! Schedule programmed.", Toast.LENGTH_SHORT).show() } else -> { Toast.makeText(context, "Oops! Impossible to set schedule: "+result?.message, Toast.LENGTH_SHORT).show() } } robot?.updateRobotState() updateUIButtons() } } private fun getScheduling() { uiScope.launch { val result = robot?.schedulingService?.getSchedule(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.SUCCESS -> { Toast.makeText( context, "The robot has " + (result.data?.events?.size?:0) + " scheduled events.", Toast.LENGTH_SHORT ).show() } Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.updateRobotState() updateUIButtons() } } private fun getMapDetails(mapId: String) { uiScope.launch { val result = robot?.mapService?.getCleaningMap(robot!!, mapId) if(!isAdded) return@launch when(result?.status) { Resource.Status.SUCCESS -> { showMapImage(result.data?.url?:"") } null -> showNotSupportedService() else -> { Toast.makeText(context, "Oops! Impossible to get map details.", Toast.LENGTH_SHORT).show() } } } } private fun showMapImage(url: String) { Glide.with(this).load(url).into(mapImage) } private fun getMaps() { uiScope.launch { val result = robot?.mapService?.getCleaningMaps(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.SUCCESS -> { if (result.data != null && result.data?.isNotEmpty() == true) { // now you can get a map id and retrieve the map details // to download the map image use the map "url" property // this second call is needed because the map urls expire after a while getMapDetails(result.data!![0].id?:"") } else { Toast.makeText( context, "No maps available yet. Complete at least one house cleaning to view maps.", Toast.LENGTH_SHORT ).show() } } null -> showNotSupportedService() else -> { Toast.makeText(context, "Oops! Impossible to get robot maps.", Toast.LENGTH_SHORT).show() } } } } private fun executeStop() { uiScope.launch { val result = robot?.cleaningService?.stopCleaning(robot!!) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } } private fun executeSpotCleaning() { uiScope.launch { val params = CleaningParams(category = CleaningCategory.SPOT, mode = CleaningMode.TURBO, modifier = CleaningModifier.DOUBLE) val result = robot?.spotCleaningService?.startCleaning(robot!!, params) if(!isAdded) return@launch when(result?.status) { Resource.Status.ERROR -> Toast.makeText(context, result.message, Toast.LENGTH_SHORT).show() } robot?.state = result?.data updateUIButtons() } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (savedInstanceState != null) { restoreState(savedInstanceState) } } fun injectRobot(r: Robot) { this.robot = r updateUIButtons() } fun reloadRobotState() { uiScope.launch { robot?.updateRobotState() updateUIButtons() } } private fun showNotSupportedService() { Toast.makeText(context, "Service non supported", Toast.LENGTH_SHORT).show() } }
mit
b1c8b413491cc08a95774c435a877a9a
36.956772
143
0.593425
5.03094
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/credits/Credits.kt
2
3061
package io.github.chrislo27.rhre3.credits import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.sfxdb.SFXDatabase import io.github.chrislo27.toolboks.i18n.Localization import java.util.* object Credits { private val sfxCreditsFallback: String = listOf("Lvl100Feraligatr", "GenericArrangements", "Draster", "NP", "Eggman199", "Huebird", "oofie", "Miracle22", "MF5K", "The Golden Station", "GuardedLolz", "GlitchyPSIX", "sp00pster", "Maxanum").sortedBy { it.toLowerCase(Locale.ROOT) }.joinToString(separator = ", ") fun generateList(): List<Credit> { return listOf( "title" crediting RHRE3.GITHUB, "programming" crediting "chrislo27\n${Localization["credits.title.programming.contributions", "Kamayana"]}", "localization" crediting """[LIGHT_GRAY]Français (French)[] |inkedsplat, minenice55, Pengu123 | |[LIGHT_GRAY]Español (Spanish)[] |chipdamage, Cosmicfab, (◉.◉)☂, GlitchyPSIX, Killble, meuol, quantic, SJGarnet, Suwa-ko | |[LIGHT_GRAY]Deutsch (German)[] |Zenon""".trimMargin(), "sfx" crediting (SFXDatabase.let { if (!it.isDataLoading()) it.data.sfxCredits.sortedBy { it.toLowerCase(Locale.ROOT) }.joinToString(separator = ", ") else null } ?: sfxCreditsFallback), "gfx" crediting "GlitchyPSIX, lilbitdun, Steppy, Tickflow", "extras" crediting "GenericArrangements, Malalaika, The Drummer", "specialThanks" crediting """Alchemyking, AngryTapper, ArsenArsen, baguette, bin5s5, Chillius, ChorusSquid, Clone5184, danthonywalker, Dracobot, Draster, Dream Top, Dylstructor, EBPB2K, Fco, flyance, Fringession, garbo, GenericArrangements, (◉.◉)☂, GinoTitan, GlitchyPSIX, GrueKun, inkedsplat, iRonnoc5, jos, Lvl100Feraligatr, Malalaika, Maziodyne, Mezian, minenice55, Miracle22, Mixelz, nave, nerd, oofie, Pengu123, PikaMasterJesi, Rabbidking, RobSetback, SJGarnet, sp00pster, Ssure2, SuicuneWiFi, susmobile, TheRhythmKid, Turtike, Zenon, RHModding and Custom Remix Tourney Discord servers""", "resources" crediting """Rhythm Heaven assets by Nintendo [#FF8900]Kotlin[] [DARK_GRAY]lib[][#E10000]GDX[] LWJGL Toolboks Beads Async HTTP Client Jackson JGit Apache Commons IO SLF4J OSHI jump3r musique java-discord-rpc rhmodding/bread JCommander SoundStretch and SoundTouch zip4j Jam3/glsl-fast-gaussian-blur""", "donators" crediting "", "you" crediting "" ) } private infix fun String.crediting(persons: String): Credit = Credit(this, persons) data class Credit(val type: String, val persons: String) { private val localization: String by lazy { "credits.title.$type" } private val isTitle by lazy { type == "title" } val text: String = if (isTitle) RHRE3.TITLE_3 else Localization[localization] } }
gpl-3.0
742e8f59114b3d1db3ccc2d03c40d9ac
42.542857
610
0.655399
3.341009
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/presentation/achievement/AchievementsPresenter.kt
2
1802
package org.stepik.android.presentation.achievement import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.achievement.interactor.AchievementInteractor import org.stepik.android.presentation.base.PresenterBase import javax.inject.Inject class AchievementsPresenter @Inject constructor( private val achievementInteractor: AchievementInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<AchievementsView>() { private var state: AchievementsView.State = AchievementsView.State.Idle set(value) { field = value view?.setState(value) } override fun attachView(view: AchievementsView) { super.attachView(view) view.setState(state) } fun showAchievementsForUser(userId: Long, isMyProfile: Boolean, forceUpdate: Boolean = false) { if (state == AchievementsView.State.Idle || (forceUpdate && state == AchievementsView.State.Error)) { state = AchievementsView.State.Loading(userId, isMyProfile) compositeDisposable += achievementInteractor .getAchievements(userId) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { achievements -> state = AchievementsView.State.AchievementsLoaded(achievements, userId, isMyProfile) }, onError = { state = AchievementsView.State.Error } ) } } }
apache-2.0
15cc5808c25f70e09d6578cb5390b769
36.5625
109
0.687569
5.223188
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/merge/MultipleFileMergeDialog.kt
2
19964
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.merge import com.intellij.CommonBundle import com.intellij.configurationStore.StoreReloadManager import com.intellij.diff.DiffManager import com.intellij.diff.DiffRequestFactory import com.intellij.diff.InvalidDiffRequestException import com.intellij.diff.merge.MergeRequest import com.intellij.diff.merge.MergeResult import com.intellij.diff.merge.MergeUtil import com.intellij.diff.util.DiffUserDataKeysEx.EDITORS_TITLE_CUSTOMIZER import com.intellij.diff.util.DiffUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.command.WriteCommandAction.writeCommandAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsContexts.ColumnName import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.io.FileTooBigException import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.changes.ui.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.DoubleClickListener import com.intellij.ui.TableSpeedSearch import com.intellij.ui.UIBundle import com.intellij.ui.components.Label import com.intellij.ui.layout.* import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.ui.treeStructure.treetable.TreeTableModel import com.intellij.util.EditSourceOnDoubleClickHandler import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.Convertor import com.intellij.util.ui.ColumnInfo import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.NonNls import java.awt.event.ActionEvent import java.awt.event.MouseEvent import java.io.IOException import java.util.* import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JButton import javax.swing.JComponent import javax.swing.table.AbstractTableModel import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.TreeNode /** * @author yole */ open class MultipleFileMergeDialog( private val project: Project?, files: List<VirtualFile>, private val mergeProvider: MergeProvider, private val mergeDialogCustomizer: MergeDialogCustomizer ) : DialogWrapper(project) { private var unresolvedFiles = files.toMutableList() private val mergeSession = (mergeProvider as? MergeProvider2)?.createMergeSession(files) val processedFiles: MutableList<VirtualFile> = mutableListOf() private lateinit var table: TreeTable private lateinit var acceptYoursButton: JButton private lateinit var acceptTheirsButton: JButton private lateinit var mergeButton: JButton private val tableModel = ListTreeTableModelOnColumns(DefaultMutableTreeNode(), createColumns()) private val descriptionLabel = Label(VcsBundle.message("merge.loading.merge.details")) private var groupByDirectory: Boolean = false get() = when { project != null -> VcsConfiguration.getInstance(project).GROUP_MULTIFILE_MERGE_BY_DIRECTORY else -> field } set(value) = when { project != null -> VcsConfiguration.getInstance(project).GROUP_MULTIFILE_MERGE_BY_DIRECTORY = value else -> field = value } private val virtualFileRenderer = object : ChangesBrowserNodeRenderer(project, { !groupByDirectory }, false) { override fun calcFocusedState() = UIUtil.isAncestor([email protected], IdeFocusManager.getInstance(project).focusOwner) } init { StoreReloadManager.getInstance().blockReloadingProjectOnExternalChanges() title = mergeDialogCustomizer.getMultipleFileDialogTitle() virtualFileRenderer.font = UIUtil.getListFont() @Suppress("LeakingThis") init() updateTree() table.tree.selectionModel.addTreeSelectionListener { updateButtonState() } updateButtonState() selectFirstFile() object : DoubleClickListener() { override fun onDoubleClick(event: MouseEvent): Boolean { if (EditSourceOnDoubleClickHandler.isToggleEvent(table.tree, event)) return false showMergeDialog() return true } }.installOn(table.tree) TableSpeedSearch(table, Convertor { (it as? VirtualFile)?.name }) val modalityState = ModalityState.stateForComponent(descriptionLabel) BackgroundTaskUtil.executeOnPooledThread(disposable, Runnable { val description = mergeDialogCustomizer.getMultipleFileMergeDescription(unresolvedFiles) runInEdt(modalityState) { descriptionLabel.text = description } }) } private fun selectFirstFile() { if (!groupByDirectory) { table.selectionModel.setSelectionInterval(0, 0) } else { TreeUtil.promiseSelectFirstLeaf(table.tree) } } override fun createCenterPanel(): JComponent { return panel { row { descriptionLabel() } row { scrollPane(MergeConflictsTreeTable(tableModel).also { table = it it.setTreeCellRenderer(virtualFileRenderer) it.rowHeight = virtualFileRenderer.preferredSize.height it.preferredScrollableViewportSize = JBUI.size(600, 300) }).constraints(growX, growY, pushX, pushY) cell(isVerticalFlow = true) { JButton(VcsBundle.message("multiple.file.merge.accept.yours")).also { it.addActionListener { acceptRevision(MergeSession.Resolution.AcceptedYours) } acceptYoursButton = it }(growX) JButton(VcsBundle.message("multiple.file.merge.accept.theirs")).also { it.addActionListener { acceptRevision(MergeSession.Resolution.AcceptedTheirs) } acceptTheirsButton = it }(growX) val mergeAction = object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { showMergeDialog() } } mergeAction.putValue(DEFAULT_ACTION, java.lang.Boolean.TRUE) createJButtonForAction(mergeAction).also { it.text = VcsBundle.message("multiple.file.merge.merge") mergeButton = it }(growX) } } if (project != null) { row { checkBox(VcsBundle.message("multiple.file.merge.group.by.directory.checkbox"), groupByDirectory) { _, component -> toggleGroupByDirectory(component.isSelected) } } } } } private fun createColumns(): Array<ColumnInfo<*, *>> { val columns = ArrayList<ColumnInfo<*, *>>() columns.add(object : ColumnInfo<DefaultMutableTreeNode, Any>(VcsBundle.message("multiple.file.merge.column.name")) { override fun valueOf(node: DefaultMutableTreeNode) = node.userObject override fun getColumnClass(): Class<*> = TreeTableModel::class.java }) val mergeInfoColumns = mergeSession?.mergeInfoColumns if (mergeInfoColumns != null) { var customColumnNames = mergeDialogCustomizer.getColumnNames() if (customColumnNames != null && customColumnNames.size != mergeInfoColumns.size) { LOG.error("Custom column names ($customColumnNames) don't match default columns ($mergeInfoColumns)") customColumnNames = null } mergeInfoColumns.mapIndexedTo(columns) { index, columnInfo -> ColumnInfoAdapter(columnInfo, customColumnNames?.get(index) ?: columnInfo.name) } } return columns.toTypedArray() } private class ColumnInfoAdapter(private val base: ColumnInfo<Any, Any>, private val columnName: @ColumnName String) : ColumnInfo<DefaultMutableTreeNode, Any>(columnName) { override fun valueOf(node: DefaultMutableTreeNode) = (node.userObject as? VirtualFile)?.let { base.valueOf(it) } override fun getMaxStringValue() = base.maxStringValue override fun getAdditionalWidth() = base.additionalWidth override fun getTooltipText() = base.tooltipText ?: columnName } private fun toggleGroupByDirectory(state: Boolean) { groupByDirectory = state val firstSelectedFile = getSelectedFiles().firstOrNull() updateTree() if (firstSelectedFile != null) { val node = TreeUtil.findNodeWithObject(tableModel.root as DefaultMutableTreeNode, firstSelectedFile) node?.let { TreeUtil.selectNode(table.tree, node) } } } private fun updateTree() { val factory = when { project != null && groupByDirectory -> ChangesGroupingSupport.getFactory(ChangesGroupingSupport.DIRECTORY_GROUPING) else -> NoneChangesGroupingFactory } val model = TreeModelBuilder.buildFromVirtualFiles(project, factory, unresolvedFiles) tableModel.setRoot(model.root as TreeNode) TreeUtil.expandAll(table.tree) (table.model as? AbstractTableModel)?.fireTableDataChanged() } private fun updateButtonState() { val selectedFiles = getSelectedFiles() val haveSelection = selectedFiles.any() val haveUnmergeableFiles = selectedFiles.any { mergeSession?.canMerge(it) == false } val haveUnacceptableFiles = selectedFiles.any { mergeSession != null && mergeSession !is MergeSessionEx && !mergeSession.canMerge(it)} acceptYoursButton.isEnabled = haveSelection && !haveUnacceptableFiles acceptTheirsButton.isEnabled = haveSelection && !haveUnacceptableFiles mergeButton.isEnabled = haveSelection && !haveUnmergeableFiles } private fun getSelectedFiles(): List<VirtualFile> { return VcsTreeModelData.selected(table.tree).userObjects(VirtualFile::class.java) } override fun createActions(): Array<Action> { cancelAction.putValue(Action.NAME, CommonBundle.getCloseButtonText()) return arrayOf(cancelAction) } override fun dispose() { StoreReloadManager.getInstance().unblockReloadingProjectOnExternalChanges() super.dispose() } @NonNls override fun getDimensionServiceKey(): String = "MultipleFileMergeDialog" @JvmSuppressWildcards protected open fun beforeResolve(files: Collection<VirtualFile>): Boolean { return true } private fun acceptRevision(resolution: MergeSession.Resolution) { assert(resolution == MergeSession.Resolution.AcceptedYours || resolution == MergeSession.Resolution.AcceptedTheirs) FileDocumentManager.getInstance().saveAllDocuments() val files = getSelectedFiles() ProgressManager.getInstance().run(object : Task.Modal(project, VcsBundle.message( "multiple.file.merge.dialog.progress.title.resolving.conflicts"), false) { override fun run(indicator: ProgressIndicator) { if (!beforeResolve(files)) { return } try { if (mergeSession is MergeSessionEx) { mergeSession.acceptFilesRevisions(files, resolution) for (file in files) { checkMarkModifiedProject(file) } markFilesProcessed(files, resolution) } else { for (file in files) { val data = mergeProvider.loadRevisions(file) ApplicationManager.getApplication().invokeAndWait({ resolveFileViaContent(file, resolution, data) }, indicator.modalityState) checkMarkModifiedProject(file) markFileProcessed(file, resolution) } } } catch (e: Exception) { LOG.warn(e) ApplicationManager.getApplication().invokeAndWait({ Messages.showErrorDialog(contentPanel, VcsBundle.message( "multiple.file.merge.dialog.message.error.saving.merged.data", e.message)) }, indicator.modalityState) } } }) updateModelFromFiles() } @RequiresEdt private fun resolveFileViaContent(file: VirtualFile, resolution: MergeSession.Resolution, data: MergeData) { if (!DiffUtil.makeWritable(project, file)) { throw IOException(UIBundle.message("file.is.read.only.message.text", file.presentableUrl)) } val isCurrent = resolution == MergeSession.Resolution.AcceptedYours val message = if (isCurrent) VcsBundle.message("multiple.file.merge.dialog.command.name.accept.yours") else VcsBundle.message("multiple.file.merge.dialog.command.name.accept.theirs") writeCommandAction(project).withName(message).run<Exception> { if (isCurrent) { file.setBinaryContent(data.CURRENT) } else { file.setBinaryContent(data.LAST) } } } private fun markFilesProcessed(files: List<VirtualFile>, resolution: MergeSession.Resolution) { unresolvedFiles.removeAll(files) if (mergeSession is MergeSessionEx) { mergeSession.conflictResolvedForFiles(files, resolution) } else if (mergeSession != null) { files.forEach { mergeSession.conflictResolvedForFile(it, resolution) } } else { files.forEach { mergeProvider.conflictResolvedForFile(it) } } processedFiles.addAll(files) if (project != null) VcsDirtyScopeManager.getInstance(project).filesDirty(files, emptyList()) } private fun markFileProcessed(file: VirtualFile, resolution: MergeSession.Resolution) { markFilesProcessed(listOf(file), resolution) } private fun updateModelFromFiles() { if (unresolvedFiles.isEmpty()) { doCancelAction() } else { var selIndex = table.selectionModel.minSelectionIndex updateTree() if (selIndex >= table.rowCount) { selIndex = table.rowCount - 1 } table.selectionModel.setSelectionInterval(selIndex, selIndex) table.requestFocusInWindow() } } private fun showMergeDialog() { val requestFactory = DiffRequestFactory.getInstance() val files = getSelectedFiles() if (files.isEmpty()) return if (!beforeResolve(files)) { return } for (file in files) { val filePath = VcsUtil.getFilePath(file) val conflictData: ConflictData try { conflictData = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable<ConflictData, VcsException> { val mergeData = mergeProvider.loadRevisions(file) val title = tryCompute { mergeDialogCustomizer.getMergeWindowTitle(file) } val conflictTitles = listOf( tryCompute { mergeDialogCustomizer.getLeftPanelTitle(file) }, tryCompute { mergeDialogCustomizer.getCenterPanelTitle(file) }, tryCompute { mergeDialogCustomizer.getRightPanelTitle(file, mergeData.LAST_REVISION_NUMBER) } ) val titleCustomizer = tryCompute { mergeDialogCustomizer.getTitleCustomizerList(filePath) } ?: MergeDialogCustomizer.DEFAULT_CUSTOMIZER_LIST ConflictData(mergeData, title, conflictTitles, titleCustomizer) }, VcsBundle.message("multiple.file.merge.dialog.progress.title.loading.revisions"), true, project) } catch (ex: VcsException) { Messages.showErrorDialog(contentPanel, VcsBundle.message("multiple.file.merge.dialog.error.loading.revisions.to.merge", ex.message)) break } val mergeData = conflictData.mergeData val byteContents = listOf(mergeData.CURRENT, mergeData.ORIGINAL, mergeData.LAST) val contentTitles = conflictData.contentTitles val title = conflictData.title val callback = { result: MergeResult -> val document = FileDocumentManager.getInstance().getCachedDocument(file) if (document != null) FileDocumentManager.getInstance().saveDocument(document) checkMarkModifiedProject(file) if (result != MergeResult.CANCEL) { ProgressManager.getInstance() .runProcessWithProgressSynchronously({ markFileProcessed(file, getSessionResolution(result)) }, VcsBundle.message("multiple.file.merge.dialog.progress.title.resolving.conflicts"), true, project, contentPanel) } } val request: MergeRequest try { if (mergeProvider.isBinary(file)) { // respect MIME-types in svn request = requestFactory.createBinaryMergeRequest(project, file, byteContents, title, contentTitles, callback) } else { request = requestFactory.createMergeRequest(project, file, byteContents, title, contentTitles, callback) } MergeUtils.putRevisionInfos(request, mergeData) } catch (e: InvalidDiffRequestException) { if (e.cause is FileTooBigException) { Messages.showErrorDialog(contentPanel, VcsBundle.message("multiple.file.merge.dialog.message.file.too.big.to.be.loaded"), VcsBundle.message("multiple.file.merge.dialog.title.can.t.show.merge.dialog")) } else { LOG.error(e) Messages.showErrorDialog(contentPanel, e.message, VcsBundle.message("multiple.file.merge.dialog.title.can.t.show.merge.dialog")) } break } conflictData.contentTitleCustomizers.run { request.putUserData(EDITORS_TITLE_CUSTOMIZER, listOf(leftTitleCustomizer, centerTitleCustomizer, rightTitleCustomizer)) } DiffManager.getInstance().showMerge(project, request) } updateModelFromFiles() } private fun getSessionResolution(result: MergeResult): MergeSession.Resolution = when (result) { MergeResult.LEFT -> MergeSession.Resolution.AcceptedYours MergeResult.RIGHT -> MergeSession.Resolution.AcceptedTheirs MergeResult.RESOLVED -> MergeSession.Resolution.Merged else -> throw IllegalArgumentException(result.name) } private fun checkMarkModifiedProject(file: VirtualFile) { MergeUtil.reportProjectFileChangeIfNeeded(project, file) } override fun getPreferredFocusedComponent(): JComponent? = table private fun <T> tryCompute(task: () -> T): T? { try { return task() } catch (e: ProcessCanceledException) { throw e } catch (e: VcsException) { LOG.warn(e) } catch (e: Exception) { LOG.error(e) } return null } companion object { private val LOG = Logger.getInstance(MultipleFileMergeDialog::class.java) } private data class ConflictData( val mergeData: MergeData, val title: String?, val contentTitles: List<String?>, val contentTitleCustomizers: MergeDialogCustomizer.DiffEditorTitleCustomizerList ) }
apache-2.0
f451012247cbb904f16ee6385cde1432
38.691849
151
0.69425
4.969878
false
false
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-reactive/src/Migration.kt
1
1395
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("FlowKt") package kotlinx.coroutines.reactive import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import org.reactivestreams.* // Binary compatibility with Spring 5.2 RC /** @suppress */ @Deprecated( message = "Replaced in favor of ReactiveFlow extension, please import kotlinx.coroutines.reactive.* instead of kotlinx.coroutines.reactive.FlowKt", level = DeprecationLevel.HIDDEN ) @JvmName("asFlow") public fun <T : Any> Publisher<T>.asFlowDeprecated(): Flow<T> = asFlow() // Binary compatibility with Spring 5.2 RC /** @suppress */ @Deprecated( message = "Replaced in favor of ReactiveFlow extension, please import kotlinx.coroutines.reactive.* instead of kotlinx.coroutines.reactive.FlowKt", level = DeprecationLevel.HIDDEN ) @JvmName("asPublisher") public fun <T : Any> Flow<T>.asPublisherDeprecated(): Publisher<T> = asPublisher() /** @suppress */ @FlowPreview @Deprecated( message = "batchSize parameter is deprecated, use .buffer() instead to control the backpressure", level = DeprecationLevel.HIDDEN, replaceWith = ReplaceWith("asFlow().buffer(batchSize)", imports = ["kotlinx.coroutines.flow.*"]) ) public fun <T : Any> Publisher<T>.asFlow(batchSize: Int): Flow<T> = asFlow().buffer(batchSize)
apache-2.0
615b3e230559da45a7267adfaaf440fa
34.769231
151
0.741219
4.020173
false
false
false
false
walkingice/MomoDict
app/src/main/java/org/zeroxlab/momodict/Controller.kt
1
3465
package org.zeroxlab.momodict import android.content.Context import androidx.room.Room.databaseBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.zeroxlab.momodict.db.room.RoomStore import org.zeroxlab.momodict.model.Book import org.zeroxlab.momodict.model.Card import org.zeroxlab.momodict.model.Entry import org.zeroxlab.momodict.model.Record import org.zeroxlab.momodict.model.Store // TODO: How to handle exception in each function call? class Controller @JvmOverloads constructor( private val mCtx: Context, private val mStore: Store = databaseBuilder( mCtx.applicationContext, RoomStore::class.java, RoomStore.DB_NAME ) .allowMainThreadQueries() .build() ) { // sorting by time. Move latest one to head private val recordTimeComparator: Comparator<Record> = Comparator { left, right -> if (left.time!!.before(right.time)) 1 else -1 } // sorting by time. Move latest one to head private val cardTimeComparator = Comparator<Card> { left, right -> if (left.time!!.before(right.time)) 1 else -1 } suspend fun getBooks(): List<Book> = withContext(Dispatchers.IO) { mStore.getBooks() } suspend fun removeBook(bookName: String): Boolean = withContext(Dispatchers.IO) { mStore.removeBook(bookName) } suspend fun queryEntries( keyWord: String ): List<Entry> = withContext(Dispatchers.IO) { // to make sure exact matched words are returned val exact = syncGetEntries(keyWord) val list = mStore.queryEntries(keyWord) val comparator = Comparator<Entry> { left, right -> left.wordStr!!.indexOf(keyWord) - right.wordStr!!.indexOf(keyWord) } list.sortWith(comparator) exact.forEach { list.add(0, it) } val distinct = list.distinctBy { item -> item.wordStr } distinct } suspend fun getEntries(keyWord: String): List<Entry> = withContext(Dispatchers.IO) { // to make sure exact matched words are returned syncGetEntries(keyWord) } suspend fun getRecords(): (List<Record>) = withContext(Dispatchers.IO) { mStore.getRecords().apply { sortWith(recordTimeComparator) } } suspend fun clearRecords() = withContext(Dispatchers.IO) { val records = getRecords() records.forEach { r -> mStore.removeRecords(r.wordStr) } } suspend fun setRecord(record: Record): Boolean = withContext(Dispatchers.IO) { mStore.upsertRecord(record) } suspend fun removeRecord(keyWord: String): Boolean = withContext(Dispatchers.IO) { mStore.removeRecords(keyWord) } suspend fun getCards(): List<Card> = withContext(Dispatchers.IO) { val cards = mStore.getCards() cards.sortWith(cardTimeComparator) cards } suspend fun setCard(card: Card): Boolean = withContext(Dispatchers.IO) { mStore.upsertCard(card) } suspend fun removeCards(keyWord: String): Boolean = withContext(Dispatchers.IO) { mStore.removeCards(keyWord) } private fun syncGetEntries(keyWord: String): List<Entry> { val list = mStore.getEntries(keyWord) val comparator = Comparator<Entry> { left, right -> left.wordStr!!.indexOf(keyWord) - right.wordStr!!.indexOf(keyWord) } list.sortWith(comparator) return list } }
mit
37186506b466754b8ec92d6e49085fb7
31.688679
88
0.668398
4.241126
false
false
false
false
googlecodelabs/android-performance
benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/components/Button.kt
1
4813
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.macrobenchmark_codelab.ui.components import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.indication import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ButtonDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.ProvideTextStyle import androidx.compose.material.Text import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.semantics.Role import androidx.compose.ui.tooling.preview.Preview import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme @Composable fun JetsnackButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, shape: Shape = ButtonShape, border: BorderStroke? = null, backgroundGradient: List<Color> = JetsnackTheme.colors.interactivePrimary, disabledBackgroundGradient: List<Color> = JetsnackTheme.colors.interactiveSecondary, contentColor: Color = JetsnackTheme.colors.textInteractive, disabledContentColor: Color = JetsnackTheme.colors.textHelp, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit ) { JetsnackSurface( shape = shape, color = Color.Transparent, contentColor = if (enabled) contentColor else disabledContentColor, border = border, modifier = modifier .clip(shape) .background( Brush.horizontalGradient( colors = if (enabled) backgroundGradient else disabledBackgroundGradient ) ) .clickable( onClick = onClick, enabled = enabled, role = Role.Button, interactionSource = interactionSource, indication = null ) ) { ProvideTextStyle( value = MaterialTheme.typography.button ) { Row( Modifier .defaultMinSize( minWidth = ButtonDefaults.MinWidth, minHeight = ButtonDefaults.MinHeight ) .indication(interactionSource, rememberRipple()) .padding(contentPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } } private val ButtonShape = RoundedCornerShape(percent = 50) @Preview("default", "round") @Preview("dark theme", "round", uiMode = UI_MODE_NIGHT_YES) @Preview("large font", "round", fontScale = 2f) @Composable private fun ButtonPreview() { JetsnackTheme { JetsnackButton(onClick = {}) { Text(text = "Demo") } } } @Preview("default", "rectangle") @Preview("dark theme", "rectangle", uiMode = UI_MODE_NIGHT_YES) @Preview("large font", "rectangle", fontScale = 2f) @Composable private fun RectangleButtonPreview() { JetsnackTheme { JetsnackButton( onClick = {}, shape = RectangleShape ) { Text(text = "Demo") } } }
apache-2.0
f2e811319ad51eca15059d29f7f2ff2b
35.740458
92
0.699979
4.901222
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/tasker/TaskerSettingViewModel.kt
2
3521
/* * Copyright 2018 Google 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 com.google.android.apps.muzei.tasker import android.app.Application import android.graphics.drawable.Drawable import androidx.core.content.ContextCompat import androidx.lifecycle.AndroidViewModel import com.google.android.apps.muzei.legacy.BuildConfig.LEGACY_AUTHORITY import com.google.android.apps.muzei.room.getInstalledProviders import kotlinx.coroutines.flow.map import net.nurik.roman.muzei.R internal data class Action( val icon: Drawable, val text: String, val action: TaskerAction, val packageName: String? = null) internal class TaskerSettingViewModel( application: Application ) : AndroidViewModel(application) { private val imageSize = application.resources.getDimensionPixelSize( R.dimen.tasker_action_icon_size) private val comparator = Comparator<Action> { a1, a2 -> // The Next Artwork action should always be first if (a1.action is NextArtworkAction) { return@Comparator -1 } else if (a2.action is NextArtworkAction) { return@Comparator 1 } // The SourceArtProvider should always the last provider listed if (a1.action is SelectProviderAction && a1.action.authority == LEGACY_AUTHORITY) { return@Comparator 1 } else if (a2.action is SelectProviderAction && a2.action.authority == LEGACY_AUTHORITY) { return@Comparator -1 } // Then put providers from Muzei on top val pn1 = a1.packageName val pn2 = a2.packageName if (pn1 != pn2) { if (application.packageName == pn1) { return@Comparator -1 } else if (application.packageName == pn2) { return@Comparator 1 } } // Finally, sort actions by their text a1.text.compareTo(a2.text) } private val nextArtworkAction = Action( ContextCompat.getDrawable(application, R.drawable.ic_launcher_next_artwork)!!.apply { setBounds(0, 0, imageSize, imageSize) }, application.getString(R.string.action_next_artwork), NextArtworkAction) fun getActions() = getInstalledProviders(getApplication()).map { providers -> val application = getApplication<Application>() val pm = application.packageManager val actionsList = mutableListOf(nextArtworkAction) providers.forEach { providerInfo -> actionsList.add(Action( providerInfo.loadIcon(pm).apply { setBounds(0, 0, imageSize, imageSize) }, application.getString(R.string.tasker_action_select_provider, providerInfo.loadLabel(pm)), SelectProviderAction(providerInfo.authority))) } actionsList.sortedWith(comparator) } }
apache-2.0
fa603ed32e7f9d72c3021a5c4c76cb53
37.271739
97
0.649531
4.694667
false
false
false
false
romannurik/muzei
android-client-common/src/main/java/com/google/android/apps/muzei/room/ArtworkDao.kt
2
2883
/* * Copyright 2017 Google 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 com.google.android.apps.muzei.room import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import kotlinx.coroutines.flow.Flow /** * Dao for Artwork */ @Dao abstract class ArtworkDao { @Query("SELECT * FROM artwork ORDER BY date_added DESC LIMIT 100") abstract suspend fun getArtwork(): List<Artwork> @get:Query(""" SELECT artwork.* FROM artwork inner join provider on providerAuthority = authority ORDER BY date_added DESC""") abstract val currentArtwork: Flow<Artwork?> @get:Query(""" SELECT artwork.* FROM artwork inner join provider on providerAuthority = authority ORDER BY date_added DESC""") abstract val currentArtworkLiveData: LiveData<Artwork?> @get:Query(""" SELECT artwork.* FROM artwork inner join provider on providerAuthority = authority ORDER BY date_added DESC""") internal abstract val currentArtworkBlocking: Artwork? @Query(""" SELECT artwork.* FROM artwork inner join provider on providerAuthority = authority ORDER BY date_added DESC""") abstract suspend fun getCurrentArtwork(): Artwork? @Insert abstract suspend fun insert(artwork: Artwork): Long @Query(""" SELECT * FROM artwork WHERE providerAuthority = :providerAuthority ORDER BY date_added DESC""") abstract suspend fun getCurrentArtworkForProvider(providerAuthority: String): Artwork? @get:Query(""" SELECT art1.* FROM artwork art1, (SELECT _id, max(date_added) FROM artwork GROUP BY providerAuthority) as art2 WHERE art1._id=art2._id""") abstract val currentArtworkByProvider : Flow<List<Artwork>> @Query("SELECT * FROM artwork WHERE _id=:id") internal abstract fun getArtworkByIdBlocking(id: Long): Artwork? @Query("SELECT * FROM artwork WHERE _id=:id") abstract suspend fun getArtworkById(id: Long): Artwork? @Query(""" SELECT * FROM artwork WHERE title LIKE :query OR byline LIKE :query OR attribution LIKE :query""") abstract suspend fun searchArtwork(query: String): List<Artwork> @Query("DELETE FROM artwork WHERE _id=:id") abstract fun deleteById(id: Long) }
apache-2.0
9174d2533cd8cf71ffe54273a7d8a29f
32.523256
90
0.696844
4.540157
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/CardFormViewManager.kt
2
2618
package abi43_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk import abi43_0_0.com.facebook.react.bridge.ReadableArray import abi43_0_0.com.facebook.react.bridge.ReadableMap import abi43_0_0.com.facebook.react.common.MapBuilder import abi43_0_0.com.facebook.react.uimanager.SimpleViewManager import abi43_0_0.com.facebook.react.uimanager.ThemedReactContext import abi43_0_0.com.facebook.react.uimanager.annotations.ReactProp class CardFormViewManager : SimpleViewManager<CardFormView>() { override fun getName() = "CardForm" private var reactContextRef: ThemedReactContext? = null override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> { return MapBuilder.of( CardFocusEvent.EVENT_NAME, MapBuilder.of("registrationName", "onFocusChange"), CardFormCompleteEvent.EVENT_NAME, MapBuilder.of("registrationName", "onFormComplete") ) } override fun receiveCommand(root: CardFormView, commandId: String?, args: ReadableArray?) { when (commandId) { "focus" -> root.requestFocusFromJS() "blur" -> root.requestBlurFromJS() "clear" -> root.requestClearFromJS() } } @ReactProp(name = "dangerouslyGetFullCardDetails") fun setDangerouslyGetFullCardDetails(view: CardFormView, dangerouslyGetFullCardDetails: Boolean = false) { view.setDangerouslyGetFullCardDetails(dangerouslyGetFullCardDetails) } @ReactProp(name = "postalCodeEnabled") fun setPostalCodeEnabled(view: CardFormView, postalCodeEnabled: Boolean = false) { view.setPostalCodeEnabled(postalCodeEnabled) } // @ReactProp(name = "placeholder") // fun setPlaceHolders(view: CardFormView, placeholder: ReadableMap) { // view.setPlaceHolders(placeholder); // } @ReactProp(name = "autofocus") fun setAutofocus(view: CardFormView, autofocus: Boolean = false) { view.setAutofocus(autofocus) } @ReactProp(name = "cardStyle") fun setCardStyle(view: CardFormView, cardStyle: ReadableMap) { view.setCardStyle(cardStyle) } override fun createViewInstance(reactContext: ThemedReactContext): CardFormView { val stripeSdkModule: StripeSdkModule? = reactContext.getNativeModule(StripeSdkModule::class.java) val view = CardFormView(reactContext) reactContextRef = reactContext stripeSdkModule?.cardFormView = view return view } override fun onDropViewInstance(view: CardFormView) { super.onDropViewInstance(view) val stripeSdkModule: StripeSdkModule? = reactContextRef?.getNativeModule(StripeSdkModule::class.java) stripeSdkModule?.cardFormView = null reactContextRef = null } }
bsd-3-clause
0838a4b7610ac93df7031654c6ccc840
35.361111
108
0.764324
4.052632
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/checker/Shadowing.kt
13
887
class A { operator fun component1() = 42 operator fun component2() = 42 } fun arrayA(): Array<A> = null!! fun foo(a: A, <warning descr="[UNUSED_PARAMETER] Parameter 'c' is never used">c</warning>: Int) { val (<warning descr="[NAME_SHADOWING] Name shadowed: a"><warning descr="[UNUSED_VARIABLE] Variable 'a' is never used">a</warning></warning>, <warning descr="[UNUSED_VARIABLE] Variable 'b' is never used">b</warning>) = a val arr = arrayA() for ((<warning descr="[NAME_SHADOWING] Name shadowed: c"><warning descr="[UNUSED_VARIABLE] Variable 'c' is never used">c</warning></warning>, <warning descr="[UNUSED_VARIABLE] Variable 'd' is never used">d</warning>) in arr) { } } fun f(<warning descr="[UNUSED_PARAMETER] Parameter 'p' is never used">p</warning>: Int): Int { val <error descr="">p</error> = 2 val <error descr="">p</error> = 3 return p }
apache-2.0
b9abca1c5b090aedf0ddff37bcfcf4f1
45.684211
230
0.655017
3.492126
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/ui/views/LearningItems.kt
1
7271
// 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 training.ui.views import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.util.IconUtil import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import training.FeaturesTrainerIcons import training.learn.CourseManager import training.learn.LearnBundle import training.learn.course.IftModule import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.statistic.LessonStartingWay import training.ui.UISettings import training.util.* import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.border.EmptyBorder private val HOVER_COLOR: Color get() = JBColor.namedColor("Plugins.hoverBackground", JBColor(0xEDF6FE, 0x464A4D)) class LearningItems(private val project: Project) : JPanel() { var modules: Collection<IftModule> = emptyList() private val expanded: MutableSet<IftModule> = mutableSetOf() init { name = "learningItems" layout = VerticalLayout(0, UISettings.instance.let { it.panelWidth - (it.westInset + it.eastInset) }) isOpaque = false isFocusable = false } fun updateItems(showModule: IftModule? = null) { if (showModule != null) expanded.add(showModule) removeAll() for (module in modules) { if (module.lessons.isEmpty()) continue add(createModuleItem(module), VerticalLayout.FILL_HORIZONTAL) if (expanded.contains(module)) { for (lesson in module.lessons) { add(createLessonItem(lesson), VerticalLayout.FILL_HORIZONTAL) } } } revalidate() repaint() } private fun createLessonItem(lesson: Lesson): JPanel { val name = JLabel(lesson.name).also { it.foreground = JBUI.CurrentTheme.Link.Foreground.ENABLED } val clickAction: () -> Unit = l@{ val cantBeOpenedInDumb = DumbService.getInstance(project).isDumb && !lesson.properties.canStartInDumbMode if (cantBeOpenedInDumb && !LessonManager.instance.lessonShouldBeOpenedCompleted(lesson)) { val balloon = createBalloon(LearnBundle.message("indexing.message")) balloon.showInCenterOf(name) return@l } CourseManager.instance.openLesson(project, lesson, LessonStartingWay.LEARN_TAB) } val result = LearningItemPanel(clickAction) result.layout = BoxLayout(result, BoxLayout.X_AXIS) result.alignmentX = LEFT_ALIGNMENT result.border = EmptyBorder(JBUI.scale(7), JBUI.scale(7), JBUI.scale(6), JBUI.scale(7)) val checkmarkIconLabel = createLabelIcon(if (lesson.passed) FeaturesTrainerIcons.Img.GreenCheckmark else EmptyIcon.ICON_16) result.add(createLabelIcon(EmptyIcon.ICON_16)) result.add(scaledRigid(UISettings.instance.expandAndModuleGap, 0)) result.add(checkmarkIconLabel) result.add(rigid(4, 0)) result.add(name) if (iftPluginIsUsing && lesson.isNewLesson()) { result.add(rigid(10, 0)) result.add(NewContentLabel()) } result.add(Box.createHorizontalGlue()) return result } private fun createModuleItem(module: IftModule): JPanel { val modulePanel = JPanel() modulePanel.isOpaque = true modulePanel.layout = BoxLayout(modulePanel, BoxLayout.Y_AXIS) modulePanel.alignmentY = TOP_ALIGNMENT modulePanel.background = Color(0, 0, 0, 0) val clickAction: () -> Unit = { if (expanded.contains(module)) { expanded.remove(module) } else { expanded.clear() expanded.add(module) } updateItems() } val result = LearningItemPanel(clickAction) result.background = UISettings.instance.backgroundColor result.layout = BoxLayout(result, BoxLayout.X_AXIS) result.border = EmptyBorder(JBUI.scale(8), JBUI.scale(7), JBUI.scale(10), JBUI.scale(7)) result.alignmentX = LEFT_ALIGNMENT val expandPanel = JPanel().also { it.layout = BoxLayout(it, BoxLayout.Y_AXIS) it.isOpaque = false it.background = Color(0, 0, 0, 0) it.alignmentY = TOP_ALIGNMENT it.add(rigid(0, 1)) val rawIcon = if (expanded.contains(module)) UIUtil.getTreeExpandedIcon() else UIUtil.getTreeCollapsedIcon() it.add(createLabelIcon(rawIcon)) } result.add(expandPanel) val name = JLabel(module.name) name.font = UISettings.instance.modulesFont if (!iftPluginIsUsing || expanded.contains(module) || !module.lessons.any { it.isNewLesson() }) { modulePanel.add(name) } else { val nameLine = JPanel() nameLine.isOpaque = false nameLine.layout = BoxLayout(nameLine, BoxLayout.X_AXIS) nameLine.alignmentX = LEFT_ALIGNMENT nameLine.add(name) nameLine.add(rigid(10, 0)) nameLine.add(NewContentLabel()) modulePanel.add(nameLine) } modulePanel.add(scaledRigid(0, UISettings.instance.progressModuleGap)) if (expanded.contains(module)) { modulePanel.add(JLabel("<html>${module.description}</html>").also { it.font = UISettings.instance.getFont(-1) it.foreground = UIUtil.getLabelForeground() }) } else { modulePanel.add(createModuleProgressLabel(module)) } result.add(scaledRigid(UISettings.instance.expandAndModuleGap, 0)) result.add(modulePanel) result.add(Box.createHorizontalGlue()) return result } private fun createLabelIcon(rawIcon: Icon): JLabel = JLabel(IconUtil.toSize(rawIcon, JBUI.scale(16), JBUI.scale(16))) private fun createModuleProgressLabel(module: IftModule): JBLabel { val progressStr = learningProgressString(module.lessons) val progressLabel = JBLabel(progressStr) progressLabel.name = "progressLabel" val hasNotPassedLesson = module.lessons.any { !it.passed } progressLabel.foreground = if (hasNotPassedLesson) UISettings.instance.moduleProgressColor else UISettings.instance.completedColor progressLabel.font = UISettings.instance.getFont(-1) progressLabel.alignmentX = LEFT_ALIGNMENT return progressLabel } } private class LearningItemPanel(clickAction: () -> Unit) : JPanel() { init { isOpaque = false cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (!visibleRect.contains(e.point)) return clickAction() } override fun mouseEntered(e: MouseEvent) { repaint() } override fun mouseExited(e: MouseEvent) { repaint() } }) } override fun paint(g: Graphics) { if (mousePosition != null) { val g2 = g.create() as Graphics2D g2.color = HOVER_COLOR g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE) g2.fillRoundRect(0, 0, size.width, size.height, JBUI.scale(5), JBUI.scale(5)) } super.paint(g) } }
apache-2.0
9e59468d6df2d4cceae3cdcbd325ce2e
34.817734
158
0.710906
4.100959
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertJavaCopyPasteProcessor.kt
1
14540
// 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.conversion.copy import com.intellij.codeInsight.editorActions.CopyPastePostProcessor import com.intellij.codeInsight.editorActions.TextBlockTransferableData import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.refactoring.suggested.range import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor import org.jetbrains.kotlin.idea.codeInsight.KotlinReferenceData import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices import org.jetbrains.kotlin.idea.statistics.ConversionType import org.jetbrains.kotlin.idea.statistics.J2KFusCollector import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.j2k.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import java.awt.datatransfer.Transferable import kotlin.system.measureTimeMillis class ConvertJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() { private val LOG = Logger.getInstance(ConvertJavaCopyPasteProcessor::class.java) override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> { try { if (content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR)) { return listOf(content.getTransferData(CopiedJavaCode.DATA_FLAVOR) as TextBlockTransferableData) } } catch (e: Throwable) { if (e is ControlFlowException) throw e LOG.error(e) } return listOf() } override fun collectTransferableData( file: PsiFile, editor: Editor, startOffsets: IntArray, endOffsets: IntArray ): List<TextBlockTransferableData> { if (file !is PsiJavaFile) return listOf() return listOf(CopiedJavaCode(file.getText()!!, startOffsets, endOffsets)) } override fun processTransferableData( project: Project, editor: Editor, bounds: RangeMarker, caretOffset: Int, indented: Ref<in Boolean>, values: List<TextBlockTransferableData> ) { if (DumbService.getInstance(project).isDumb) return if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return val data = values.single() as CopiedJavaCode val document = editor.document val targetFile = PsiDocumentManager.getInstance(project).getPsiFile(document) as? KtFile ?: return val useNewJ2k = checkUseNewJ2k(targetFile) val targetModule = targetFile.module if (isNoConversionPosition(targetFile, bounds.startOffset)) return data class Result( val text: String?, val referenceData: Collection<KotlinReferenceData>, val explicitImports: Set<FqName>, val converterContext: ConverterContext? ) val dataForConversion = DataForConversion.prepare(data, project) fun doConversion(): Result { val result = dataForConversion.elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k) val referenceData = buildReferenceData(result.text, result.parseContext, dataForConversion.importsAndPackage, targetFile) val text = if (result.textChanged) result.text else null return Result(text, referenceData, result.importsToAdd, result.converterContext) } fun insertImports( bounds: TextRange, referenceData: Collection<KotlinReferenceData>, explicitImports: Collection<FqName> ): TextRange? { if (referenceData.isEmpty() && explicitImports.isEmpty()) return bounds PsiDocumentManager.getInstance(project).commitDocument(document) val rangeMarker = document.createRangeMarker(bounds) rangeMarker.isGreedyToLeft = true rangeMarker.isGreedyToRight = true KotlinCopyPasteReferenceProcessor() .processReferenceData(project, editor, targetFile, bounds.startOffset, referenceData.toTypedArray()) runWriteAction { explicitImports.forEach { fqName -> targetFile.resolveImportReference(fqName).firstOrNull()?.let { ImportInsertHelper.getInstance(project).importDescriptor(targetFile, it) } } } return rangeMarker.range } var conversionResult: Result? = null fun doConversionAndInsertImportsIfUnchanged(): Boolean { conversionResult = doConversion() if (conversionResult!!.text != null) return false insertImports( bounds.range ?: return true, conversionResult!!.referenceData, conversionResult!!.explicitImports ) return true } val textLength = data.startOffsets.indices.sumBy { data.endOffsets[it] - data.startOffsets[it] } // if the text to convert is short enough, try to do conversion without permission from user and skip the dialog if nothing converted if (textLength < 1000 && doConversionAndInsertImportsIfUnchanged()) return fun convert() { if (conversionResult == null && doConversionAndInsertImportsIfUnchanged()) return val (text, referenceData, explicitImports) = conversionResult!! text!! // otherwise we should get true from doConversionAndInsertImportsIfUnchanged and return above val boundsAfterReplace = runWriteAction { val startOffset = bounds.startOffset document.replaceString(startOffset, bounds.endOffset, text) val endOffsetAfterCopy = startOffset + text.length editor.caretModel.moveToOffset(endOffsetAfterCopy) TextRange(startOffset, endOffsetAfterCopy) } val newBounds = insertImports(boundsAfterReplace, referenceData, explicitImports) PsiDocumentManager.getInstance(project).commitDocument(document) runPostProcessing(project, targetFile, newBounds, conversionResult?.converterContext, useNewJ2k) conversionPerformed = true } if (confirmConvertJavaOnPaste(project, isPlainText = false)) { val conversionTime = measureTimeMillis { convert() } J2KFusCollector.log( ConversionType.PSI_EXPRESSION, ExperimentalFeatures.NewJ2k.isEnabled, conversionTime, dataForConversion.elementsAndTexts.linesCount(), filesCount = 1 ) } } private fun buildReferenceData( text: String, parseContext: ParseContext, importsAndPackage: String, targetFile: KtFile ): Collection<KotlinReferenceData> { var blockStart: Int var blockEnd: Int val fileText = buildString { append(importsAndPackage) val (contextPrefix, contextSuffix) = when (parseContext) { ParseContext.CODE_BLOCK -> "fun ${generateDummyFunctionName(text)}() {\n" to "\n}" ParseContext.TOP_LEVEL -> "" to "" } append(contextPrefix) blockStart = length append(text) blockEnd = length append(contextSuffix) } val dummyFile = KtPsiFactory(targetFile.project).createAnalyzableFile("dummy.kt", fileText, targetFile) val startOffset = blockStart val endOffset = blockEnd return KotlinCopyPasteReferenceProcessor().collectReferenceData(dummyFile, intArrayOf(startOffset), intArrayOf(endOffset)).map { it.copy(startOffset = it.startOffset - startOffset, endOffset = it.endOffset - startOffset) } } private fun generateDummyFunctionName(convertedCode: String): String { var i = 0 while (true) { val name = "dummy$i" if (convertedCode.indexOf(name) < 0) return name i++ } } companion object { @get:TestOnly var conversionPerformed: Boolean = false } } internal class ConversionResult( val text: String, val parseContext: ParseContext, val importsToAdd: Set<FqName>, val textChanged: Boolean, val converterContext: ConverterContext? ) internal fun ElementAndTextList.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult { val converter = J2kConverterExtension.extension(useNewJ2k).createJavaToKotlinConverter( project, targetModule, ConverterSettings.defaultSettings, IdeaJavaToKotlinServices ) val inputElements = toList().filterIsInstance<PsiElement>() val (results, _, converterContext) = ProgressManager.getInstance().runProcessWithProgressSynchronously( ThrowableComputable<Result, Exception> { runReadAction { converter.elementsToKotlin(inputElements) } }, JavaToKotlinAction.title, true, project ) val importsToAdd = LinkedHashSet<FqName>() var resultIndex = 0 val convertedCodeBuilder = StringBuilder() val originalCodeBuilder = StringBuilder() var parseContext: ParseContext? = null this.process(object : ElementsAndTextsProcessor { override fun processElement(element: PsiElement) { val originalText = element.text originalCodeBuilder.append(originalText) val result = results[resultIndex++] if (result != null) { convertedCodeBuilder.append(result.text) if (parseContext == null) { // use parse context of the first converted element as parse context for the whole text parseContext = result.parseContext } importsToAdd.addAll(result.importsToAdd) } else { // failed to convert element to Kotlin, insert "as is" convertedCodeBuilder.append(originalText) } } override fun processText(string: String) { originalCodeBuilder.append(string) convertedCodeBuilder.append(string) } }) val convertedCode = convertedCodeBuilder.toString() val originalCode = originalCodeBuilder.toString() return ConversionResult( convertedCode, parseContext ?: ParseContext.CODE_BLOCK, importsToAdd, convertedCode != originalCode, converterContext ) } internal fun isNoConversionPosition(file: KtFile, offset: Int): Boolean { if (offset == 0) return false val token = file.findElementAt(offset - 1) ?: return true if (token !is PsiWhiteSpace && token.endOffset != offset) return true // pasting into the middle of token for (element in token.parentsWithSelf) { when (element) { is PsiComment -> return element.node.elementType == KtTokens.EOL_COMMENT || offset != element.endOffset is KtStringTemplateEntryWithExpression -> return false is KtStringTemplateExpression -> return true } } return false } internal fun confirmConvertJavaOnPaste(project: Project, isPlainText: Boolean): Boolean { if (KotlinEditorOptions.getInstance().isDonTShowConversionDialog) return true val dialog = KotlinPasteFromJavaDialog(project, isPlainText) dialog.show() return dialog.isOK } fun ElementAndTextList.linesCount() = toList() .filterIsInstance<PsiElement>() .sumBy { StringUtil.getLineBreakCount(it.text) } fun checkUseNewJ2k(targetFile: KtFile): Boolean { if (targetFile is KtCodeFragment) return false return ExperimentalFeatures.NewJ2k.isEnabled } fun runPostProcessing( project: Project, file: KtFile, bounds: TextRange?, converterContext: ConverterContext?, useNewJ2k: Boolean ) { val postProcessor = J2kConverterExtension.extension(useNewJ2k).createPostProcessor(formatCode = true) if (useNewJ2k) { ProgressManager.getInstance().runProcessWithProgressSynchronously( { val processor = J2kConverterExtension.extension(useNewJ2k).createWithProgressProcessor( ProgressManager.getInstance().progressIndicator!!, emptyList(), postProcessor.phasesCount ) AfterConversionPass(project, postProcessor) .run( file, converterContext, bounds ) { phase, description -> processor.updateState(0, phase, description) } }, @Suppress("DialogTitleCapitalization") KotlinBundle.message("copy.text.convert.java.to.kotlin.title"), true, project ) } else { AfterConversionPass(project, postProcessor) .run( file, converterContext, bounds ) } }
apache-2.0
1fc7c604d78021efa265ab830aff244c
37.366755
141
0.668776
5.417288
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt
2
5042
// 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.createFromUsage.createClass import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeIntersector import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.ifEmpty import java.util.* object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory<KtUserType>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtUserType? { return diagnostic.psiElement.findParentOfType(strict = false) } override fun getPossibleClassKinds(element: KtUserType, diagnostic: Diagnostic): List<ClassKind> { val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return Collections.emptyList() val isQualifier = (element.parent as? KtUserType)?.let { it.qualifier == element } ?: false val typeReference = element.parent as? KtTypeReference val isUpperBound = typeReference?.getParentOfTypeAndBranch<KtTypeParameter> { extendsBound } != null || typeReference?.getParentOfTypeAndBranch<KtTypeConstraint> { boundTypeReference } != null return when (typeRefParent) { is KtSuperTypeEntry -> listOfNotNull( ClassKind.INTERFACE, if (typeRefParent.classExpected()) ClassKind.PLAIN_CLASS else null ) else -> ClassKind.values().filter { val noTypeArguments = element.typeArgumentsAsTypes.isEmpty() when (it) { ClassKind.OBJECT -> noTypeArguments && isQualifier ClassKind.ANNOTATION_CLASS -> noTypeArguments && !isQualifier && !isUpperBound ClassKind.ENUM_ENTRY -> false ClassKind.ENUM_CLASS -> noTypeArguments && !isUpperBound else -> true } } } } private fun KtSuperTypeEntry.classExpected(): Boolean { val containingClass = getStrictParentOfType<KtClass>() ?: return false return !containingClass.hasModifier(KtTokens.ANNOTATION_KEYWORD) && !containingClass.hasModifier(KtTokens.ENUM_KEYWORD) && !containingClass.hasModifier(KtTokens.INLINE_KEYWORD) } private fun getExpectedUpperBound(element: KtUserType, context: BindingContext): KotlinType? { val projection = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null val argumentList = projection.parent as? KtTypeArgumentList ?: return null val index = argumentList.arguments.indexOf(projection) val callElement = argumentList.parent as? KtCallElement ?: return null val resolvedCall = callElement.getResolvedCall(context) ?: return null val typeParameterDescriptor = resolvedCall.candidateDescriptor.typeParameters.getOrNull(index) ?: return null if (typeParameterDescriptor.upperBounds.isEmpty()) return null return TypeIntersector.getUpperBoundsAsType(typeParameterDescriptor) } override fun extractFixData(element: KtUserType, diagnostic: Diagnostic): ClassInfo? { val name = element.referenceExpression?.getReferencedName() ?: return null val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return null val (context, module) = element.analyzeAndGetResult() val qualifier = element.qualifier?.referenceExpression val qualifierDescriptor = qualifier?.let { context[BindingContext.REFERENCE_TARGET, it] } val targetParents = getTargetParentsByQualifier(element, qualifier != null, qualifierDescriptor).ifEmpty { return null } val expectedUpperBound = getExpectedUpperBound(element, context) val anyType = module.builtIns.anyType return ClassInfo( name = name, targetParents = targetParents, expectedTypeInfo = expectedUpperBound?.let { TypeInfo.ByType(it, Variance.INVARIANT) } ?: TypeInfo.Empty, open = typeRefParent is KtSuperTypeEntry && typeRefParent.classExpected(), typeArguments = element.typeArgumentsAsTypes.map { if (it != null) TypeInfo(it, Variance.INVARIANT) else TypeInfo(anyType, Variance.INVARIANT) } ) } }
apache-2.0
525060984c7a28fa0d2893335d25f7b6
51.520833
185
0.716977
5.492375
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/config/common/CommonFlankConfig.kt
1
10004
package ftl.config.common import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import ftl.args.ArgsHelper import ftl.args.yml.IYmlKeys import ftl.args.yml.ymlKeys import ftl.config.Config import ftl.config.FtlConstants import ftl.reports.output.OutputReportType import ftl.shard.DEFAULT_CLASS_TEST_TIME_SEC import ftl.shard.DEFAULT_TEST_TIME_SEC import picocli.CommandLine /** Flank specific parameters for both iOS and Android */ @CommandLine.Command @JsonIgnoreProperties(ignoreUnknown = true) data class CommonFlankConfig @JsonIgnore constructor( @field:JsonIgnore override val data: MutableMap<String, Any?> ) : Config { @set:CommandLine.Option( names = ["--max-test-shards"], description = ["The amount of matrices to split the tests across."] ) @set:JsonProperty("max-test-shards") var maxTestShards: Int? by data @set:CommandLine.Option( names = ["--shard-time"], description = ["The max amount of seconds each shard should run."] ) @set:JsonProperty("shard-time") var shardTime: Int? by data @set:CommandLine.Option( names = ["--num-test-runs"], description = ["The amount of times to run the test executions."] ) @set:JsonProperty("num-test-runs") var repeatTests: Int? by data @set:CommandLine.Option( names = ["--smart-flank-gcs-path"], description = ["Google cloud storage path to save test timing data used by smart flank."] ) @set:JsonProperty("smart-flank-gcs-path") var smartFlankGcsPath: String? by data @set:CommandLine.Option( names = ["--smart-flank-disable-upload"], description = ["Disables smart flank JUnit XML uploading. Useful for preventing timing data from being updated."] ) @set:JsonProperty("smart-flank-disable-upload") var smartFlankDisableUpload: Boolean? by data @set:CommandLine.Option( names = ["--disable-sharding"], description = ["Disable sharding."] ) @set:JsonProperty("disable-sharding") var disableSharding: Boolean? by data @set:CommandLine.Option( names = ["--test-targets-always-run"], split = ",", description = [ "A list of one or more test methods to be added at the top of every shard. " + "Flank doesn't ensure execution order of added tests." ] ) @set:JsonProperty("test-targets-always-run") var testTargetsAlwaysRun: List<String>? by data @set:CommandLine.Option( names = ["--files-to-download"], split = ",", description = [ "A list of paths that will be downloaded from the resulting bucket " + "to the local results folder after the test is complete. These must be absolute paths " + "(for example, --files-to-download /images/tempDir1,/data/local/tmp/tempDir2). " + "Path names are restricted to the characters a-zA-Z0-9_-./+." ] ) @set:JsonProperty("files-to-download") var filesToDownload: List<String>? by data @set:CommandLine.Option( names = ["--project"], description = [ "The Google Cloud Platform project name to use for this invocation. " + "If omitted, then the project from the service account credential is used" ] ) @set:JsonProperty("project") var project: String? by data @set:CommandLine.Option( names = ["--local-result-dir"], description = ["Saves test result to this local folder. Deleted before each run."] ) @set:JsonProperty("local-result-dir") var localResultsDir: String? by data @set:CommandLine.Option( names = ["--run-timeout"], description = ["The max time this test run can execute before it is cancelled (default: unlimited)."] ) @set:JsonProperty("run-timeout") var runTimeout: String? by data @set:CommandLine.Option( names = ["--full-junit-result"], description = ["Enable create additional local junit result on local storage with failure nodes on passed flaky tests."] ) @set:JsonProperty("full-junit-result") var fullJUnitResult: Boolean? by data @set:CommandLine.Option( names = ["--ignore-failed-tests"], description = [ "Terminate with exit code 0 when there are failed tests. " + "Useful for Fladle and other gradle plugins that don't expect the process to have a non-zero exit code. " + "The JUnit XML is used to determine failure. (default: false)" ] ) @set:JsonProperty("ignore-failed-tests") var ignoreFailedTests: Boolean? by data @set:CommandLine.Option( names = ["--ignore-non-global-tests"], description = [ "Test discovery for iOS considers by default global tests only. " + "Disabling this flag will result in test discovery for private, public and global tests" + "The technical difference is the flag used for nm test discovery. " + "true: 'nm -gU' vs false: 'nm -U'" ] ) @set:JsonProperty("ignore-non-global-tests") var ignoreNonGlobalTests: Boolean? by data @set:CommandLine.Option( names = ["--keep-file-path"], description = [ "Keeps the full path of downloaded files. " + "Required when file names are not unique." ] ) @set:JsonProperty("keep-file-path") var keepFilePath: Boolean? by data @set:CommandLine.Option( names = ["--output-style"], description = [ "Output style of execution status. May be one of [verbose, multi, single]. " + "For runs with only one test execution the default value is 'verbose', in other cases " + "'multi' is used as the default. The output style 'multi' is not displayed correctly on consoles " + "which don't support ansi codes, to avoid corrupted output use `single` or `verbose`." ] ) @set:JsonProperty("output-style") var outputStyle: String? by data @set:CommandLine.Option( names = ["--disable-results-upload"], description = ["Disables flank results upload on gcloud storage."] ) @set:JsonProperty("disable-results-upload") var disableResultsUpload: Boolean? by data @set:CommandLine.Option( names = ["--default-test-time"], description = ["Set default test time used for calculating shards."] ) @set:JsonProperty("default-test-time") var defaultTestTime: Double? by data @set:JsonProperty("default-class-test-time") var defaultClassTestTime: Double? by data @set:CommandLine.Option( names = ["--use-average-test-time-for-new-tests"], description = ["Enable using average time from previous tests duration when using SmartShard and tests did not run before."] ) @set:JsonProperty("use-average-test-time-for-new-tests") var useAverageTestTimeForNewTests: Boolean? by data @set:CommandLine.Option( names = ["--disable-usage-statistics"], description = ["If set to true flank not send usage statistics."] ) @set:JsonProperty("disable-usage-statistics") var disableUsageStatistics: Boolean? by data @set:CommandLine.Option( names = ["--output-report"], description = ["Saves output results as parsable file and optionally upload it to Gcloud."] ) @set:JsonProperty("output-report") var outputReport: String? by data @set:CommandLine.Option( names = ["--skip-config-validation"], description = [ "If true, Flank won't validate options provided by the user. In general, it's not a good idea but, " + "there are cases when this could be useful for a user (example: project can use devices " + "that are not commonly available, the project has higher sharding limits, etc." ] ) @set:JsonProperty("skip-config-validation") var skipConfigValidation: Boolean? by data @set:CommandLine.Option( names = ["--custom-sharding-json"], description = [ "Path to custom sharding JSON file. Flank will apply provided sharding to the configuration.", "More info https://github.com/Flank/flank/blob/master/docs/feature/1665-custom-sharding.md" ] ) @set:JsonProperty("custom-sharding-json") var customShardingJson: String? by data constructor() : this(mutableMapOf<String, Any?>().withDefault { null }) companion object : IYmlKeys { override val group = IYmlKeys.Group.FLANK override val keys by lazy { CommonFlankConfig::class.ymlKeys } const val defaultLocalResultsDir = "results" fun default() = CommonFlankConfig().apply { project = ArgsHelper.getDefaultProjectIdOrNull() maxTestShards = 1 shardTime = -1 repeatTests = 1 smartFlankGcsPath = "" smartFlankDisableUpload = false testTargetsAlwaysRun = emptyList() filesToDownload = emptyList() disableSharding = false localResultsDir = defaultLocalResultsDir runTimeout = FtlConstants.runTimeout fullJUnitResult = false ignoreFailedTests = false keepFilePath = false outputStyle = null disableResultsUpload = false defaultTestTime = DEFAULT_TEST_TIME_SEC defaultClassTestTime = DEFAULT_CLASS_TEST_TIME_SEC useAverageTestTimeForNewTests = false disableUsageStatistics = false outputReport = OutputReportType.NONE.name skipConfigValidation = false customShardingJson = "" ignoreNonGlobalTests = true } } }
apache-2.0
75eef853d793b0e4aca319561913560b
37.038023
132
0.638645
4.462087
false
true
false
false
mdaniel/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/EmptyListLiteralType.kt
14
2051
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.typing import com.intellij.pom.java.LanguageLevel import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClassType import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil.isInheritorOrSelf import com.intellij.util.lazyPub import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.impl.getTypeArgumentsFromResult import org.jetbrains.plugins.groovy.lang.resolve.BaseGroovyResolveResult import org.jetbrains.plugins.groovy.lang.resolve.asJavaClassResult import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.getExpectedType import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.inferDerivedSubstitutor class EmptyListLiteralType(literal: GrListOrMap) : ListLiteralType(literal) { private val resolveResult: GroovyResolveResult? by lazyPub(fun(): GroovyResolveResult? { val clazz = resolve() ?: return null val lType = getExpectedType(literal) as? PsiClassType val substitutor = if (lType == null || lType.isRaw || !isInheritorOrSelf(clazz, lType.resolve(), true)) { JavaPsiFacade.getInstance(literal.project).elementFactory.createRawSubstitutor(clazz) } else { inferDerivedSubstitutor(lType, clazz, literal) } return BaseGroovyResolveResult(clazz, literal, substitutor = substitutor) }) override fun resolveGenerics(): ClassResolveResult = resolveResult.asJavaClassResult() override fun getParameters(): Array<out PsiType?> = resolveResult?.getTypeArgumentsFromResult() ?: PsiType.EMPTY_ARRAY override fun setLanguageLevel(languageLevel: LanguageLevel): PsiClassType = error("This method must not be called") override fun getLeastUpperBound(vararg psiTypes: PsiType?): PsiType = error("This method must not be called") }
apache-2.0
fe9019295fb67bf08622bffd2e1f8f41
51.589744
140
0.804973
4.439394
false
false
false
false
zsmb13/MaterialDrawerKt
library/src/main/java/co/zsmb/materialdrawerkt/builders/AccountHeaderBuilderKt.kt
1
26437
@file:Suppress("RedundantVisibilityModifier") package co.zsmb.materialdrawerkt.builders import android.app.Activity import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Bundle import android.view.View import android.widget.ImageView import co.zsmb.materialdrawerkt.DrawerMarker import co.zsmb.materialdrawerkt.nonReadable import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.AccountHeaderBuilder import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.model.interfaces.IProfile /** * Adds an [AccountHeader] to the drawer. * @return The created [AccountHeader] instance */ public fun DrawerBuilderKt.accountHeader(setup: AccountHeaderBuilderKt.() -> Unit = {}): AccountHeader { val header = AccountHeaderBuilderKt(activity) header.setup() return header.build().apply { attachHeader(this) } } @DrawerMarker public class AccountHeaderBuilderKt(activity: Activity) { //region Builder basics public val builder: AccountHeaderBuilder = AccountHeaderBuilder().withActivity(activity) internal fun build(): AccountHeader { if (onProfileImageListener.isInitialized) { builder.withOnAccountHeaderProfileImageListener(onProfileImageListener) } return builder.build() } internal fun addItem(profile: IProfile<*>) = builder.addProfiles(profile) //endregion //region Listener helper private val onProfileImageListener = object : AccountHeader.OnAccountHeaderProfileImageListener { var isInitialized = false var onClick: ((view: View, profile: IProfile<*>, current: Boolean) -> Boolean)? = null set(value) { isInitialized = true field = value } override fun onProfileImageClick(view: View, profile: IProfile<*>, current: Boolean): Boolean { return onClick?.invoke(view, profile, current) ?: false } var onLongClick: ((view: View, profile: IProfile<*>, current: Boolean) -> Boolean)? = null set(value) { isInitialized = true field = value } override fun onProfileImageLongClick(view: View, profile: IProfile<*>, current: Boolean): Boolean { return onLongClick?.invoke(view, profile, current) ?: false } } //endregion //region AccountHeaderBuilder methods /** * By default, the small profile icons in the header show the most recently used profiles, the leftmost being the * last one used before the current one. If this setting is enabled, the small profile icons will still display the * most recently used profiles, but instead of being ordered by the time they were last used, they will stay in one * position as long as possible. * Default value is false. * * Non-readable property. Wraps the [AccountHeaderBuilder.withAlternativeProfileHeaderSwitching] method. */ public var alternativeSwitching: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withAlternativeProfileHeaderSwitching(value) } /** * The background of the header, as a drawable resource. * * Convenience for [backgroundRes]. Non-readable property. Wraps the [AccountHeaderBuilder.withHeaderBackground] * method. */ public var background: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderBackground(value) } /** * The background of the header, as a Drawable. * * Non-readable property. Wraps the [AccountHeaderBuilder.withHeaderBackground] method. */ public var backgroundDrawable: Drawable @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderBackground(value) } /** * The background of the header, as a drawable resource. * * See [background] as an alternative. * * Non-readable property. Wraps the [AccountHeaderBuilder.withHeaderBackground] method. */ @Deprecated(level = DeprecationLevel.WARNING, replaceWith = ReplaceWith("background"), message = "Alternatives are available, check the documentation.") public var backgroundRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderBackground(value) } /** * Defines the way the background drawable will scale. * * Non-readable property. Wraps the [AccountHeaderBuilder.withHeaderBackgroundScaleType] method. */ public var backgroundScaleType: ImageView.ScaleType @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderBackgroundScaleType(value) } /** * Whether the drawer should be closed when a profile item is clicked. * Default value is true. * * See [closeOnClick] as an alternative. * * Non-readable property. Wraps the [AccountHeaderBuilder.withCloseDrawerOnProfileListClick] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var closeDrawerOnProfileListClick: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCloseDrawerOnProfileListClick(value) } /** * Whether to close the profile selection list after a profile in it has been selected. * Default value is true. * * Convenience for [resetDrawerOnProfileListClick]. Non-readable property. Wraps the * [AccountHeaderBuilder.withResetDrawerOnProfileListClick] method. */ public var closeListAfterSelection: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withResetDrawerOnProfileListClick(value) } /** * Whether the drawer should be closed when a profile item is clicked. * Default value is true. * * Convenience for [closeDrawerOnProfileListClick]. Non-readable property. Wraps the * [AccountHeaderBuilder.withCloseDrawerOnProfileListClick] method. */ public var closeOnClick: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCloseDrawerOnProfileListClick(value) } /** * Whether to use a smaller, compact style drawer. * Default value is false. * * Non-readable property. Wraps the [AccountHeaderBuilder.withCompactStyle] method. */ public var compactStyle: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCompactStyle(value) } /** * Whether the current profile should be hidden from the profile selection list. * Default value is false. * * Convenience for [currentProfileHiddenInList]. Non-readable property. Wraps the * [AccountHeaderBuilder.withCurrentProfileHiddenInList] method. */ public var currentHidden: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCurrentProfileHiddenInList(value) } /** * Whether the current profile should be hidden from the profile selection list. * Default value is false. * * See [currentHidden] as an alternative. * * Non-readable property. Wraps the [AccountHeaderBuilder.withCurrentProfileHiddenInList] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var currentProfileHiddenInList: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCurrentProfileHiddenInList(value) } /** * A completely custom View for the header. * * Non-readable property. Wraps the [AccountHeaderBuilder.withAccountHeader] method. */ public var customView: View @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withAccountHeader(value) } /** * A completely custom view for the header, as a layout resource. * * Non-readable property. Wraps the [AccountHeaderBuilder.withAccountHeader] method. */ public var customViewRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withAccountHeader(value) } /** * The delay (in milliseconds) for the drawer close operation after a click. This is a small trick to improve * performance and prevent lag if you open a new Activity after a drawer item was selected. Set to -1 to disable * this behavior entirely. * The default value is 100. * * Non-readable property. Wraps the [AccountHeaderBuilder.withOnProfileClickDrawerCloseDelay] method. */ public var delayOnDrawerClose: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withOnProfileClickDrawerCloseDelay(value) } /** * Whether there should be a divider below the header. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withDividerBelowHeader] method. */ public var dividerBelow: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDividerBelowHeader(value) } /** * The drawer this header belongs to. Not recommended since it will be automatically set to the right drawer anyway. * * Non-readable property. Wraps the [AccountHeaderBuilder.withDrawer] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Setting this manually is not recommended.") public var drawer: Drawer @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawer(value) } /** * The typeface used for displaying the email of the currently selected profile. * * Non-readable property. Wraps the [AccountHeaderBuilder.withEmailTypeface] method. */ public var emailTypeface: Typeface @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withEmailTypeface(value) } /** * The height of the header, in dps. * * Non-readable property. Wraps the [AccountHeaderBuilder.withHeightDp] method. */ public var heightDp: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeightDp(value) } /** * The height of the header, in pixels. * * Non-readable property. Wraps the [AccountHeaderBuilder.withHeightPx] method. */ public var heightPx: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeightPx(value) } /** * The height of the header, as a dimension resource. * * Non-readable property. Wraps the [AccountHeaderBuilder.withHeightRes] method. */ public var heightRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeightRes(value) } /** * The typeface used for displaying the name of the currently selected profile. * * Non-readable property. Wraps the [AccountHeaderBuilder.withNameTypeface] method. */ public var nameTypeface: Typeface @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withNameTypeface(value) } /** * Adds an event [handler] to the header that's called when one of the profile items in the list is long clicked. * The handler should return true if the event has been completely handled. * * Wraps the [AccountHeaderBuilder.withOnAccountHeaderItemLongClickListener] method. * * @param view The View that was clicked * @param profile The profile that was clicked * @param current Whether the clicked profile is the currently selected one */ fun onItemLongClick(handler: (view: View, profile: IProfile<*>, current: Boolean) -> Boolean) { builder.withOnAccountHeaderItemLongClickListener(object : AccountHeader.OnAccountHeaderItemLongClickListener { override fun onProfileLongClick(view: View, profile: IProfile<*>, current: Boolean): Boolean { return handler(view, profile, current) } }) } /** * If set to true, hides the small profile images. If you want to hide all profile images, see the * [profileImagesVisible] property. * Default value is false. * * Non-readable property. Wraps the [AccountHeaderBuilder.withOnlyMainProfileImageVisible] method. */ public var onlyMainProfileImageVisible: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withOnlyMainProfileImageVisible(value) } /** * If set to true, hides the profile image of the selected user. If you want to hide all profile images, see the * [profileImagesVisible] property. * Default value is false. * * Non-readable property. Wraps the [AccountHeaderBuilder.withOnlySmallProfileImagesVisible] method. */ public var onlySmallProfileImagesVisible: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withOnlySmallProfileImagesVisible(value) } /** * Adds an event [handler] to the header that's called when one of the profile items in the list is selected. * The handler should return true if the event has been completely handled. * * Wraps the [AccountHeaderBuilder.withOnAccountHeaderListener] method. * * @param view The View that was clicked * @param profile The profile that was clicked * @param current Whether the clicked profile is the currently selected one */ fun onProfileChanged(handler: (view: View?, profile: IProfile<*>, current: Boolean) -> Boolean) { builder.withOnAccountHeaderListener(object : AccountHeader.OnAccountHeaderListener { override fun onProfileChanged(view: View?, profile: IProfile<*>, current: Boolean): Boolean { return handler(view, profile, current) } }) } /** * Adds an event [handler] to the header that's called when one of the profile images is clicked. * The handler should return true if the event has been completely handled. * * Wraps the [AccountHeaderBuilder.withOnAccountHeaderProfileImageListener] method. * * @param view The View that was clicked * @param profile The profile that was clicked * @param current Whether the clicked profile is the currently selected one */ fun onProfileImageClick(handler: (view: View, profile: IProfile<*>, current: Boolean) -> Boolean) { onProfileImageListener.onClick = handler } /** * Adds an event [handler] to the header that's called when one of the profile images is long clicked. * The handler should return true if the event has been completely handled. * * Wraps the [AccountHeaderBuilder.withOnAccountHeaderProfileImageListener] method. * * @param view The View that was clicked * @param profile The profile that was clicked * @param current Whether the clicked profile is the currently selected one */ fun onProfileImageLongClick(handler: (view: View, profile: IProfile<*>, current: Boolean) -> Boolean) { onProfileImageListener.onLongClick = handler } /** * Adds an event [handler] to the header that's called when the header is clicked somewhere that toggles opening * and closing the list view (anywhere other than the profile icons). * The handler should return true if the event has been completely handled. * * Wraps the [AccountHeaderBuilder.withOnAccountHeaderSelectionViewClickListener] method. * * @param view The View containing the header * @param profile The currently selected profile */ fun onSelectionViewClick(handler: (view: View, profile: IProfile<*>) -> Boolean) { builder.withOnAccountHeaderSelectionViewClickListener(object : AccountHeader.OnAccountHeaderSelectionViewClickListener { override fun onClick(view: View, profile: IProfile<*>): Boolean { return handler(view, profile) } }) } /** * Whether to include padding below the header. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withPaddingBelowHeader] method. */ public var paddingBelow: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withPaddingBelowHeader(value) } /** * Whether the profile images can be clicked to change profiles. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withProfileImagesClickable] method. */ public var profileImagesClickable: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withProfileImagesClickable(value) } /** * Whether any of the profile images (large and small) are visible. If you only want to hide only some profile * images, see the [onlyMainProfileImageVisible] and [onlySmallProfileImagesVisible] properties. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withProfileImagesVisible] method. */ public var profileImagesVisible: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withProfileImagesVisible(value) } /** * Whether to close the profile selection list after a profile in it has been selected. * Default value is true. * * See [closeListAfterSelection] as an alternative. * * Non-readable property. Wraps the [AccountHeaderBuilder.withResetDrawerOnProfileListClick] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var resetDrawerOnProfileListClick: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withResetDrawerOnProfileListClick(value) } /** * The bundle to restore state from after a configuration change. * * Remember to store the AccountHeader instance and call its * [saveInstanceState][com.mikepenz.materialdrawer.AccountHeader.saveInstanceState] method in the Activity's * [onSaveInstanceState][Activity.onSaveInstanceState] method, before calling super, to store the current state of * the header. Note that this has to be done in addition to doing it for the Drawer. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSavedInstance] method. */ public var savedInstance: Bundle? @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSavedInstance(value) } /** * Overrides the currently selected user's name display. * Default value is the user's name. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSelectionFirstLine] method. */ public var selectionFirstLine: String @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectionFirstLine(value) } /** * Whether to display the currently selected user's name. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSelectionFirstLineShown] method. */ public var selectionFirstLineShown: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectionFirstLineShown(value) } /** * Whether the profile selection list can be opened. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSelectionListEnabled] method. */ public var selectionListEnabled: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectionListEnabled(value) } /** * Whether the profile selection list can be opened if there is only one profile in the header. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSelectionListEnabledForSingleProfile] method. */ public var selectionListEnabledForSingleProfile: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectionListEnabledForSingleProfile(value) } /** * Overrides the currently selected user's email display. * Default value is the user's email. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSelectionSecondLine] method. */ public var selectionSecondLine: String @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectionSecondLine(value) } /** * Whether to display the currently selected user's email. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withSelectionSecondLineShown] method. */ public var selectionSecondLineShown: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectionSecondLineShown(value) } /** * The color of the currently selected user's name, email, and the list's toggle arrow, as an argb Long. * * Non-readable property. Wraps the [AccountHeaderBuilder.withTextColor] method. */ public var textColor: Long @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTextColor(value.toInt()) } /** * The color of the currently selected user's name, email, and the list's toggle arrow, as a color resource. * * Non-readable property. Wraps the [AccountHeaderBuilder.withTextColorRes] method. */ public var textColorRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTextColorRes(value) } /** * Whether to display three small profile images instead of the default two. * Default value is false. * * Non-readable property. Wraps the [AccountHeaderBuilder.withThreeSmallProfileImages] method. */ public var threeSmallProfileImages: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withThreeSmallProfileImages(value) } /** * This should be enabled if you're using a translucent status bar. * Default value is true. * * Non-readable property. Wraps the [AccountHeaderBuilder.withTranslucentStatusBar] method. */ public var translucentStatusBar: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTranslucentStatusBar(value) } /** * The typeface used for displaying the name and email of the currently selected profile. This is overriden by the * [nameTypeface] and [emailTypeface] properties if they are set. * * Non-readable property. Wraps the [AccountHeaderBuilder.withTypeface] method. */ public var typeface: Typeface @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTypeface(value) } //endregion }
apache-2.0
e3d810c1b188c157de4868cbdf37fc35
37.314493
128
0.664183
4.83309
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/network/NetworkHelper.kt
2
1113
package eu.kanade.tachiyomi.data.network import android.content.Context import okhttp3.Cache import okhttp3.OkHttpClient import java.io.File class NetworkHelper(context: Context) { private val cacheDir = File(context.cacheDir, "network_cache") private val cacheSize = 5L * 1024 * 1024 // 5 MiB private val cookieManager = PersistentCookieJar(context) val client = OkHttpClient.Builder() .cookieJar(cookieManager) .cache(Cache(cacheDir, cacheSize)) .build() val forceCacheClient = client.newBuilder() .addNetworkInterceptor { chain -> val originalResponse = chain.proceed(chain.request()) originalResponse.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "max-age=600") .build() } .build() val cloudflareClient = client.newBuilder() .addInterceptor(CloudflareInterceptor(cookies)) .build() val cookies: PersistentCookieStore get() = cookieManager.store }
gpl-3.0
5fd219ef2951d5fe2c90432bf34bb0dd
28.289474
69
0.615454
5.105505
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/segmentedActionBar/SegmentedActionToolbarComponent.kt
1
7547
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.actionSystem.impl.segmentedActionBar import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.actionSystem.ex.ComboBoxAction.ComboBoxButton import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.* import javax.swing.JComponent import javax.swing.border.Border open class SegmentedActionToolbarComponent(place: String, group: ActionGroup, val paintBorderForSingleItem: Boolean = true) : ActionToolbarImpl(place, group, true) { companion object { internal const val CONTROL_BAR_PROPERTY = "CONTROL_BAR_PROPERTY" internal const val CONTROL_BAR_FIRST = "CONTROL_BAR_PROPERTY_FIRST" internal const val CONTROL_BAR_LAST = "CONTROL_BAR_PROPERTY_LAST" internal const val CONTROL_BAR_MIDDLE = "CONTROL_BAR_PROPERTY_MIDDLE" internal const val CONTROL_BAR_SINGLE = "CONTROL_BAR_PROPERTY_SINGLE" const val RUN_TOOLBAR_COMPONENT_ACTION = "RUN_TOOLBAR_COMPONENT_ACTION" private val LOG = Logger.getInstance(SegmentedActionToolbarComponent::class.java) internal val segmentedButtonLook = object : ActionButtonLook() { override fun paintBorder(g: Graphics, c: JComponent, state: Int) { } override fun paintBackground(g: Graphics, component: JComponent, state: Int) { SegmentedBarPainter.paintActionButtonBackground(g, component, state) } } fun isCustomBar(component: Component): Boolean { if (component !is JComponent) return false return component.getClientProperty(CONTROL_BAR_PROPERTY)?.let { it != CONTROL_BAR_SINGLE } ?: false } fun paintButtonDecorations(g: Graphics2D, c: JComponent, paint: Paint): Boolean { return SegmentedBarPainter.paintButtonDecorations(g, c, paint) } } init { layoutPolicy = NOWRAP_LAYOUT_POLICY } private var isActive = false private var visibleActions: List<AnAction>? = null override fun getInsets(): Insets { return JBInsets.emptyInsets() } override fun setBorder(border: Border?) { } override fun createCustomComponent(action: CustomComponentAction, presentation: Presentation): JComponent { if (!isActive) { return super.createCustomComponent(action, presentation) } var component = super.createCustomComponent(action, presentation) if (action is ComboBoxAction) { UIUtil.uiTraverser(component).filter(ComboBoxButton::class.java).firstOrNull()?.let { component.remove(it) component = it } } else if (component is ActionButton) { val actionButton = component as ActionButton updateActionButtonLook(actionButton) } component.border = JBUI.Borders.empty() return component } override fun createToolbarButton(action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Dimension): ActionButton { if (!isActive) { return super.createToolbarButton(action, look, place, presentation, minimumSize) } val createToolbarButton = super.createToolbarButton(action, segmentedButtonLook, place, presentation, minimumSize) updateActionButtonLook(createToolbarButton) return createToolbarButton } private fun updateActionButtonLook(actionButton: ActionButton) { actionButton.border = JBUI.Borders.empty(0, 3) actionButton.setLook(segmentedButtonLook) } override fun fillToolBar(actions: List<AnAction>, layoutSecondaries: Boolean) { if (!isActive) { super.fillToolBar(actions, layoutSecondaries) return } val rightAligned: MutableList<AnAction> = ArrayList() for (i in actions.indices) { val action = actions[i] if (action is RightAlignedToolbarAction) { rightAligned.add(action) continue } if (action is CustomComponentAction) { val component = getCustomComponent(action) addMetadata(component, i, actions.size) add(CUSTOM_COMPONENT_CONSTRAINT, component) component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action) } else { val component = createToolbarButton(action) addMetadata(component, i, actions.size) add(ACTION_BUTTON_CONSTRAINT, component) component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action) } } } protected open fun isSuitableAction(action: AnAction): Boolean { return true } override fun paintComponent(g: Graphics) { super.paintComponent(g) paintActiveBorder(g) } private fun paintActiveBorder(g: Graphics) { if((isActive || paintBorderForSingleItem) && visibleActions != null) { SegmentedBarPainter.paintActionBarBorder(this, g) } } override fun paintBorder(g: Graphics) { super.paintBorder(g) paintActiveBorder(g) } override fun paint(g: Graphics) { super.paint(g) paintActiveBorder(g) } private fun addMetadata(component: JComponent, index: Int, count: Int) { if (count == 1) { component.putClientProperty(CONTROL_BAR_PROPERTY, CONTROL_BAR_SINGLE) return } val property = when (index) { 0 -> CONTROL_BAR_FIRST count - 1 -> CONTROL_BAR_LAST else -> CONTROL_BAR_MIDDLE } component.putClientProperty(CONTROL_BAR_PROPERTY, property) } protected open fun logNeeded() = false protected fun forceUpdate() { if(logNeeded()) LOG.info("RunToolbar MAIN SLOT forceUpdate") visibleActions?.let { update(true, it) revalidate() repaint() } } override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) { visibleActions = newVisibleActions update(forced, newVisibleActions) } private var lastIds: List<String> = emptyList() private fun update(forced: Boolean, newVisibleActions: List<AnAction>) { val filtered = newVisibleActions.filter { isSuitableAction(it) } val ides = newVisibleActions.map { ActionManager.getInstance().getId(it) }.toList() val filteredIds = filtered.map { ActionManager.getInstance().getId(it) }.toList() traceState(lastIds, filteredIds, ides) lastIds = filteredIds isActive = filtered.size > 1 super.actionsUpdated(forced, if (isActive) filtered else newVisibleActions) } protected open fun traceState(lastIds: List<String>, filteredIds: List<String>, ides: List<String>) { // if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT new filtered: ${filteredIds}} visible: $ides RunToolbar") } override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) { bounds.clear() for (i in 0 until componentCount) { bounds.add(Rectangle()) } var offset = 0 for (i in 0 until componentCount) { val d = getChildPreferredSize(i) val r = bounds[i] r.setBounds(insets.left + offset, insets.top, d.width, DEFAULT_MINIMUM_BUTTON_SIZE.height) offset += d.width } } }
apache-2.0
cdcea7891cd500995971ed594623945d
31.817391
165
0.704386
4.632904
false
false
false
false
jwren/intellij-community
build/launch/src/com/intellij/tools/launch/impl/ClassPathBuilder.kt
1
4335
package com.intellij.tools.launch.impl import com.intellij.execution.CommandLineWrapperUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.tools.launch.ModulesProvider import com.intellij.tools.launch.PathsProvider import com.intellij.util.SystemProperties import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleDependency import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import java.io.File import java.util.* import java.util.logging.Logger class ClassPathBuilder(private val paths: PathsProvider, private val modules: ModulesProvider) { private val logger = Logger.getLogger(ClassPathBuilder::class.java.name) companion object { fun createClassPathArgFile(paths: PathsProvider, classpath: List<String>): File { val launcherFolder = paths.logFolder if (!launcherFolder.exists()) { launcherFolder.mkdirs() } val classPathArgFile = launcherFolder.resolve("${paths.productId}Launcher_${UUID.randomUUID()}.classpath") CommandLineWrapperUtil.writeArgumentsFile(classPathArgFile, listOf("-classpath", classpath.distinct().joinToString(File.pathSeparator)), Charsets.UTF_8) return classPathArgFile } } private val model = JpsElementFactory.getInstance().createModel() ?: throw Exception("Couldn't create JpsModel") fun build(logClasspath: Boolean): File { val pathVariablesConfiguration = JpsModelSerializationDataService.getOrCreatePathVariablesConfiguration(model.global) val m2HomePath = File(SystemProperties.getUserHome()) .resolve(".m2") .resolve("repository") pathVariablesConfiguration.addPathVariable("MAVEN_REPOSITORY", m2HomePath.canonicalPath) val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) JpsProjectLoader.loadProject(model.project, pathVariables, paths.sourcesRootFolder.canonicalPath) val productionOutput = paths.outputRootFolder.resolve("production") if (!productionOutput.isDirectory) { error("Production classes output directory is missing: $productionOutput") } JpsJavaExtensionService.getInstance().getProjectExtension(model.project)!!.outputUrl = "file://${FileUtil.toSystemIndependentName(paths.outputRootFolder.path)}" val modulesList = arrayListOf<String>() modulesList.add("intellij.platform.boot") modulesList.add(modules.mainModule) modulesList.addAll(modules.additionalModules) modulesList.add("intellij.configurationScript") return createClassPathArgFileForModules(modulesList, logClasspath) } private fun createClassPathArgFileForModules(modulesList: List<String>, logClasspath: Boolean): File { val classpath = mutableListOf<String>() for (moduleName in modulesList) { val module = model.project.modules.singleOrNull { it.name == moduleName } ?: throw Exception("Module $moduleName not found") if (isModuleExcluded(module)) continue classpath.addAll(getClasspathForModule(module)) } // Uncomment for big debug output // seeing as client classpath gets logged anyway, there's no need to comment this out if (logClasspath) { logger.info("Created classpath:") for (path in classpath.distinct().sorted()) { logger.info(" $path") } logger.info("-- END") } else { logger.warning("Verbose classpath logging is disabled, set logClasspath to true to see it.") } return createClassPathArgFile(paths, classpath) } private fun getClasspathForModule(module: JpsModule): List<String> { return JpsJavaExtensionService .dependencies(module) .recursively() .satisfying { if (it is JpsModuleDependency) !isModuleExcluded(it.module) else true } .includedIn(JpsJavaClasspathKind.runtime(modules.includeTestDependencies)) .classes().roots.filter { it.exists() }.map { it.path }.toList() } private fun isModuleExcluded(module: JpsModule?): Boolean { if (module == null) return true return modules.excludedModules.contains(module.name) } }
apache-2.0
5b8d29afec17f6401d4fb64633c0870d
41.097087
158
0.758478
4.898305
false
false
false
false
nonylene/PhotoLinkViewer-Core
photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/view/SaveDialogItemView.kt
1
2442
package net.nonylene.photolinkviewer.core.view import android.content.Context import android.support.v4.view.ViewCompat import android.support.v4.view.animation.FastOutSlowInInterpolator import android.util.AttributeSet import android.view.MotionEvent import android.widget.Checkable import android.widget.EditText import android.widget.ImageView import android.widget.LinearLayout import butterknife.bindView import com.bumptech.glide.Glide import net.nonylene.photolinkviewer.core.R class SaveDialogItemView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs), Checkable { private var mChecked: Boolean = true set(value) { field = value checkedChangeListener?.invoke(value) // request focus to remove focus on other view requestFocus() fileNameEditText.isEnabled = value thumbImageView.imageAlpha = if (value) 0xFF else 0x66 ViewCompat.animate(thumbImageView) .scaleX(if (value) 0.85f else 1.0f) .scaleY(if (value) 0.85f else 1.0f) .setInterpolator(FastOutSlowInInterpolator()) .setDuration(250) .start() thumbCheckImageView.visibility = if (value) VISIBLE else GONE } private val thumbImageView: ImageView by bindView(R.id.path_image_view) private val thumbCheckImageView: ImageView by bindView(R.id.path_check_image_view) private val fileNameEditText: EditText by bindView(R.id.path_edit_text) var checkedChangeListener: ((checked: Boolean) -> Unit)? = null init { setOnClickListener { toggle() } } // pass event or not override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { if (!mChecked) { // if not checked, intercept event on editText onTouchEvent(ev) } return !mChecked } override fun toggle() { mChecked = !mChecked } override fun isChecked(): Boolean { return mChecked } override fun setChecked(checked: Boolean) { mChecked = checked } fun getFileName(): String { return fileNameEditText.text.toString() } fun setFileName(path: CharSequence) { fileNameEditText.setText(path) } fun setThumbnailUrl(url: String) { Glide.with(context.applicationContext).load(url).into(thumbImageView) } }
gpl-2.0
c8614acd29f27e64bd14fb60cb665d15
31.131579
109
0.66421
4.633776
false
false
false
false
alisle/Penella
src/main/java/org/penella/database/DatabaseImpl.kt
1
2203
package org.penella.database import org.penella.index.IIndexFactory import org.penella.index.IndexType import org.penella.query.* import org.penella.shards.Shard import org.penella.store.IStore import org.penella.structures.triples.HashTriple import org.penella.structures.triples.Triple import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* /** * 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. * * * Created by alisle on 9/29/16. */ class DatabaseImpl constructor(val name: String, private val store: IStore, private val indexFactory: IIndexFactory , numberOfShards: Int) : IDatabase { companion object { val log : Logger = LoggerFactory.getLogger(DatabaseImpl::class.java) } private val shards = Array(numberOfShards, { x -> Shard("$name-shard-$x-", indexFactory) }) private val size = shards.size.toLong() private val processor = QueryProcessor(this, store) override fun add(triple : Triple) { if(log.isTraceEnabled) log.trace("Adding $triple to store") store.add(triple) val shard = Math.abs(triple.hash % size).toInt() if(log.isTraceEnabled) log.trace("Adding $triple to shard: $shard") shards[shard].add(triple.hashTriple) } override fun get(indexType: IndexType, triple: HashTriple) : Set<HashTriple> { val set = HashSet<HashTriple>() shards.forEach { it.get(indexType, triple).triples.forEach { x -> set.add(x) } } return set } override fun bulkAdd(triples: Array<Triple>) = triples.forEach { i -> add(i) } override fun query(query: Query) = processor.process(query) override fun size() : Long = shards.fold(0L) { x, y -> x + y.size() } }
apache-2.0
9ec79489ec38254c301de2086c34b69c
36.982759
153
0.709487
3.837979
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/keyvalue/SmsExportPhase.kt
1
1042
package org.thoughtcrime.securesms.keyvalue import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.util.Util import kotlin.time.Duration.Companion.days enum class SmsExportPhase(val duration: Long) { PHASE_0(-1), PHASE_1(0.days.inWholeMilliseconds), PHASE_2(45.days.inWholeMilliseconds), PHASE_3(105.days.inWholeMilliseconds); fun allowSmsFeatures(): Boolean { return this == PHASE_0 || (Util.isDefaultSmsProvider(ApplicationDependencies.getApplication()) && SignalStore.misc().smsExportPhase.isSmsSupported()) } fun isSmsSupported(): Boolean { return this != PHASE_3 } fun isFullscreen(): Boolean { return this.ordinal > PHASE_1.ordinal } fun isBlockingUi(): Boolean { return this == PHASE_3 } fun isAtLeastPhase1(): Boolean { return this.ordinal >= PHASE_1.ordinal } companion object { @JvmStatic fun getCurrentPhase(duration: Long): SmsExportPhase { return values().findLast { duration >= it.duration }!! } } }
gpl-3.0
d4fef1f7698e91d55729b6157abcf95b
25.717949
153
0.723608
3.902622
false
false
false
false
androidx/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/accessibility/Accessibility.kt
3
6411
/* * 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. */ // Ignore lint warnings in documentation snippets @file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE") package androidx.compose.integration.docs.accessibility import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.foundation.selection.toggleable import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Share import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.customActions import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.unit.dp /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/xxxxxxxxxxxxxxx * * No action required if it's modified. */ private object AccessibilitySnippet1 { @Composable fun ShareButton(onClick: () -> Unit) { IconButton(onClick = onClick) { Icon( imageVector = Icons.Filled.Share, contentDescription = stringResource(R.string.label_share) ) } } } private object AccessibilitySnippet2 { @Composable fun PostImage(post: Post, modifier: Modifier = Modifier) { val image = if (post.imageThumb != null) { BitmapPainter(post.imageThumb) } else { painterResource(R.drawable.placeholder) } Image( painter = image, // Specify that this image has no semantic meaning contentDescription = null, modifier = modifier .size(40.dp, 40.dp) .clip(MaterialTheme.shapes.small) ) } } private object AccessibilitySnippet4 { @Composable private fun PostMetadata(metadata: Metadata) { // Merge elements below for accessibility purposes Row(modifier = Modifier.semantics(mergeDescendants = true) {}) { Image( imageVector = Icons.Filled.AccountCircle, // As this image is decorative, contentDescription is set to null contentDescription = null ) Column { Text(metadata.author.name) Text("${metadata.date} • ${metadata.readTimeMinutes} min read") } } } } private object AccessibilitySnippet5 { @Composable fun PostCardSimple( /* ... */ isFavorite: Boolean, onToggleFavorite: () -> Boolean ) { val actionLabel = stringResource( if (isFavorite) R.string.unfavorite else R.string.favorite ) Row( modifier = Modifier .clickable(onClick = { /* ... */ }) .semantics { // Set any explicit semantic properties customActions = listOf( CustomAccessibilityAction(actionLabel, onToggleFavorite) ) } ) { /* ... */ BookmarkButton( isBookmarked = isFavorite, onClick = onToggleFavorite, // Clear any semantics properties set on this node modifier = Modifier.clearAndSetSemantics { } ) } } } private object AccessibilitySnippet6 { @Composable private fun TopicItem(itemTitle: String, selected: Boolean, onToggle: () -> Unit) { val stateSubscribed = stringResource(R.string.subscribed) val stateNotSubscribed = stringResource(R.string.not_subscribed) Row( modifier = Modifier .semantics { // Set any explicit semantic properties stateDescription = if (selected) stateSubscribed else stateNotSubscribed } .toggleable( value = selected, onValueChange = { onToggle() } ) ) { /* ... */ } } } private object AccessibilitySnippet7 { @Composable private fun Subsection(text: String) { Text( text = text, style = MaterialTheme.typography.h5, modifier = Modifier.semantics { heading() } ) } } /* Fakes needed for snippets to build: */ private object R { object string { const val label_share = 4 const val unfavorite = 6 const val favorite = 7 const val subscribed = 8 const val not_subscribed = 9 } object drawable { const val placeholder = 1 } } private class Post(val imageThumb: ImageBitmap? = null) private class Metadata( val author: Author = Author(), val date: String? = null, val readTimeMinutes: String? = null ) private class Author(val name: String = "fake") private class BookmarkButton(isBookmarked: Boolean, onClick: () -> Boolean, modifier: Modifier)
apache-2.0
21b735391547a169dea5a34cabd123f1
31.532995
95
0.647839
4.826054
false
false
false
false
androidx/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/LinearProgressIndicator.kt
3
4494
/* * 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.glance.appwidget import androidx.compose.runtime.Composable import androidx.glance.Emittable import androidx.glance.GlanceModifier import androidx.glance.GlanceNode import androidx.compose.ui.graphics.Color import androidx.glance.unit.ColorProvider /** * Adds a determinate linear progress indicator view to the glance view. * * @param progress of this progress indicator, where 0.0 represents no progress and 1.0 represents full progress * @param modifier the modifier to apply to the progress bar * @param color The color of the progress indicator. * @param backgroundColor The color of the background behind the indicator, visible when the * progress has not reached that area of the overall indicator yet. */ @Composable fun LinearProgressIndicator( /*@FloatRange(from = 0.0, to = 1.0)*/ progress: Float, modifier: GlanceModifier = GlanceModifier, color: ColorProvider = ProgressIndicatorDefaults.IndicatorColorProvider, backgroundColor: ColorProvider = ProgressIndicatorDefaults.BackgroundColorProvider ) { GlanceNode( factory = ::EmittableLinearProgressIndicator, update = { this.set(modifier) { this.modifier = it } this.set(progress) { this.progress = it } this.set(color) { this.color = it } this.set(backgroundColor) { this.backgroundColor = it } } ) } /** * Adds an indeterminate linear progress indicator view to the glance view. * * @param modifier the modifier to apply to the progress bar * @param color The color of the progress indicator. * @param backgroundColor The color of the background behind the indicator, visible when the * progress has not reached that area of the overall indicator yet. */ @Composable fun LinearProgressIndicator( modifier: GlanceModifier = GlanceModifier, color: ColorProvider = ProgressIndicatorDefaults.IndicatorColorProvider, backgroundColor: ColorProvider = ProgressIndicatorDefaults.BackgroundColorProvider ) { GlanceNode( factory = ::EmittableLinearProgressIndicator, update = { this.set(modifier) { this.modifier = it } this.set(true) { this.indeterminate = it } this.set(color) { this.color = it } this.set(backgroundColor) { this.backgroundColor = it } } ) } internal class EmittableLinearProgressIndicator : Emittable { override var modifier: GlanceModifier = GlanceModifier var progress: Float = 0.0f var indeterminate: Boolean = false var color: ColorProvider = ProgressIndicatorDefaults.IndicatorColorProvider var backgroundColor: ColorProvider = ProgressIndicatorDefaults.BackgroundColorProvider override fun copy(): Emittable = EmittableLinearProgressIndicator().also { it.modifier = modifier it.progress = progress it.indeterminate = indeterminate it.color = color it.backgroundColor = backgroundColor } override fun toString(): String = "EmittableLinearProgressIndicator(" + "modifier=$modifier, " + "progress=$progress, " + "indeterminate=$indeterminate, " + "color=$color, " + "backgroundColor=$backgroundColor" + ")" } /** * Contains the default values used for [LinearProgressIndicator]. */ object ProgressIndicatorDefaults { /** * Default color for [LinearProgressIndicator]. * [Material color specification](https://material.io/design/color/the-color-system.html#color-theme-creation) */ private val Color = Color(0xFF6200EE) /** * Default ColorProvider for the progress indicator in [LinearProgressIndicator]. */ val IndicatorColorProvider = ColorProvider(Color) /** * Default ColorProvider for the background in [LinearProgressIndicator]. */ val BackgroundColorProvider = ColorProvider(Color.copy(alpha = 0.24f)) }
apache-2.0
e7af678a7a3e3005a2e1638a953177d8
35.536585
112
0.719849
4.796158
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/src/service/project/GradleDependencyCollector.kt
3
2394
// 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.plugins.gradle.service.project import com.intellij.ide.plugins.DependencyCollector import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginAdvertiserService import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.util.GradleConstants internal class GradleDependencyCollector : DependencyCollector { override fun collectDependencies(project: Project): Set<String> { return ProjectDataManager.getInstance() .getExternalProjectsData(project, GradleConstants.SYSTEM_ID) .asSequence() .mapNotNull { it.externalProjectStructure } .flatMap { projectStructure -> projectStructure.getChildrenSequence(ProjectKeys.MODULE) .flatMap { it.getChildrenSequence(GradleSourceSetData.KEY) } .flatMap { it.getChildrenSequence(ProjectKeys.LIBRARY_DEPENDENCY) } }.map { it.data.target } .mapNotNull { libraryData -> val groupId = libraryData.groupId val artifactId = libraryData.artifactId if (groupId != null && artifactId != null) "$groupId:$artifactId" else null }.toSet() } private fun <T> DataNode<*>.getChildrenSequence(key: Key<T>) = ExternalSystemApiUtil.getChildren(this, key).asSequence() } internal class GradleDependencyUpdater : ExternalSystemTaskNotificationListenerAdapter() { override fun onEnd(id: ExternalSystemTaskId) { if (id.projectSystemId == GradleConstants.SYSTEM_ID && id.type == ExternalSystemTaskType.RESOLVE_PROJECT) { id.findProject()?.let { PluginAdvertiserService.getInstance(it).rescanDependencies() } } } }
apache-2.0
a0af73f287cd3fd234f6074b1ef754f5
46.88
122
0.783626
4.936082
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IntroduceBackingPropertyIntention.kt
3
6045
// 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 org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext class IntroduceBackingPropertyIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("introduce.backing.property") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean { if (!canIntroduceBackingProperty(element)) return false return element.nameIdentifier?.textRange?.containsOffset(caretOffset) == true } override fun applyTo(element: KtProperty, editor: Editor?) = introduceBackingProperty(element) companion object { fun canIntroduceBackingProperty(property: KtProperty): Boolean { val name = property.name ?: return false if (property.hasModifier(KtTokens.CONST_KEYWORD)) return false if (property.hasJvmFieldAnnotation()) return false val bindingContext = property.getResolutionFacade().analyzeWithAllCompilerChecks(property).bindingContext val descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, property) as? PropertyDescriptor ?: return false if (bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor) != true) return false val containingClass = property.getStrictParentOfType<KtClassOrObject>() ?: return false if (containingClass.isExpectDeclaration()) return false return containingClass.declarations.none { it is KtProperty && it.name == "_$name" } } fun introduceBackingProperty(property: KtProperty) { createBackingProperty(property) property.removeModifier(KtTokens.LATEINIT_KEYWORD) if (property.typeReference == null) { val type = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(property) SpecifyTypeExplicitlyIntention.addTypeAnnotation(null, property, type) } val getter = property.getter if (getter == null) { createGetter(property) } else { replaceFieldReferences(getter, property.name!!) } if (property.isVar) { val setter = property.setter if (setter == null) { createSetter(property) } else { replaceFieldReferences(setter, property.name!!) } } property.initializer = null } private fun createGetter(element: KtProperty) { val body = "get() = ${backingName(element)}" val newGetter = KtPsiFactory(element).createProperty("val x $body").getter!! element.addAccessor(newGetter) } private fun createSetter(element: KtProperty) { val body = "set(value) { ${backingName(element)} = value }" val newSetter = KtPsiFactory(element).createProperty("val x $body").setter!! element.addAccessor(newSetter) } private fun KtProperty.addAccessor(newAccessor: KtPropertyAccessor) { val semicolon = node.findChildByType(KtTokens.SEMICOLON) addBefore(newAccessor, semicolon?.psi) } private fun createBackingProperty(property: KtProperty) { val backingProperty = KtPsiFactory(property).buildDeclaration { appendFixedText("private ") appendFixedText(property.valOrVarKeyword.text) appendFixedText(" ") appendNonFormattedText(backingName(property)) if (property.typeReference != null) { appendFixedText(": ") appendTypeReference(property.typeReference) } if (property.initializer != null) { appendFixedText(" = ") appendExpression(property.initializer) } } if (property.hasModifier(KtTokens.LATEINIT_KEYWORD)) { backingProperty.addModifier(KtTokens.LATEINIT_KEYWORD) } property.parent.addBefore(backingProperty, property) } private fun backingName(property: KtProperty): String { return if (property.nameIdentifier?.text?.startsWith('`') == true) "`_${property.name}`" else "_${property.name}" } private fun replaceFieldReferences(element: KtElement, propertyName: String) { element.acceptChildren(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val target = expression.resolveToCall()?.resultingDescriptor if (target is SyntheticFieldDescriptor) { expression.replace(KtPsiFactory(element).createSimpleName("_$propertyName")) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { // don't go into accessors of properties in local classes because 'field' will mean something different in them } }) } } }
apache-2.0
b4489a9d7e17f929b14c9f8e7b0fefac
44.451128
158
0.653929
5.581717
false
false
false
false
kivensolo/UiUsingListView
module-Demo/src/main/java/com/zeke/demo/meterial/AppBarNormalActivity.kt
1
1354
package com.zeke.demo.meterial import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.kingz.module.common.adapter.SimpleLabelAdapter import com.zeke.demo.R import java.util.* /** * author:ZekeWang * date:2021/2/28 * description:常规的上下隐藏效果的Demo */ class AppBarNormalActivity: AppCompatActivity() { private var mAdapter: SimpleLabelAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_appbarlayout_normal) val datas = ArrayList<String>() for (i in 0..29) { datas.add(String.format("我是第%s个Item", i + 1)) } mAdapter = SimpleLabelAdapter(datas) val recyclerView = findViewById<RecyclerView>(R.id.content_recycler) recyclerView?.apply { addItemDecoration( DividerItemDecoration( this@AppBarNormalActivity, DividerItemDecoration.VERTICAL ) ) layoutManager = LinearLayoutManager(this@AppBarNormalActivity) adapter = mAdapter } } }
gpl-2.0
4a420f898baacf5dbc8713c23a7154a0
32.025
76
0.684848
4.765343
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/testing/library_user.kt
4
1764
import kotlin.native.internal.test.* import kotlin.test.* import library.* open class B : A() { // Override test methods without a test annotation. // We should run these methods anyway. override fun before() { output.add("B.before") } // test0 should be executed. // Should be executed. override fun test1() { output.add("B.test1") } // Should be executed @Ignore override fun test2() { output.add("B.test2") } // Should be ignored. @Ignore @Test override fun test3() { output.add("B.test3") } // ignored0 should be ignored. // Should be ignored. override fun ignored1() { output.add("B.ignored1") } // Should be executed. @Test override fun ignored2() { output.add("B.ignored2") } } // All test methods from B should be executed for C. class C: B() {} class D: I1, I2 { // This method shouldn't be executed because its parent methods annotated // with @Test belong to an interface instead of an abstract class. override fun foo(){ output.add("D.foo") } } fun main(args: Array<String>) { testLauncherEntryPoint(args) output.forEach(::println) assertEquals(8, output.count { it == "A.after" }) assertEquals(8, output.count { it == "B.before" }) assertEquals(2, output.count { it == "A.test0" }) assertEquals(2, output.count { it == "B.test1" }) assertEquals(2, output.count { it == "B.test2" }) assertEquals(2, output.count { it == "B.ignored2" }) assertTrue(output.none { it == "B.test3" }) assertTrue(output.none { it == "A.ignored0" }) assertTrue(output.none { it == "B.ignored1" }) assertTrue(output.none { it == "D.foo" }) }
apache-2.0
c9872d6cc8b7de668ee43511a54aac4c
22.851351
77
0.598639
3.578093
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkUpdater.kt
5
7152
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.projectRoots.impl.jdkDownloader import com.intellij.ProjectTopics import com.intellij.execution.wsl.WslDistributionManager import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.* import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.ui.configuration.UnknownSdk import com.intellij.openapi.startup.ProjectPostStartupActivity import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.text.VersionComparatorUtil import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong /** * This extension point is used to collect * additional [Sdk] instances to check for a possible * JDK update */ private val EP_NAME = ExtensionPointName.create<JdkUpdateCheckContributor>("com.intellij.jdkUpdateCheckContributor") interface JdkUpdateCheckContributor { /** * Executed from any thread (possibly without read-lock) to * collect SDKs, which should be considered for * JDK Update check */ fun contributeJdks(project: Project): List<Sdk> } private fun isEnabled(project: Project) = !project.isDefault && Registry.`is`("jdk.updater") && !ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment internal class JdkUpdaterStartup : ProjectPostStartupActivity { override suspend fun execute(project: Project) { if (!isEnabled(project)) { return } project.service<JdkUpdatesCollector>().updateNotifications() } } private val LOG = logger<JdkUpdatesCollector>() @Service // project private class JdkUpdatesCollectorQueue : UnknownSdkCollectorQueue(7_000) @Service internal class JdkUpdatesCollector( private val project: Project ) : Disposable { override fun dispose() = Unit init { schedule() } private fun isEnabled() = isEnabled(project) private fun schedule() { if (!isEnabled()) return val future = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay( Runnable { if (project.isDisposed) return@Runnable try { updateNotifications() } catch (t: Throwable) { if (t is ControlFlowException) return@Runnable LOG.warn("Failed to complete JDK Update check. ${t.message}", t) } }, 12, 12, TimeUnit.HOURS ) Disposer.register(this, Disposable { future.cancel(false) }) val myLastKnownModificationId = AtomicLong(-100_500) project.messageBus .connect(this) .subscribe( ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { if (event.isCausedByFileTypesChange) return //an optimization - we do not scan for JDKs if there we no ProjectRootManager modifications change //this avoids VirtualFilePointers invalidation val newCounterValue = ProjectRootManager.getInstance(project).modificationCount if (myLastKnownModificationId.getAndSet(newCounterValue) == newCounterValue) return updateNotifications() } }) } fun updateNotifications() { if (!isEnabled()) return project.service<JdkUpdatesCollectorQueue>().queue(object: UnknownSdkTrackerTask { override fun createCollector(): UnknownSdkCollector? { if (!isEnabled()) return null return object : UnknownSdkCollector(project) { override fun getContributors(): List<UnknownSdkContributor> { return super.getContributors() + EP_NAME.extensionList.map { object : UnknownSdkContributor { override fun contributeUnknownSdks(project: Project) = listOf<UnknownSdk>() override fun contributeKnownSdks(project: Project): List<Sdk> = it.contributeJdks(project) } } } } } override fun onLookupCompleted(snapshot: UnknownSdkSnapshot) { if (!isEnabled()) return //this callback happens in the GUI thread! val knownSdks = snapshot .knownSdks .filter { it.sdkType is JavaSdkType && it.sdkType !is DependentSdkType } if (knownSdks.isEmpty()) return ProgressManager.getInstance().run( object : Task.Backgroundable(project, ProjectBundle.message("progress.title.checking.for.jdk.updates"), true, ALWAYS_BACKGROUND) { override fun run(indicator: ProgressIndicator) { updateWithSnapshot(knownSdks.distinct().sortedBy { it.name }, indicator) } } ) } }) } private fun updateWithSnapshot(knownSdks: List<Sdk>, indicator: ProgressIndicator) { val jdkFeed by lazy { val listDownloader = JdkListDownloader.getInstance() var items = listDownloader.downloadModelForJdkInstaller(predicate = JdkPredicate.default(), progress = indicator) if (SystemInfo.isWindows && WslDistributionManager.getInstance().installedDistributions.isNotEmpty()) { @Suppress("SuspiciousCollectionReassignment") items += listDownloader.downloadModelForJdkInstaller(predicate = JdkPredicate.forWSL(), progress = indicator) } items.toList() } val notifications = service<JdkUpdaterNotifications>() val noUpdatesFor = HashSet<Sdk>(knownSdks) for (jdk in knownSdks) { val actualItem = JdkInstaller.getInstance().findJdkItemForInstalledJdk(jdk.homePath) ?: continue val feedItem = jdkFeed.firstOrNull { it.suggestedSdkName == actualItem.suggestedSdkName && it.arch == actualItem.arch && it.os == actualItem.os } ?: continue //internal versions are not considered here (JBRs?) if (VersionComparatorUtil.compare(feedItem.jdkVersion, actualItem.jdkVersion) <= 0) continue notifications.showNotification(jdk, actualItem, feedItem) noUpdatesFor -= jdk } //handle the case, when a JDK is no longer requires an update for (jdk in noUpdatesFor) { notifications.hideNotification(jdk) } } }
apache-2.0
88608bdace89828a781cf5ea9a860c1e
35.865979
140
0.712808
4.885246
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRReviewThreadsPanel.kt
4
2787
// 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.timeline import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.application.ApplicationBundle import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.SingleComponentCenteringLayout import com.intellij.util.ui.UIUtil import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadModel import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener object GHPRReviewThreadsPanel { fun create(model: GHPRReviewThreadsModel, threadComponentFactory: (GHPRReviewThreadModel) -> JComponent): JComponent { val panel = JPanel(VerticalLayout(JBUIScale.scale(12))).apply { isOpaque = false } val loadingPanel = JPanel(SingleComponentCenteringLayout()).apply { isOpaque = false add(JLabel(ApplicationBundle.message("label.loading.page.please.wait")).apply { foreground = UIUtil.getContextHelpForeground() }) } Controller(model, panel, loadingPanel, threadComponentFactory) return panel } private class Controller(private val model: GHPRReviewThreadsModel, private val panel: JPanel, private val loadingPanel: JPanel, private val threadComponentFactory: (GHPRReviewThreadModel) -> JComponent) { init { model.addListDataListener(object : ListDataListener { override fun intervalRemoved(e: ListDataEvent) { for (i in e.index1 downTo e.index0) { panel.remove(i) } updateVisibility() panel.revalidate() panel.repaint() } override fun intervalAdded(e: ListDataEvent) { for (i in e.index0..e.index1) { panel.add(threadComponentFactory(model.getElementAt(i)), VerticalLayout.FILL_HORIZONTAL, i) } updateVisibility() panel.revalidate() panel.repaint() } override fun contentsChanged(e: ListDataEvent) { if (model.loaded) panel.remove(loadingPanel) updateVisibility() panel.validate() panel.repaint() } }) if (!model.loaded) { panel.add(loadingPanel, VerticalLayout.FILL_HORIZONTAL) } else for (i in 0 until model.size) { panel.add(threadComponentFactory(model.getElementAt(i)), VerticalLayout.FILL_HORIZONTAL, i) } updateVisibility() } private fun updateVisibility() { panel.isVisible = panel.componentCount > 0 } } }
apache-2.0
e455502ac23299bb1f713faa3c01e143
33.85
140
0.678149
4.78866
false
false
false
false
smmribeiro/intellij-community
jps/jps-builders/testSrc/org/jetbrains/jps/builders/ModuleClasspathTest.kt
13
4134
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.builders import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtil.toCanonicalPath import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName import com.intellij.openapi.util.text.StringUtil import org.jetbrains.jps.ModuleChunk import org.jetbrains.jps.ProjectPaths import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.incremental.ModuleBuildTarget import org.junit.Assert import java.io.File class ModuleClasspathTest : JpsBuildTestCase() { override fun setUp() { super.setUp() addJdk("1.6", "/jdk.jar") addJdk("1.5", "/jdk15.jar") loadProject("moduleClasspath/moduleClasspath.ipr") } private fun getProjectPath() = FileUtil.toSystemIndependentName(testDataRootPath) + "/moduleClasspath/moduleClasspath.ipr" override fun getTestDataRootPath(): String = FileUtil.toCanonicalPath(PathManagerEx.findFileUnderCommunityHome("jps/jps-builders/testData/output")!!.absolutePath, '/')!! fun testSimpleClasspath() { assertClasspath("util", false, listOf("util/lib/exported.jar", "/jdk15.jar")) } fun testScopes() { assertClasspath("test-util", false, listOf("/jdk.jar", "test-util/lib/provided.jar")) assertClasspath("test-util", true, listOf("/jdk.jar", "test-util/lib/provided.jar", "test-util/lib/test.jar", "out/production/test-util")) } fun testDepModules() { assertClasspath("main", false, listOf("util/lib/exported.jar", "out/production/util", "/jdk.jar", "main/lib/service.jar")) assertClasspath("main", true, listOf("out/production/main", "util/lib/exported.jar", "out/test/util", "out/production/util", "/jdk.jar", "out/test/test-util", "out/production/test-util", "main/lib/service.jar")) } fun testCompilationClasspath() { val chunk = createChunk("main") assertClasspath(listOf("util/lib/exported.jar", "out/production/util", "/jdk.jar"), getPathsList(ProjectPaths.getPlatformCompilationClasspath(chunk, true))) assertClasspath(listOf("main/lib/service.jar"), getPathsList(ProjectPaths.getCompilationClasspath(chunk, true))) assertClasspath(listOf("main/lib/service.jar"), getPathsList(ProjectPaths.getCompilationModulePath(chunk, true))) } private fun assertClasspath(moduleName: String, includeTests: Boolean, expected: List<String>) { val classpath = getPathsList(ProjectPaths.getCompilationClasspathFiles(createChunk(moduleName), includeTests, true, true)) assertClasspath(expected, toSystemIndependentPaths(classpath)) } private fun createChunk(moduleName: String): ModuleChunk { val module = myProject.modules.first { it.name == moduleName } return ModuleChunk(setOf(ModuleBuildTarget(module, JavaModuleBuildTargetType.PRODUCTION))) } private fun assertClasspath(expected: List<String>, classpath: List<String>) { val basePath = FileUtil.toSystemIndependentName(File(getProjectPath()).parentFile!!.absolutePath) + "/" val actual = toSystemIndependentPaths(classpath).map { StringUtil.trimStart(it, basePath) } Assert.assertEquals(expected.joinToString("\n"), actual.joinToString("\n")) } private fun toSystemIndependentPaths(classpath: List<String>) = classpath.map(FileUtil::toSystemIndependentName) private fun getPathsList(files: Collection<File>): List<String> { return files.map { file -> val path = file.path if (path.contains(".")) toCanonicalPath(path)!! else toSystemIndependentName(path) } } }
apache-2.0
85bb929f0e4812d28804e1c5d6b416d3
45.988636
215
0.753749
4.10119
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/DefaultAnnotationMethodKotlinImplicitReferenceSearcher.kt
3
2763
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.ideaExtensions import com.intellij.openapi.application.QueryExecutorBase import com.intellij.openapi.application.ReadActionProcessor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReference import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiUtil import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.idea.references.ReferenceImpl as ImplicitReference class DefaultAnnotationMethodKotlinImplicitReferenceSearcher : QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters>(true) { private val PsiMethod.isDefaultAnnotationMethod: Boolean get() = PsiUtil.isAnnotationMethod(this) && name == PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME && parameterList.parametersCount == 0 private fun createReferenceProcessor(consumer: Processor<in PsiReference>) = object : ReadActionProcessor<PsiReference>() { override fun processInReadAction(reference: PsiReference): Boolean { if (reference !is KtSimpleNameReference) return true val annotationEntry = reference.expression.getParentOfTypeAndBranch<KtAnnotationEntry> { typeReference } ?: return true val argument = annotationEntry.valueArguments.singleOrNull() as? KtValueArgument ?: return true val implicitRef = argument.references.firstIsInstanceOrNull<ImplicitReference>() ?: return true return consumer.process(implicitRef) } } override fun processQuery(queryParameters: MethodReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { runReadAction { val method = queryParameters.method if (!method.isDefaultAnnotationMethod) return@runReadAction null val annotationClass = method.containingClass ?: return@runReadAction null val searchScope = queryParameters.effectiveSearchScope.restrictToKotlinSources() ReferencesSearch.search(annotationClass, searchScope) }?.forEach(createReferenceProcessor(consumer)) } }
apache-2.0
6ebdc2323532440830083ecae04fe266
57.787234
158
0.794426
5.375486
false
false
false
false
mr-max/anko
dsl/testData/functional/recyclerview-v7/ComplexListenerClassTest.kt
3
3191
class __RecyclerView_OnChildAttachStateChangeListener : android.support.v7.widget.RecyclerView.OnChildAttachStateChangeListener { private var _onChildViewAttachedToWindow: ((android.view.View?) -> Unit)? = null private var _onChildViewDetachedFromWindow: ((android.view.View?) -> Unit)? = null override fun onChildViewAttachedToWindow(view: android.view.View?) { _onChildViewAttachedToWindow?.invoke(view) } public fun onChildViewAttachedToWindow(listener: (android.view.View?) -> Unit) { _onChildViewAttachedToWindow = listener } override fun onChildViewDetachedFromWindow(view: android.view.View?) { _onChildViewDetachedFromWindow?.invoke(view) } public fun onChildViewDetachedFromWindow(listener: (android.view.View?) -> Unit) { _onChildViewDetachedFromWindow = listener } } class __RecyclerView_OnScrollListener : android.support.v7.widget.RecyclerView.OnScrollListener() { private var _onScrollStateChanged: ((android.support.v7.widget.RecyclerView?, Int) -> Unit)? = null private var _onScrolled: ((android.support.v7.widget.RecyclerView?, Int, Int) -> Unit)? = null override fun onScrollStateChanged(recyclerView: android.support.v7.widget.RecyclerView?, newState: Int) { _onScrollStateChanged?.invoke(recyclerView, newState) } public fun onScrollStateChanged(listener: (android.support.v7.widget.RecyclerView?, Int) -> Unit) { _onScrollStateChanged = listener } override fun onScrolled(recyclerView: android.support.v7.widget.RecyclerView?, dx: Int, dy: Int) { _onScrolled?.invoke(recyclerView, dx, dy) } public fun onScrolled(listener: (android.support.v7.widget.RecyclerView?, Int, Int) -> Unit) { _onScrolled = listener } } class __RecyclerView_OnItemTouchListener : android.support.v7.widget.RecyclerView.OnItemTouchListener { private var _onInterceptTouchEvent: ((android.support.v7.widget.RecyclerView?, android.view.MotionEvent?) -> Boolean)? = null private var _onTouchEvent: ((android.support.v7.widget.RecyclerView?, android.view.MotionEvent?) -> Unit)? = null private var _onRequestDisallowInterceptTouchEvent: ((Boolean) -> Unit)? = null override fun onInterceptTouchEvent(rv: android.support.v7.widget.RecyclerView?, e: android.view.MotionEvent?) = _onInterceptTouchEvent?.invoke(rv, e) ?: false public fun onInterceptTouchEvent(listener: (android.support.v7.widget.RecyclerView?, android.view.MotionEvent?) -> Boolean) { _onInterceptTouchEvent = listener } override fun onTouchEvent(rv: android.support.v7.widget.RecyclerView?, e: android.view.MotionEvent?) { _onTouchEvent?.invoke(rv, e) } public fun onTouchEvent(listener: (android.support.v7.widget.RecyclerView?, android.view.MotionEvent?) -> Unit) { _onTouchEvent = listener } override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { _onRequestDisallowInterceptTouchEvent?.invoke(disallowIntercept) } public fun onRequestDisallowInterceptTouchEvent(listener: (Boolean) -> Unit) { _onRequestDisallowInterceptTouchEvent = listener } }
apache-2.0
8bc60d0e89fd39fa71036ad8acb21a91
43.333333
162
0.731119
4.611272
false
false
false
false
mr-max/anko
preview/xml-converter/testData/attributes/layout.kt
6
773
frameLayout { textView("Text") { backgroundColor = 0xff0000.opaque enabled = false hint = "Hint" id = Ids.textView1 lines = 5 paddingBottom = dip(4) paddingLeft = dip(1) paddingRight = dip(3) paddingTop = dip(2) tag = "Tag" textColor = 0x00ff00.opaque textSize = 17f visibility = View.INVISIBLE }.layoutParams(width = wrapContent, height = wrapContent) textView { backgroundColor = 0xeeffff00.toInt() textSize = 17f }.layoutParams(width = wrapContent, height = wrapContent) textView { backgroundResource = android.R.color.background_light textSize = 17f }.layoutParams(width = wrapContent, height = wrapContent) }
apache-2.0
7babf9b7e558ed5532a41a7667c56797
29.96
61
0.602846
4.60119
false
false
true
false
mr-max/anko
dsl/testData/functional/design/ComplexListenerClassTest.kt
3
2083
class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener { private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) { _onChildViewAdded?.invoke(parent, child) } public fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) { _onChildViewAdded = listener } override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) { _onChildViewRemoved?.invoke(parent, child) } public fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) { _onChildViewRemoved = listener } } class __TabLayout_OnTabSelectedListener : android.support.design.widget.TabLayout.OnTabSelectedListener { private var _onTabSelected: ((android.support.design.widget.TabLayout.Tab?) -> Unit)? = null private var _onTabUnselected: ((android.support.design.widget.TabLayout.Tab?) -> Unit)? = null private var _onTabReselected: ((android.support.design.widget.TabLayout.Tab?) -> Unit)? = null override fun onTabSelected(tab: android.support.design.widget.TabLayout.Tab?) { _onTabSelected?.invoke(tab) } public fun onTabSelected(listener: (android.support.design.widget.TabLayout.Tab?) -> Unit) { _onTabSelected = listener } override fun onTabUnselected(tab: android.support.design.widget.TabLayout.Tab?) { _onTabUnselected?.invoke(tab) } public fun onTabUnselected(listener: (android.support.design.widget.TabLayout.Tab?) -> Unit) { _onTabUnselected = listener } override fun onTabReselected(tab: android.support.design.widget.TabLayout.Tab?) { _onTabReselected?.invoke(tab) } public fun onTabReselected(listener: (android.support.design.widget.TabLayout.Tab?) -> Unit) { _onTabReselected = listener } }
apache-2.0
373f0dab42e2cd95311830c528f94ad2
39.076923
105
0.702832
4.348643
false
false
false
false
tlaukkan/kotlin-web-vr
client/test/JsonTests.kt
1
3254
import util.fromJson import util.toJson import java.util.* class Pair(val key: String, val value: String) class Test(val pairs: Array<Pair> = arrayOf(), val obj: Pair? = null) { fun print() { println(this) } } fun <V> PrimitiveHashMap(container: dynamic): HashMap<String, Any> { val m = HashMap<String, Any>().asDynamic() m.map = container val keys = js("Object.keys") m.`$size` = keys(container).length return m } /* fun deepCopy(source: Any, target: Any) { val sourceMap = PrimitiveHashMap<Any>(source) val targetMap = PrimitiveHashMap<Any>(target) println("Target value type: ${target.jsClass.name}") for (key in sourceMap.keys) { val sourceValue = sourceMap[key] val sourceValueString = JSON.stringify(sourceValue!!) val sourceValueType = sourceValue.jsClass.name println("$key=$sourceValueString ($sourceValueType)") if (!sourceValueType.equals("String")) { val targetValue = targetMap[key] if (sourceValue != null && sourceValue != undefined) { if (targetValue != null) { deepCopy(sourceValue, targetValue) } else { println("Target value null.") } } } else { if (sourceValue != null && sourceValue != undefined) { targetMap[key] = sourceValue!! } } } } */ fun jsonTests() { qunit.test( "json parser test") { val test: Test = fromJson("{\"pairs\": [{\"key\":\"ka\", \"value\":\"va\"}, {\"key\":\"kb\", \"value\":\"vb\"}, {\"key\":\"kc\", \"value\":\"vc\"}], \"obj\": {\"key\":\"kd\", \"value\":\"vd\"}}") assert.equal(test.pairs[0].key, "ka") assert.equal(test.pairs[0].value, "va") assert.equal(test.pairs[1].key, "kb") assert.equal(test.pairs[1].value, "vb") assert.equal(test.pairs[2].key, "kc") assert.equal(test.pairs[2].value, "vc") assert.equal(test.obj!!.key, "kd") assert.equal(test.obj!!.value, "vd") val testJson = toJson(test) val test2: Test = fromJson(testJson) assert.equal(test2.pairs[0].key, "ka") assert.equal(test2.pairs[0].value, "va") assert.equal(test2.pairs[1].key, "kb") assert.equal(test2.pairs[1].value, "vb") assert.equal(test2.pairs[2].key, "kc") assert.equal(test2.pairs[2].value, "vc") assert.equal(test2.obj!!.key, "kd") assert.equal(test2.obj!!.value, "vd") //println(test.display()) /*val testCopy: Test = Test() deepCopy(test, testCopy) assert.equal(testCopy.pairs[0].key, "ka") assert.equal(testCopy.pairs[0].value, "va") assert.equal(testCopy.pairs[1].key, "kb") assert.equal(testCopy.pairs[1].value, "vb") assert.equal(testCopy.pairs[2].key, "kc") assert.equal(testCopy.pairs[2].value, "vc") assert.equal(JSON.stringify(test), JSON.stringify(testCopy)) testCopy.display()*/ /*val testCopy: Test = Test(arrayOf()) val map = PrimitiveHashMap<Any>(test) for (property in map.keys) { println(property + "=" + map[property]) }*/ } }
mit
e7e6e293d6ca56feb0824c53c80f5d8f
32.214286
203
0.562999
3.615556
false
true
false
false
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/bookmarklist/BookmarkListAdapter.kt
1
3472
package me.kirimin.mitsumine.bookmarklist import android.content.Context import android.text.TextUtils import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import com.makeramen.RoundedTransformationBuilder import com.squareup.picasso.Picasso import me.kirimin.mitsumine.R import me.kirimin.mitsumine._common.domain.model.Bookmark import me.kirimin.mitsumine._common.network.repository.StarRepository import rx.Subscription class BookmarkListAdapter(context: Context, val presenter: BookmarkListPresenter, val entryId: String) : ArrayAdapter<Bookmark>(context, 0) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view: View val holder: ViewHolder if (convertView == null) { view = LayoutInflater.from(context).inflate(R.layout.row_bookmark_list, null) val popupWindow = BookmarkPopupWindowBuilder.build(context) holder = ViewHolder(view, popupWindow) view.tag = holder holder.comment.movementMethod = LinkMovementMethod.getInstance() holder.more.setOnClickListener { v -> popupWindow.showAsDropDown(v, v.width, -v.height); } } else { view = convertView holder = view.tag as ViewHolder } val bookmark = getItem(position) holder.cardView.tag = bookmark holder.userName.text = bookmark.user holder.comment.text = bookmark.comment holder.tag.text = TextUtils.join(", ", bookmark.tags) holder.timeStamp.text = bookmark.timestamp holder.stars.visibility = View.GONE if (holder.stars.tag is Subscription) { (holder.stars.tag as Subscription).unsubscribe() } holder.stars.visibility = View.GONE bookmark.stars?.let { if (it.allStarsCount > 0) { holder.stars.visibility = View.VISIBLE holder.stars.text = it.allStarsCount.toString() } } val transformation = RoundedTransformationBuilder().borderWidthDp(0f).cornerRadiusDp(32f).oval(false).build() Picasso.with(context).load(bookmark.userIcon).fit().transform(transformation).into(holder.userIcon) holder.popupList.setOnItemClickListener { adapterView, view, i, l -> presenter.onMoreIconClick(bookmark, entryId, i) holder.popupWindow.dismiss() } return view } class ViewHolder(view: View, val popupWindow: PopupWindow) { val cardView: View = view.findViewById(R.id.card_view) val userName: TextView = view.findViewById(R.id.BookmarkListUserNameTextView) as TextView val userIcon: ImageView = view.findViewById(R.id.BookmarkListUserIconImageView) as ImageView val comment: TextView = view.findViewById(R.id.BookmarkListCommentTextView) as TextView val tag: TextView = view.findViewById(R.id.BookmarkListUserTagTextView) as TextView val timeStamp: TextView = view.findViewById(R.id.BookmarkListTimeStampTextView) as TextView val stars: TextView = view.findViewById(R.id.BookmarkListStarsTextView) as TextView val more: ImageView = view.findViewById(R.id.BookmarkListMoreImageView) as ImageView val popupList: ListView = popupWindow.contentView.findViewById(R.id.popupWindowListView) as ListView } }
apache-2.0
8a6d8d1a970714cb83feea7b1d184497
44.090909
141
0.698157
4.538562
false
false
false
false
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/_common/domain/model/Bookmark.kt
1
1306
package me.kirimin.mitsumine._common.domain.model import android.text.Html import me.kirimin.mitsumine._common.network.entity.BookmarkResponse import java.io.Serializable import java.util.regex.Pattern open class Bookmark(private val response: BookmarkResponse) : Serializable { var stars: Stars? = null val user: String get() = response.user val tags: List<String> get() = response.tags val timestamp: String get() = response.timestamp?.let { it.substring(0, it.indexOf(" ")) } ?: "" val comment: CharSequence get() = response.comment?.let { parseCommentToHtmlTag(it) } ?: "" val userIcon: String get() = "http://cdn1.www.st-hatena.com/users/" + user.subSequence(0, 2) + "/" + user + "/profile.gif" val hasComment = comment.toString() != "" val isPrivate get() = response.private private fun parseCommentToHtmlTag(comment: String): CharSequence { val matcher = urlLinkPattern.matcher(comment) return Html.fromHtml(matcher.replaceAll("<a href=\"$0\">$0</a>")) } class EmptyBookmark : Bookmark(BookmarkResponse()) companion object { private val urlLinkPattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:\\#\\?\\=\\&\\;\\%\\~\\+]+", Pattern.CASE_INSENSITIVE) } }
apache-2.0
76fce3a63c71c6def61907cb167aa5be
30.119048
141
0.643951
3.921922
false
false
false
false
google/secrets-gradle-plugin
secrets-gradle-plugin/src/main/java/com/google/android/libraries/mapsplatform/secrets_gradle_plugin/SecretsPluginExtension.kt
1
1385
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.mapsplatform.secrets_gradle_plugin /** * Configuration object for [SecretsPlugin]. */ open class SecretsPluginExtension { /** * The name of the properties file containing secrets. Defaults to "$defaultPropertiesFile" */ var propertiesFileName: String = defaultPropertiesFile /** * A list of keys this plugin should ignore and not inject. Defaults to $defaultIgnoreList */ var ignoreList: MutableList<String> = defaultIgnoreList /** * The name of the properties file containing secrets' default values. */ var defaultPropertiesFileName: String? = null companion object { const val defaultPropertiesFile = "local.properties" val defaultIgnoreList = mutableListOf("sdk.dir") } }
apache-2.0
ae889ef20f487fbc49a614c44306ec6c
33.65
95
0.722022
4.647651
false
false
false
false
badoualy/kotlogram
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTRpcResult.kt
1
1155
package com.github.badoualy.telegram.mtproto.tl import com.github.badoualy.telegram.tl.StreamUtils.* import com.github.badoualy.telegram.tl.TLContext import com.github.badoualy.telegram.tl.core.TLObject import java.io.IOException import java.io.InputStream import java.io.OutputStream class MTRpcResult @JvmOverloads constructor(var messageId: Long = 0, var content: ByteArray = ByteArray(0), var contentLen: Int = 0) : TLObject() { override fun getConstructorId(): Int { return CONSTRUCTOR_ID } @Throws(IOException::class) override fun serializeBody(stream: OutputStream) { writeLong(messageId, stream) writeByteArray(content, 0, contentLen, stream) } @Throws(IOException::class) override fun deserializeBody(stream: InputStream, context: TLContext) { messageId = readLong(stream) contentLen = stream.available() content = ByteArray(contentLen) readBytes(content, 0, contentLen, stream) } override fun toString(): String { return "rpc_result#f35c6d01" } companion object { @JvmField val CONSTRUCTOR_ID = -212046591 } }
mit
176b1914083dcfccd69442297db5bdd1
29.394737
147
0.702165
4.125
false
false
false
false
CyroPCJr/Kotlin-Koans
src/main/kotlin/collections/TestShop.kt
1
2487
package collections //products val idea = Product("IntelliJ IDEA Ultimate", 199.0) val reSharper = Product("ReSharper", 149.0) val dotTrace = Product("DotTrace", 159.0) val dotMemory = Product("DotTrace", 129.0) val dotCover = Product("DotCover", 99.0) val appCode = Product("AppCode", 99.0) val phpStorm = Product("PhpStorm", 99.0) val pyCharm = Product("PyCharm", 99.0) val rubyMine = Product("RubyMine", 99.0) val webStorm = Product("WebStorm", 49.0) val teamCity = Product("TeamCity", 299.0) val youTrack = Product("YouTrack", 500.0) //customers val lucas = "Lucas" val cooper = "Cooper" val nathan = "Nathan" val reka = "Reka" val bajram = "Bajram" val asuka = "Asuka" val riku = "Riku" //cities val Canberra = City("Canberra") val Vancouver = City("Vancouver") val Budapest = City("Budapest") val Ankara = City("Ankara") val Tokyo = City("Tokyo") fun customer(name: String, city: City, vararg orders: Order) = Customer(name, city, orders.toList()) fun order(vararg products: Product, isDelivered: Boolean = true) = Order(products.toList(), isDelivered) fun shop(name: String, vararg customers: Customer) = Shop(name, customers.toList()) val shop = shop("jb test shop", customer(lucas, Canberra, order(reSharper), order(reSharper, dotMemory, dotTrace) ), customer(cooper, Canberra), customer(nathan, Vancouver, order(rubyMine, webStorm) ), customer(reka, Budapest, order(idea, isDelivered = false), order(idea, isDelivered = false), order(idea) ), customer(bajram, Ankara, order(reSharper) ), customer(asuka, Tokyo, order(idea) ), customer(riku, Tokyo, order(phpStorm, phpStorm), order(phpStorm) ) ) val customers: Map<String, Customer> = shop.customers.fold(hashMapOf(), { map, customer -> map[customer.name] = customer map }) val orderedProducts = setOf(idea, reSharper, dotTrace, dotMemory, rubyMine, webStorm, phpStorm) val sortedCustomers = listOf(cooper, nathan, bajram, asuka, lucas, riku, reka).map { customers[it] } val groupedByCities = mapOf( Canberra to listOf(lucas, cooper), Vancouver to listOf(nathan), Budapest to listOf(reka), Ankara to listOf(bajram), Tokyo to listOf(asuka, riku) ).mapValues { it.value.map { name -> customers[name] } }
apache-2.0
830500501a2059620ce88c0db0923d7d
30.0875
104
0.634499
3.342742
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/test/testdata/inspections/logLevel/Test.kt
1
1180
package inspections.flushInsideLoop import com.badlogic.gdx.Application import com.badlogic.gdx.Gdx import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.utils.Logger fun main() { <warning>Gdx.app.logLevel = Application.LOG_DEBUG</warning> <warning>Gdx.app.logLevel = 3</warning> <warning>Gdx.app.logLevel = 4</warning> Gdx.app.logLevel = 0 <warning>Gdx.app.logLevel = Application.LOG_INFO</warning> Gdx.app.logLevel = Application.LOG_ERROR Gdx.app.<warning>setLogLevel(3)</warning> Gdx.app.setLogLevel(Application.LOG_ERROR) Gdx.app.<warning>setLogLevel(Application.LOG_DEBUG)</warning> Gdx.app.setLogLevel(0) val a = Gdx.app <warning>a.logLevel = 3</warning> Logger("").<warning>setLevel(3)</warning> Logger("").<warning>setLevel(Logger.DEBUG)</warning> <warning>Logger("").level = 3</warning> <warning>Logger("").level = Logger.INFO</warning> Logger("").level = Logger.ERROR <warning>AssetManager().getLogger().level = 3</warning> <warning>AssetManager().logger.level = Logger.DEBUG</warning> AssetManager().logger.level = 1 }
apache-2.0
98e4eefa3b179dd9b3848f88fb61ab0d
30.078947
63
0.738136
3.522388
false
false
false
false
dmitryustimov/weather-kotlin
app/src/main/java/ru/ustimov/weather/ui/EmptyView.kt
1
3281
package ru.ustimov.weather.ui import android.content.Context import android.graphics.drawable.Drawable import android.support.v7.content.res.AppCompatResources import android.util.AttributeSet import android.view.Gravity import android.widget.LinearLayout import kotlinx.android.extensions.CacheImplementation import kotlinx.android.extensions.ContainerOptions import kotlinx.android.synthetic.main.view_empty.view.* import ru.ustimov.weather.R @ContainerOptions(CacheImplementation.SPARSE_ARRAY) class EmptyView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { private companion object { private const val INDEX_DRAWABLE_TOP = 1 } var onActionButtonClickListener: () -> Unit = {} var text: CharSequence? get() = textView.text set(value) { textView.text = value textView.visibility = if (value.isNullOrEmpty() && textView.compoundDrawables[INDEX_DRAWABLE_TOP] == null) GONE else VISIBLE } var drawable: Drawable? get() = textView.compoundDrawables[INDEX_DRAWABLE_TOP] set(value) { textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null) textView.visibility = if (text.isNullOrEmpty() && drawable == null) GONE else VISIBLE } var drawableRes: Int get() = 0 set(value) { drawable = AppCompatResources.getDrawable(context, drawableRes) } var action: CharSequence? get() = actionButton.text set(value) { actionButton.text = value actionButton.visibility = if (value.isNullOrEmpty()) GONE else VISIBLE } init { orientation = VERTICAL gravity = Gravity.CENTER val paddingHorizontal = resources.getDimensionPixelSize(R.dimen.empty_view_margin_horizontal) val paddingVertical = resources.getDimensionPixelSize(R.dimen.empty_view_margin_vertical) setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical) inflate(context, R.layout.view_empty, this) val a = context.theme.obtainStyledAttributes(attrs, R.styleable.EmptyView, defStyleAttr, 0) try { val text = a.getText(R.styleable.EmptyView_android_text) this.text = text if (a.hasValue(R.styleable.EmptyView_android_drawable)) { drawableRes = a.getResourceId(R.styleable.EmptyView_android_drawable, 0) } val action = a.getText(R.styleable.EmptyView_android_action) this.action = action actionButton.setOnClickListener({ onActionButtonClickListener() }) } finally { a.recycle() } } data class Info( private val text: CharSequence? = null, private val drawable: Drawable? = null, private val action: CharSequence? = null, private val listener: () -> Unit = {} ) { fun apply(emptyView: EmptyView) { emptyView.action = action emptyView.drawable = drawable emptyView.action = action emptyView.onActionButtonClickListener = listener } } }
apache-2.0
a9c8a0e1fc422b3d6c136498510d52ad
33.547368
136
0.659555
4.867953
false
false
false
false
gradle/gradle
.teamcity/src/main/kotlin/model/FunctionalTestBucketGenerator.kt
2
10894
package model import com.alibaba.fastjson.JSON import com.alibaba.fastjson.JSONArray import com.alibaba.fastjson.JSONObject import com.alibaba.fastjson.serializer.SerializerFeature import common.Os import common.VersionedSettingsBranch import java.io.File import java.util.LinkedList const val MASTER_CHECK_CONFIGURATION = "Gradle_Master_Check" const val MAX_PROJECT_NUMBER_IN_BUCKET = 11 /** * Process test-class-data.json and generates test-buckets.json * * Usage: `mvn compile exec:java@update-test-buckets -DinputTestClassDataJson=/path/to/test-class-data.json`. * You can get the JSON file as an artifacts of the "autoUpdateTestSplitJsonOnGradleMaster" pipeline in TeamCity. */ fun main() { val model = CIBuildModel( projectId = "Check", branch = VersionedSettingsBranch("master", true), buildScanTags = listOf("Check"), subprojects = JsonBasedGradleSubprojectProvider(File("./subprojects.json")) ) val testClassDataJson = File(System.getProperty("inputTestClassDataJson") ?: throw IllegalArgumentException("Input file not found!")) val generatedBucketsJson = File(System.getProperty("outputBucketSplitJson", "./test-buckets.json")) FunctionalTestBucketGenerator(model, testClassDataJson).generate(generatedBucketsJson) } class TestClassTime( val testClassAndSourceSet: TestClassAndSourceSet, val buildTimeMs: Int ) { constructor(jsonObject: JSONObject) : this( TestClassAndSourceSet( jsonObject.getString("testClass"), jsonObject.getString("sourceSet") ), jsonObject.getIntValue("buildTimeMs") ) } data class TestCoverageAndBucketSplits( val testCoverageUuid: Int, val buckets: List<FunctionalTestBucket> ) interface FunctionalTestBucket { fun toBuildTypeBucket(gradleSubprojectProvider: GradleSubprojectProvider): BuildTypeBucket } fun fromJsonObject(jsonObject: JSONObject): FunctionalTestBucket = if (jsonObject.containsKey("classes")) { FunctionalTestBucketWithSplitClasses(jsonObject) } else { MultipleSubprojectsFunctionalTestBucket(jsonObject) } data class FunctionalTestBucketWithSplitClasses( val subproject: String, val number: Int, val classes: List<String>, val include: Boolean ) : FunctionalTestBucket { constructor(jsonObject: JSONObject) : this( jsonObject.getString("subproject"), jsonObject.getIntValue("number"), jsonObject.getJSONArray("classes").map { it.toString() }, jsonObject.getBoolean("include") ) override fun toBuildTypeBucket(gradleSubprojectProvider: GradleSubprojectProvider): BuildTypeBucket = LargeSubprojectSplitBucket( gradleSubprojectProvider.getSubprojectByName(subproject)!!, number, include, classes.map { TestClassAndSourceSet(it) } ) } data class MultipleSubprojectsFunctionalTestBucket( val subprojects: List<String>, val enableTD: Boolean ) : FunctionalTestBucket { constructor(jsonObject: JSONObject) : this( jsonObject.getJSONArray("subprojects").map { it.toString() }, jsonObject.getBoolean("enableTD") ) override fun toBuildTypeBucket(gradleSubprojectProvider: GradleSubprojectProvider): BuildTypeBucket { return SmallSubprojectBucket( subprojects.map { gradleSubprojectProvider.getSubprojectByName(it)!! }, enableTD ) } } fun BuildTypeBucket.toJsonBucket(): FunctionalTestBucket { return when (this) { is SmallSubprojectBucket -> MultipleSubprojectsFunctionalTestBucket(subprojects.map { it.name }, enableTestDistribution) is LargeSubprojectSplitBucket -> FunctionalTestBucketWithSplitClasses(subproject.name, number, classes.map { it.toPropertiesLine() }, include) else -> throw IllegalStateException("Unsupported type: ${this.javaClass}") } } class SubprojectTestClassTime( val subProject: GradleSubproject, val testClassTimes: List<TestClassTime> = emptyList() ) { val totalTime: Int = testClassTimes.sumOf { it.buildTimeMs } fun split(expectedBucketNumber: Int, enableTestDistribution: Boolean = false): List<BuildTypeBucket> { return if (expectedBucketNumber == 1) { listOf( SmallSubprojectBucket( listOf(subProject), enableTestDistribution ) ) } else { // fun <T, R> split(list: LinkedList<T>, toIntFunction: (T) -> Int, largeElementSplitFunction: (T, Int) -> List<R>, smallElementAggregateFunction: (List<T>) -> R, expectedBucketNumber: Int, maxNumberInBucket: Int): List<R> { // T TestClassTime // R List<TestClassTime> val list = LinkedList(testClassTimes.sortedBy { -it.buildTimeMs }) val toIntFunction = TestClassTime::buildTimeMs val largeElementSplitFunction: (TestClassTime, Int) -> List<List<TestClassTime>> = { testClassTime: TestClassTime, _: Int -> listOf(listOf(testClassTime)) } val smallElementAggregateFunction: (List<TestClassTime>) -> List<TestClassTime> = { it } val buckets: List<List<TestClassTime>> = splitIntoBuckets(list, toIntFunction, largeElementSplitFunction, smallElementAggregateFunction, expectedBucketNumber, Integer.MAX_VALUE) buckets.mapIndexed { index: Int, classesInBucket: List<TestClassTime> -> val include = index != buckets.size - 1 val classes = if (include) classesInBucket else buckets.subList(0, buckets.size - 1).flatten() LargeSubprojectSplitBucket(subProject, index + 1, include, classes.map { it.testClassAndSourceSet }) } } } override fun toString(): String { return "SubprojectTestClassTime(subProject=${subProject.name}, totalTime=$totalTime)" } } class FunctionalTestBucketGenerator(private val model: CIBuildModel, testTimeDataJson: File) { private val buckets: Map<TestCoverage, List<BuildTypeBucket>> = buildBuckets(testTimeDataJson, model) fun generate(jsonFile: File) { jsonFile.writeText( JSON.toJSONString( buckets.map { TestCoverageAndBucketSplits(it.key.uuid, it.value.map { it.toJsonBucket() }) }, SerializerFeature.PrettyFormat ) ) } private fun buildBuckets(buildClassTimeJson: File, model: CIBuildModel): Map<TestCoverage, List<BuildTypeBucket>> { val jsonObj = JSON.parseObject(buildClassTimeJson.readText()) as JSONObject val buildProjectClassTimes: BuildProjectToSubprojectTestClassTimes = jsonObj.map { buildProjectToSubprojectTestClassTime -> buildProjectToSubprojectTestClassTime.key to (buildProjectToSubprojectTestClassTime.value as JSONObject).map { subProjectToTestClassTime -> subProjectToTestClassTime.key to (subProjectToTestClassTime.value as JSONArray).map { TestClassTime(it as JSONObject) } }.toMap() }.toMap() val result = mutableMapOf<TestCoverage, List<BuildTypeBucket>>() for (stage in model.stages) { for (testCoverage in stage.functionalTests) { if (testCoverage.testType !in listOf(TestType.allVersionsCrossVersion, TestType.quickFeedbackCrossVersion, TestType.soak)) { result[testCoverage] = splitBucketsByTestClassesForBuildProject(testCoverage, buildProjectClassTimes) } } } return result } private fun splitBucketsByTestClassesForBuildProject(testCoverage: TestCoverage, buildProjectClassTimes: BuildProjectToSubprojectTestClassTimes): List<BuildTypeBucket> { val validSubprojects = model.subprojects.getSubprojectsForFunctionalTest(testCoverage) // Build project not found, don't split into buckets val subProjectToClassTimes: MutableMap<String, List<TestClassTime>> = determineSubProjectClassTimes(testCoverage, buildProjectClassTimes)?.toMutableMap() ?: return validSubprojects.map { SmallSubprojectBucket(it, false) } validSubprojects.forEach { if (!subProjectToClassTimes.containsKey(it.name)) { subProjectToClassTimes[it.name] = emptyList() } } val subProjectTestClassTimes: List<SubprojectTestClassTime> = subProjectToClassTimes .entries .filter { "UNKNOWN" != it.key } .filter { model.subprojects.getSubprojectByName(it.key) != null } .map { SubprojectTestClassTime(model.subprojects.getSubprojectByName(it.key)!!, it.value.filter { it.testClassAndSourceSet.sourceSet != "test" }) } .sortedBy { -it.totalTime } return when { testCoverage.os == Os.LINUX -> splitIntoBuckets(subProjectTestClassTimes, testCoverage, true) else -> splitIntoBuckets(subProjectTestClassTimes, testCoverage, false) } } private fun splitIntoBuckets( subProjectTestClassTimes: List<SubprojectTestClassTime>, testCoverage: TestCoverage, enableTestDistribution: Boolean = false ): List<BuildTypeBucket> { return splitIntoBuckets( LinkedList(subProjectTestClassTimes), SubprojectTestClassTime::totalTime, { largeElement: SubprojectTestClassTime, size: Int -> if (enableTestDistribution) largeElement.split(1, enableTestDistribution) else largeElement.split(size) }, { list: List<SubprojectTestClassTime> -> SmallSubprojectBucket(list.map { it.subProject }, enableTestDistribution) }, testCoverage.expectedBucketNumber, MAX_PROJECT_NUMBER_IN_BUCKET ) } private fun determineSubProjectClassTimes(testCoverage: TestCoverage, buildProjectClassTimes: BuildProjectToSubprojectTestClassTimes): Map<String, List<TestClassTime>>? { val testCoverageId = testCoverage.asId(MASTER_CHECK_CONFIGURATION) return buildProjectClassTimes[testCoverageId] ?: if (testCoverage.testType == TestType.soak) { null } else { val testCoverages = model.stages.flatMap { it.functionalTests } val foundTestCoverage = testCoverages.firstOrNull { it.testType == TestType.platform && it.os == testCoverage.os && it.buildJvm == testCoverage.buildJvm } foundTestCoverage?.let { buildProjectClassTimes[it.asId(MASTER_CHECK_CONFIGURATION)] }?.also { println("No test statistics found for ${testCoverage.asName()} (${testCoverage.uuid}), re-using the data from ${foundTestCoverage.asName()} (${foundTestCoverage.uuid})") } } } }
apache-2.0
9859ac20119978e6d64362b489e23531
43.105263
236
0.68579
4.763446
false
true
false
false
interedition/collatex
collatex-core/src/main/java/eu/interedition/collatex/util/VariantGraphTraversal.kt
1
2741
/* * Copyright (c) 2015 The Interedition Development Group. * * This file is part of CollateX. * * CollateX 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. * * CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.collatex.util import eu.interedition.collatex.VariantGraph import eu.interedition.collatex.Witness /** * @author [Gregor Middell](http://gregor.middell.net/) * @author Ronald Haentjens Dekker */ class VariantGraphTraversal private constructor(private val graph: VariantGraph, private val witnesses: Set<Witness?>?) : Iterable<VariantGraph.Vertex?> { fun topologicallySortedTextNodes(graph: VariantGraph): List<VariantGraph.Vertex> { // https://en.wikipedia.org/wiki/Topological_sorting // Kahn's algorithm val sorted: MutableList<VariantGraph.Vertex> = mutableListOf() val todo: MutableSet<VariantGraph.Vertex> = mutableSetOf(graph.start) val handledEdges: MutableSet<VariantGraph.Edge> = mutableSetOf() while (todo.isNotEmpty()) { val node = todo.iterator().next() todo.remove(node) sorted += node for ((targetNode, e) in node.outgoingEdges()) { if (e !in handledEdges) { handledEdges += e if (handledEdges.containsAll(targetNode.incomingEdges().values)) { todo += targetNode } } } } return if (witnesses==null) { sorted } else { sorted.filter { vertex -> vertex === graph.start || vertex.witnesses().containsAll(witnesses) } } } override fun iterator(): Iterator<VariantGraph.Vertex?> { val topologicallySortedTextNodes = topologicallySortedTextNodes(graph) return topologicallySortedTextNodes.iterator() } companion object { @JvmStatic fun of(graph: VariantGraph, witnesses: Set<Witness>): VariantGraphTraversal { return VariantGraphTraversal(graph, witnesses) } @JvmStatic fun of(graph: VariantGraph): VariantGraphTraversal { return VariantGraphTraversal(graph, null) } } }
gpl-3.0
48412dbc239d3c969455c1fc5e47d357
37.083333
154
0.65487
4.392628
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/ProjectileComponent.kt
1
2608
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.entity.component.Component import com.almasb.fxgl.entity.component.CopyableComponent import javafx.beans.property.DoubleProperty import javafx.beans.property.SimpleDoubleProperty import javafx.beans.value.ChangeListener import javafx.geometry.Point2D /** * Generic projectile component. * Automatically rotates the entity based on velocity direction. * The rotation of 0 degrees is assumed to be facing right. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ class ProjectileComponent(direction: Point2D, speed: Double) : Component(), CopyableComponent<ProjectileComponent> { /** * Constructs the component with direction facing right and 1.0 speed. */ constructor() : this(Point2D(1.0, 0.0), 1.0) var velocity: Point2D = direction.normalize().multiply(speed) private set /** * Set direction in which projectile is moving. */ var direction: Point2D get() = velocity.normalize() set(direction) { velocity = direction.normalize().multiply(speed) updateRotation() } private val speedProp = SimpleDoubleProperty(speed) private val speedListener = ChangeListener<Number> { _, _, newSpeed -> velocity = velocity.normalize().multiply(newSpeed.toDouble()) updateRotation() } fun speedProperty(): DoubleProperty = speedProp var speed: Double get() = speedProp.value set(value) { speedProp.value = value } private var isAllowRotation: Boolean = true /** * Allow to disable / enable projectile rotation towards direction of travel. */ fun allowRotation(allowRotation: Boolean): ProjectileComponent { isAllowRotation = allowRotation return this } /** * Checks if rotation is enabled, if so then rotate. */ private fun updateRotation(){ if (isAllowRotation) entity.rotateToVector(velocity) } override fun onAdded() { updateRotation() speedProp.addListener(speedListener) } override fun onUpdate(tpf: Double) { entity.translate(velocity.multiply(tpf)) } override fun onRemoved() { speedProp.removeListener(speedListener) } override fun copy(): ProjectileComponent { return ProjectileComponent(direction, speed) } override fun isComponentInjectionRequired(): Boolean = false }
mit
4c9b912982cacf5eee437ce11d0f6b59
27.043011
116
0.680215
4.543554
false
false
false
false
duftler/orca
orca-core/src/main/java/com/netflix/spinnaker/orca/commands/ForceExecutionCancellationCommand.kt
1
2378
/* * Copyright 2018 Netflix, 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 com.netflix.spinnaker.orca.commands import com.netflix.spinnaker.orca.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.pipeline.model.Execution import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import org.slf4j.LoggerFactory import java.time.Clock /** * When an [Execution] is zombied and cannot be rehydrated back onto the queue, this * command can be used to cleanup. * * TODO(rz): Fix zombies. */ class ForceExecutionCancellationCommand( private val executionRepository: ExecutionRepository, private val clock: Clock ) { private val log = LoggerFactory.getLogger(javaClass) fun forceCancel(executionType: Execution.ExecutionType, executionId: String, canceledBy: String) { log.info("Forcing cancel of $executionType:$executionId by: $canceledBy") val execution = executionRepository.retrieve(executionType, executionId) if (forceCancel(execution, canceledBy)) { executionRepository.store(execution) } } private fun forceCancel(execution: Execution, canceledBy: String): Boolean { val now = clock.instant().toEpochMilli() var changes = false execution.stages .filter { !it.status.isComplete && it.status != NOT_STARTED } .forEach { stage -> stage.tasks.forEach { task -> task.status = CANCELED task.endTime = now } stage.status = CANCELED stage.endTime = now changes = true } if (!execution.status.isComplete) { execution.status = CANCELED execution.canceledBy = canceledBy execution.cancellationReason = "Force canceled by admin" execution.endTime = now changes = true } return changes } }
apache-2.0
d4a18f9ff7965ad2d6bec4add6378a85
30.706667
100
0.720774
4.363303
false
false
false
false
shawyou/MyTestProject
MyTestApp/app/src/main/java/linshaoyou/meizu/com/mytestapp/MyApplication.kt
1
2650
package linshaoyou.meizu.com.mytestapp import android.app.Application import android.content.Context import android.support.multidex.MultiDexApplication import android.util.Log import com.taobao.sophix.PatchStatus import com.taobao.sophix.SophixManager import com.taobao.sophix.SophixManager.* import com.taobao.sophix.listener.PatchLoadStatusListener import com.taobao.weex.InitConfig import com.taobao.weex.WXSDKEngine import linshaoyou.meizu.com.mytestapp.weex.WXImageLoaderAdapter /** * Created by linshaoyou on 17/8/26. */ class MyApplication : MultiDexApplication(){ override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) Log.e("LSY", "attachBastContext start") // initialize最好放在attachBaseContext最前面 SophixManager.getInstance() .setContext(this) .setAppVersion("1.0.0") .setAesKey(null) .setEnableDebug(true) .setPatchLoadStatusStub(object : PatchLoadStatusListener { override fun onLoad(mode: Int, code: Int, info: String, handlePatchVersion: Int) { Log.e("LSY", "补丁加载回调通知 code == " + code) // 补丁加载回调通知 if (code == PatchStatus.CODE_LOAD_SUCCESS) { // 表明补丁加载成功 } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) { // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启; // 建议: 用户可以监听进入后台事件, 然后调用killProcessSafely自杀,以此加快应用补丁,详见1.3.2.3 } else { // 其它错误信息, 查看PatchStatus类说明 } } }).initialize() Log.e("LSY", "attachBastContext finish") } override fun onCreate() { super.onCreate() Log.e("LSY", "MyApplication onCreate") initial() } private fun initial() { initSophix() initWeex() } private fun initSophix() { // queryAndLoadNewPatch不可放在attachBaseContext 中,否则无网络权限,建议放在后面任意时刻,如onCreate中 SophixManager.getInstance().queryAndLoadNewPatch() } private fun initWeex() { var initConfig = InitConfig .Builder() .setImgAdapter(WXImageLoaderAdapter()) .build() WXSDKEngine.initialize(this,initConfig) } }
apache-2.0
5b181a15498c409c6741a4450acbaeff
33.753623
102
0.591326
3.746875
false
true
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/tut11/gaussianSpecularLighting.kt
2
13709
package glNext.tut11 import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.MouseEvent import com.jogamp.opengl.GL2ES3.* import com.jogamp.opengl.GL3 import glNext.* import glNext.tut11.GaussianSpecularLighting_Next.LightingModel.BlinnOnly import glm.glm import glm.vec._3.Vec3 import glm.vec._4.Vec4 import glm.quat.Quat import glm.mat.Mat4 import main.framework.Framework import main.framework.Semantic import main.framework.component.Mesh import glNext.tut11.GaussianSpecularLighting_Next.LightingModel.BlinnSpecular import glNext.tut11.GaussianSpecularLighting_Next.LightingModel.GaussianSpecular import glNext.tut11.GaussianSpecularLighting_Next.LightingModel.PhongOnly import glNext.tut11.GaussianSpecularLighting_Next.LightingModel.PhongSpecular import uno.buffer.destroy import uno.buffer.intBufferBig import uno.glm.MatrixStack import uno.glsl.programOf import uno.mousePole.* import uno.time.Timer /** * Created by GBarbieri on 24.03.2017. */ fun main(args: Array<String>) { GaussianSpecularLighting_Next().setup("Tutorial 11 - Gaussian Specular Lighting") } class GaussianSpecularLighting_Next : Framework() { lateinit var programs: Array<ProgramPairs> lateinit var unlit: UnlitProgData val initialViewData = ViewData( Vec3(0.0f, 0.5f, 0.0f), Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f), 5.0f, 0.0f) val viewScale = ViewScale( 3.0f, 20.0f, 1.5f, 0.5f, 0.0f, 0.0f, //No camera movement. 90.0f / 250.0f) val initialObjectData = ObjectData( Vec3(0.0f, 0.5f, 0.0f), Quat(1.0f, 0.0f, 0.0f, 0.0f)) val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1) val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole) lateinit var cylinder: Mesh lateinit var plane: Mesh lateinit var cube: Mesh var lightModel = BlinnSpecular var drawColoredCyl = false var drawLightSource = false var scaleCyl = false var drawDark = false var lightHeight = 1.5f var lightRadius = 1.0f val lightAttenuation = 1.2f val darkColor = Vec4(0.2f, 0.2f, 0.2f, 1.0f) val lightColor = Vec4(1.0f) val lightTimer = Timer(Timer.Type.Loop, 5.0f) val projectionUniformBuffer = intBufferBig(1) override fun init(gl: GL3) = with(gl) { initializePrograms(gl) cylinder = Mesh(gl, javaClass, "tut11/UnitCylinder.xml") plane = Mesh(gl, javaClass, "tut11/LargePlane.xml") cube = Mesh(gl, javaClass, "tut11/UnitCube.xml") val depthZNear = 0.0f val depthZFar = 1.0f cullFace { enable() cullFace = back frontFace = cw } depth { test = true mask = true func = lEqual rangef = depthZNear .. depthZFar clamp = true } initUniformBuffer(projectionUniformBuffer) { data(Mat4.SIZE, GL_DYNAMIC_DRAW) //Bind the static buffers. range(Semantic.Uniform.PROJECTION, 0, Mat4.SIZE) } } fun initializePrograms(gl: GL3) { val FRAGMENTS = arrayOf("phong-lighting", "phong-only", "blinn-lighting", "blinn-only", "gaussian-lighting", "gaussian-only") programs = Array(LightingModel.MAX, { ProgramPairs(ProgramData(gl, "pn.vert", "${FRAGMENTS[it]}.frag"), ProgramData(gl, "pcn.vert", "${FRAGMENTS[it]}.frag")) }) unlit = UnlitProgData(gl, "pos-transform.vert", "uniform-color.frag") } override fun display(gl: GL3) = with(gl) { lightTimer.update() clear { color(0) depth() } val modelMatrix = MatrixStack() modelMatrix.setMatrix(viewPole.calcMatrix()) val worldLightPos = calcLightPosition() val lightPosCameraSpace = modelMatrix.top() * worldLightPos val whiteProg = programs[lightModel].whiteProgram val colorProg = programs[lightModel].colorProgram usingProgram(whiteProg.theProgram) { glUniform4f(whiteProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f) glUniform4f(whiteProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f) glUniform3f(whiteProg.cameraSpaceLightPosUnif, lightPosCameraSpace) glUniform1f(whiteProg.lightAttenuationUnif, lightAttenuation) glUniform1f(whiteProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel)) glUniform4f(whiteProg.baseDiffuseColorUnif, if (drawDark) darkColor else lightColor) name = colorProg.theProgram glUniform4f(colorProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f) glUniform4f(colorProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f) glUniform3f(colorProg.cameraSpaceLightPosUnif, lightPosCameraSpace) glUniform1f(colorProg.lightAttenuationUnif, lightAttenuation) glUniform1f(colorProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel)) } modelMatrix run { //Render the ground plane. run { val normMatrix = top().toMat3() normMatrix.inverse_().transpose_() usingProgram(whiteProg.theProgram) { whiteProg.modelToCameraMatrixUnif.mat4 = top() glUniformMatrix3f(whiteProg.normalModelToCameraMatrixUnif, normMatrix) plane.render(gl) } } //Render the Cylinder run { applyMatrix(objectPole.calcMatrix()) if (scaleCyl) scale(1.0f, 1.0f, 0.2f) val normMatrix = modelMatrix.top().toMat3() normMatrix.inverse_().transpose_() val prog = if (drawColoredCyl) colorProg else whiteProg usingProgram(prog.theProgram) { prog.modelToCameraMatrixUnif.mat4 = top() glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix) cylinder.render(gl, if (drawColoredCyl) "lit-color" else "lit") } } //Render the light if (drawLightSource) run { translate(worldLightPos) scale(0.1f) usingProgram(unlit.theProgram) { unlit.modelToCameraMatrixUnif.mat4 = modelMatrix.top() glUniform4f(unlit.objectColorUnif, 0.8078f, 0.8706f, 0.9922f, 1.0f) cube.render(gl, "flat") } } } } fun calcLightPosition(): Vec4 { val currentTimeThroughLoop = lightTimer.getAlpha() val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f) ret.x = glm.cos(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius ret.z = glm.sin(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius return ret } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { val zNear = 1.0f val zFar = 1_000f val perspMatrix = MatrixStack() val proj = perspMatrix.perspective(45.0f, w.toFloat() / h, zNear, zFar).top() withUniformBuffer(projectionUniformBuffer) { subData(proj) } glViewport(w, h) } override fun mousePressed(e: MouseEvent) { viewPole.mousePressed(e) objectPole.mousePressed(e) } override fun mouseDragged(e: MouseEvent) { viewPole.mouseDragged(e) objectPole.mouseDragged(e) } override fun mouseReleased(e: MouseEvent) { viewPole.mouseReleased(e) objectPole.mouseReleased(e) } override fun mouseWheelMoved(e: MouseEvent) { viewPole.mouseWheel(e) } override fun keyPressed(e: KeyEvent) { var changedShininess = false when (e.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl KeyEvent.VK_I -> lightHeight += if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_K -> lightHeight -= if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_L -> lightRadius += if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_J -> lightRadius -= if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_O -> { MaterialParameters.increment(lightModel, !e.isShiftDown) changedShininess = true } KeyEvent.VK_U -> { MaterialParameters.decrement(lightModel, !e.isShiftDown) changedShininess = true } KeyEvent.VK_Y -> drawLightSource = !drawLightSource KeyEvent.VK_T -> scaleCyl = !scaleCyl KeyEvent.VK_B -> lightTimer.togglePause() KeyEvent.VK_G -> drawDark = !drawDark KeyEvent.VK_H -> { if (e.isShiftDown) if (lightModel % 2 != 0) lightModel -= 1 else lightModel += 1 else lightModel = (lightModel + 2) % LightingModel.MAX println(when (lightModel) { PhongSpecular -> "PhongSpecular" PhongOnly -> "PhongOnly" BlinnSpecular -> "BlinnSpecular" BlinnOnly -> "BlinnOnly" GaussianSpecular -> "GaussianSpecular" else -> "GaussianOnly" }) } } if (lightRadius < 0.2f) lightRadius = 0.2f if (changedShininess) println("Shiny: " + MaterialParameters.getSpecularValue(lightModel)) } override fun end(gl: GL3) = with(gl) { programs.forEach { glDeletePrograms(it.whiteProgram.theProgram, it.colorProgram.theProgram) } glDeleteProgram(unlit.theProgram) glDeleteBuffer(projectionUniformBuffer) cylinder.dispose(gl) plane.dispose(gl) cube.dispose(gl) projectionUniformBuffer.destroy() } object LightingModel { val PhongSpecular = 0 val PhongOnly = 1 val BlinnSpecular = 2 val BlinnOnly = 3 val GaussianSpecular = 4 val GaussianOnly = 5 val MAX = 6 } class ProgramPairs(val whiteProgram: ProgramData, val colorProgram: ProgramData) class ProgramData(gl: GL3, vertex: String, fragment: String) { val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment) val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity") val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity") val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix") val cameraSpaceLightPosUnif = gl.glGetUniformLocation(theProgram, "cameraSpaceLightPos") val lightAttenuationUnif = gl.glGetUniformLocation(theProgram, "lightAttenuation") val shininessFactorUnif = gl.glGetUniformLocation(theProgram, "shininessFactor") val baseDiffuseColorUnif = gl.glGetUniformLocation(theProgram, "baseDiffuseColor") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } inner class UnlitProgData(gl: GL3, vertex: String, fragment: String) { val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment) val objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor") val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } object MaterialParameters { var phongExponent = 4.0f var blinnExponent = 4.0f var gaussianRoughness = 0.5f fun getSpecularValue(model: Int) = when (model) { PhongSpecular, PhongOnly -> phongExponent BlinnSpecular, BlinnOnly -> blinnExponent else -> gaussianRoughness } fun increment(model: Int, isLarge: Boolean) { when (model) { PhongSpecular, PhongOnly -> phongExponent += if (isLarge) 0.5f else 0.1f BlinnSpecular, BlinnOnly -> blinnExponent += if (isLarge) 0.5f else 0.1f else -> gaussianRoughness += if (isLarge) 0.1f else 0.01f } clampParam(model) } fun decrement(model: Int, isLarge: Boolean) { when (model) { PhongSpecular, PhongOnly -> phongExponent -= if (isLarge) 0.5f else 0.1f BlinnSpecular, BlinnOnly -> blinnExponent -= if (isLarge) 0.5f else 0.1f else -> gaussianRoughness -= if (isLarge) 0.1f else 0.01f } clampParam(model) } fun clampParam(model: Int) { when (model) { PhongSpecular, PhongOnly -> if (phongExponent <= 0.0f) phongExponent = 0.0001f BlinnSpecular, BlinnOnly -> if (blinnExponent <= 0.0f) blinnExponent = 0.0001f else -> gaussianRoughness = glm.clamp(gaussianRoughness, 0.00001f, 1.0f) } } } }
mit
5fdcf40fbaa447458b537306db729905
32.357664
133
0.604348
4.113111
false
false
false
false
yangpeiyong/android-samples
kotlin-demo/app/src/main/kotlin/net/gouline/kotlindemo/app/WifiListFragment.kt
3
3568
package net.gouline.kotlindemo.app import android.app.ListFragment import android.net.wifi.ScanResult import android.os.Bundle import android.widget.ArrayAdapter import net.gouline.kotlindemo.model.WifiStation import android.view.View import android.view.ViewGroup import android.content.Context import android.view.LayoutInflater import net.gouline.kotlindemo.R import android.widget.TextView import android.widget.ListView /** * Fragment for listing Wi-Fi base stations. * * @author Mike Gouline */ open class WifiListFragment() : ListFragment() { class object { fun newInstance(): WifiListFragment { return WifiListFragment() } } private var emptyView: View? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_wifi_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super<ListFragment>.onViewCreated(view, savedInstanceState) emptyView = view.findViewById(R.id.progress) setListAdapter(WifiListAdapter(getActivity())) getListView().setEmptyView(emptyView) } override fun onResume() { super<ListFragment>.onResume() val activity = getActivity() if (activity is WifiActivity) { activity.onResumeFragment(this) } } override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) { super<ListFragment>.onListItemClick(l, v, position, id) val activity = getActivity() if (activity is WifiActivity) { val item = l.getItemAtPosition(position) as WifiStation activity.transitionToDetail(item) } } /** * Updates adapter and calls notify. * * @param stations List of scan results. */ fun updateItems(stations: List<ScanResult>? = null) { val adapter = getListAdapter() if (adapter is WifiListAdapter) { adapter.clear() if (stations != null) { val emptyVisible: Int = if (stations.size() > 0) View.VISIBLE else View.GONE emptyView?.setVisibility(emptyVisible) adapter.addAll(WifiStation.newList(stations)) } adapter.notifyDataSetChanged() } } /** * Clears adapter items and calls notify. */ fun clearItems() { updateItems() } /** * Array adapter for stations. */ class WifiListAdapter(context: Context) : ArrayAdapter<WifiStation>(context, 0) { val inflater = LayoutInflater.from(context) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val item = getItem(position) val view = convertView ?: inflater.inflate(R.layout.list_item_wifi, parent, false) val ssidTextView = view.findViewById(R.id.txt_ssid) as TextView ssidTextView.setText(item.ssid) val bssidTextView = view.findViewById(R.id.txt_bssid) as TextView bssidTextView.setText(item.bssid) val frequencyTextView = view.findViewById(R.id.txt_frequency) as TextView frequencyTextView.setText(getContext().getString(R.string.station_frequency, item.frequency)) val levelTextView = view.findViewById(R.id.txt_level) as TextView levelTextView.setText(getContext().getString(R.string.station_level, item.level)) return view } } }
mit
386dfd589977c8032ed9b885f557fc86
30.857143
114
0.65583
4.615783
false
false
false
false
weisterjie/FamilyLedger
app/src/main/java/ycj/com/familyledger/ui/KRegisterActivity.kt
1
6018
package ycj.com.familyledger.ui import android.text.InputFilter import android.text.InputType import android.view.Gravity import android.view.View import android.widget.EditText import org.jetbrains.anko.* import ycj.com.familyledger.Consts import ycj.com.familyledger.R import ycj.com.familyledger.bean.BaseResponse import ycj.com.familyledger.bean.UserBean import ycj.com.familyledger.http.HttpUtils import ycj.com.familyledger.impl.BaseCallBack import ycj.com.familyledger.utils.RegexUtils import ycj.com.familyledger.utils.SPUtils class KRegisterActivity : KBaseActivity(), BaseCallBack<UserBean> { private var edxPhone: android.widget.EditText? = null private var btnGo: android.widget.Button? = null private var edxName: EditText? = null private var edxPassword: android.widget.EditText? = null override fun initialize() { val phone = SPUtils.getInstance().getString(Consts.SP_PHONE) val password = SPUtils.getInstance().getString(Consts.SP_PASSWORD) val userName = SPUtils.getInstance().getString(Consts.SP_USER_NAME) edxName?.visibility = if (userName.isEmpty()) View.VISIBLE else View.GONE edxName!!.setText(userName) edxPhone!!.setText(phone) edxPassword!!.setText(password) } override fun initView() { linearLayout { lparams(height = matchParent, width = matchParent) { orientation = android.widget.LinearLayout.VERTICAL } linearLayout { textView("Ledger") { textSize = resources.getDimension(R.dimen.title_size) gravity = Gravity.CENTER textColor = resources.getColor(R.color.white) backgroundResource = R.color.color_title_bar }.lparams(height = dip(48), width = matchParent) } linearLayout { lparams(height = matchParent, width = matchParent) { gravity = android.view.Gravity.CENTER orientation = android.widget.LinearLayout.VERTICAL topMargin = dip(40) } edxName = editText { id = R.id.edx_phone_main maxLines = 1 maxEms = 20 filters = arrayOf<InputFilter>(InputFilter.LengthFilter(11)) backgroundResource = R.drawable.edx_input_bg hint = "留下你的名号" }.lparams(width = matchParent, height = dip(40)) { bottomMargin = dip(40) leftMargin = dip(40) rightMargin = dip(40) } edxPhone = editText { id = R.id.edx_phone_main maxLines = 1 maxEms = 11 inputType = InputType.TYPE_CLASS_PHONE filters = arrayOf<InputFilter>(InputFilter.LengthFilter(11)) backgroundResource = R.drawable.edx_input_bg hint = "请输入手机号" }.lparams(width = matchParent, height = dip(40)) { bottomMargin = dip(40) leftMargin = dip(40) rightMargin = dip(40) } edxPassword = editText { id = R.id.edx_password_main maxLines = 1 inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD filters = arrayOf<InputFilter>(InputFilter.LengthFilter(20)) backgroundResource = R.drawable.edx_input_bg hint = "请输密码" }.lparams(width = matchParent, height = dip(40)) { bottomMargin = dip(40) leftMargin = dip(40) rightMargin = dip(40) } btnGo = button { id = R.id.btn_go_main text = "进入应用" textSize = sp(6).toFloat() textColor = resources.getColor(R.color.white) backgroundResource = R.drawable.bg_btn }.lparams(width = matchParent, height = dip(40)) { leftMargin = dip(40) rightMargin = dip(40) } } } } override fun initListener() { btnGo!!.setOnClickListener { val userName = edxName!!.text.toString().trim() val phone = edxPhone!!.text.toString().trim() val password = edxPassword!!.text.toString().trim() if (userName.isEmpty()) { toast(getString(R.string.error_user_name)) } else if (phone.length < 11) { toast(getString(R.string.error_phone_number)) } else if (password.length < 3) { toast(getString(R.string.password_not_full_six)) } else if (!RegexUtils.create().isMobileExact(phone)) { toast(getString(R.string.not_phone_number)) } else { showLoading() HttpUtils.getInstance().login(phone, password, this@KRegisterActivity) } } } override fun onSuccess(data: BaseResponse<UserBean>) { hideLoading() if (data.result == 1) { saveData(data.data!!) startActivity<KHomeActivity>() finish() } toast("登录成功") } override fun onFail(msg: String) { hideLoading() toast(getString(R.string.fail_login_in)) } private fun saveData(user: UserBean) { SPUtils.getInstance().putString(Consts.SP_PHONE, edxPhone!!.text.toString()) SPUtils.getInstance().putString(Consts.SP_PASSWORD, edxPassword!!.text.toString()) SPUtils.getInstance().putLong(Consts.SP_USER_ID, user.userId!!) SPUtils.getInstance().putString(Consts.SP_USER_NAME, user.user_name!!) } }
apache-2.0
acf214be4f3f8d47454ffce8b97fc077
37.269231
90
0.550586
4.779824
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/adapter/FeedbackAdapter.kt
1
2265
package org.miaowo.miaowo.adapter import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.view.View import android.view.ViewGroup import android.widget.TextView import com.blankj.utilcode.util.ActivityUtils import com.sdsmdg.tastytoast.TastyToast import org.miaowo.miaowo.activity.UserActivity import org.miaowo.miaowo.base.ListAdapter import org.miaowo.miaowo.base.ListHolder import org.miaowo.miaowo.base.extra.toast import org.miaowo.miaowo.other.BaseListTouchListener import org.miaowo.miaowo.other.Const class FeedbackAdapter(context: Context): ListAdapter<Array<String>>(object : ViewCreator<Array<String>> { override fun createHolder(parent: ViewGroup, viewType: Int) = ListHolder(android.R.layout.simple_list_item_activated_2, parent, context) override fun bindView(item: Array<String>, holder: ListHolder, type: Int) { if (item.size >= 2) { holder.find<TextView>(android.R.id.text1)?.text = item[0] holder.find<TextView>(android.R.id.text2)?.text = item[1] } } }) class FeedbackListener(context: Context): BaseListTouchListener(context) { override fun onClick(view: View?, position: Int): Boolean { var ret = true when (position) { 0 -> openUri("mqqwpa://im/chat?chat_type=group&uin=385231397&version=1", "无法打开 QQ 临时会话") 1 -> openUri("mqqwpa://im/chat?chat_type=wpa&uin=1105188240", "无法打开 QQ 临时会话") 2 -> context.startActivity(Intent(context, UserActivity::class.java).putExtra(Const.TYPE, UserActivity.USER_FROM_NAME).putExtra(Const.NAME, "Systemd")) 3 -> openUri("mqqwpa://im/chat?chat_type=wpa&uin=1289770378", "无法打开 QQ 临时会话") else -> ret = false } return ret } private fun openUri(uri: String, errString: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) val support = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) if (support?.isNotEmpty() == true) context.startActivity(intent) else ActivityUtils.getTopActivity().toast(errString, TastyToast.ERROR) } }
apache-2.0
ccf33ec0dac674d942fe2fd15792d027
43.36
163
0.711773
3.640394
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/view/datepicker/values.kt
1
7516
package at.cpickl.gadsu.view.datepicker import at.cpickl.gadsu.global.GadsuException import at.cpickl.gadsu.view.Images import java.awt.Color import java.awt.SystemColor import java.io.IOException import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Calendar import java.util.Properties import javax.swing.Icon object ComponentColorDefaults { enum class Key { FG_MONTH_SELECTOR, BG_MONTH_SELECTOR, FG_GRID_HEADER, BG_GRID_HEADER, FG_GRID_THIS_MONTH, FG_GRID_OTHER_MONTH, FG_GRID_TODAY, BG_GRID, BG_GRID_NOT_SELECTABLE, FG_GRID_SELECTED, BG_GRID_SELECTED, FG_GRID_TODAY_SELECTED, BG_GRID_TODAY_SELECTED, FG_TODAY_SELECTOR_ENABLED, FG_TODAY_SELECTOR_DISABLED, BG_TODAY_SELECTOR, POPUP_BORDER } private val colors = mutableMapOf( Key.FG_MONTH_SELECTOR to SystemColor.activeCaptionText, Key.BG_MONTH_SELECTOR to SystemColor.activeCaption, Key.FG_GRID_HEADER to Color(10, 36, 106), Key.BG_GRID_HEADER to Color.LIGHT_GRAY, Key.FG_GRID_THIS_MONTH to Color.BLACK, Key.FG_GRID_OTHER_MONTH to Color.LIGHT_GRAY, Key.FG_GRID_TODAY to Color.RED, Key.BG_GRID to Color.WHITE, Key.BG_GRID_NOT_SELECTABLE to Color(240, 240, 240), Key.FG_GRID_SELECTED to Color.WHITE, Key.BG_GRID_SELECTED to Color(10, 36, 106), Key.FG_GRID_TODAY_SELECTED to Color.RED, Key.BG_GRID_TODAY_SELECTED to Color(10, 36, 106), Key.FG_TODAY_SELECTOR_ENABLED to Color.BLACK, Key.FG_TODAY_SELECTOR_DISABLED to Color.LIGHT_GRAY, Key.BG_TODAY_SELECTOR to Color.WHITE, Key.POPUP_BORDER to Color.BLACK ) fun getColor(key: Key) = colors[key]!! fun setColor(key: Key, color: Color) { colors.put(key, color) } } object ComponentFormatDefaults { enum class Key { TODAY_SELECTOR, DOW_HEADER, MONTH_SELECTOR, SELECTED_DATE_FIELD } private val formats = mutableMapOf( Key.TODAY_SELECTOR to SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM), Key.DOW_HEADER to SimpleDateFormat("EE"), Key.MONTH_SELECTOR to SimpleDateFormat("MMMM"), Key.SELECTED_DATE_FIELD to SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM) ) fun getFormat(key: Key) = formats[key]!! fun setFormat(key: Key, format: DateFormat) { formats.put(key, format) } } object ComponentIconDefaults { private val CLEAR = "/gadsu/images/datepicker_clear.png" enum class Key var clearIcon: Icon? = null var nextMonthIconEnabled: Icon? = null var nextYearIconEnabled: Icon? = null var previousMonthIconEnabled: Icon? = null var previousYearIconEnabled: Icon? = null var nextMonthIconDisabled: Icon? = null var nextYearIconDisabled: Icon? = null var previousMonthIconDisabled: Icon? = null var previousYearIconDisabled: Icon? = null var popupButtonIcon: Icon? = null init { try { clearIcon = Images.loadFromClasspath(CLEAR) nextMonthIconEnabled = JNextIcon(4, 7, false, true) nextYearIconEnabled = JNextIcon(8, 7, true, true) previousMonthIconEnabled = JPreviousIcon(4, 7, false, true) previousYearIconEnabled = JPreviousIcon(8, 7, true, true) nextMonthIconDisabled = JNextIcon(4, 7, false, false) nextYearIconDisabled = JNextIcon(8, 7, true, false) previousMonthIconDisabled = JPreviousIcon(4, 7, false, false) previousYearIconDisabled = JPreviousIcon(8, 7, true, false) popupButtonIcon = null } catch (e: IOException) { throw GadsuException("Oh noes, load icons failed!", e) } } } /** * Instantiated with the values which is default for the current locale. */ object ComponentTextDefaults { enum class Key constructor(val property: String, val kind: String, val index: Int? = null) { // General texts TODAY("text.today", "general"), MONTH("text.month", "general"), YEAR("text.year", "general"), CLEAR("text.clear", "general"), // Months of the year JANUARY("text.january", "month", 0), FEBRUARY("text.february", "month", 1), MARCH("text.march", "month", 2), APRIL("text.april", "month", 3), MAY("text.may", "month", 4), JUNE("text.june", "month", 5), JULY("text.july", "month", 6), AUGUST("text.august", "month", 7), SEPTEMBER("text.september", "month", 8), OCTOBER("text.october", "month", 9), NOVEMBER("text.november", "month", 10), DECEMBER("text.december", "month", 11), // Days of the week abbreviated where necessary SUN("text.sun", "dow", Calendar.SUNDAY), MON("text.mon", "dow", Calendar.MONDAY), TUE("text.tue", "dow", Calendar.TUESDAY), WED("text.wed", "dow", Calendar.WEDNESDAY), THU("text.thu", "dow", Calendar.THURSDAY), FRI("text.fri", "dow", Calendar.FRIDAY), SAT("text.sat", "dow", Calendar.SATURDAY); companion object { fun getMonthKey(index: Int) = values().firstOrNull { "month" == it.kind && index == it.index } ?: throw IllegalArgumentException("Invalid index: $index") fun getDowKey(index: Int) = values().firstOrNull { "dow" == it.kind && index == it.index } ?: throw IllegalArgumentException("Invalid index: $index") } } private val texts = Properties().apply { put("text.today", "Heute") put("text.month", "Monat") put("text.year", "Jahr") put("text.clear", "L\u00f6schen") } //toProperties(ResourceBundle.getBundle("org.jdatepicker.i18n.Text", Locale.getDefault())) // private fun toProperties(resource: ResourceBundle): Properties { // val result = Properties() // val keys = resource.keys // while (keys.hasMoreElements()) { // val key = keys.nextElement() // result.put(key, resource.getString(key)) // } // return result // } /** * For general texts retrieve from the resource bundles. * * For months and day of the week use the SimpleDateFormat symbols. In most cases these are the correct ones, but * we may want to override it, so if a text is specified then we will not consider the SimpleDateFormat symbols. */ fun getText(key: Key): String { val text: String? = texts.getProperty(key.property) if (text != null) return text return if ("month" == key.kind) { val c = Calendar.getInstance() c.set(Calendar.MONTH, key.index!!) val monthFormat = ComponentFormatDefaults.getFormat(ComponentFormatDefaults.Key.MONTH_SELECTOR) monthFormat.format(c.time) } else if ("dow" == key.kind) { val c = Calendar.getInstance() c.set(Calendar.DAY_OF_WEEK, key.index!!) val dowFormat = ComponentFormatDefaults.getFormat(ComponentFormatDefaults.Key.DOW_HEADER) dowFormat.format(c.time) } else { throw IllegalArgumentException("Unhandled key: $key") } } fun setText(key: Key, value: String) { texts.setProperty(key.property, value) } }
apache-2.0
78f1af90039ed379ea5a185b54d83db7
33.00905
165
0.616551
3.848438
false
false
false
false
HelloHuDi/usb-with-serial-port
usb-serial-port-measure/src/main/java/com/aio/usbserialport/utils/PreferenceUtil.kt
1
3279
package com.aio.usbserialport.utils import android.content.Context import android.content.SharedPreferences import android.util.Log import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method /** * Created by hd on 2017/8/31 . * */ object PreferenceUtil{ val FILE_NAME = "usb_serial_port_measure_data" fun put(context: Context, key: String, any: Any) { val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) val editor = sp.edit() when (any) { is String -> editor.putString(key, any) is Int -> editor.putInt(key, any) is Boolean -> editor.putBoolean(key, any) is Float -> editor.putFloat(key, any) is Long -> editor.putLong(key, any) else -> editor.putString(key, any.toString()) } SharedPreferencesCompat.apply(editor) } fun get(context: Context, key: String, defaultObject: Any): Any { val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) if (contains(context, key)) { when (defaultObject) { is String -> return sp.getString(key, defaultObject) is Int -> return sp.getInt(key, defaultObject) is Boolean -> return sp.getBoolean(key, defaultObject) is Float -> return sp.getFloat(key, defaultObject) is Long -> return sp.getLong(key, defaultObject) else -> { Log.e("tag","==others type:$defaultObject") } } } return defaultObject } fun remove(context: Context, key: String) { val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) val editor = sp.edit() if (contains(context, key)) { editor.remove(key) SharedPreferencesCompat.apply(editor) } } fun clear(context: Context) { val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) val editor = sp.edit() editor.clear() SharedPreferencesCompat.apply(editor) } fun contains(context: Context, key: String): Boolean { val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) return sp.contains(key) } fun getAll(context: Context): Map<String, *> { val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) return sp.all } private object SharedPreferencesCompat { private val sApplyMethod = findApplyMethod() private fun findApplyMethod(): Method? { try { val clz = SharedPreferences.Editor::class.java return clz.getMethod("apply") } catch (e: NoSuchMethodException) { } return null } fun apply(editor: SharedPreferences.Editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor) return } } catch (e: IllegalArgumentException) { } catch (e: IllegalAccessException) { } catch (e: InvocationTargetException) { } editor.commit() } } }
apache-2.0
e464b6b91b8c747829f18e5913859f3d
31.475248
78
0.578835
4.54785
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/types/path.kt
1
2794
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.types.Path import org.apache.tools.ant.types.ResourceCollection /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IPathNested : INestedComponent { fun path( location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) { _addPath(Path(component.project).apply { component.project.setProjectReference(this); _init(location, path, cache, nested) }) } fun _addPath(value: Path) } fun IResourceCollectionNested.path( location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) { _addResourceCollection(Path(component.project).apply { component.project.setProjectReference(this); _init(location, path, cache, nested) }) } fun Path._init( location: String?, path: String?, cache: Boolean?, nested: (KPath.() -> Unit)?) { if (location != null) setLocation(project.resolveFile(location)) if (path != null) setPath(path) if (cache != null) setCache(cache) if (nested != null) nested(KPath(this)) } class KPath(override val component: Path) : IPathNested, IResourceCollectionNested { fun pathelement(location: String? = null, path: String? = null) { component.createPathElement().apply { _init(component.project, location, path) } } fun existing(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) { component.addExisting(Path(component.project).apply { component.project.setProjectReference(this) _init(location, path, cache, nested) }) } fun extdirs(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) { component.addExtdirs(Path(component.project).apply { component.project.setProjectReference(this) _init(location, path, cache, nested) }) } override fun _addPath(value: Path) = component.add(value) override fun _addResourceCollection(value: ResourceCollection) = component.add(value) }
apache-2.0
fc41b366247a3b7143cefba9a5574152
29.043011
123
0.668576
3.541191
false
false
false
false
jsocle/jsocle-html
generator/khtml/element.kt
2
2376
package com.khtml.elements import com.khtml.BaseElement import com.khtml.BaseEmptyElement import com.khtml.attributeHandler public abstract class EmptyElement(elementName: String, {% for _, name in element_attrs %}{{name}}:String? = null{% if not loop.last %}, {% endif %}{%endfor%}): BaseEmptyElement(elementName = elementName) { {% for _, name in element_attrs -%} public var {{name}}: String? by attributeHandler {% endfor %} init { {% for _, name in element_attrs -%} this.{{name}} = {{name}} {% endfor %} } } public abstract class Element0(elementName: String, text_:String? = null, {% for _, name in element_attrs %}{{name}}:String? = null{% if not loop.last %}, {% endif %}{%endfor%}): BaseElement(elementName = elementName, text_ = text_) { {% for _, name in element_attrs -%} public var {{name}}: String? by attributeHandler {% endfor %} init { {% for _, name in element_attrs -%} this.{{name}} = {{name}} {% endfor %} } } {% for case, case_succ in cases %} public abstract class Element{{case.upper()}}(elementName: String, text_:String?, {% for _, name in element_attrs %}{{name}}:String? = null{% if not loop.last %}, {% endif %}{%endfor%}):Element{{ case_succ.upper() }}(elementName = elementName, text_ = text_, {% for _, name in element_attrs %}{{name}} = {{name}}{% if not loop.last %}, {% endif %}{%endfor%}) { {% for name, class_name, all_attrs, my_attrs, is_empty, fun_name in elements if name[0] == case %} public fun {{fun_name}}({% if not is_empty %}text_:String? = null, {% endif %}{% for _, i in all_attrs %}{{i}}: String? = null{% if not loop.last%}, {% endif %}{% endfor %}, init: {{class_name}}.() -> Unit = {}): {{class_name}} { val el = {{class_name}}({% if not is_empty %}text_ = text_, {% endif %}{% for _, i in all_attrs %}{{i}} = {{i}}{% if not loop.last%}, {% endif %}{% endfor %}, init = init) addNode(el) return el } {% endfor %} } {% endfor %} public abstract class Element(elementName: String, text_:String? = null, {% for _, name in element_attrs %}{{name}}:String? = null{% if not loop.last %}, {% endif %}{%endfor%}): ElementZ(elementName = elementName, text_ = text_, {% for _, name in element_attrs %}{{name}} = {{name}}{% if not loop.last %}, {% endif %}{%endfor%})
mit
32a0e53af95fd167cbd482a64cbea5fa
53
360
0.58165
3.499264
false
false
false
false
jitsi/jitsi-videobridge
rtp/src/main/kotlin/org/jitsi/rtp/rtp/RtpSequenceNumber.kt
1
4466
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtp import org.jitsi.rtp.util.RtpUtils /** * An inline class representing an RTP sequence number. The class operates just like * an Int but takes rollover into account for all operations. * * This constructor assumes that the value is already coerced. It MUST NOT be used outside this class, but it can not * be marked private. Use [Int.toRtpSequenceNumber] to create instances. */ @Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS") @JvmInline value class RtpSequenceNumber internal constructor(val value: Int) : Comparable<RtpSequenceNumber> { // These are intentionally not implemented, because using them as operators leads to inconsistent results. The // following code: // var n1 = RtpSequenceNumber(65535) // var n2 = RtpSequenceNumber(65535) // ++n1 // n2++ // System.err.println("n1=$n1, n2=$n2") // // Produces this result: // n1=RtpSequenceNumber(value=65536) n2=RtpSequenceNumber(value=0) // // Using "+= 1" yields the expected result. Note that if the same code above is in a "should" block, the result is // different (as expected). So if/when this is brought back, it should be tested outside a regular "should" block! // // operator fun inc(): RtpSequenceNumber = plus(1) // operator fun dec(): RtpSequenceNumber = minus(1) operator fun plus(num: Int): RtpSequenceNumber = (value + num).toRtpSequenceNumber() operator fun plus(seqNum: RtpSequenceNumber): RtpSequenceNumber = (value + seqNum.value).toRtpSequenceNumber() operator fun minus(num: Int): RtpSequenceNumber = plus(-num) operator fun minus(seqNum: RtpSequenceNumber): RtpSequenceNumber = plus(-seqNum.value) override operator fun compareTo(other: RtpSequenceNumber): Int = RtpUtils.getSequenceNumberDelta(value, other.value) operator fun rangeTo(other: RtpSequenceNumber) = RtpSequenceNumberProgression(this, other) companion object { val INVALID = RtpSequenceNumber(-1) } } fun Int.toRtpSequenceNumber() = RtpSequenceNumber(this and 0xffff) // Copied mostly from IntProgression. // NOTE(brian): technically this should probably inherit from ClosedRange, but // the inheritance causes issues with boxing and the inline types. See // https://youtrack.jetbrains.com/issue/KT-30716 and the bug linked there. class RtpSequenceNumberProgression( val start: RtpSequenceNumber, val endInclusive: RtpSequenceNumber, val step: Int = 1 ) : Iterable<RtpSequenceNumber> /*, ClosedRange<RtpSequenceNumber> */ { override fun iterator(): Iterator<RtpSequenceNumber> = RtpSequenceNumberProgressionIterator(start, endInclusive, step) companion object { fun fromClosedRange( rangeStart: RtpSequenceNumber, rangeEnd: RtpSequenceNumber, step: Int ): RtpSequenceNumberProgression = RtpSequenceNumberProgression(rangeStart, rangeEnd, step) } } // Copied mostly from IntProgressionIterator class RtpSequenceNumberProgressionIterator( first: RtpSequenceNumber, last: RtpSequenceNumber, val step: Int ) : Iterator<RtpSequenceNumber> { private val finalElement = last private var hasNext: Boolean = if (step > 0) first <= last else first >= last private var next = if (hasNext) first else finalElement override fun hasNext(): Boolean = hasNext override fun next(): RtpSequenceNumber = nextSeqNum() fun nextSeqNum(): RtpSequenceNumber { val value = next if (value == finalElement) { if (!hasNext) throw kotlin.NoSuchElementException() hasNext = false } else { next += step } return value } } infix fun RtpSequenceNumber.downTo(to: RtpSequenceNumber): RtpSequenceNumberProgression = RtpSequenceNumberProgression.fromClosedRange(this, to, -1)
apache-2.0
d9c3b378c3a9b19ae431af5c9dabb704
37.834783
118
0.714957
4.452642
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/map/detail/UserPhone.kt
1
4622
package mil.nga.giat.mage.map.detail import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Message import androidx.compose.material.icons.filled.Phone import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.lifecycle.LiveData import mil.nga.giat.mage.sdk.datastore.user.User import mil.nga.giat.mage.ui.theme.MageTheme sealed class UserPhoneAction { class Call(val user: User): UserPhoneAction() class Message(val user: User): UserPhoneAction() object Dismiss : UserPhoneAction() } @Composable fun UserPhoneDetails( liveData: LiveData<User?>, onAction: ((UserPhoneAction) -> Unit)? = null ) { val userState by liveData.observeAsState() val openDialog = userState != null MageTheme { if (openDialog) { Dialog( onDismissRequest = { onAction?.invoke(UserPhoneAction.Dismiss) } ) { Surface( shape = MaterialTheme.shapes.medium, color = MaterialTheme.colors.surface ) { Column(Modifier.padding(16.dp)) { Text( text = "Contact ${userState?.displayName}", style = MaterialTheme.typography.h6, modifier = Modifier.padding(bottom = 8.dp) ) Text( text = "${userState?.primaryPhone}", style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(bottom = 16.dp) ) UserPhoneOptions(userState) } } } } } } @Composable private fun UserPhoneOptions( user: User?, onAction: ((UserPhoneAction) -> Unit)? = null ) { if (user == null) return Column { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .clickable { onAction?.invoke(UserPhoneAction.Call(user)) } .padding(vertical = 16.dp, horizontal = 16.dp) ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Box( contentAlignment = Alignment.Center, modifier = Modifier .height(48.dp) .width(48.dp) .clip(RoundedCornerShape(24.dp)) .background(Color.Gray) ) { Icon( Icons.Default.Phone, tint = Color.White, contentDescription = "Phone" ) } Text( text = "Talk", style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.Medium, modifier = Modifier.padding(start = 24.dp) ) } } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .clickable { onAction?.invoke(UserPhoneAction.Message(user)) } .padding(vertical = 16.dp, horizontal = 16.dp) ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Box( contentAlignment = Alignment.Center, modifier = Modifier .height(48.dp) .width(48.dp) .clip(RoundedCornerShape(24.dp)) .background(Color.Gray) ) { Icon( Icons.Default.Message, tint = Color.White, contentDescription = "Message" ) } Text( text = "Text", style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.Medium, modifier = Modifier.padding(start = 24.dp) ) } } } }
apache-2.0
34a0711c54b390862c7fc93c3cef1f8c
30.664384
83
0.571614
5.007584
false
false
false
false
HughG/partial-order
partial-order-app/src/main/kotlin/org/tameter/partialorder/source/RedmineSource.kt
1
3168
package org.tameter.partialorder.source import org.tameter.kotlin.js.jsobject import org.tameter.kotlin.js.promise.Promise import org.tameter.kpouchdb.PouchDB import org.tameter.partialorder.dag.kpouchdb.NodeDoc import org.tameter.partialorder.lib.jquery.* import org.tameter.partialorder.source.kpouchdb.RedmineSourceSpecDoc import kotlin.js.json external interface RedmineIssue { val id: Long val subject: String } external interface RedmineIssueResponse { val issues: Array<RedmineIssue> } external interface RedmineSourceSpec { val url: String val apiKey: String? val projectId: String? } // By default, a REST query returns 25 pages, and returns only open issues // The version of Redmine used allows a maximum of 100 issues per query via the 'limit' keyword // Later versions allow the administrator to increase this maximum // The 'offset' keyword allows us to skip a number of issues // We use this keyword to recursively request until we have all issues private const val PAGE_SIZE_LIMIT = 100 class RedmineSource(val spec: RedmineSourceSpecDoc) : Source { override fun populate(db: PouchDB): Promise<PouchDB> { return doPopulate(db = db, pageNumber = 0) } // Recursively populate database with requests until all pages are found private fun doPopulate(db: PouchDB, pageNumber: Int): Promise<PouchDB> { return makeRequest(pageNumber).thenP { db.bulkDocs(it) }.thenP { results -> console.log("Redmine bulk store results, page ${pageNumber}:") for (it in results) { console.log(it) } if (results.size < PAGE_SIZE_LIMIT) { kotlin.js.Promise.resolve(db) } else { doPopulate(db, pageNumber + 1) } } } override val sourceId = "${spec.url}/issues" // Perform the Redmine REST API request for a page of open issues, and convert these into NodeDoc format. private fun makeRequest(pageNumber: Int): Promise<Array<NodeDoc>> { return jQuery.get(jsobject<JQueryAjaxSettings> { dataType = "json" if (spec.apiKey != null) { headers = json("X-Redmine-API-Key" to spec.apiKey) } url = queryUrl(pageNumber) }).then({ data: Any, _: String, _: JQueryXHR -> val issues = data.unsafeCast<RedmineIssueResponse>().issues issues.map { NodeDoc(sourceId, spec._id, spec.description, it.id, it.subject) }.toTypedArray() }).toPouchDB() } // Form the query URL for the specified results page. private fun queryUrl(pageNumber: Int): String { // TODO 2017-08-10 HughG: Retrieve the user ID using the apiKey, and add that to the query filter, to get only // tasks assigned to "me" (and, optionally, not assigned). val offset = pageNumber * PAGE_SIZE_LIMIT var queryURL = "${spec.url}/issues.json?offset=${offset}&limit=${PAGE_SIZE_LIMIT}" if (spec.projectId != null) { queryURL += "&project_id=${spec.projectId}" } return queryURL } }
mit
6d52b683c6b915e7317a24bd6c033c9e
36.282353
118
0.651199
4.071979
false
false
false
false
MichaelObi/PaperPlayer
app/src/main/java/xyz/michaelobi/paperplayer/playback/queue/LocalQueueManager.kt
1
5904
/* * MIT License * * Copyright (c) 2017 MIchael Obi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package xyz.michaelobi.paperplayer.playback.queue import rx.Observable import xyz.michaelobi.paperplayer.data.model.Song import xyz.michaelobi.paperplayer.playback.events.RepeatState import java.util.* class LocalQueueManager : QueueManager { /** * Now Playing Queue */ private var playingQueue = mutableListOf<QueueItem>() private var originalQueue = mutableListOf<QueueItem>() private var currentIndex: Int = 0 private var queueActionListener: QueueManager.QueueActionListener? = null private var title: String? = null private var shuffled = false private var repeatState = RepeatState.REPEAT_NONE init { currentIndex = 0 title = "" } override fun getCurrentIndex() = currentIndex override fun setCurrentIndex(index: Int) { if (index >= 0 && index < playingQueue.size) { this.currentIndex = index } } override fun setQueue(songs: List<Song>, startSongId: Long) = setQueue("", songs, startSongId) override fun setQueue(title: String, songs: List<Song>, startSongId: Long) { this.title = title var firstSongId = songs[0].id if (startSongId != 0L) firstSongId = startSongId playingQueue.clear() songs.forEach { song -> val item = QueueItem(song) playingQueue.add(item) if (song.id == startSongId) { currentIndex = playingQueue.lastIndexOf(item) } } } override fun getQueue(): Observable<MutableList<QueueItem>> = Observable.just(playingQueue) override fun getQueueTitle(): String? = null override fun getCurrentSong(): Song? { if (currentIndex >= playingQueue.size) { return null } return playingQueue[currentIndex].song } override fun next(ignoreRepeatOnce: Boolean): Song? { // return current song if repeat one is activated and not ignored if ((!ignoreRepeatOnce) and (repeatState == RepeatState.REPEAT_ONE)) { return playingQueue[currentIndex].song } // If repeat one and its ignore flag turn out to be false, increment the index currentIndex++ // If we've come to the end of the queue, reset to the beginning. if (currentIndex >= playingQueue.size) { currentIndex = 0 // If repeat all is activated return the song at index 0 so playback can restart if (repeatState == RepeatState.REPEAT_ALL) { return playingQueue[currentIndex].song } // If repeat all isn't activated, return null to stop playback return null } // Fallback for all conditions condition return playingQueue[currentIndex].song } override fun previous(): Song? { currentIndex-- if (currentIndex < 0) { currentIndex = 0 } return playingQueue[currentIndex].song } override fun hasSongs() = playingQueue.size > 0 override fun toggleShuffle(): Boolean { if (!shuffled) { shuffle() } else { unshuffle() } return shuffled } override fun isShuffled() = shuffled private fun shuffle() { val currentSongId = currentSong?.id originalQueue = playingQueue.toMutableList() val random = Random() for (i in playingQueue.size - 1 downTo 0) { // Get Pseudo-random number val index = random.nextInt(i + 1) if (playingQueue[index].song.id == currentSongId || playingQueue[i].song.id == currentSongId) { // Dont swap playing track continue } // Swap out the tracks for one another playingQueue[index] = playingQueue.set(i, playingQueue[index]) } shuffled = true } private fun unshuffle() { val currentSongId = currentSong?.id ?: -1L if (currentSongId != -1L) { playingQueue = originalQueue.toMutableList() for (i in playingQueue.size - 1 downTo 0) { val queueItem = playingQueue[i] if (queueItem.song.id == currentSongId) { currentIndex = i } } } shuffled = false } override fun toggleRepeat(): Int { if (repeatState < RepeatState.REPEAT_ONE) { repeatState++ } else { repeatState = 0 } return repeatState } override fun getRepeatState(): Int { return repeatState } fun setQueueActionListener(queueActionListener: QueueManager.QueueActionListener) { this.queueActionListener = queueActionListener } }
mit
b30a2c045d35ed2578bf45d3b833e711
31.805556
107
0.629573
4.742169
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/animations/expandableelement/ExpandableElementOther.kt
1
2465
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.animations.expandableelement import ExpandableElementMessageContent import android.graphics.Color import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.OvalShape import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.ResourcesScope import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.core.width import com.facebook.litho.dp import com.facebook.litho.flexbox.alignSelf import com.facebook.litho.flexbox.flex import com.facebook.litho.view.background import com.facebook.yoga.YogaAlign class ExpandableElementOther( private val messageText: String, private val timestamp: String, private val seen: Boolean = false ) : KComponent() { override fun ComponentScope.render(): Component? { return ExpandableElement( Row(style = Style.padding(end = 5.dp)) { child(getSenderTitle()) child( ExpandableElementMessageContent( backgroundColor = 0xFFEAEAEA.toInt(), messageTextColor = Color.BLACK, messageText = messageText)) }, timestamp = timestamp, seen = seen) } private fun ResourcesScope.getSenderTitle(): Component = Row( style = Style.margin(all = 5.dp) .alignSelf(YogaAlign.CENTER) .width(55.dp) .height(55.dp) .flex(shrink = 0f) .background(getCircle())) private fun getCircle(): ShapeDrawable = ShapeDrawable(OvalShape()).also { it.paint.color = Color.LTGRAY } }
apache-2.0
aa1283ae8fd365fc7d564e9e641aeb33
33.71831
75
0.703043
4.370567
false
false
false
false
owncloud/android
owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt
2
2481
/** * ownCloud Android client application * * @author Abel García de Prada * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.domain.shares.usecases import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.sharing.shares.ShareRepository import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase import com.owncloud.android.testutil.OC_SHARE import io.mockk.every import io.mockk.spyk import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test class GetSharesAsLiveDataUseCaseTest { @Rule @JvmField var instantTaskExecutorRule = InstantTaskExecutorRule() private val shareRepository: ShareRepository = spyk() private val useCase = GetSharesAsLiveDataUseCase((shareRepository)) private val useCaseParams = GetSharesAsLiveDataUseCase.Params("", "") private lateinit var sharesEmitted: MutableList<OCShare> @Before fun init() { sharesEmitted = mutableListOf() } @Test fun getSharesAsLiveDataOk() { val sharesLiveData = MutableLiveData<List<OCShare>>() every { shareRepository.getSharesAsLiveData(any(), any()) } returns sharesLiveData val sharesToEmit = listOf(OC_SHARE, OC_SHARE.copy(id = 2), OC_SHARE.copy(id = 3)) useCase.execute(useCaseParams).observeForever { it?.forEach { ocShare -> sharesEmitted.add(ocShare) } } sharesLiveData.postValue(sharesToEmit) Assert.assertEquals(sharesToEmit, sharesEmitted) } @Test(expected = Exception::class) fun getSharesAsLiveDataException() { every { shareRepository.getSharesAsLiveData(any(), any()) } throws Exception() useCase.execute(useCaseParams) } }
gpl-2.0
bfa5bb7c8ddbc3ce32415c2b045361b3
33.444444
90
0.741532
4.428571
false
true
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/setting/database/ClearDatabaseSourceItem.kt
1
2273
package eu.kanade.tachiyomi.ui.setting.database import android.view.View import androidx.recyclerview.widget.RecyclerView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.databinding.ClearDatabaseSourceItemBinding import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.icon data class ClearDatabaseSourceItem(val source: Source, private val mangaCount: Int) : AbstractFlexibleItem<ClearDatabaseSourceItem.Holder>() { override fun getLayoutRes(): Int { return R.layout.clear_database_source_item } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder { return Holder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>?, holder: Holder?, position: Int, payloads: MutableList<Any>?) { if (payloads.isNullOrEmpty()) { holder?.bind(source, mangaCount) } else { holder?.updateCheckbox() } } class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) { private val binding = ClearDatabaseSourceItemBinding.bind(view) fun bind(source: Source, count: Int) { binding.title.text = source.toString() binding.description.text = itemView.context.getString(R.string.clear_database_source_item_count, count) itemView.post { when { source.id == LocalSource.ID -> binding.thumbnail.setImageResource(R.mipmap.ic_local_source) source is SourceManager.StubSource -> binding.thumbnail.setImageDrawable(null) source.icon() != null -> binding.thumbnail.setImageDrawable(source.icon()) } } } fun updateCheckbox() { binding.checkbox.isChecked = (bindingAdapter as FlexibleAdapter<*>).isSelected(bindingAdapterPosition) } } }
apache-2.0
58265a4546dfe0951435e83599d74435
40.327273
157
0.708315
4.846482
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/management/config/subcontent/caller/ActivityCallerSubContent.kt
1
1250
package com.example.android.eyebody.management.config.subcontent.caller import android.app.Activity import android.content.Intent import android.support.v7.app.AppCompatActivity /** * Created by YOON on 2017-12-02 */ class ActivityCallerSubContent(text: String, preferenceName: String?, hasSwitch: Boolean, preferenceValueExplanation: List<String>? = null, private val activityJavaClass: List<Class<AppCompatActivity>?>?, requestCode: Int = 0) : CallableSubContent( text = text, preferenceName = preferenceName, hasSwitch = hasSwitch, preferenceValueExplanation = preferenceValueExplanation, callableList = activityJavaClass, requestCode = requestCode ) { /** attach call method to config storedInt on click listener */ override fun canCall(order: Int): Boolean = activityJavaClass?.get(order) != null override fun call(callerActivity: Activity, order: Int) { val mIntent = Intent(callerActivity.baseContext, activityJavaClass?.get(order)) callerActivity.startActivityForResult(mIntent, requestCode) } }
mit
3c128fd9d7c0679b957af0e4cc5b640d
40.7
95
0.6488
5.081301
false
true
false
false
Reyurnible/gitsalad-android
app/src/main/kotlin/com/hosshan/android/salad/component/scene/add/AddFragment.kt
1
4846
package com.hosshan.android.salad.component.scene.add import android.Manifest import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import com.hosshan.android.salad.R import com.hosshan.android.salad.component.scene.commit.CommitActivity import com.hosshan.android.salad.component.scene.commit.createIntent import com.hosshan.android.salad.ext.bindView import com.hosshan.android.salad.ext.checkGrantResult import com.hosshan.android.salad.ext.checkPermission import com.hosshan.android.salad.ext.start import com.hosshan.android.salad.manager.IntentManager import com.hosshan.android.salad.manager.PermissionManager import com.jakewharton.rxbinding.view.clicks import com.trello.rxlifecycle.FragmentLifecycleProvider import com.trello.rxlifecycle.components.support.RxFragment import com.trello.rxlifecycle.kotlin.bindToLifecycle import rx.android.schedulers.AndroidSchedulers import timber.log.Timber import javax.inject.Inject import kotlin.properties.Delegates /** * AddFragment */ class AddFragment : RxFragment(), AddView { companion object { } private var cameraButton: LinearLayout by Delegates.notNull() private var libraryButton: LinearLayout by Delegates.notNull() @Inject internal lateinit var presenter: AddPresenter private var imageUri: Uri? = null override fun onAttach(context: Context?) { super.onAttach(context) AddComponent.Initializer.init(activity).inject(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater?.inflate(R.layout.fragment_add, container, false)?.apply { cameraButton = bindView(R.id.add_layout_camera) libraryButton = bindView(R.id.add_layout_library) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) presenter.initialize(this) cameraButton.clicks() .observeOn(AndroidSchedulers.mainThread()) .bindToLifecycle(this) .subscribe { if (activity.checkPermission(Manifest.permission.CAMERA) && activity.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { imageUri = IntentManager.intentCamera(activity) } else { PermissionManager.requestCamera(activity) } } libraryButton.clicks() .observeOn(AndroidSchedulers.mainThread()) .bindToLifecycle(this) .subscribe { if (activity.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) { IntentManager.intentGallery(activity) } else { PermissionManager.requestReadExternalStorage(activity) } } } override fun provideLifecycle(): FragmentLifecycleProvider = this override fun onError(throwable: Throwable) { } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { Timber.d("onRequestPermissionsResult(${requestCode}, ${permissions})") when (requestCode) { PermissionManager.Code.CAMERA -> { if (activity.checkGrantResult(grantResults)) { imageUri = IntentManager.intentCamera(activity) } else { // TODO Show Dialog } } PermissionManager.Code.READ_EXTERNAL_STORAGE -> { if (activity.checkGrantResult(grantResults)) { IntentManager.intentGallery(activity) } else { // TODO Show Dialog } } else -> { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { Timber.d("onActivityResult(${requestCode}, ${resultCode})") when (requestCode) { IntentManager.Code.CAMERA -> { imageUri?.let { intentCommit(it) } } IntentManager.Code.GALLERY -> { data?.data?.let { intentCommit(it) } } else -> { super.onActivityResult(requestCode, resultCode, data) } } } private fun intentCommit(uri: Uri) { CommitActivity.createIntent(activity, uri).start(activity) } }
mit
af133934f4ef35a54580a927c4c0bf41
35.43609
119
0.640941
5.166311
false
false
false
false
Kotlin/dokka
core/src/main/kotlin/pages/utils.kt
1
3239
package org.jetbrains.dokka.pages import kotlin.reflect.KClass inline fun <reified T : ContentNode, R : ContentNode> R.mapTransform(noinline operation: (T) -> T): R = mapTransform(T::class, operation) inline fun <reified T : ContentNode, R : ContentNode> R.recursiveMapTransform(noinline operation: (T) -> T): R = recursiveMapTransform(T::class, operation) @PublishedApi @Suppress("UNCHECKED_CAST") internal fun <T : ContentNode, R : ContentNode> R.mapTransform(type: KClass<T>, operation: (T) -> T): R { if (this::class == type) { return operation(this as T) as R } val new = when (this) { is ContentGroup -> copy(children = children.map { it.mapTransform(type, operation) }) is ContentHeader -> copy(children = children.map { it.mapTransform(type, operation) }) is ContentCodeBlock -> copy(children = children.map { it.mapTransform(type, operation) }) is ContentCodeInline -> copy(children = children.map { it.mapTransform(type, operation) }) is ContentTable -> copy(header = header.map { it.recursiveMapTransform(type, operation) }, children = children.map { it.recursiveMapTransform(type, operation) }) is ContentList -> copy(children = children.map { it.mapTransform(type, operation) }) is ContentDivergentGroup -> copy(children = children.map { it.mapTransform(type, operation) }) is ContentDivergentInstance -> copy( before = before?.mapTransform(type, operation), divergent = divergent.mapTransform(type, operation), after = after?.mapTransform(type, operation) ) is PlatformHintedContent -> copy(inner = inner.mapTransform(type, operation)) else -> this } return new as R } @PublishedApi @Suppress("UNCHECKED_CAST") internal fun <T : ContentNode, R : ContentNode> R.recursiveMapTransform(type: KClass<T>, operation: (T) -> T): R { val new = when (this) { is ContentGroup -> copy(children = children.map { it.recursiveMapTransform(type, operation) }) is ContentHeader -> copy(children = children.map { it.recursiveMapTransform(type, operation) }) is ContentCodeBlock -> copy(children = children.map { it.recursiveMapTransform(type, operation) }) is ContentCodeInline -> copy(children = children.map { it.recursiveMapTransform(type, operation) }) is ContentTable -> copy(header = header.map { it.recursiveMapTransform(type, operation) }, children = children.map { it.recursiveMapTransform(type, operation) }) is ContentList -> copy(children = children.map { it.recursiveMapTransform(type, operation) }) is ContentDivergentGroup -> copy(children = children.map { it.recursiveMapTransform(type, operation) }) is ContentDivergentInstance -> copy( before = before?.recursiveMapTransform(type, operation), divergent = divergent.recursiveMapTransform(type, operation), after = after?.recursiveMapTransform(type, operation) ) is PlatformHintedContent -> copy(inner = inner.recursiveMapTransform(type, operation)) else -> this } if (new::class == type) { return operation(new as T) as R } return new as R }
apache-2.0
bb99c70018f16eb755583c1e06cde189
53.898305
169
0.676443
4.131378
false
false
false
false
dushmis/dagger
java/dagger/hilt/android/plugin/src/main/kotlin/dagger/hilt/android/plugin/util/AggregatedPackagesTransform.kt
3
3889
/* * Copyright (C) 2021 The Dagger 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 dagger.hilt.android.plugin.util import dagger.hilt.android.plugin.root.AggregatedAnnotation import java.io.ByteArrayOutputStream import java.io.File import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream import org.gradle.api.artifacts.transform.CacheableTransform import org.gradle.api.artifacts.transform.InputArtifact import org.gradle.api.artifacts.transform.TransformAction import org.gradle.api.artifacts.transform.TransformOutputs import org.gradle.api.artifacts.transform.TransformParameters import org.gradle.api.file.FileSystemLocation import org.gradle.api.provider.Provider import org.gradle.api.tasks.Classpath /** * A transform that outputs classes and jars containing only classes in key aggregating Hilt * packages that are used to pass dependencies between compilation units. */ @CacheableTransform abstract class AggregatedPackagesTransform : TransformAction<TransformParameters.None> { // TODO(danysantiago): Make incremental by using InputChanges and try to use @CompileClasspath @get:Classpath @get:InputArtifact abstract val inputArtifactProvider: Provider<FileSystemLocation> override fun transform(outputs: TransformOutputs) { val input = inputArtifactProvider.get().asFile when { input.isFile -> transformFile(outputs, input) input.isDirectory -> input.walkTopDown().filter { it.isFile }.forEach { transformFile(outputs, it) } else -> error("File/directory does not exist: ${input.absolutePath}") } } private fun transformFile(outputs: TransformOutputs, file: File) { if (file.isJarFile()) { var atLeastOneEntry = false // TODO(danysantiago): This is an in-memory buffer stream, consider using a temp file. val tmpOutputStream = ByteArrayOutputStream() ZipOutputStream(tmpOutputStream).use { outputStream -> ZipInputStream(file.inputStream()).forEachZipEntry { inputStream, inputEntry -> if (inputEntry.isClassFile()) { val parentDirectory = inputEntry.name.substringBeforeLast('/') val match = AggregatedAnnotation.AGGREGATED_PACKAGES.any { aggregatedPackage -> parentDirectory.endsWith(aggregatedPackage) } if (match) { outputStream.putNextEntry(ZipEntry(inputEntry.name)) inputStream.copyTo(outputStream) outputStream.closeEntry() atLeastOneEntry = true } } } } if (atLeastOneEntry) { outputs.file(JAR_NAME).outputStream().use { tmpOutputStream.writeTo(it) } } } else if (file.isClassFile()) { // If transforming a file, check if the parent directory matches one of the known aggregated // packages structure. File and Path APIs are used to avoid OS-specific issues when comparing // paths. val parentDirectory: File = file.parentFile val match = AggregatedAnnotation.AGGREGATED_PACKAGES.any { aggregatedPackage -> parentDirectory.endsWith(aggregatedPackage) } if (match) { outputs.file(file) } } } companion object { // The output file name containing classes in the aggregated packages. val JAR_NAME = "hiltAggregated.jar" } }
apache-2.0
dfc180f974e5d7fefa9bcec5f4bdc516
38.683673
99
0.720237
4.640811
false
false
false
false
y2k/ProjectCaerus
app/src/test/kotlin/android/content/res/EditTextAttributeTest.kt
1
1283
package android.content.res import android.content.Context import android.emoji.EmojiFactory import android.graphics.Canvas import android.view.View import android.widget.EditText import com.projectcaerus.AwtCanvas import com.projectcaerus.Size import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner /** * Created by y2k on 11/06/16. */ @RunWith(PowerMockRunner::class) @PrepareForTest(Resources.Theme::class, Context::class, EmojiFactory::class) class EditTextAttributeTest { val screen = Size(320, 480) lateinit var context: Context lateinit var canvas: Canvas @Before fun setUp() { context = ContextFactory().make() canvas = AwtCanvas(screen) } @Test fun test() { val editText = EditText(context) editText.hint = "Hint Hello World" editText.measure( View.MeasureSpec.makeMeasureSpec(screen.width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(screen.height, View.MeasureSpec.EXACTLY)) editText.layout(0, 0, screen.width, screen.height) editText.draw(canvas) canvas.setBitmap(null) } }
gpl-3.0
67c193fd1dbdede7ba0bdf184dd5f91f
26.319149
90
0.720966
4.125402
false
true
false
false
roylanceMichael/yaorm
yaorm/src/main/java/org/roylance/yaorm/services/hive/HiveGeneratorService.kt
1
15956
package org.roylance.yaorm.services.hive import org.roylance.yaorm.models.ColumnNameTuple import org.roylance.yaorm.YaormModel import org.roylance.yaorm.services.ISQLGeneratorService import org.roylance.yaorm.utilities.ProjectionUtilities import org.roylance.yaorm.utilities.YaormUtils import java.util.* class HiveGeneratorService(override val bulkInsertSize: Int = 2000, private val emptyAsNull: Boolean = false) : ISQLGeneratorService { override val textTypeName: String get() = SqlTextName override val integerTypeName: String get() = SqlIntegerName override val realTypeName: String get() = SqlRealName override val blobTypeName: String get() = SqlBlobName override val protoTypeToSqlType = HashMap<YaormModel.ProtobufType, String>() override val sqlTypeToProtoType = HashMap<String, YaormModel.ProtobufType>() override val insertSameAsUpdate: Boolean get() = true init { protoTypeToSqlType.put(YaormModel.ProtobufType.STRING, SqlTextName) protoTypeToSqlType.put(YaormModel.ProtobufType.INT32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.INT64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.UINT32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.UINT64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SINT32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SINT64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.FIXED32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.FIXED64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SFIXED32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SFIXED64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.BOOL, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.BYTES, SqlTextName) protoTypeToSqlType.put(YaormModel.ProtobufType.DOUBLE, SqlRealName) protoTypeToSqlType.put(YaormModel.ProtobufType.FLOAT, SqlRealName) sqlTypeToProtoType.put(SqlTextName, YaormModel.ProtobufType.STRING) sqlTypeToProtoType.put(SqlIntegerName, YaormModel.ProtobufType.INT64) sqlTypeToProtoType.put(SqlRealName, YaormModel.ProtobufType.DOUBLE) sqlTypeToProtoType.put(SqlTextName, YaormModel.ProtobufType.STRING) } override fun buildJoinSql(joinTable: YaormModel.JoinTable): String { return """select * from ${this.buildKeyword(joinTable.firstTable.name)} a join ${this.buildKeyword(joinTable.secondTable.name)} b on a.${buildKeyword(joinTable.firstColumn.name)} = b.${buildKeyword(joinTable.secondColumn.name)} """ } override fun buildSelectIds(definition: YaormModel.TableDefinition): String { return "select id from ${this.buildKeyword(definition.name)}" } override fun buildCountSql(definition: YaormModel.TableDefinition): String { return "select count(1) as ${this.buildKeyword("longVal")} from ${this.buildKeyword(definition.name)}" } override fun buildCreateColumn( definition: YaormModel.TableDefinition, propertyDefinition: YaormModel.ColumnDefinition): String? { if (!this.protoTypeToSqlType.containsKey(propertyDefinition.type)) { return null } return "alter table ${this.buildKeyword(definition.name)} add columns (${this.buildKeyword(propertyDefinition.name)}, ${this.protoTypeToSqlType[propertyDefinition.type]})" } override fun buildDropColumn( definition: YaormModel.TableDefinition, propertyDefinition: YaormModel.ColumnDefinition): String? { val columnNames = YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) .map { "${this.buildKeyword(it.sqlColumnName)} ${it.dataType}" } .joinToString(YaormUtils.Comma) return "alter table ${this.buildKeyword(definition.name)} replace columns ($columnNames)" } override fun buildDropIndex( definition: YaormModel.TableDefinition, columns: Map<String, YaormModel.ColumnDefinition>): String? { return null } override fun buildCreateIndex( definition: YaormModel.TableDefinition, properties: Map<String, YaormModel.ColumnDefinition>, includes: Map<String, YaormModel.ColumnDefinition>): String? { return null } override fun buildUpdateWithCriteria( definition: YaormModel.TableDefinition, record: YaormModel.Record, whereClauseItem: YaormModel.WhereClause): String? { try { val nameTypeMap = HashMap<String, ColumnNameTuple<String>>() YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) .forEach { nameTypeMap.put(it.sqlColumnName, it) } if (nameTypeMap.size == 0) { return null } val criteriaString: String = YaormUtils .buildWhereClause(whereClauseItem, this) val updateKvp = ArrayList<String>() record .columnsList .forEach { updateKvp.add(this.buildKeyword(it.definition.name) + YaormUtils.Equals + YaormUtils.getFormattedString(it, emptyAsNull)) } // nope, not updating entire table if (criteriaString.isEmpty()) { return null } val updateSql = java.lang.String.format( UpdateTableMultipleTemplate, this.buildKeyword(definition.name), updateKvp.joinToString(YaormUtils.Comma + YaormUtils.Space), criteriaString) return updateSql } catch (e: Exception) { e.printStackTrace() return null } } override fun buildDropTable(definition: YaormModel.TableDefinition): String { return "drop table ${this.buildKeyword(definition.name)}" } override fun buildDeleteAll(definition: YaormModel.TableDefinition): String { return "delete from ${this.buildKeyword(definition.name)}" } override fun buildDeleteWithCriteria( definition: YaormModel.TableDefinition, whereClauseItem: YaormModel.WhereClause): String { val whereClause = YaormUtils.buildWhereClause(whereClauseItem, this) return "delete from ${this.buildKeyword(definition.name)} where $whereClause" } override fun buildBulkInsert( definition: YaormModel.TableDefinition, records: YaormModel.Records): String { val tableName = definition.name val nameTypeMap = HashMap<String, ColumnNameTuple<String>>() YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) .forEach { nameTypeMap.put(it.sqlColumnName, it) } val columnNames = ArrayList<String>() val sortedColumns = definition.columnDefinitionsList.sortedBy { it.order } sortedColumns .forEach { if (nameTypeMap.containsKey(it.name)) { columnNames.add(this.buildKeyword(it.name)) } } val initialStatement = "insert into table ${this.buildKeyword(tableName)} \nselect * from\n" val selectStatements = ArrayList<String>() records .recordsList .forEach { instance -> val valueColumnPairs = ArrayList<String>() sortedColumns.forEach { columnDefinition -> val foundColumn = instance.columnsList.firstOrNull { column -> column.definition.name == columnDefinition.name } if (foundColumn != null) { val formattedString = YaormUtils.getFormattedString(foundColumn, emptyAsNull) if (valueColumnPairs.isEmpty()) { valueColumnPairs.add("select $formattedString as ${this.buildKeyword(foundColumn.definition.name)}") } else { valueColumnPairs.add("$formattedString as ${this.buildKeyword(foundColumn.definition.name)}") } } else { val actualColumn = YaormUtils.buildColumn(YaormUtils.EmptyString, columnDefinition) val formattedValue = YaormUtils.getFormattedString(actualColumn, emptyAsNull) if (valueColumnPairs.isEmpty()) { valueColumnPairs.add("select $formattedValue as ${this.buildKeyword(columnDefinition.name)}") } else { valueColumnPairs.add("$formattedValue as ${this.buildKeyword(columnDefinition.name)}") } } } selectStatements.add(valueColumnPairs.joinToString(YaormUtils.Comma)) } val carriageReturnSeparatedRows = selectStatements.joinToString("${YaormUtils.Comma}${YaormUtils.CarriageReturn}") return "$initialStatement(\nselect stack(\n ${selectStatements.size},\n $carriageReturnSeparatedRows)) s" } override fun buildSelectAll(definition: YaormModel.TableDefinition, limit: Int, offset: Int): String { return java.lang.String.format(SelectAllTemplate, this.buildKeyword(definition.name), limit) } override fun buildWhereClause( definition: YaormModel.TableDefinition, whereClauseItem: YaormModel.WhereClause): String? { val whereClauseItems = YaormUtils.buildWhereClause(whereClauseItem, this) val whereSql = java.lang.String.format( WhereClauseTemplate, this.buildKeyword(definition.name), whereClauseItems) return whereSql } override fun buildDeleteTable(definition: YaormModel.TableDefinition, primaryKey: YaormModel.Column): String? { val deleteSql = java.lang.String.format( DeleteTableTemplate, this.buildKeyword(definition.name), YaormUtils.getFormattedString(primaryKey, emptyAsNull)) return deleteSql } override fun buildUpdateTable(definition: YaormModel.TableDefinition, record: YaormModel.Record): String? { try { val nameTypeMap = HashMap<String, ColumnNameTuple<String>>() YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) .forEach { nameTypeMap.put(it.sqlColumnName, it) } if (nameTypeMap.size == 0) { return null } var stringId: String? = null val updateKvp = ArrayList<String>() record .columnsList .sortedBy { it.definition.order } .forEach { val formattedString = YaormUtils.getFormattedString(it, emptyAsNull) if (it.definition.name == YaormUtils.IdName) { stringId = formattedString } else { updateKvp.add(this.buildKeyword(it.definition.name) + YaormUtils.Equals + formattedString) } } if (stringId == null) { return null } val updateSql = java.lang.String.format( UpdateTableSingleTemplate, this.buildKeyword(definition.name), updateKvp.joinToString(YaormUtils.Comma + YaormUtils.Space), stringId!!) return updateSql } catch (e: Exception) { e.printStackTrace() return null } } override fun buildInsertIntoTable( definition: YaormModel.TableDefinition, record: YaormModel.Record): String? { try { val values = ArrayList<String>() record .columnsList .sortedBy { it.definition.order } .forEach { values.add(YaormUtils.getFormattedString(it, emptyAsNull)) } val insertSql = java.lang.String.format( InsertIntoTableSingleTemplate, this.buildKeyword(definition.name), values.joinToString(YaormUtils.Comma)) return insertSql } catch (e: Exception) { e.printStackTrace() return null } } override fun buildCreateTable(definition: YaormModel.TableDefinition): String? { val nameTypes = YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) if (nameTypes.isEmpty()) { return null } val workspace = StringBuilder() for (nameType in nameTypes) { if (workspace.isEmpty()) { workspace .append(YaormUtils.Space) .append(this.buildKeyword(nameType.sqlColumnName)) .append(YaormUtils.Space) .append(nameType.dataType) } else { workspace .append(YaormUtils.Comma) .append(YaormUtils.Space) .append(this.buildKeyword(nameType.sqlColumnName)) .append(YaormUtils.Space) .append(nameType.dataType) } } val createTableSql = java.lang.String.format( CreateInitialTableTemplate, this.buildKeyword(definition.name), workspace.toString(), 10) return createTableSql } override fun buildKeyword(keyword: String): String { return keyword } override fun getSchemaNames(): String { return "" } override fun getTableNames(schemaName: String): String { return ".tables" } override fun buildTableDefinitionSQL(schemaName: String, tableName: String): String { return "" } override fun buildTableDefinition(tableName: String, records: YaormModel.Records): YaormModel.TableDefinition { return YaormModel.TableDefinition.getDefaultInstance() } override fun buildProjectionSQL(projection: YaormModel.Projection): String { return ProjectionUtilities.buildProjectionSQL(projection, this) } companion object { private const val CreateInitialTableTemplate = "create table if not exists %s (%s)\nclustered by (${YaormUtils.IdName})\ninto %s buckets\nstored as orc TBLPROPERTIES ('transactional'='true')" private const val InsertIntoTableSingleTemplate = "insert into %s values (%s)" private const val UpdateTableSingleTemplate = "update %s set %s where id=%s" private const val UpdateTableMultipleTemplate = "update %s set %s where %s" private const val DeleteTableTemplate = "delete from %s where id=%s" private const val WhereClauseTemplate = "select * from %s where %s" private const val SelectAllTemplate = "select * from %s limit %s" private const val SqlTextName = "string" private const val SqlRealName = "double" private const val SqlIntegerName = "bigint" private const val SqlBlobName = "string" } }
mit
82f30fd9c85481cdb2093f853f14a389
38.989975
199
0.618513
5.114103
false
false
false
false
stoman/CompetitiveProgramming
problems/2021adventofcode22a/submissions/accepted/StefanAxisBucketsLists.kt
2
2076
import java.util.* private data class Instruction2( val on: Boolean, val xMin: Int, val xMax: Int, val yMin: Int, val yMax: Int, val zMin: Int, val zMax: Int ) private fun List<Int>.distToNext(i: Int): Long = if (get(i) !in -50..50) 0 else (get(i + 1) - get(i)).toLong() @ExperimentalStdlibApi fun main() { val s = Scanner(System.`in`).useDelimiter("""\sx=|\.\.|,y=|,z=|\n""") val instructions = buildList { while (s.hasNext()) { add( Instruction2( s.next() == "on", s.nextInt().coerceAtLeast(-51), s.nextInt().coerceAtMost(51), s.nextInt().coerceAtLeast(-51), s.nextInt().coerceAtMost(51), s.nextInt().coerceAtLeast(-51), s.nextInt().coerceAtMost(51) ) ) } } val xValues = (instructions.map { it.xMin } + instructions.map { it.xMax + 1 }).toSet().sorted() val yValues = (instructions.map { it.yMin } + instructions.map { it.yMax + 1 }).toSet().sorted() val zValues = (instructions.map { it.zMin } + instructions.map { it.zMax + 1 }).toSet().sorted() val xIndex = xValues.mapIndexed { i, v -> v to i }.toMap() val yIndex = yValues.mapIndexed { i, v -> v to i }.toMap() val zIndex = zValues.mapIndexed { i, v -> v to i }.toMap() val status = List(xValues.size) { List(yValues.size) { MutableList(zValues.size) { false } } } for (instruction in instructions) { for (x in xIndex[instruction.xMin]!! until xIndex[instruction.xMax+1]!!) { for (y in yIndex[instruction.yMin]!! until yIndex[instruction.yMax+1]!!) { for (z in zIndex[instruction.zMin]!! until zIndex[instruction.zMax+1]!!) { status[x][y][z] = instruction.on } } } } var sum = 0L for (x in status.indices) { val xDist = xValues.distToNext(x) for (y in status[x].indices) { val yDist = yValues.distToNext(y) for (z in status[x][y].indices) { if (status[x][y][z]) { val zDist = zValues.distToNext(z) sum += xDist * yDist * zDist } } } } println(sum) }
mit
298d8b0d663686cd23d4e40be2803a4c
31.4375
110
0.580443
3.332263
false
false
false
false
googlecreativelab/digital-wellbeing-experiments-toolkit
copresence/app/src/main/java/com/digitalwellbeingexperiments/toolkit/copresence/DataStore.kt
1
2397
// 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 // // 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.digitalwellbeingexperiments.toolkit.copresence import android.content.Context import android.os.Build import java.util.* class DataStore(context: Context) { companion object { private const val PREF_NAME = "datastore" private const val KEY_NAME = "name" private const val KEY_DEVICE_ID = "device_id" } interface Listener { fun onSessionListUpdated() } var listener: Listener? = null private val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) private val sessions = HashMap<String, NearbyDeviceSession>() fun getLocalDeviceId(): String { var deviceId = prefs.getString(KEY_DEVICE_ID, null) if (deviceId == null) { deviceId = UUID.randomUUID().toString() prefs.edit().putString(KEY_DEVICE_ID, deviceId).apply() } return deviceId } fun getName(): String { val defaultName = "${Build.MANUFACTURER} ${Build.MODEL} [${getLocalDeviceId().take(8)}]" return prefs.getString(KEY_NAME, defaultName) ?: defaultName } fun addSession(session: NearbyDeviceSession) { sessions[session.deviceId] = session listener?.onSessionListUpdated() } fun removeSession(deviceId: String) { sessions.remove(deviceId) listener?.onSessionListUpdated() } fun sessionExists(deviceId: String) = sessions.keys.contains(deviceId) fun clearExpiredSessions() { val sessionsToRemove = sessions.filter { it.value.hasExpired() }.keys sessionsToRemove.forEach { deviceId -> sessions.remove(deviceId) } if (sessionsToRemove.isNotEmpty()) { listener?.onSessionListUpdated() } } fun getAllSessions() = sessions.values.toList() }
apache-2.0
ae56e7af04380680fcec29489028514f
30.552632
96
0.675428
4.480374
false
false
false
false
alashow/music-android
modules/base-android/src/main/java/tm/alashow/base/util/arch/Event.kt
1
912
/* * Copyright (C) 2019, Alashov Berkeli * All rights reserved. */ package tm.alashow.base.util.arch import tm.alashow.domain.models.Optional typealias LiveEvent<T> = SingleLiveEvent<Event<T>> open class Event<out T>(private val data: T) { var consumed = false private set // disallow external change /** * Returns the data and prevents its use again. */ fun value(): Optional<T> = when (consumed) { true -> Optional.None false -> { consumed = true Optional.Some(data) } } /** * Invokes [action] iff not consumed yet. */ fun consume(action: (T) -> Unit) = this.value().optional(onSome = action) /** * Returns the content, even if it's already been consumed. */ fun peek(): T = data } fun <T> T.asEvent() = Event(this) fun <T> LiveEvent<T>.post(value: T) = postValue(value.asEvent())
apache-2.0
0b072d7f6731c75b189806a8e34a5944
22.384615
77
0.598684
3.737705
false
false
false
false
hschroedl/FluentAST
core/src/main/kotlin/at.hschroedl.fluentast/ast/expression/ThisExpression.kt
1
812
package at.hschroedl.fluentast.ast.expression import org.eclipse.jdt.core.dom.AST import org.eclipse.jdt.core.dom.ThisExpression /** * Used to build a [ThisExpression]. * * Java: * ~~~ java * this * ~~~ * * JDT: * ~~~ java * ThisExpression exp = ast.newThisExpression(); * ~~~ * * Fluentast: * ~~~ java * ThisExpression exp = this_().build(ast); * ~~~ * * @constructor takes an optional qualifier for the this expression. * * @see [ThisExpression] * */ class FluentThisExpression internal constructor(private val qualifier: String? = null) : FluentExpression() { override fun build(ast: AST): ThisExpression { val exp = ast.newThisExpression() if (qualifier != null) { exp.qualifier = FluentName(qualifier).build(ast) } return exp } }
apache-2.0
e72288b6f3b0c975464dc495b32f6ec2
20.368421
109
0.639163
3.724771
false
false
false
false
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/session/UserSession.kt
1
1057
package lt.vilnius.tvarkau.session import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import io.reactivex.Completable import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.CompletableSubject import lt.vilnius.tvarkau.api.TvarkauMiestaApi import lt.vilnius.tvarkau.entity.User import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class UserSession @Inject constructor( private val api: TvarkauMiestaApi ) { init { Timber.d("Creating user session") } private val _user = MutableLiveData<User>() val user: LiveData<User> get() = _user fun refreshUser(): Completable { val result = CompletableSubject.create() api.getCurrentUser() .map { it.user } .subscribeBy( onSuccess = { _user.postValue(it) result.onComplete() }, onError = { result.onError(it) } ) return result } }
mit
a1a80873e4d89f073d8b383692bc2bd6
24.166667
48
0.647114
4.459916
false
false
false
false
ankidroid/Anki-Android
lint-rules/src/main/java/com/ichi2/anki/lint/rules/HardcodedPreferenceKey.kt
1
2826
/* * Copyright (c) 2022 Brayan Oliveira <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ @file:Suppress("UnstableApiUsage") package com.ichi2.anki.lint.rules import com.android.resources.ResourceFolderType import com.android.tools.lint.detector.api.* import com.google.common.annotations.VisibleForTesting import com.ichi2.anki.lint.utils.Constants import org.w3c.dom.Element /** * A Lint check to prevent using hardcoded strings on preferences keys */ class HardcodedPreferenceKey : ResourceXmlDetector() { companion object { @VisibleForTesting val ID = "HardcodedPreferenceKey" @VisibleForTesting val DESCRIPTION = "Preference key should not be hardcoded" private const val EXPLANATION = "Extract the key to a resources XML so it can be reused" private val implementation = Implementation(HardcodedPreferenceKey::class.java, Scope.RESOURCE_FILE_SCOPE) val ISSUE: Issue = Issue.create( ID, DESCRIPTION, EXPLANATION, Constants.ANKI_XML_CATEGORY, Constants.ANKI_XML_PRIORITY, Constants.ANKI_XML_SEVERITY, implementation ) } override fun getApplicableElements(): Collection<String>? { return ALL } override fun visitElement(context: XmlContext, element: Element) { reportAttributeIfHardcoded(context, element, "android:key") reportAttributeIfHardcoded(context, element, "android:dependency") } private fun reportAttributeIfHardcoded(context: XmlContext, element: Element, attributeName: String) { val attrNode = element.getAttributeNode(attributeName) ?: return if (isHardcodedString(attrNode.value)) { context.report(ISSUE, element, context.getLocation(attrNode), DESCRIPTION) } } private fun isHardcodedString(string: String): Boolean { // resources start with a `@`, and attributes start with a `?` return string.isNotEmpty() && !string.startsWith("@") && !string.startsWith("?") } override fun appliesTo(folderType: ResourceFolderType): Boolean { return folderType == ResourceFolderType.XML } }
gpl-3.0
ca59bc03721adb4c77dc5b92a55b6659
37.189189
114
0.700991
4.471519
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnusedPrivateClassSpec.kt
1
10114
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.test.compileAndLint import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class UnusedPrivateClassSpec : Spek({ val subject by memoized { UnusedPrivateClass() } describe("top level interfaces") { it("should report them if not used") { val code = """ private interface Foo class Bar """ val lint = subject.compileAndLint(code) assertThat(lint).hasSize(1) with(lint[0].entity) { assertThat(ktElement?.text).isEqualTo("private interface Foo") } } describe("top level private classes") { it("should report them if not used") { val code = """ private class Foo class Bar """ val lint = subject.compileAndLint(code) assertThat(lint).hasSize(1) with(lint[0].entity) { assertThat(ktElement?.text).isEqualTo("private class Foo") } } it("should not report them if used as parent") { val code = """ private open class Foo private class Bar : Foo() """ val lint = subject.compileAndLint(code) assertThat(lint).hasSize(1) with(lint[0].entity) { assertThat(ktElement?.text).isEqualTo("private class Bar : Foo()") } } it("should not report them used as generic parent type") { val code = """ class Bar private interface Foo<in T> { operator fun invoke(b: T): Unit } data class FooOne(val b: Bar) : Foo<Bar> { override fun invoke(b: Bar): Unit = Unit } """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } } it("should not report them if used inside a function") { val code = """ private class Foo fun something() { val foo: Foo = Foo() } """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as function parameter") { val code = """ private class Foo private object Bar { fun bar(foo: Foo) = Unit } """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as nullable variable type") { val code = """ private class Foo private val a: Foo? = null """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as variable type") { val code = """ private class Foo private lateinit var a: Foo """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as generic type") { val code = """ private class Foo private lateinit var foos: List<Foo> """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as generic type in functions") { val code = """ private class Foo private var a = bar<Foo>() fun <T> bar(): T { throw Exception() } """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as nested generic type") { val code = """ private class Foo private lateinit var foos: List<List<Foo>> """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as type with generics") { val code = """ private class Foo<T> private lateinit var foos: Foo<String> """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as nullable type with generics") { val code = """ private class Foo<T> private var foos: Foo<String>? = Foo() """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as non-argument constructor") { val code = """ private class Foo private val a = Foo() """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as constructor with arguments") { val code = """ private class Foo(val a: String) private val a = Foo("test") """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as function return type") { val code = """ private class Foo(val a: String) private object Bar { fun foo(): Foo? = null } """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as lambda declaration parameter") { val code = """ private class Foo private val lambda: ((Foo) -> Unit)? = null """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as lambda declaration return type") { val code = """ private class Foo private val lambda: (() -> Foo)? = null """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as lambda declaration generic type") { val code = """ private class Foo private val lambda: (() -> List<Foo>)? = null """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } it("should not report them if used as inline object type") { val code = """ private abstract class Foo { abstract fun bar() } private object Bar { private fun foo() = object : Foo() { override fun bar() = Unit } } """ val lint = subject.compileAndLint(code) assertThat(lint).isEmpty() } } describe("testcase for reported false positives") { it("does not crash when using wildcards in generics - #1345") { val code = """ import kotlin.reflect.KClass private class Foo fun bar(clazz: KClass<*>) = Unit """ val findings = UnusedPrivateClass().compileAndLint(code) assertThat(findings).hasSize(1) } it("does not report (companion-)object/named-dot references - #1347") { val code = """ class Test { val items = Item.values().map { it.text }.toList() } private enum class Item(val text: String) { A("A"), B("B"), C("C") } """ val findings = UnusedPrivateClass().compileAndLint(code) assertThat(findings).isEmpty() } it("does not report classes that are used with ::class - #1390") { val code = """ class UnusedPrivateClassTest { private data class SomeClass(val name: String) private data class AnotherClass(val id: Long) fun `verify class is used`(): Boolean { val instance = SomeClass(name = "test") return AnotherClass::class.java.simpleName == instance::class.java.simpleName } fun getSomeObject(): ((String) -> Any) = ::InternalClass private class InternalClass(val param: String) } """ val findings = UnusedPrivateClass().compileAndLint(code) assertThat(findings).isEmpty() } it("does not report used private annotations - #2093") { val code = """ private annotation class Test1 private annotation class Test2 private annotation class Test3 private annotation class Test4 @Test1 class Custom(@Test2 param: String) { @Test3 val property = "" @Test4 fun function() {} } """ val findings = UnusedPrivateClass().compileAndLint(code) assertThat(findings).isEmpty() } } })
apache-2.0
b34e3b9369779628f4a13f90efe0acab
28.48688
105
0.467767
5.60643
false
false
false
false
SchoolPower/SchoolPower-Android
app/src/main/java/com/carbonylgroup/schoolpower/fragments/DonationFragment.kt
1
2751
package com.carbonylgroup.schoolpower.fragments import android.content.Intent import android.didikee.donate.AlipayDonate import android.os.Bundle import androidx.fragment.app.Fragment import androidx.cardview.widget.CardView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.carbonylgroup.schoolpower.R import com.carbonylgroup.schoolpower.activities.WechatIntroActivity import com.carbonylgroup.schoolpower.utils.CryptoDonationDialog import com.carbonylgroup.schoolpower.utils.Utils class DonationFragment : Fragment() { val WECHAT_INTRO = 1 private lateinit var utils: Utils private val AlipayToken = "tsx09230fuwngogndwbkg3b" override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_donation, container, false) utils = Utils(activity!!) view.findViewById<CardView>(R.id.alipay_card).setOnClickListener { gotoAlipay() } view.findViewById<CardView>(R.id.wechat_card).setOnClickListener { gotoWechatPay() } view.findViewById<CardView>(R.id.paypal_card).setOnClickListener { gotoPaypal() } view.findViewById<CardView>(R.id.bitcoin_card).setOnClickListener { gotoCrypto(CryptoDonationDialog.CRYPTO_TYPE.BITCOIN) } view.findViewById<CardView>(R.id.eth_card).setOnClickListener { gotoCrypto(CryptoDonationDialog.CRYPTO_TYPE.ETHER) } return view } fun gotoAlipay() { if (AlipayDonate.hasInstalledAlipayClient(activity)) { AlipayDonate.startAlipayClient(activity, AlipayToken) setIsDonated(true) } else { utils.showSnackBar(view!!.findViewById(R.id.donation_fragment), getString(R.string.AlipayNotFound), true) } } fun gotoWechatPay() { startActivityForResult(Intent(activity, WechatIntroActivity::class.java), WECHAT_INTRO) } fun gotoPaypal() { AlipayDonate.startIntentUrl(activity, getString(R.string.paypalDonationURL)) setIsDonated(true) } fun gotoCrypto(crypto: CryptoDonationDialog.CRYPTO_TYPE) { CryptoDonationDialog(activity!!, crypto).show() setIsDonated(true) } private fun setIsDonated(donated: Boolean) { utils.setPreference("Donated", donated, Utils.TmpData) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == WECHAT_INTRO && resultCode == WechatIntroActivity().WECHAT_NOT_FOUND) { utils.showSnackBar(activity!!.findViewById(R.id.donation_fragment), getString(R.string.WechatNotFound), true) } } }
gpl-3.0
fb2ef61328b196f70a5189eeddc13a9b
40.059701
130
0.732097
4.285047
false
false
false
false
matkoniecz/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/data/osm/edits/update_tags/StringMapEntryDeleteTest.kt
1
1256
package de.westnordost.streetcomplete.data.osm.edits.update_tags import org.junit.Test import org.junit.Assert.* class StringMapEntryDeleteTest { @Test fun `conflicts if already changed to different value`() { assertTrue(StringMapEntryDelete("a", "b").conflictsWith(mutableMapOf("a" to "c"))) } @Test fun `does not conflict if already deleted key`() { assertFalse(StringMapEntryDelete("a", "b").conflictsWith(mutableMapOf())) } @Test fun `does not conflict if not deleted yet`() { assertFalse(StringMapEntryDelete("a", "b").conflictsWith(mutableMapOf("a" to "b"))) } @Test fun `toString is as expected`() { assertEquals( "DELETE \"a\"=\"b\"", StringMapEntryDelete("a", "b").toString() ) } @Test fun apply() { val m = mutableMapOf("a" to "b") StringMapEntryDelete("a", "b").applyTo(m) assertFalse(m.containsKey("a")) } @Test fun reverse() { val m = mutableMapOf("a" to "b") val delete = StringMapEntryDelete("a", "b") val reverseDelete = delete.reversed() delete.applyTo(m) reverseDelete.applyTo(m) assertEquals(1, m.size) assertEquals("b", m["a"]) } }
gpl-3.0
da9fe3d6643d482d80d06baa2a6e2f3a
26.304348
91
0.601911
4.145215
false
true
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/WebView.kt
1
575
package com.boardgamegeek.extensions import android.webkit.WebView fun WebView.setWebViewText(html: String) { this.loadDataWithBaseURL(null, fixInternalLinks(html), "text/html", "UTF-8", null) } private fun fixInternalLinks(text: String): String { // ensure internal, path-only links are complete with the hostname if (text.isEmpty()) return "" var fixedText = text.replace("<a\\s+href=\"/".toRegex(), "<a href=\"https://www.boardgamegeek.com/") fixedText = fixedText.replace("<img\\s+src=\"//".toRegex(), "<img src=\"https://") return fixedText }
gpl-3.0
19395e2dad57974aed0c53ed2d381e2b
37.333333
104
0.695652
3.782895
false
false
false
false
kropp/intellij-makefile
src/main/kotlin/name/kropp/intellij/makefile/MakefileParserUtil.kt
1
6163
@file:Suppress("UNUSED_PARAMETER") package name.kropp.intellij.makefile import com.intellij.lang.* import com.intellij.lang.parser.* import com.intellij.psi.* import com.intellij.psi.tree.* import name.kropp.intellij.makefile.psi.MakefileTypes.* object MakefileParserUtil : GeneratedParserUtilBase() { private val nonTargetTokens = setOf(EOL, COLON, TAB, SPLIT) private val nonPrereqTokens = setOf(EOL, TAB, COLON, OPEN_CURLY, CLOSE_CURLY, ASSIGN, STRING, PIPE, SEMICOLON, SPLIT) private val nonIdentifierTokens = setOf(EOL, TAB, SPLIT, COLON, OPEN_PAREN, CLOSE_PAREN, OPEN_CURLY, CLOSE_CURLY, ASSIGN, STRING, COMMA) // targets @JvmStatic fun parseNoWhitespaceOrColon(builder: PsiBuilder, level: Int): Boolean = consumeAllNonWsExceptTokens(builder, level, nonTargetTokens) @JvmStatic fun parseToDollarNoWhitespaceOrColon(builder: PsiBuilder, level: Int): Boolean = consumeAllNonWsExceptTokens(builder, level, nonTargetTokens, errorOnWs = true) @JvmStatic fun parseNoWhitespaceOrColonBehind(builder: PsiBuilder, level: Int): Boolean { if (isWhitespaceBehind(builder)) return true return consumeAllNonWsExceptTokens(builder, level, nonTargetTokens, allowEmpty = true) } @JvmStatic fun parseToDollarNoWhitespaceOrColonBehind(builder: PsiBuilder, level: Int): Boolean { if (isWhitespaceBehind(builder)) return false return consumeAllNonWsExceptTokens(builder, level, nonTargetTokens, allowEmpty = true, errorOnWs = true) } // prerequisites @JvmStatic fun parsePrereqNoWhitespace(builder: PsiBuilder, level: Int): Boolean = consumeAllNonWsExceptTokens(builder, level, nonPrereqTokens) @JvmStatic fun parsePrereqToDollarNoWhitespace(builder: PsiBuilder, level: Int): Boolean = consumeAllNonWsExceptTokens(builder, level, nonPrereqTokens, errorOnWs = true) @JvmStatic fun parsePrereqNoWhitespaceBehind(builder: PsiBuilder, level: Int): Boolean { if (isWhitespaceBehind(builder)) return true return consumeAllNonWsExceptTokens(builder, level, nonPrereqTokens, allowEmpty = true) } @JvmStatic fun parsePrereqToDollarNoWhitespaceBehind(builder: PsiBuilder, level: Int): Boolean { if (isWhitespaceBehind(builder)) return false return consumeAllNonWsExceptTokens(builder, level, nonPrereqTokens, allowEmpty = true, errorOnWs = true) } // identifiers @JvmStatic fun parseNoWhitespace(builder: PsiBuilder, level: Int): Boolean = consumeAllNonWsExceptTokens(builder, level, nonIdentifierTokens) @JvmStatic fun parseToDollarNoWhitespace(builder: PsiBuilder, level: Int): Boolean = consumeAllNonWsExceptTokens(builder, level, nonIdentifierTokens, errorOnWs = true) @JvmStatic fun parseNoWhitespaceBehind(builder: PsiBuilder, level: Int): Boolean { if (isWhitespaceBehind(builder)) return true return consumeAllNonWsExceptTokens(builder, level, nonIdentifierTokens, allowEmpty = true) } @JvmStatic fun parseToDollarNoWhitespaceBehind(builder: PsiBuilder, level: Int): Boolean { if (isWhitespaceBehind(builder)) return false return consumeAllNonWsExceptTokens(builder, level, nonIdentifierTokens, allowEmpty = true, errorOnWs = true) } private fun isWhitespaceBehind(builder: PsiBuilder): Boolean { return builder.rawLookup(0) == TokenType.WHITE_SPACE || builder.rawLookup(-1) == TokenType.WHITE_SPACE } private fun consumeAllNonWsExceptTokens(builder: PsiBuilder, level: Int, tokens: Set<IElementType>, allowEmpty: Boolean = false, errorOnWs: Boolean = false): Boolean { // accept everything till the end of line var hasAny = allowEmpty do { if (builder.tokenType == DOLLAR) { val lookAhead = builder.lookAhead(1) if (lookAhead == OPEN_CURLY || lookAhead == OPEN_PAREN) { return hasAny } } if (builder.tokenType in tokens || builder.tokenType == null) return hasAny if (builder.rawLookup(1) == TokenType.WHITE_SPACE) { if (errorOnWs) return false builder.advanceLexer() return true } builder.advanceLexer() hasAny = true } while (true) } @JvmStatic fun parseLine(builder: PsiBuilder, level: Int): Boolean = parseLineTokens(builder, setOf(EOL, BACKTICK, DOUBLEQUOTE, QUOTE)) @JvmStatic fun parseLineNotEndef(builder: PsiBuilder, level: Int): Boolean = parseLineTokens(builder, setOf(EOL, KEYWORD_ENDEF, DOUBLEQUOTE, QUOTE)) @JvmStatic fun parseDoubleQuotedString(builder: PsiBuilder, level: Int): Boolean = parseLineTokens(builder, setOf(EOL, DOUBLEQUOTE)) @JvmStatic fun parseSingleQuotedString(builder: PsiBuilder, level: Int): Boolean = parseLineTokens(builder, setOf(EOL, QUOTE)) private fun parseLineTokens(builder: PsiBuilder, tokens: Set<IElementType>): Boolean { // accept everything till the end of line var hasAny = false do { if (builder.tokenType == DOLLAR) { val lookAhead = builder.lookAhead(1) if (lookAhead == OPEN_CURLY || lookAhead == OPEN_PAREN) { return hasAny } } if (builder.tokenType in tokens || builder.tokenType == null) return hasAny builder.advanceLexer() hasAny = true } while (true) } @JvmStatic fun parseVariableUsageCurly(builder: PsiBuilder, level: Int): Boolean = parseVariableUsage(builder, level, true, CLOSE_CURLY) @JvmStatic fun parseVariableUsageParen(builder: PsiBuilder, level: Int): Boolean = parseVariableUsage(builder, level, false, CLOSE_PAREN) @JvmStatic fun parseVariableUsage(builder: PsiBuilder, level: Int, acceptFunctionNames: Boolean, end: IElementType): Boolean { var curly = 0 var paren = 0 if (builder.tokenType == FUNCTION_NAME) { if (!acceptFunctionNames) { return false } builder.advanceLexer() } do { when (builder.tokenType) { OPEN_PAREN -> paren++ CLOSE_PAREN -> if (paren > 0) paren-- else return consumeToken(builder, end) OPEN_CURLY -> curly++ CLOSE_CURLY -> if (curly > 0) curly-- else return consumeToken(builder, end) EOL -> return false null -> return false } builder.advanceLexer() } while (true) } }
mit
7dc42e49ef6936d90f552a83d9d2014d
39.025974
169
0.725458
4.189667
false
false
false
false
LISTEN-moe/android-app
app/src/main/kotlin/me/echeung/moemoekyun/ui/theme/Theme.kt
1
556
package me.echeung.moemoekyun.ui.theme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val DarkColorPalette = darkColors( primary = Color(0xFFFF015B), primaryVariant = Color(0xFFFF015B), secondary = Color(0xFFC7CCD8), background = Color(0xFF1C1D1C), ) @Composable fun AppTheme(content: @Composable () -> Unit) { MaterialTheme( colors = DarkColorPalette, content = content, ) }
mit
59062bd829d5e157421b9b6ed440f40c
25.47619
47
0.746403
4
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/readers/ExchangeStepAttemptReader.kt
1
4982
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers import com.google.cloud.spanner.Struct import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.gcloud.common.toProtoDate import org.wfanet.measurement.gcloud.spanner.appendClause import org.wfanet.measurement.gcloud.spanner.getProtoEnum import org.wfanet.measurement.gcloud.spanner.getProtoMessage import org.wfanet.measurement.gcloud.spanner.toProtoEnum import org.wfanet.measurement.internal.kingdom.ExchangeStep import org.wfanet.measurement.internal.kingdom.ExchangeStepAttempt import org.wfanet.measurement.internal.kingdom.ExchangeStepAttemptDetails import org.wfanet.measurement.internal.kingdom.exchangeStepAttempt /** Reads [ExchangeStepAttempt] protos from Spanner. */ class ExchangeStepAttemptReader : SpannerReader<ExchangeStepAttemptReader.Result>() { data class Result(val exchangeStepAttempt: ExchangeStepAttempt, val recurringExchangeId: Long) override val baseSql: String = """ SELECT $SELECT_COLUMNS_SQL FROM ExchangeStepAttempts JOIN RecurringExchanges USING (RecurringExchangeId) JOIN ExchangeSteps USING (RecurringExchangeId, Date, StepIndex) """ .trimIndent() override suspend fun translate(struct: Struct): Result { return Result( exchangeStepAttempt = exchangeStepAttempt { externalRecurringExchangeId = struct.getLong("ExternalRecurringExchangeId") date = struct.getDate("Date").toProtoDate() stepIndex = struct.getLong("StepIndex").toInt() attemptNumber = struct.getLong("AttemptIndex").toInt() state = struct.getProtoEnum("State", ExchangeStepAttempt.State::forNumber) details = struct.getProtoMessage( "ExchangeStepAttemptDetails", ExchangeStepAttemptDetails.parser() ) }, recurringExchangeId = struct.getLong("RecurringExchangeId") ) } companion object { private val SELECT_COLUMNS = listOf( "ExchangeStepAttempts.RecurringExchangeId", "ExchangeStepAttempts.Date", "ExchangeStepAttempts.StepIndex", "ExchangeStepAttempts.AttemptIndex", "ExchangeStepAttempts.State", "ExchangeStepAttempts.ExchangeStepAttemptDetails", "ExchangeStepAttempts.ExchangeStepAttemptDetailsJson", "RecurringExchanges.ExternalRecurringExchangeId" ) val SELECT_COLUMNS_SQL = SELECT_COLUMNS.joinToString(", ") fun forExpiredAttempts( externalModelProviderId: ExternalId?, externalDataProviderId: ExternalId?, limit: Long = 10 ): SpannerReader<Result> { require((externalModelProviderId == null) != (externalDataProviderId == null)) { "Specify exactly one of `externalDataProviderId` and `externalModelProviderId`" } return ExchangeStepAttemptReader().fillStatementBuilder { appendClause( """ WHERE ExchangeSteps.State = @exchange_step_state AND ExchangeStepAttempts.State = @exchange_step_attempt_state AND ExchangeStepAttempts.ExpirationTime <= CURRENT_TIMESTAMP() """ .trimIndent() ) bind("exchange_step_state").toProtoEnum(ExchangeStep.State.IN_PROGRESS) bind("exchange_step_attempt_state").toProtoEnum(ExchangeStepAttempt.State.ACTIVE) if (externalModelProviderId != null) { appendClause( """ | AND ExchangeSteps.ModelProviderId = ( | SELECT ModelProviderId | FROM ModelProviders | WHERE ExternalModelProviderId = @external_model_provider_id | ) """ .trimMargin() ) bind("external_model_provider_id").to(externalModelProviderId.value) } if (externalDataProviderId != null) { appendClause( """ | AND ExchangeSteps.DataProviderId = ( | SELECT DataProviderId | FROM DataProviders | WHERE ExternalDataProviderId = @external_data_provider_id | ) """ .trimMargin() ) bind("external_data_provider_id").to(externalDataProviderId.value) } appendClause("LIMIT @limit") bind("limit").to(limit) } } } }
apache-2.0
c399e1ac7cf6a55655b0ac8ec2a49fef
37.030534
96
0.682658
5.063008
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/retry/backoff/Backoffx.kt
1
1232
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("Backoffx") package debop4k.core.retry.backoff /** 기본 증가자 */ const val DEFAULT_MULTIPLIER = 0.1 /** 최소 지연 시간 (milliseconds) */ const val DEFAULT_MIN_DELAY_MILLIS = 100L /** 최대 지연 시간 (milliseconds) */ const val DEFAULT_MAX_DELAY_MILLIS = 10000L /** 기본 Backoff 시간 (milliseconds) */ const val DEFAULT_PERIOD_MILLIS = 1000L /** 기본 Random Backoff 시간 (milliseconds) */ const val DEFAULT_RANDOM_RANGE_MILLIS = 100L /** 기본 Backoff 인스턴스 [FixedIntervalBackoff] */ @JvmField val DEFAULT_BACKOFF: Backoff = FixedIntervalBackoff()
apache-2.0
e1aaac35116834fff123fdcd5dd839fc
30.621622
75
0.728205
3.482143
false
false
false
false
dumptruckman/PluginBase
pluginbase-core/messages/src/main/kotlin/pluginbase/messages/Theme.kt
1
6655
package pluginbase.messages import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.NodeList import java.util.EnumSet import java.util.HashMap enum class Theme constructor(tag: Char, private var color: ChatColor?, private var style: ChatColor? = null) { SUCCESS('+', ChatColor.GREEN), ERROR('-', ChatColor.RED), INVALID('^', ChatColor.RED), PLAIN('.', ChatColor.RESET), IMPORTANT('!', null, ChatColor.BOLD), IMPORTANT2('*', null, ChatColor.ITALIC), IMPORTANT3('_', null, ChatColor.UNDERLINE), HELP('h', ChatColor.WHITE), INFO('i', ChatColor.AQUA), SORRY('$', ChatColor.DARK_GRAY), RETRY(',', ChatColor.GRAY), DO_THIS('~', ChatColor.BLUE), VALUE('v', ChatColor.DARK_GREEN), TITLE('t', ChatColor.DARK_AQUA), PLEASE_WAIT('w', ChatColor.GRAY), QUESTION('?', ChatColor.DARK_PURPLE), CMD_USAGE('c', ChatColor.WHITE), CMD_FLAG('f', ChatColor.GOLD, ChatColor.ITALIC), OPT_ARG('o', ChatColor.GOLD), REQ_ARG('r', ChatColor.GREEN), CMD_HIGHLIGHT('C', null, ChatColor.BOLD), HEADER('=', ChatColor.LIGHT_PURPLE), LIST_ODD(':', ChatColor.WHITE), LIST_EVEN(';', ChatColor.YELLOW); var tag: Char = tag private set override fun toString(): String { return getColor(color, style) } companion object { private val tagMap = HashMap<Char, String>() val themeResource = "theme.xml" fun loadTheme(document: Document) { tagMap.clear() // Create a set of all the enum Theme elements so we can tell what wasn't handled in the file val themeSet = EnumSet.allOf(Theme::class.java) document.documentElement.normalize() // Grab the main set of nodes from the document node and iterate over them val nodes = document.documentElement.childNodes for (i in 0..nodes.length - 1) { var node: Node? = nodes.item(i) if (node!!.nodeType != Node.ELEMENT_NODE) { continue } val element = node as Element? // Check to see if the node name represents a Theme enum var applicableTheme: Theme? = null try { applicableTheme = Theme.valueOf(element!!.nodeName.toUpperCase()) } catch (ignore: IllegalArgumentException) { } // Some references for the data we pull out of each theme node var tag: Char? = null var color: ChatColor? = null var style: ChatColor? = null // Grab the tag value node = element!!.getElementsByTagName("tag").item(0) if (node != null) { val value = node.textContent if (value != null && !value.isEmpty()) { tag = value[0] } } // Grab the color value node = element.getElementsByTagName("color").item(0) if (node != null) { val value = node.textContent if (value != null && !value.isEmpty()) { try { color = ChatColor.valueOf(value.toUpperCase()) } catch (ignore: IllegalArgumentException) { } } } // Grab the style value node = element.getElementsByTagName("style").item(0) if (node != null) { val value = node.textContent if (value != null && !value.isEmpty()) { try { style = ChatColor.valueOf(value.toUpperCase()) } catch (ignore: IllegalArgumentException) { } } } // We have to have found a color and tag to care about the theme in the xml if ((color != null || style != null) && tag != null && !tagMap.containsKey(tag)) { tagMap.put(tag, getColor(color, style)) if (applicableTheme != null) { themeSet.remove(applicableTheme) applicableTheme.tag = tag applicableTheme.color = color applicableTheme.style = style } } } // Now we iterate over any of the remaining enum elements to add them as defaults. for (theme in themeSet) { tagMap.putIfAbsent(theme.tag, getColor(theme.color, theme.style)) } } private fun getColor(color: ChatColor?, style: ChatColor?): String { val result = (color?.toString() ?: "") + (style?.toString() ?: "") return if (result.isEmpty()) ChatColor.RESET.toString() else result } /** * Gets the Minecraft color string associated with the given theme tag, if any. * * @param themeTag the theme tag to convert to color * @return the Minecraft color code string or null if themeTag is not valid. */ fun getColorByTag(themeTag: Char): String? { return tagMap[themeTag] } /** * The character that indicates a theme tag is being used. */ val THEME_MARKER = '$' /** * The character that represents the following [.THEME_MARKER] is not actually a theme. */ val THEME_ESCAPE_CHAR = '\\' internal fun parseMessage(message: String): String { val buffer = StringBuilder(message.length + 10) var previousChar = ' ' var i = 0 while (i < message.length - 1) { val currentChar = message[i] if (currentChar == THEME_MARKER && previousChar != THEME_ESCAPE_CHAR) { val color = tagMap[message[i + 1]] if (color != null) { buffer.append(color) i++ } else { buffer.append(currentChar) } } else { buffer.append(currentChar) } previousChar = currentChar i++ } if (!message.isEmpty()) { buffer.append(message[message.length - 1]) } return buffer.toString() } } }
mpl-2.0
96558e39c43b2ea473fa3944a11b7b0d
35.36612
110
0.504733
4.977562
false
false
false
false
nemerosa/ontrack
ontrack-ui/src/test/java/net/nemerosa/ontrack/boot/resources/ValidationStampFilterResourceDecoratorIT.kt
1
9919
package net.nemerosa.ontrack.boot.resources import net.nemerosa.ontrack.model.security.Roles import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.ValidationStampFilter import net.nemerosa.ontrack.test.TestUtils.uid import net.nemerosa.ontrack.ui.resource.AbstractResourceDecoratorTestSupport import org.junit.Test import org.springframework.beans.factory.annotation.Autowired /** * Testing the update, delete, share to project, share to global, links when * using the [ValidationStampFilterResourceDecorator]. * * The tests are a matrix on following axes: * * * scope: branch, project, global * * role: view only, participant, validation stamp manager, project manager, project owner, global config */ class ValidationStampFilterResourceDecoratorIT : AbstractResourceDecoratorTestSupport() { @Autowired private lateinit var decorator: ValidationStampFilterResourceDecorator @Test fun `Branch filter for view only`() { project { branch { asUserWithView(this) { filter(branch = this).decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } } @Test fun `Branch filter for participant`() { project { branch { asAccountWithProjectRole(Roles.PROJECT_PARTICIPANT) { filter(branch = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } } @Test fun `Branch filter for validation stamp manager`() { project { branch { asAccountWithProjectRole(Roles.PROJECT_VALIDATION_MANAGER) { filter(branch = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } } @Test fun `Branch filter for project manager`() { project { branch { asAccountWithProjectRole(Roles.PROJECT_MANAGER) { filter(branch = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } } @Test fun `Branch filter for project owner`() { project { branch { asAccountWithProjectRole(Roles.PROJECT_OWNER) { filter(branch = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } } @Test fun `Branch filter for admin`() { project { branch { asAccountWithGlobalRole(Roles.GLOBAL_ADMINISTRATOR) { filter(branch = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkPresent("_shareAtProject") assertLinkPresent("_shareAtGlobal") } } } } } @Test fun `Project filter for view only`() { project { asUserWithView(this) { filter(project = this).decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Project filter for participant`() { project { asAccountWithProjectRole(Roles.PROJECT_PARTICIPANT) { filter(project = this).decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Project filter for validation stamp manager`() { project { asAccountWithProjectRole(Roles.PROJECT_VALIDATION_MANAGER) { filter(project = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Project filter for project manager`() { project { asAccountWithProjectRole(Roles.PROJECT_MANAGER) { filter(project = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Project filter for project owner`() { project { asAccountWithProjectRole(Roles.PROJECT_OWNER) { filter(project = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Project filter for admin`() { project { asAccountWithGlobalRole(Roles.GLOBAL_ADMINISTRATOR) { filter(project = this).decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkPresent("_shareAtGlobal") } } } } @Test fun `Global filter for view only`() { project { asUserWithView(this) { filter().decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Global filter for participant`() { project { asAccountWithProjectRole(Roles.PROJECT_PARTICIPANT) { filter().decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Global filter for validation stamp manager`() { project { asAccountWithProjectRole(Roles.PROJECT_VALIDATION_MANAGER) { filter().decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Global filter for project manager`() { project { asAccountWithProjectRole(Roles.PROJECT_MANAGER) { filter().decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Global filter for project owner`() { project { asAccountWithProjectRole(Roles.PROJECT_OWNER) { filter().decorate(decorator) { assertLinkNotPresent("_update") assertLinkNotPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } @Test fun `Global filter for admin`() { project { asAccountWithGlobalRole(Roles.GLOBAL_ADMINISTRATOR) { filter().decorate(decorator) { assertLinkPresent("_update") assertLinkPresent("_delete") assertLinkNotPresent("_shareAtProject") assertLinkNotPresent("_shareAtGlobal") } } } } private fun filter(project: Project? = null, branch: Branch? = null) = ValidationStampFilter( name = uid("F"), project = project, branch = branch, vsNames = listOf("VS") ) }
mit
894362b6f705792ef64f70c5ed5ed020
32.288591
106
0.510233
5.746813
false
true
false
false
jraska/github-client
plugins/src/main/java/com/jraska/github/client/release/GradleFileUtils.kt
1
2713
package com.jraska.github.client.release import java.util.regex.Pattern object GradleFileUtils { private val VERSION_PATTERN = Pattern.compile("""versionName '([0-9]*)\.([0-9]*)\.([0-9]*)'""") fun versionName(gradleFileText: String): String { val versionNamePattern = Pattern.compile("""versionName '([0-9]*\.[0-9]*\.[0-9]*)'""") val versionNameMatcher = versionNamePattern.matcher(gradleFileText) val found = versionNameMatcher.find() if (!found) { throw IllegalStateException("No match found for $versionNamePattern") } return versionNameMatcher.group(1) } fun incrementVersionCode(gradleFileText: String): String { val versionCodePattern = Pattern.compile("""versionCode ([0-9]*)""") val versionCodeMatcher = versionCodePattern.matcher(gradleFileText) val found = versionCodeMatcher.find() if (!found) { throw IllegalStateException("No match found for $versionCodePattern") } val oldVersionCode = versionCodeMatcher.group(1).toLong() val newVersionCode = oldVersionCode + 1 return gradleFileText.replace(versionCodeMatcher.group(0), "versionCode $newVersionCode") } fun incrementVersionNamePatch(gradleFileText: String): String { val versionNameMatcher = VERSION_PATTERN.matcher(gradleFileText) val found = versionNameMatcher.find() if (!found) { throw IllegalStateException("No match found for $VERSION_PATTERN") } val oldPatch = versionNameMatcher.group(3).toLong() val newPatch = oldPatch + 1 val newText = "versionName '${versionNameMatcher.group(1)}.${versionNameMatcher.group(2)}.$newPatch'" return gradleFileText.replace(versionNameMatcher.group(0), newText) } fun incrementVersionNameMinor(gradleFileText: String): String { val versionNameMatcher = VERSION_PATTERN.matcher(gradleFileText) val found = versionNameMatcher.find() if (!found) { throw IllegalStateException("No match found for $VERSION_PATTERN") } val oldMinor = versionNameMatcher.group(2).toLong() val newMinor = oldMinor + 1 val newText = "versionName '${versionNameMatcher.group(1)}.$newMinor.0'" return gradleFileText.replace(versionNameMatcher.group(0), newText) } fun incrementVersionNameMajor(gradleFileText: String): String { val versionNameMatcher = VERSION_PATTERN.matcher(gradleFileText) val found = versionNameMatcher.find() if (!found) { throw IllegalStateException("No match found for $VERSION_PATTERN") } val oldMajor = versionNameMatcher.group(1).toLong() val newMajor = oldMajor + 1 val newText = "versionName '$newMajor.0.0'" return gradleFileText.replace(versionNameMatcher.group(0), newText) } }
apache-2.0
a7ea0e7b68d0e92697d908ccece313a9
34.233766
105
0.718024
4.347756
false
false
false
false
goodwinnk/intellij-community
platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonUtilAutoTest.kt
1
25394
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.HeavyDiffTestCase import com.intellij.diff.fragments.DiffFragment import com.intellij.diff.fragments.LineFragment import com.intellij.diff.fragments.MergeLineFragment import com.intellij.diff.fragments.MergeWordFragment import com.intellij.diff.tools.util.base.HighlightPolicy import com.intellij.diff.tools.util.base.IgnorePolicy import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.Range import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.ex.createRanges class ComparisonUtilAutoTest : HeavyDiffTestCase() { val RUNS = 30 val MAX_LENGTH = 300 fun testChar() { doTestChar(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testWord() { doTestWord(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLine() { doTestLine(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLineSquashed() { doTestLineSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testLineTrimSquashed() { doTestLineTrimSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testExplicitBlocks() { doTestExplicitBlocks(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testMerge() { doTestMerge(System.currentTimeMillis(), RUNS, MAX_LENGTH) } fun testThreeWayDiff() { doTestThreeWayDiff(System.currentTimeMillis(), RUNS, MAX_LENGTH) } private fun doTestLine(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) checkResultLine(text1, text2, fragments, policy, true) } } private fun doTestLineSquashed(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) val squashedFragments = MANAGER.squash(fragments) debugData.put("Squashed Fragments", squashedFragments) checkResultLine(text1, text2, squashedFragments, policy, false) } } private fun doTestLineTrimSquashed(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) val processed = MANAGER.processBlocks(fragments, sequence1, sequence2, policy, true, true) debugData.put("Processed Fragments", processed) checkResultLine(text1, text2, processed, policy, false) } } private fun doTestChar(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareChars(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) checkResultChar(sequence1, sequence2, fragments, policy) } } private fun doTestWord(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val fragments = MANAGER.compareWords(sequence1, sequence2, policy, INDICATOR) debugData.put("Fragments", fragments) checkResultWord(sequence1, sequence2, fragments, policy) } } private fun doTestExplicitBlocks(seed: Long, runs: Int, maxLength: Int) { val ignorePolicies = listOf(IgnorePolicy.DEFAULT, IgnorePolicy.TRIM_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES_CHUNKS) val highlightPolicies = listOf(HighlightPolicy.BY_LINE, HighlightPolicy.BY_WORD, HighlightPolicy.BY_WORD_SPLIT) doTest(seed, runs, maxLength) { text1, text2, debugData -> for (highlightPolicy in highlightPolicies) { for (ignorePolicy in ignorePolicies) { debugData.put("HighlightPolicy", highlightPolicy) debugData.put("IgnorePolicy", ignorePolicy) val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val ranges = createRanges(sequence2, sequence1).map { Range(it.vcsLine1, it.vcsLine2, it.line1, it.line2) } debugData.put("Ranges", ranges) val fragments = compareExplicitBlocks(sequence1, sequence2, ranges, highlightPolicy, ignorePolicy) debugData.put("Fragments", fragments) checkResultLine(text1, text2, fragments, ignorePolicy.comparisonPolicy, !highlightPolicy.isShouldSquash) } } } } private fun doTestThreeWayDiff(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest3(seed, runs, maxLength, policies) { text1, text2, text3, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val sequence3 = text3.charsSequence val fragments = MANAGER.compareLines(sequence1, sequence2, sequence3, policy, INDICATOR) val fineFragments = fragments.map { f -> val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) val wordFragments = ByWord.compare(chunk1, chunk2, chunk3, policy, INDICATOR) Pair(f, wordFragments) } debugData.put("Fragments", fineFragments) checkResultMerge(text1, text2, text3, fineFragments, policy, false) } } private fun doTestMerge(seed: Long, runs: Int, maxLength: Int) { val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES) doTest3(seed, runs, maxLength, policies) { text1, text2, text3, policy, debugData -> val sequence1 = text1.charsSequence val sequence2 = text2.charsSequence val sequence3 = text3.charsSequence val fragments = MANAGER.mergeLines(sequence1, sequence2, sequence3, policy, INDICATOR) val fineFragments = fragments.map { f -> val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) val wordFragments = ByWord.compare(chunk1, chunk2, chunk3, policy, INDICATOR) Pair(f, wordFragments) } debugData.put("Fragments", fineFragments) checkResultMerge(text1, text2, text3, fineFragments, policy, policy != ComparisonPolicy.DEFAULT) } } private fun doTest(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>, test: (Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) { doTest(seed, runs, maxLength) { text1, text2, debugData -> for (comparisonPolicy in policies) { debugData.put("Policy", comparisonPolicy) test(text1, text2, comparisonPolicy, debugData) } } } private fun doTest(seed: Long, runs: Int, maxLength: Int, test: (Document, Document, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) test(text1, text2, debugData) } } private fun doTest3(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>, test: (Document, Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) val text3 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) debugData.put("Text3", textToReadableFormat(text3.charsSequence)) for (comparisonPolicy in policies) { debugData.put("Policy", comparisonPolicy) test(text1, text2, text2, comparisonPolicy, debugData) } } } private fun checkResultLine(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) { checkLineConsistency(text1, text2, fragments, allowNonSquashed) for (fragment in fragments) { if (fragment.innerFragments != null) { val sequence1 = text1.subSequence(fragment.startOffset1, fragment.endOffset1) val sequence2 = text2.subSequence(fragment.startOffset2, fragment.endOffset2) checkResultWord(sequence1, sequence2, fragment.innerFragments!!, policy) } } checkValidRanges(text1.charsSequence, text2.charsSequence, fragments, policy, true) checkCantTrimLines(text1, text2, fragments, policy, allowNonSquashed) } private fun checkResultWord(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) { checkDiffConsistency(fragments) checkValidRanges(text1, text2, fragments, policy, false) } private fun checkResultChar(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) { checkDiffConsistency(fragments) checkValidRanges(text1, text2, fragments, policy, false) } private fun checkResultMerge(text1: Document, text2: Document, text3: Document, fragments: List<Pair<MergeLineFragment, List<MergeWordFragment>>>, policy: ComparisonPolicy, allowIgnoredBlocks: Boolean) { val lineFragments = fragments.map { it.first } checkLineConsistency3(text1, text2, text3, lineFragments, allowIgnoredBlocks) checkValidRanges3(text1, text2, text3, lineFragments, policy) if (!allowIgnoredBlocks) checkCantTrimLines3(text1, text2, text3, lineFragments, policy) for (pair in fragments) { val f = pair.first val innerFragments = pair.second val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1) val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2) val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3) checkDiffConsistency3(innerFragments) checkValidRanges3(chunk1, chunk2, chunk3, innerFragments, policy) } } private fun checkLineConsistency(text1: Document, text2: Document, fragments: List<LineFragment>, allowNonSquashed: Boolean) { var last1 = -1 var last2 = -1 for (fragment in fragments) { val startOffset1 = fragment.startOffset1 val startOffset2 = fragment.startOffset2 val endOffset1 = fragment.endOffset1 val endOffset2 = fragment.endOffset2 val start1 = fragment.startLine1 val start2 = fragment.startLine2 val end1 = fragment.endLine1 val end2 = fragment.endLine2 assertTrue(startOffset1 >= 0) assertTrue(startOffset2 >= 0) assertTrue(endOffset1 <= text1.textLength) assertTrue(endOffset2 <= text2.textLength) assertTrue(start1 >= 0) assertTrue(start2 >= 0) assertTrue(end1 <= getLineCount(text1)) assertTrue(end2 <= getLineCount(text2)) assertTrue(startOffset1 <= endOffset1) assertTrue(startOffset2 <= endOffset2) assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start1 != end1 || start2 != end2) assertTrue(allowNonSquashed || start1 != last1 || start2 != last2) checkLineOffsets(fragment, text1, text2) last1 = end1 last2 = end2 } } private fun checkLineConsistency3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, allowNonSquashed: Boolean) { var last1 = -1 var last2 = -1 var last3 = -1 for (fragment in fragments) { val start1 = fragment.startLine1 val start2 = fragment.startLine2 val start3 = fragment.startLine3 val end1 = fragment.endLine1 val end2 = fragment.endLine2 val end3 = fragment.endLine3 assertTrue(start1 >= 0) assertTrue(start2 >= 0) assertTrue(start3 >= 0) assertTrue(end1 <= getLineCount(text1)) assertTrue(end2 <= getLineCount(text2)) assertTrue(end3 <= getLineCount(text3)) assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start3 <= end3) assertTrue(start1 != end1 || start2 != end2 || start3 != end3) assertTrue(allowNonSquashed || start1 != last1 || start2 != last2 || start3 != last3) last1 = end1 last2 = end2 last3 = end3 } } private fun checkDiffConsistency(fragments: List<DiffFragment>) { var last1 = -1 var last2 = -1 for (diffFragment in fragments) { val start1 = diffFragment.startOffset1 val start2 = diffFragment.startOffset2 val end1 = diffFragment.endOffset1 val end2 = diffFragment.endOffset2 assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start1 != end1 || start2 != end2) assertTrue(start1 != last1 || start2 != last2) last1 = end1 last2 = end2 } } private fun checkDiffConsistency3(fragments: List<MergeWordFragment>) { var last1 = -1 var last2 = -1 var last3 = -1 for (diffFragment in fragments) { val start1 = diffFragment.startOffset1 val start2 = diffFragment.startOffset2 val start3 = diffFragment.startOffset3 val end1 = diffFragment.endOffset1 val end2 = diffFragment.endOffset2 val end3 = diffFragment.endOffset3 assertTrue(start1 <= end1) assertTrue(start2 <= end2) assertTrue(start3 <= end3) assertTrue(start1 != end1 || start2 != end2 || start3 != end3) assertTrue(start1 != last1 || start2 != last2 || start3 != last3) last1 = end1 last2 = end2 last3 = end3 } } private fun checkLineOffsets(fragment: LineFragment, before: Document, after: Document) { checkLineOffsets(before, fragment.startLine1, fragment.endLine1, fragment.startOffset1, fragment.endOffset1) checkLineOffsets(after, fragment.startLine2, fragment.endLine2, fragment.startOffset2, fragment.endOffset2) } private fun checkLineOffsets(document: Document, startLine: Int, endLine: Int, startOffset: Int, endOffset: Int) { if (startLine != endLine) { assertEquals(document.getLineStartOffset(startLine), startOffset) var offset = document.getLineEndOffset(endLine - 1) if (offset < document.textLength) offset++ assertEquals(offset, endOffset) } else { val offset = if (startLine == getLineCount(document)) document.textLength else document.getLineStartOffset(startLine) assertEquals(offset, startOffset) assertEquals(offset, endOffset) } } private fun checkValidRanges(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy, skipNewline: Boolean) { // TODO: better check for Trim spaces case ? val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES var last1 = 0 var last2 = 0 for (fragment in fragments) { val start1 = fragment.startOffset1 val start2 = fragment.startOffset2 val end1 = fragment.endOffset1 val end2 = fragment.endOffset2 val chunk1 = text1.subSequence(last1, start1) val chunk2 = text2.subSequence(last2, start2) assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline) val chunkContent1 = text1.subSequence(start1, end1) val chunkContent2 = text2.subSequence(start2, end2) if (!skipNewline) { assertNotEqualsCharSequences(chunkContent1, chunkContent2, ignoreSpacesChanged, skipNewline) } last1 = fragment.endOffset1 last2 = fragment.endOffset2 } val chunk1 = text1.subSequence(last1, text1.length) val chunk2 = text2.subSequence(last2, text2.length) assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline) } private fun checkValidRanges3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { val ignoreSpaces = policy != ComparisonPolicy.DEFAULT var last1 = 0 var last2 = 0 var last3 = 0 for (fragment in fragments) { val start1 = fragment.startLine1 val start2 = fragment.startLine2 val start3 = fragment.startLine3 val content1 = DiffUtil.getLinesContent(text1, last1, start1) val content2 = DiffUtil.getLinesContent(text2, last2, start2) val content3 = DiffUtil.getLinesContent(text3, last3, start3) assertEqualsCharSequences(content2, content1, ignoreSpaces, false) assertEqualsCharSequences(content2, content3, ignoreSpaces, false) last1 = fragment.endLine1 last2 = fragment.endLine2 last3 = fragment.endLine3 } val content1 = DiffUtil.getLinesContent(text1, last1, getLineCount(text1)) val content2 = DiffUtil.getLinesContent(text2, last2, getLineCount(text2)) val content3 = DiffUtil.getLinesContent(text3, last3, getLineCount(text3)) assertEqualsCharSequences(content2, content1, ignoreSpaces, false) assertEqualsCharSequences(content2, content3, ignoreSpaces, false) } private fun checkValidRanges3(text1: CharSequence, text2: CharSequence, text3: CharSequence, fragments: List<MergeWordFragment>, policy: ComparisonPolicy) { val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES var last1 = 0 var last2 = 0 var last3 = 0 for (fragment in fragments) { val start1 = fragment.startOffset1 val start2 = fragment.startOffset2 val start3 = fragment.startOffset3 val end1 = fragment.endOffset1 val end2 = fragment.endOffset2 val end3 = fragment.endOffset3 val content1 = text1.subSequence(last1, start1) val content2 = text2.subSequence(last2, start2) val content3 = text3.subSequence(last3, start3) assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false) assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false) val chunkContent1 = text1.subSequence(start1, end1) val chunkContent2 = text2.subSequence(start2, end2) val chunkContent3 = text3.subSequence(start3, end3) assertFalse(isEqualsCharSequences(chunkContent2, chunkContent1, ignoreSpacesChanged) && isEqualsCharSequences(chunkContent2, chunkContent3, ignoreSpacesChanged)) last1 = fragment.endOffset1 last2 = fragment.endOffset2 last3 = fragment.endOffset3 } val content1 = text1.subSequence(last1, text1.length) val content2 = text2.subSequence(last2, text2.length) val content3 = text3.subSequence(last3, text3.length) assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false) assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false) } private fun checkCantTrimLines(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) { for (fragment in fragments) { val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1) val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2) if (sequence1 == null || sequence2 == null) continue checkNonEqualsIfLongEnough(sequence1.first, sequence2.first, policy, allowNonSquashed) checkNonEqualsIfLongEnough(sequence1.second, sequence2.second, policy, allowNonSquashed) } } private fun checkCantTrimLines3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) { for (fragment in fragments) { val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1) val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2) val sequence3 = getFirstLastLines(text3, fragment.startLine3, fragment.endLine3) if (sequence1 == null || sequence2 == null || sequence3 == null) continue assertFalse(MANAGER.isEquals(sequence2.first, sequence1.first, policy) && MANAGER.isEquals(sequence2.first, sequence3.first, policy)) assertFalse(MANAGER.isEquals(sequence2.second, sequence1.second, policy) && MANAGER.isEquals(sequence2.second, sequence3.second, policy)) } } private fun checkNonEqualsIfLongEnough(line1: CharSequence, line2: CharSequence, policy: ComparisonPolicy, allowNonSquashed: Boolean) { // in non-squashed blocks non-trimmed elements are possible if (allowNonSquashed) { if (policy != ComparisonPolicy.IGNORE_WHITESPACES) return if (countNonWhitespaceCharacters(line1) <= ComparisonUtil.getUnimportantLineCharCount()) return if (countNonWhitespaceCharacters(line2) <= ComparisonUtil.getUnimportantLineCharCount()) return } assertFalse(MANAGER.isEquals(line1, line2, policy)) } private fun countNonWhitespaceCharacters(line: CharSequence): Int { return (0 until line.length).count { !StringUtil.isWhiteSpace(line[it]) } } private fun getFirstLastLines(text: Document, start: Int, end: Int): Couple<CharSequence>? { if (start == end) return null val firstLineRange = DiffUtil.getLinesRange(text, start, start + 1) val lastLineRange = DiffUtil.getLinesRange(text, end - 1, end) val firstLine = firstLineRange.subSequence(text.charsSequence) val lastLine = lastLineRange.subSequence(text.charsSequence) return Couple.of(firstLine, lastLine) } private fun Document.subSequence(start: Int, end: Int): CharSequence { return this.charsSequence.subSequence(start, end) } private val MergeLineFragment.startLine1: Int get() = this.getStartLine(ThreeSide.LEFT) private val MergeLineFragment.startLine2: Int get() = this.getStartLine(ThreeSide.BASE) private val MergeLineFragment.startLine3: Int get() = this.getStartLine(ThreeSide.RIGHT) private val MergeLineFragment.endLine1: Int get() = this.getEndLine(ThreeSide.LEFT) private val MergeLineFragment.endLine2: Int get() = this.getEndLine(ThreeSide.BASE) private val MergeLineFragment.endLine3: Int get() = this.getEndLine(ThreeSide.RIGHT) private val MergeWordFragment.startOffset1: Int get() = this.getStartOffset(ThreeSide.LEFT) private val MergeWordFragment.startOffset2: Int get() = this.getStartOffset(ThreeSide.BASE) private val MergeWordFragment.startOffset3: Int get() = this.getStartOffset(ThreeSide.RIGHT) private val MergeWordFragment.endOffset1: Int get() = this.getEndOffset(ThreeSide.LEFT) private val MergeWordFragment.endOffset2: Int get() = this.getEndOffset(ThreeSide.BASE) private val MergeWordFragment.endOffset3: Int get() = this.getEndOffset(ThreeSide.RIGHT) }
apache-2.0
66e4dc798d95beb58179d112f36d4fd2
39.307937
158
0.718437
4.374505
false
true
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/search/RsFindUsagesProvider.kt
1
753
package org.rust.ide.search import com.intellij.lang.HelpID import com.intellij.lang.findUsages.FindUsagesProvider import com.intellij.psi.PsiElement import org.rust.lang.core.psi.ext.RsNamedElement class RsFindUsagesProvider : FindUsagesProvider { // XXX: must return new instance of WordScanner here, because it is not thread safe override fun getWordsScanner() = RsWordScanner() override fun canFindUsagesFor(element: PsiElement) = element is RsNamedElement override fun getHelpId(element: PsiElement) = HelpID.FIND_OTHER_USAGES override fun getType(element: PsiElement) = "" override fun getDescriptiveName(element: PsiElement) = "" override fun getNodeText(element: PsiElement, useFullName: Boolean) = "" }
mit
2b312b2cf63806da2410c695ba656d76
36.65
87
0.770252
4.536145
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/test/kotlin/platform/mixin/implements/InterfaceIsInterfaceTest.kt
1
2311
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.implements import com.demonwav.mcdev.framework.EdtInterceptor import com.demonwav.mcdev.platform.mixin.BaseMixinTest import com.demonwav.mcdev.platform.mixin.inspection.implements.InterfaceIsInterfaceInspection import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(EdtInterceptor::class) @DisplayName("@Interface Is Interface Inspection Tests") class InterfaceIsInterfaceTest : BaseMixinTest() { @BeforeEach fun setupProject() { buildProject { dir("test") { java( "DummyFace.java", """ package test; interface DummyFace { } """, configure = false ) java( "DummyClass.java", """ package test; class DummyClass { } """, configure = false ) java( "InterfaceIsInterfaceMixin.java", """ package test; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Interface; @Mixin @Implements({ @Interface(iface = DummyFace.class, prefix = "good$"), @Interface(iface = <error descr="Interface expected here">DummyClass.class</error>, prefix = "bad$"), }) class InterfaceIsInterfaceMixin { } """ ) } } } @Test @DisplayName("Highlight On @Interface Test") fun highlightOnInterfaceTest() { fixture.enableInspections(InterfaceIsInterfaceInspection::class) fixture.checkHighlighting(true, false, false) } }
mit
faceb5876bafbb7f50b000764184813a
27.182927
125
0.519256
5.437647
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/translations/lang/formatting/LangBlock.kt
1
1913
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang.formatting import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes import com.intellij.formatting.Alignment import com.intellij.formatting.Block import com.intellij.formatting.Indent import com.intellij.formatting.SpacingBuilder import com.intellij.formatting.Wrap import com.intellij.formatting.WrapType import com.intellij.lang.ASTNode import com.intellij.psi.TokenType import com.intellij.psi.formatter.common.AbstractBlock class LangBlock(node: ASTNode, wrap: Wrap?, alignment: Alignment?, private val spacingBuilder: SpacingBuilder) : AbstractBlock(node, wrap, alignment) { override fun buildChildren(): List<Block> { val blocks = ArrayList<Block>() var child: ASTNode? = myNode.firstChildNode var previousChild: ASTNode? = null while (child != null) { if ( child.elementType !== TokenType.WHITE_SPACE && ( previousChild == null || previousChild.elementType !== LangTypes.LINE_ENDING || child.elementType !== LangTypes.LINE_ENDING ) ) { val block = LangBlock( child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(), spacingBuilder ) blocks.add(block) } previousChild = child child = child.treeNext } return blocks } override fun getIndent() = Indent.getNoneIndent() override fun getSpacing(child1: Block?, child2: Block) = spacingBuilder.getSpacing(this, child1, child2) override fun isLeaf() = myNode.firstChildNode == null }
mit
721c91207fe2514806ab0b4d1db2bfee
31.982759
112
0.623628
4.735149
false
false
false
false
karollewandowski/aem-intellij-plugin
src/main/kotlin/co/nums/intellij/aem/htl/psi/search/HtlSearch.kt
1
2918
package co.nums.intellij.aem.htl.psi.search import co.nums.intellij.aem.htl.data.blocks.HtlBlockVariable import co.nums.intellij.aem.htl.definitions.HtlBlock import co.nums.intellij.aem.htl.extensions.* import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.xml.* object HtlSearch { private val htlVariableBlocks = HtlBlock.values().filter { it.identifierType.isVariable() } private val htlVariableBlockTypes = htlVariableBlocks.map { it.type } fun blockVariables(htmlFile: PsiFile): Collection<HtlBlockVariable> { return PsiTreeUtil.findChildrenOfType(htmlFile, XmlAttribute::class.java) .flatMap { it.toHtlVariables() } } private fun XmlAttribute.toHtlVariables(): List<HtlBlockVariable> { if (this.isHtlBlock()) { val blockType = this.nameElement.text.substringBefore(".").toLowerCase() if (blockType in htlVariableBlockTypes) { val blockDefinition = htlVariableBlocks.find { it.type == blockType } ?: return emptyList() return this.createHtlVariables(blockDefinition) } } return emptyList() } private fun XmlAttribute.createHtlVariables(blockDefinition: HtlBlock): List<HtlBlockVariable> { val identifier = this.getIdentifier(blockDefinition.iterable) ?: return emptyList() val dataType = this.getDataType(blockDefinition) val variable = HtlBlockVariable(identifier, blockDefinition.identifierType, dataType, this) if (blockDefinition.iterable) { val listVariable = createImplicitListVariable(identifier, blockDefinition) return listOf(variable, listVariable) } return listOf(variable) } private fun XmlAttribute.createImplicitListVariable(identifier: String, blockDefinition: HtlBlock): HtlBlockVariable { val listIdentifier = identifier + "List" val listDataType = this.getDataType(blockDefinition, true) return HtlBlockVariable(listIdentifier, blockDefinition.identifierType, listDataType, this) } private fun XmlAttribute.getIdentifier(iterable: Boolean): String? { val blockText = (this.firstChild as XmlToken).text if (blockText.contains('.')) { val identifier = blockText.substringAfter('.') return if (identifier.isNotBlank()) identifier else null } else if (iterable) { return "item" } return null } private fun XmlAttribute.getDataType(block: HtlBlock, implicitList: Boolean = false): String { return when { block.type == HtlBlock.USE.type -> this.getUseObjectType() ?: "Use object" block.type == HtlBlock.TEST.type -> "Test result" block.iterable -> if (implicitList) "Iterable" else "List element" // TODO: resolve Java type else -> "" } } }
gpl-3.0
f545a941693f5c72efd6b4cb7221b888
41.911765
122
0.681631
4.595276
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityMovieSeat.kt
1
1577
package com.tamsiree.rxdemo.activity import android.os.Bundle import com.tamsiree.rxdemo.R import com.tamsiree.rxkit.RxBarTool.noTitle import com.tamsiree.rxkit.RxBarTool.setTransparentStatusBar import com.tamsiree.rxkit.RxDeviceTool.setPortrait import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.view.RxSeatMovie.SeatChecker import kotlinx.android.synthetic.main.activity_movie_seat.* /** * @author tamsiree */ class ActivityMovieSeat : ActivityBase() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) noTitle(this) setTransparentStatusBar(this) setContentView(R.layout.activity_movie_seat) setPortrait(this) } override fun initView() { rx_title.setLeftFinish(mContext) seatView.setScreenName("3号厅荧幕") //设置屏幕名称 seatView.setMaxSelected(8) //设置最多选中 seatView.setSeatChecker(object : SeatChecker { override fun isValidSeat(row: Int, column: Int): Boolean { return !(column == 2 || column == 12) } override fun isSold(row: Int, column: Int): Boolean { return row == 6 && column == 6 } override fun checked(row: Int, column: Int) {} override fun unCheck(row: Int, column: Int) {} override fun checkedSeatTxt(row: Int, column: Int): Array<String>? { return null } }) seatView.setData(10, 15) } override fun initData() { } }
apache-2.0
4776e359af3d0ae088780b8a602d2f23
29.313725
80
0.645955
4.131016
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/richtext/RichTextUtil.kt
1
3888
package org.wikipedia.richtext import android.text.Spannable import android.text.Spanned import android.text.TextUtils import android.text.style.URLSpan import android.widget.TextView import androidx.annotation.IntRange import androidx.core.text.getSpans import androidx.core.text.toSpannable import androidx.core.text.toSpanned import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L object RichTextUtil { /** * Apply only the spans from src to dst specific by spans. * * @see {@link android.text.TextUtils.copySpansFrom} */ private fun copySpans(src: Spanned, dst: Spannable, spans: Collection<Any>) { for (span in spans) { val start = src.getSpanStart(span) val end = src.getSpanEnd(span) val flags = src.getSpanFlags(span) dst.setSpan(span, start, end, flags) } } /** Strips all rich text except spans used to provide compositional hints. */ fun stripRichText(str: CharSequence, start: Int, end: Int): CharSequence { val plainText = str.toString() val ret = plainText.toSpannable() if (str is Spanned) { val keyboardHintSpans = getComposingSpans(str, start, end) copySpans(str, ret, keyboardHintSpans) } return ret } /** * @return Temporary spans, often applied by the keyboard to provide hints such as typos. * * @see {@link android.view.inputmethod.BaseInputConnection.removeComposingSpans} */ private fun getComposingSpans(spanned: Spanned, start: Int, end: Int): List<Any> { return spanned.getSpans<Any>(start, end).filter { isComposingSpan(spanned, it) } } private fun isComposingSpan(spanned: Spanned, span: Any?): Boolean { return spanned.getSpanFlags(span) and Spanned.SPAN_COMPOSING == Spanned.SPAN_COMPOSING } fun removeUnderlinesFromLinks(textView: TextView) { val text = textView.text if (text is Spanned) { val spannable = text.toSpannable() removeUnderlinesFromLinks(spannable, spannable.getSpans()) textView.text = spannable } } private fun removeUnderlinesFromLinks(spannable: Spannable, spans: Array<out URLSpan>) { for (span in spans) { val start = spannable.getSpanStart(span) val end = spannable.getSpanEnd(span) spannable.removeSpan(span) spannable.setSpan(URLSpanNoUnderline(span.url), start, end, 0) } } fun removeUnderlinesFromLinksAndMakeBold(textView: TextView) { val text = textView.text if (text is Spanned) { val spannable = text.toSpannable() removeUnderlinesFromLinksAndMakeBold(spannable, spannable.getSpans()) textView.text = spannable } } private fun removeUnderlinesFromLinksAndMakeBold(spannable: Spannable, spans: Array<out URLSpan>) { for (span in spans) { val start = spannable.getSpanStart(span) val end = spannable.getSpanEnd(span) spannable.removeSpan(span) spannable.setSpan(URLSpanBoldNoUnderline(span.url), start, end, 0) } } fun stripHtml(html: String?): String { return StringUtil.fromHtml(StringUtil.removeStyleTags(html.orEmpty())).toString() } fun remove(text: CharSequence, @IntRange(from = 1) start: Int, end: Int): CharSequence { try { return TextUtils.concat(text.subSequence(0, start - 1), text.subSequence(end, text.length)).toSpanned() } catch (e: Exception) { // A number of possible exceptions can be thrown by the system from handling even // slightly malformed spans or paragraphs, so let's ignore them for now and just // return the original text. L.e(e) } return text } }
apache-2.0
88947a6058fa2310bdca39767843bbf9
36.028571
115
0.651235
4.383315
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/GroupFragment.kt
1
5978
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment import android.content.Context import android.nfc.NdefMessage import android.nfc.NdefRecord import android.nfc.NfcAdapter import android.os.Bundle import android.support.v4.app.LoaderManager.LoaderCallbacks import android.support.v4.content.FixedAsyncTaskLoader import android.support.v4.content.Loader import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.statusnet.model.Group import de.vanita5.twittnuker.Constants.* import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.SupportTabsAdapter import de.vanita5.twittnuker.fragment.statuses.GroupTimelineFragment import de.vanita5.twittnuker.fragment.users.GroupMembersFragment import de.vanita5.twittnuker.model.ParcelableGroup import de.vanita5.twittnuker.model.SingleResponse import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.util.ParcelableGroupUtils import de.vanita5.twittnuker.util.MicroBlogAPIFactory import de.vanita5.twittnuker.util.Utils class GroupFragment : AbsToolbarTabPagesFragment(), LoaderCallbacks<SingleResponse<ParcelableGroup>> { var group: ParcelableGroup? = null private set private var groupLoaderInitialized: Boolean = false override fun addTabs(adapter: SupportTabsAdapter) { val args = arguments adapter.add(cls = GroupTimelineFragment::class.java, args = args, name = getString(R.string.title_statuses), tag = "statuses") adapter.add(cls = GroupMembersFragment::class.java, args = args, name = getString(R.string.members), tag = "members") } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Utils.setNdefPushMessageCallback(activity, NfcAdapter.CreateNdefMessageCallback { val url = group?.url ?: return@CreateNdefMessageCallback null NdefMessage(arrayOf(NdefRecord.createUri(url))) }) getGroupInfo(false) } override fun onCreateLoader(id: Int, args: Bundle): Loader<SingleResponse<ParcelableGroup>> { val accountKey = args.getParcelable<UserKey?>(EXTRA_ACCOUNT_KEY) val groupId = args.getString(EXTRA_GROUP_ID) val groupName = args.getString(EXTRA_GROUP_NAME) val omitIntentExtra = args.getBoolean(EXTRA_OMIT_INTENT_EXTRA, true) return ParcelableGroupLoader(context, omitIntentExtra, arguments, accountKey, groupId, groupName) } override fun onLoadFinished(loader: Loader<SingleResponse<ParcelableGroup>>, data: SingleResponse<ParcelableGroup>) { if (data.hasData()) { displayGroup(data.data) } } override fun onLoaderReset(loader: Loader<SingleResponse<ParcelableGroup>>) { } fun displayGroup(group: ParcelableGroup?) { val activity = activity ?: return loaderManager.destroyLoader(0) this.group = group if (group != null) { activity.title = group.fullname } else { activity.setTitle(R.string.title_user_list) } activity.invalidateOptionsMenu() } fun getGroupInfo(omitIntentExtra: Boolean) { val lm = loaderManager lm.destroyLoader(0) val args = Bundle(arguments) args.putBoolean(EXTRA_OMIT_INTENT_EXTRA, omitIntentExtra) if (!groupLoaderInitialized) { lm.initLoader(0, args, this) groupLoaderInitialized = true } else { lm.restartLoader(0, args, this) } } internal class ParcelableGroupLoader( context: Context, private val omitIntentExtra: Boolean, private val extras: Bundle?, private val accountKey: UserKey?, private val groupId: String?, private val groupName: String? ) : FixedAsyncTaskLoader<SingleResponse<ParcelableGroup>>(context) { override fun loadInBackground(): SingleResponse<ParcelableGroup> { if (!omitIntentExtra && extras != null) { val cache = extras.getParcelable<ParcelableGroup?>(EXTRA_GROUP) if (cache != null) return SingleResponse(cache) } try { if (accountKey == null) throw MicroBlogException("No account") val twitter = MicroBlogAPIFactory.getInstance(context, accountKey) ?: throw MicroBlogException("No account") val group: Group if (groupId != null) { group = twitter.showGroup(groupId) } else if (groupName != null) { group = twitter.showGroupByName(groupName) } else { return SingleResponse() } return SingleResponse.getInstance(ParcelableGroupUtils.from(group, accountKey, 0, group.isMember)) } catch (e: MicroBlogException) { return SingleResponse(e) } } override fun onStartLoading() { forceLoad() } } }
gpl-3.0
05c6a1c24c667fdc0fac291cb932c5f7
38.078431
134
0.677484
4.707087
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/readinglist/ReadingListsShareHelper.kt
1
4092
package org.wikipedia.readinglist import android.content.Intent import android.util.Base64 import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.launch import kotlinx.serialization.Serializable import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.ReadingListsFunnel import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.json.JsonUtil import org.wikipedia.readinglist.database.ReadingList import org.wikipedia.settings.Prefs import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.GeoUtil import org.wikipedia.util.ReleaseUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L object ReadingListsShareHelper { fun shareEnabled(): Boolean { return ReleaseUtil.isPreBetaRelease || (listOf("EG", "DZ", "MA", "KE", "CG", "AO", "GH", "NG", "IN", "BD", "PK", "LK", "NP").contains(GeoUtil.geoIPCountry.orEmpty()) && listOf("en", "ar", "hi", "fr", "bn", "es", "pt", "de", "ur", "arz", "si", "sw", "fa", "ne", "te").contains(WikipediaApp.instance.appOrSystemLanguageCode)) } fun shareReadingList(activity: AppCompatActivity, readingList: ReadingList?) { if (readingList == null) { return } activity.lifecycleScope.launch(CoroutineExceptionHandler { _, throwable -> L.e(throwable) FeedbackUtil.showError(activity, throwable) }) { val wikiPageTitlesMap = mutableMapOf<String, MutableList<String>>() readingList.pages.forEach { wikiPageTitlesMap.getOrPut(it.lang) { mutableListOf() }.add(it.apiTitle) } val wikiPageIdsMap = mutableMapOf<String, MutableMap<String, Int>>() wikiPageTitlesMap.keys.forEach { wikiLang -> val titleList = wikiPageTitlesMap[wikiLang].orEmpty() val pages = ServiceFactory.get(WikiSite.forLanguageCode(wikiLang)).getPageIds(titleList.joinToString("|")).query?.pages!! pages.forEach { page -> wikiPageIdsMap.getOrPut(wikiLang) { mutableMapOf() }[StringUtil.addUnderscores(page.title)] = page.pageId } } val param = readingListToUrlParam(readingList, wikiPageIdsMap) val url = WikipediaApp.instance.wikiSite.url() + "/wiki/Special:ReadingLists?limport=$param" val finalUrl = if (Prefs.useUrlShortenerForSharing) ServiceFactory.get(WikipediaApp.instance.wikiSite).shortenUrl(url).shortenUrl?.shortUrl.orEmpty() else url ReadingListsFunnel().logShareList(readingList) val intent = Intent(Intent.ACTION_SEND) .putExtra(Intent.EXTRA_SUBJECT, readingList.title) .putExtra(Intent.EXTRA_TEXT, activity.getString(R.string.reading_list_share_message, readingList.title) + " " + finalUrl) .setType("text/plain") activity.startActivity(intent) ReadingListsShareSurveyHelper.activateSurvey() ReadingListsShareSurveyHelper.maybeShowSurvey(activity) } } private fun readingListToUrlParam(readingList: ReadingList, pageIdMap: Map<String, Map<String, Int>>): String { val projectUrlMap = mutableMapOf<String, Collection<Int>>() pageIdMap.keys.forEach { projectUrlMap[it] = pageIdMap[it]!!.values } // TODO: for now we're not transmitting the free-form Name and Description of a reading list. val exportedReadingLists = ExportedReadingLists(projectUrlMap /*, readingList.title, readingList.description */) return Base64.encodeToString(JsonUtil.encodeToString(exportedReadingLists)!!.toByteArray(), Base64.NO_WRAP) } @Suppress("unused") @Serializable class ExportedReadingLists ( val list: Map<String, Collection<Int>>, val name: String? = null, val description: String? = null ) }
apache-2.0
6479111574a785a36c37e83a1ef24826
43.967033
178
0.680596
4.442997
false
false
false
false
UnsignedInt8/d.Wallet-Core
android/lib/src/main/java/dWallet/core/bitcoin/application/bip32/ECKey.kt
1
7979
package dwallet.core.bitcoin.application.bip32 /** * Created by unsignedint8 on 8/24/17. */ import dwallet.core.extensions.* import org.spongycastle.asn1.ASN1InputStream import org.spongycastle.asn1.ASN1Integer import org.spongycastle.asn1.DERSequenceGenerator import org.spongycastle.asn1.DLSequence import org.spongycastle.asn1.sec.SECNamedCurves import org.spongycastle.crypto.digests.SHA256Digest import org.spongycastle.crypto.params.ECDomainParameters import org.spongycastle.crypto.params.ECPrivateKeyParameters import org.spongycastle.crypto.params.ECPublicKeyParameters import org.spongycastle.crypto.signers.ECDSASigner import org.spongycastle.crypto.signers.HMacDSAKCalculator import org.spongycastle.util.Arrays import java.io.ByteArrayOutputStream import java.math.BigInteger /** * Created by Jesion on 2015-01-14. * * Elliptic Curve Key represents a pair of keys actually, * - Private which is a BigInteger * - Public which is an Elliptic Curve multiplication of private */ class ECKey { var priv: BigInteger? = null private set var public: ByteArray? = null private set var publicKeyHash: ByteArray? = null private set var isCompressed: Boolean = false private set //l is unsigned byte[] - coming from left part of bitcoin key hash //it can be converted to BigInt and saved as private master key constructor(l: ByteArray, compressed: Boolean) : this(l, compressed, true) {} //ECKey constructor with parent argument for key derivation constructor(l: ByteArray, parent: ECKey) { if (parent.hasPrivate()) { this.priv = BigInteger(1, l).add(parent.priv).mod(curve.n) setPub(parent.isCompressed, true, null) } else { throw Error("Support derived ECKey with public key only") } } //bytes is either coming from left part of bitcoin key hash //it can be converted to BigInt and saved as private master key //isPrivate is set to true in this case, //otherwise its a public key only constructor(bytes: ByteArray, compressed: Boolean, isPrivate: Boolean) { if (isPrivate) { this.priv = BigInteger(1, bytes) setPub(compressed, true, null) } else { setPub(compressed, false, bytes) } } @Throws(Exception::class) fun sign(message: ByteArray): ByteArray { if (priv == null) { throw Exception("Unable to sign") } val signer = ECDSASigner(HMacDSAKCalculator(SHA256Digest())) signer.init(true, ECPrivateKeyParameters(priv, params)) val signature = signer.generateSignature(message) val outputStream = ByteArrayOutputStream() val seqGen = DERSequenceGenerator(outputStream) seqGen.addObject(ASN1Integer(signature[0])) seqGen.addObject(ASN1Integer(signature[1])) seqGen.close() return outputStream.toByteArray() } @Throws(Exception::class) fun verify(message: ByteArray, signature: ByteArray): Boolean { val asn1 = ASN1InputStream(signature) val signer = ECDSASigner() //not for signing... signer.init(false, ECPublicKeyParameters(curve.curve.decodePoint(public!!), params)) val seq = asn1.readObject() as DLSequence val r = (seq.getObjectAt(0) as ASN1Integer).positiveValue val s = (seq.getObjectAt(1) as ASN1Integer).positiveValue return signer.verifySignature(message, r, s) } val private: ByteArray? get() { if (hasPrivate()) { var p = priv!!.toByteArray() if (p.size != 32) { val tmp = ByteArray(32) System.arraycopy(p, Math.max(0, p.size - 32), tmp, Math.max(0, 32 - p.size), Math.min(32, p.size)) p = tmp } return p } return null } val wif: String @Throws(Exception::class) get() = ByteUtil.toBase58(wifBytes) fun hasPrivate(): Boolean { return priv != null } val publicHex: String? get() = public?.toHexString() override fun equals(obj: Any?): Boolean = if (obj is ECKey) { Arrays.areEqual(obj.private, this.private) && Arrays.areEqual(obj.public, this.public) && Arrays.areEqual(obj.publicKeyHash, this.publicKeyHash) && obj.isCompressed == this.isCompressed } else false private fun setPub(compressed: Boolean, fromPrivate: Boolean, bytes: ByteArray?) { this.isCompressed = compressed if (fromPrivate) { public = curve.g.multiply(priv).getEncoded(compressed) } else { public = bytes } publicKeyHash = Hash(public!!).keyHash() } private val wifBytes: ByteArray @Throws(Exception::class) get() { if (hasPrivate()) { val k = private if (isCompressed == true) { val encoded = ByteArray(k!!.size + 6) val ek = ByteArray(k.size + 2) ek[0] = 0x80.toByte() System.arraycopy(k, 0, ek, 1, k.size) ek[k.size + 1] = 0x01 val hash = Hash.hash(ek) System.arraycopy(ek, 0, encoded, 0, ek.size) System.arraycopy(hash, 0, encoded, ek.size, 4) return encoded } else { val encoded = ByteArray(k!!.size + 5) val ek = ByteArray(k.size + 1) ek[0] = 0x80.toByte() System.arraycopy(k, 0, ek, 1, k.size) val hash = Hash.hash(ek) System.arraycopy(ek, 0, encoded, 0, ek.size) System.arraycopy(hash, 0, encoded, ek.size, 4) return encoded } } else { throw Exception("Won't provide WIF if no private key is present") } } object ECKeyParser { fun parse(wif: String): ECKey? { return try { parseBytes(ByteUtil.fromBase58(wif)) } catch (e: Exception) { null } } @Throws(Exception::class) fun parseBytes(keyBytes: ByteArray): ECKey { checkChecksum(keyBytes) //decode uncompressed if (keyBytes.size == 37) { val key = ByteArray(keyBytes.size - 5) System.arraycopy(keyBytes, 1, key, 0, keyBytes.size - 5) return ECKey(key, false) } else if (keyBytes.size == 38) { val key = ByteArray(keyBytes.size - 6) System.arraycopy(keyBytes, 1, key, 0, keyBytes.size - 6) return ECKey(key, true) }//decode compressed throw Exception("Invalid key length") } @Throws(Exception::class) private fun checkChecksum(keyBytes: ByteArray) { val checksum = ByteArray(4) //last 4 bytes of key are checksum, copy it to checksum byte[] System.arraycopy(keyBytes, keyBytes.size - 4, checksum, 0, 4) val eckey = ByteArray(keyBytes.size - 4) //anything else is the EC key base, copy it to eckey System.arraycopy(keyBytes, 0, eckey, 0, keyBytes.size - 4) //now hash the eckey val hash = Hash.hash(eckey) for (i in 0..3) { //compare first 4 bytes of the key hash with corresponding positions in checksum bytes if (hash[i] != checksum[i]) { throw Exception("checksum mismatch") } } } } companion object { val curve = SECNamedCurves.getByName("secp256k1") val params = ECDomainParameters(curve.curve, curve.g, curve.n, curve.h) } }
gpl-3.0
7d7d951947b7d38310c5dd41691cdec1
34.462222
118
0.582028
4.285177
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/RsDoubleNegInspectionTest.kt
4
1001
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections /** * Tests for Double Negation inspection. */ class RsDoubleNegInspectionTest : RsInspectionsTestBase(RsDoubleNegInspection::class) { fun testSimple() = checkByText(""" fn main() { let a = 12; let b = <warning descr="--x could be misinterpreted as a pre-decrement, but effectively is a no-op">--a</warning>; } """) fun testWithSpaces() = checkByText(""" fn main() { let i = 10; while <warning descr="--x could be misinterpreted as a pre-decrement, but effectively is a no-op">- - i</warning> > 0 {} } """) fun testExpression() = checkByText(""" fn main() { let a = 7; println!("{}", <warning descr="--x could be misinterpreted as a pre-decrement, but effectively is a no-op">--(2*a + 1)</warning>); } """) }
mit
f58ccfcba8d6b58984ade620d6db83ef
29.333333
143
0.578422
4.02008
false
true
false
false
brianwernick/ExoMedia
library/src/main/kotlin/com/devbrackets/android/exomedia/core/source/builder/DashMediaSourceBuilder.kt
1
923
package com.devbrackets.android.exomedia.core.source.builder import androidx.media3.common.MediaItem import androidx.media3.exoplayer.dash.DashMediaSource import androidx.media3.exoplayer.dash.DefaultDashChunkSource import androidx.media3.exoplayer.source.MediaSource class DashMediaSourceBuilder : MediaSourceBuilder() { override fun build(attributes: MediaSourceAttributes): MediaSource { val factoryAttributes = attributes.copy( transferListener = null ) val dataSourceFactory = buildDataSourceFactory(factoryAttributes) val meteredDataSourceFactory = buildDataSourceFactory(attributes) val mediaItem = MediaItem.Builder().setUri(attributes.uri).build() return DashMediaSource.Factory(DefaultDashChunkSource.Factory(meteredDataSourceFactory), dataSourceFactory) .setDrmSessionManagerProvider(attributes.drmSessionManagerProvider) .createMediaSource(mediaItem) } }
apache-2.0
d57bf8d04c67101655f88ea821527321
40.954545
111
0.813651
5.016304
false
false
false
false