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
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/usecase/SaveProfileUseCase.kt
1
944
package io.ipoli.android.player.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository /** * Created by Polina Zhelyazkova <polina@mypoli.fun> * on 6/6/18. */ class SaveProfileUseCase( private val playerRepository: PlayerRepository ) : UseCase<SaveProfileUseCase.Params, Player> { override fun execute(parameters: Params): Player { val player = playerRepository.find() requireNotNull(player) val displayName = if (parameters.displayName.isNullOrBlank()) null else parameters.displayName val bio = if (parameters.bio.isNullOrBlank()) null else parameters.bio return playerRepository.save( player!!.copy( displayName = displayName, bio = bio ) ) } data class Params(val displayName: String?, val bio: String?) }
gpl-3.0
8fccc8c2a2085d2d186c9d491fac65a5
29.483871
88
0.676907
4.627451
false
false
false
false
ACRA/acra
acra-notification/src/main/java/org/acra/interaction/NotificationInteraction.kt
1
7790
/* * Copyright (c) 2017 * * 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.acra.interaction import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.widget.RemoteViews import androidx.core.app.NotificationCompat import androidx.core.app.RemoteInput import com.google.auto.service.AutoService import org.acra.ACRA import org.acra.config.CoreConfiguration import org.acra.config.NotificationConfiguration import org.acra.config.getPluginConfiguration import org.acra.notification.R import org.acra.plugins.HasConfigPlugin import org.acra.prefs.SharedPreferencesFactory import org.acra.receiver.NotificationBroadcastReceiver import org.acra.sender.LegacySenderService import java.io.File /** * @author F43nd1r * @since 15.09.2017 */ @AutoService(ReportInteraction::class) class NotificationInteraction : HasConfigPlugin(NotificationConfiguration::class.java), ReportInteraction { override fun performInteraction(context: Context, config: CoreConfiguration, reportFile: File): Boolean { val prefs = SharedPreferencesFactory(context, config).create() if (prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) { return true } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return true //can't post notifications val notificationConfig = config.getPluginConfiguration<NotificationConfiguration>() //We have to create a channel on Oreo+, because notifications without one aren't allowed if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @SuppressLint("WrongConstant") val channel = NotificationChannel(CHANNEL, notificationConfig.channelName, notificationConfig.channelImportance) channel.setSound(null, null) if (notificationConfig.channelDescription?.isNotEmpty() == true) { channel.description = notificationConfig.channelDescription } notificationManager.createNotificationChannel(channel) } //configure base notification val notification = NotificationCompat.Builder(context, CHANNEL) .setWhen(System.currentTimeMillis()) .setContentTitle(notificationConfig.title) .setContentText(notificationConfig.text) .setSmallIcon(notificationConfig.resIcon) .setPriority(NotificationCompat.PRIORITY_HIGH) //add ticker if set if (notificationConfig.tickerText?.isNotEmpty() == true) { notification.setTicker(notificationConfig.tickerText) } val sendIntent = getSendIntent(context, config, reportFile) val discardIntent = getDiscardIntent(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && notificationConfig.sendWithCommentButtonText?.isNotEmpty() == true) { val remoteInput = RemoteInput.Builder(KEY_COMMENT) if (notificationConfig.commentPrompt?.isNotEmpty() == true) { remoteInput.setLabel(notificationConfig.commentPrompt) } notification.addAction( NotificationCompat.Action.Builder(notificationConfig.resSendWithCommentButtonIcon, notificationConfig.sendWithCommentButtonText, sendIntent) .addRemoteInput(remoteInput.build()).build()) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { val bigView = getBigView(context, notificationConfig) notification.addAction(notificationConfig.resSendButtonIcon, notificationConfig.sendButtonText ?: context.getString(android.R.string.ok), sendIntent) .addAction(notificationConfig.resDiscardButtonIcon, notificationConfig.discardButtonText ?: context.getString(android.R.string.cancel), discardIntent) .setCustomContentView(getSmallView(context, notificationConfig, sendIntent, discardIntent)) .setCustomBigContentView(bigView) .setCustomHeadsUpContentView(bigView) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) } //On old devices we have no notification buttons, so we have to set the intent to the only possible interaction: click if (notificationConfig.sendOnClick || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { notification.setContentIntent(sendIntent) } notification.setDeleteIntent(discardIntent) notificationManager.notify(NOTIFICATION_ID, notification.build()) return false } private val pendingIntentFlags = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } private fun getSendIntent(context: Context, config: CoreConfiguration, reportFile: File): PendingIntent { val intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.action = INTENT_ACTION_SEND intent.putExtra(LegacySenderService.EXTRA_ACRA_CONFIG, config) intent.putExtra(EXTRA_REPORT_FILE, reportFile) return PendingIntent.getBroadcast(context, ACTION_SEND, intent, pendingIntentFlags) } private fun getDiscardIntent(context: Context): PendingIntent { val intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.action = INTENT_ACTION_DISCARD return PendingIntent.getBroadcast(context, ACTION_DISCARD, intent, pendingIntentFlags) } private fun getSmallView(context: Context, notificationConfig: NotificationConfiguration, sendIntent: PendingIntent, discardIntent: PendingIntent): RemoteViews { val view = RemoteViews(context.packageName, R.layout.notification_small) view.setTextViewText(R.id.text, notificationConfig.text) view.setTextViewText(R.id.title, notificationConfig.title) view.setImageViewResource(R.id.button_send, notificationConfig.resSendButtonIcon) view.setImageViewResource(R.id.button_discard, notificationConfig.resDiscardButtonIcon) view.setOnClickPendingIntent(R.id.button_send, sendIntent) view.setOnClickPendingIntent(R.id.button_discard, discardIntent) return view } private fun getBigView(context: Context, notificationConfig: NotificationConfiguration): RemoteViews { val view = RemoteViews(context.packageName, R.layout.notification_big) view.setTextViewText(R.id.text, notificationConfig.text) view.setTextViewText(R.id.title, notificationConfig.title) return view } companion object { const val INTENT_ACTION_SEND = "org.acra.intent.send" const val INTENT_ACTION_DISCARD = "org.acra.intent.discard" const val KEY_COMMENT = "comment" const val EXTRA_REPORT_FILE = "REPORT_FILE" const val NOTIFICATION_ID = 666 private const val ACTION_SEND = 667 private const val ACTION_DISCARD = 668 private const val CHANNEL = "ACRA" } }
apache-2.0
1a1d1156307659c75adf1d67401ed0ca
50.256579
170
0.723877
4.884013
false
true
false
false
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/settings/ui/FullLineReducedConfigurable.kt
2
15747
package org.jetbrains.completion.full.line.settings.ui import com.intellij.lang.Language import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.NlsSafe import com.intellij.ui.JBColor import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.* import org.jetbrains.completion.full.line.language.* import org.jetbrains.completion.full.line.models.ModelType import org.jetbrains.completion.full.line.services.managers.ConfigurableModelsManager import org.jetbrains.completion.full.line.services.managers.excessLanguage import org.jetbrains.completion.full.line.services.managers.missedLanguage import org.jetbrains.completion.full.line.settings.MLServerCompletionBundle.Companion.message import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings import org.jetbrains.completion.full.line.settings.state.MlServerCompletionAuthState import org.jetbrains.completion.full.line.settings.ui.components.* import org.jetbrains.completion.full.line.tasks.SetupLocalModelsTask import kotlin.reflect.KMutableProperty1 @Suppress("DuplicatedCode") class FullLineReducedConfigurable : BoundConfigurable(message("fl.server.completion.display")), SearchableConfigurable { init { // It is necessary to preload the configuration services so that they are not reset service<MLServerCompletionSettings>() service<MlServerCompletionAuthState>() } private val logger = thisLogger() private val settings = MLServerCompletionSettings.getInstance() private val settingsAuth = MlServerCompletionAuthState.getInstance() private lateinit var modelType: ComboBox<ModelType> private lateinit var flccEnabled: ComponentPredicate private val langsEnabled = mutableMapOf<String, ComponentPredicate>() private val languages = MLServerCompletionSettings.availableLanguages private val generalState = settings.state private val langStates = languages.sortedBy { it.id }.map { settings.getLangState(it) } private val modelStates = languages.sortedBy { it.id }.map { language -> ModelType.values().map { settings.getModelState(language, it) } }.flatten() private val biggestLang = languages.map { it.displayName }.maxByOrNull { it.length } override fun createPanel(): DialogPanel { return panel { group(message("fl.server.completion.settings.group")) { row { flccEnabled = checkBox(message("fl.server.completion.display")) .bindSelected(generalState::enable) .selected if (settingsAuth.isVerified()) { label(message("full.line.label.verified.text")).applyToComponent { foreground = JBColor(JBColor.GREEN.darker(), JBColor.GREEN.brighter()) } } } indent { if (settingsAuth.isVerified()) { internal() } else { community() } }.enabledIf(flccEnabled) } }.also { panel -> // Unite callbacks for enabling same languages if more than on model typ provided if (settingsAuth.isVerified()) { with(LinkedHashMap<String, MutableList<JBCheckBox>>()) { panel.languageCheckboxes().groupByTo(this) { it.text } values.filter { it.size >= 2 }.forEach { (cloudState, localState) -> require(cloudState.text == localState.text) langsEnabled[localState.text] = cloudState.selected localState.connectWith(cloudState) cloudState.connectWith(localState) } } } } } private fun Panel.notAvailable(cause: String?) = row { logger.info("Settings are not available" + (cause?.let { ", cause: $cause." } ?: "")) comment("Currently, Full Line is available only for Python language, please install its plugin and restart or use PyCharm") } private fun Panel.community() { logger.info("Using community settings") val lang = Language.findLanguageByID("Python") if (lang == null) { notAvailable("Python plugin is missing") return } if (FullLineLanguageSupporter.getInstance(lang) == null) { notAvailable("Python supporter is missing") return } val langState = settings.getLangState(lang) buttonsGroup(message("fl.server.completion.enable.languages")) { localModels(listOf(lang)) } buttonsGroup(message("fl.server.completion.settings.language")) { lateinit var useBox: Cell<JBCheckBox> row { useBox = checkBox(message("fl.server.completion.top.n.use")).bindSelected(generalState::useTopN) } indent { row { intTextField(IntRange(0, 20), 1) .bindIntText(generalState::topN) .enabledIf(useBox.selected) } } row(message("fl.server.completion.ref.check")) { comboBox( RedCodePolicy.values().toList(), RedCodePolicyRenderer() ).bindItem(langState::redCodePolicy.toNullableProperty()) } row { checkBox(message("fl.server.completion.enable.strings.walking")) .bindSelected(langState::stringsWalking) .gap(RightGap.SMALL) contextHelp(message("fl.server.completion.enable.strings.walking.help")) } extended { row { checkBox(message("fl.server.completion.only.full")) .bindSelected(langState::onlyFullLines) } row { checkBox(message("fl.server.completion.group.answers")) .bindSelected(langState::groupAnswers) } row { checkBox(message("fl.server.completion.score")) .bindSelected(langState::showScore) } } } } private fun Panel.internal() { logger.info("Using internal settings") if (languages.isEmpty()) { notAvailable("No supported languages installed") return } row(message("full.line.settings.model.type")) { modelType = comboBox(ModelType.values().toList(), listCellRenderer { value, _, _ -> @NlsSafe val valueName = value.name text = valueName icon = value.icon }).bindItem(generalState::modelType.toNullableProperty()) .component }.layout(RowLayout.INDEPENDENT) buttonsGroup(message("fl.server.completion.enable.languages")) { rowsRange { localModels(languages) }.visibleIf(modelType.selectedValueIs(ModelType.Local)) rowsRange { cloudModels() }.visibleIf(modelType.selectedValueIs(ModelType.Cloud)) } buttonsGroup(message("fl.server.completion.settings.completion")) { lateinit var useBox: Cell<JBCheckBox> row { useBox = checkBox(message("fl.server.completion.top.n.use")) .bindSelected(generalState::useTopN) } indent { row { intTextField(IntRange(0, 20), 1) .bindIntText(generalState::topN) .enabledIf(useBox.selected) } } row(message("fl.server.completion.ref.check")) { comboBox(RedCodePolicy.values().toList(), RedCodePolicyRenderer() ).bindItem(langStates.toMutableProperty(LangState::redCodePolicy).toNullableProperty()) }.layout(RowLayout.INDEPENDENT) row { checkBox(message("fl.server.completion.enable.strings.walking")) .bindSelected(langStates.toMutableProperty(LangState::stringsWalking)) .gap(RightGap.SMALL) contextHelp(message("fl.server.completion.enable.strings.walking.help")) } extended { row { checkBox(message("fl.server.completion.only.full")) .bindSelected(langStates.toMutableProperty(LangState::onlyFullLines)) } row { checkBox(message("fl.server.completion.group.answers")) .bindSelected(langStates.toMutableProperty(LangState::groupAnswers)) } row { checkBox(message("fl.server.completion.score")) .bindSelected(langStates.toMutableProperty(LangState::showScore)) } } } extended { separator() row { label(message("fl.server.completion.bs")) link(message("full.line.settings.reset.default")) { generalState.langStates.keys.forEach { val lang = Language.findLanguageByID(it) ?: return@forEach generalState.langStates[it] = FullLineLanguageSupporter.getInstance(lang)?.langState ?: LangState() } }.align(AlignX.RIGHT) } row(message("fl.server.completion.bs.num.iterations")) { intTextField(IntRange(0, 50), 1) .bindIntText(modelStates.toMutableProperty(ModelState::numIterations)) } row(message("fl.server.completion.bs.beam.size")) { intTextField(IntRange(0, 20), 1) .bindIntText(modelStates.toMutableProperty(ModelState::beamSize)) } row(message("fl.server.completion.bs.len.base")) { doubleTextField(modelStates.toMutableProperty(ModelState::lenBase), IntRange(0, 10)) } row(message("fl.server.completion.bs.len.pow")) { doubleTextField(modelStates.toMutableProperty(ModelState::lenPow), IntRange(0, 1)) } row(message("fl.server.completion.bs.diversity.strength")) { doubleTextField(modelStates.toMutableProperty(ModelState::diversityStrength), IntRange(0, 10)) } row(message("fl.server.completion.bs.diversity.groups")) { intTextField(IntRange(0, 5), 1) .bindIntText(modelStates.toMutableProperty(ModelState::diversityGroups)) } indent { lateinit var groupUse: ComponentPredicate row { groupUse = checkBox(message("fl.server.completion.group.top.n.use")) .bindSelected(modelStates.toMutableProperty(ModelState::useGroupTopN)) .selected } indent { row { intTextField(IntRange(0, 20), 1) .bindIntText(modelStates.toMutableProperty(ModelState::groupTopN)) .enabledIf(groupUse) } } } lateinit var lengthUse: ComponentPredicate row { lengthUse = checkBox(message("fl.server.completion.context.length.use")) .bindSelected(modelStates.toMutableProperty(ModelState::useCustomContextLength)) .selected } indent { row { intTextField(IntRange(0, 384), 1) .bindIntText(modelStates.toMutableProperty(ModelState::customContextLength)) .enabledIf(lengthUse) } } panel { row(message("fl.server.completion.deduplication.minimum.prefix")) { doubleTextField(modelStates.toMutableProperty(ModelState::minimumPrefixDist), IntRange(0, 1)) } row(message("fl.server.completion.deduplication.minimum.edit")) { doubleTextField(modelStates.toMutableProperty(ModelState::minimumEditDist), IntRange(0, 1)) } row(message("fl.server.completion.deduplication.keep.kinds")) { KeepKind.values().map { kind -> @NlsSafe val text = kind.name.toLowerCase().capitalize() checkBox(text) .bindSelected({ modelStates.first().keepKinds.contains(kind) }, { action -> modelStates.forEach { if (action) it.keepKinds.add(kind) else it.keepKinds.remove(kind) } }) } } } } // if (language == JavaLanguage.INSTANCE) { // row { // checkBox(message("fl.server.completion.enable.psi.completion"), state::psiBased) // } // } } private fun Panel.cloudModels() { languages.forEach { language -> row { val checkBox = languageCheckBox(language, biggestLang) .bindSelected(MLServerCompletionSettings.getInstance().getLangState(language)::enabled) val loadingIcon = LoadingComponent() cell(pingButton(language, loadingIcon, null)) .enabledIf(checkBox.selected) loadingStatus(loadingIcon).forEach { // Do not show even, if model type was changed. Visibility will be controlled from LoadingComponent itself it.enabledIf(checkBox.selected).visibleIf(modelType.selectedValueMatches { false }) } } } } private fun Panel.localModels(languages: List<Language>) { val actions = mutableListOf<SetupLocalModelsTask.ToDoParams>() languages.map { language -> row { languageCheckBox(language, biggestLang).bindSelected(settings.getLangState(language)::enabled) } extended { indent { row { cell(modelFromLocalFileLinkLabel(language, actions)) service<ConfigurableModelsManager>().modelsSchema.models .find { it.currentLanguage == language.id.toLowerCase() } ?.let { comment(message("fl.server.completion.models.source.local.comment", it.version, it.uid())) } } // Removed cause deleting now exec after language turn off // row { // component(deleteCurrentModelLinkLabel(language, actions)) // } } } } var resetCount = 0 onReset { // Add download actions for languages which are enabled, but not downloaded. // resetCount flag used cause reset is called firstly called right after components initialisation resetCount++ } onIsModified { settings.getModelMode() == ModelType.Local && ((resetCount <= 1 && languages.any { service<ConfigurableModelsManager>().missedLanguage(it) }) || actions.isNotEmpty()) } onApply { if (settings.getModelMode() == ModelType.Local) { val taskActions = mutableListOf<SetupLocalModelsTask.ToDoParams>() // Add actions to import local taskActions.addAll(actions) actions.clear() // Add actions to remove local models which are downloaded, but disabled taskActions.addAll( languages.filter { service<ConfigurableModelsManager>().excessLanguage(it) }.map { SetupLocalModelsTask.ToDoParams(it, SetupLocalModelsTask.Action.REMOVE) } ) // Add actions to download local models which are removed, but enabled taskActions.addAll( languages.filter { service<ConfigurableModelsManager>().missedLanguage(it) }.map { SetupLocalModelsTask.ToDoParams(it, SetupLocalModelsTask.Action.DOWNLOAD) } ) SetupLocalModelsTask.queue(taskActions) } } } override fun getHelpTopic() = "full.line.completion.reduced" override fun getId() = helpTopic override fun getDisplayName() = message("full.line.configurable.name") } /** * Below mutable property to create settings for all language/modeltype states. * Taking value from first language (sorted by id) * Setting value for all states at ones */ private fun <T, V> List<T>.toMutableProperty(field: KMutableProperty1<T, V>): MutableProperty<V> { val bindings = map { MutableProperty({ field.getter(it) }, { value -> field.setter(it, value) }) } return MutableProperty({ bindings.first().get() }, { v -> bindings.forEach { it.set(v) } }) }
apache-2.0
e9c30e2d242c3cd8c5ae4676b0597c4b
38.171642
129
0.651108
4.626028
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithIndexingOperationInspection.kt
4
2392
// 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.inspections.substring import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.psi.KtConstantExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator class ReplaceSubstringWithIndexingOperationInspection : ReplaceSubstringInspection() { override fun inspectionText(element: KtDotQualifiedExpression): String = KotlinBundle.message("inspection.replace.substring.with.indexing.operation.display.name") override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.indexing.operation.call") override val isAlwaysStable: Boolean = true override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val expression = element.callExpression?.valueArguments?.firstOrNull()?.getArgumentExpression() ?: return element.replaceWith("$0[$1]", expression) } override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean { val arguments = element.callExpression?.valueArguments ?: return false if (arguments.size != 2) return false val arg1 = element.getValueArgument(0) ?: return false val arg2 = element.getValueArgument(1) ?: return false return arg1 + 1 == arg2 } private fun KtDotQualifiedExpression.getValueArgument(index: Int): Int? { val bindingContext = analyze() val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null val expression = resolvedCall.call.valueArguments[index].getArgumentExpression() as? KtConstantExpression ?: return null val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return null val constantType = bindingContext.getType(expression) ?: return null return constant.getValue(constantType) as? Int } }
apache-2.0
ebb35bb815de315c6669df025677209f
53.386364
158
0.773829
5.067797
false
false
false
false
poetix/centipede
src/main/java/com/codepoetics/centipede/RegexUriSetExtractor.kt
1
792
package com.codepoetics.centipede import java.net.URI import java.util.regex.Pattern class RegexUriSetExtractor() : UriSetExtractor { val uriPattern = Pattern.compile("href=\"([^\"]*)\"") override fun invoke(baseUri: URI, page: Page): Set<URI> { val matcher = uriPattern.matcher(page) var result: UriSet = emptySet() while (matcher.find()) { try { val fullUri = baseUri.resolve(URI.create(matcher.group(1))) val normalisedUri = URI(fullUri.scheme, fullUri.host, fullUri.path, null) result += normalisedUri } catch (e: Throwable) { e.printStackTrace() // just ignore all parsing failures for now } } return result } }
apache-2.0
78ae198b9d6f0c0dd504d567535c936a
27.285714
89
0.57702
4.212766
false
false
false
false
jk1/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/LookupCompletedTracker.kt
2
5083
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.stats.completion import com.intellij.codeInsight.lookup.LookupAdapter import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupEvent import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.completion.FeatureManagerImpl import com.intellij.stats.personalization.UserFactorDescriptions import com.intellij.stats.personalization.UserFactorStorage import com.jetbrains.completion.feature.impl.FeatureUtils /** * @author Vitaliy.Bibaev */ class LookupCompletedTracker : LookupAdapter() { override fun lookupCanceled(event: LookupEvent?) { val lookup = event?.lookup as? LookupImpl ?: return val element = lookup.currentItem if (element != null && isSelectedByTyping(lookup, element)) { processTypedSelect(lookup, element) } else { UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.COMPLETION_FINISH_TYPE) { updater -> updater.fireLookupCancelled() } } } override fun itemSelected(event: LookupEvent?) { val lookup = event?.lookup as? LookupImpl ?: return val element = event.item ?: return processExplicitSelect(lookup, element) } private fun isSelectedByTyping(lookup: LookupImpl, element: LookupElement): Boolean = element.lookupString == lookup.itemPattern(element) private fun processElementSelected(lookup: LookupImpl, element: LookupElement) { val relevanceObjects = lookup.getRelevanceObjects(listOf(element), false) val relevanceMap = relevanceObjects[element]?.map { it.first to it.second } ?: return val featuresValues = FeatureUtils.prepareRevelanceMap(relevanceMap, lookup.selectedIndex, lookup.prefixLength(), element.lookupString.length) val project = lookup.project val featureManager = FeatureManagerImpl.getInstance() featureManager.binaryFactors.filter { !featureManager.isUserFeature(it.name) }.forEach { feature -> UserFactorStorage.applyOnBoth(project, UserFactorDescriptions.binaryFeatureDescriptor(feature)) { updater -> updater.update(featuresValues[feature.name]) } } featureManager.doubleFactors.filter { !featureManager.isUserFeature(it.name) }.forEach { feature -> UserFactorStorage.applyOnBoth(project, UserFactorDescriptions.doubleFeatureDescriptor(feature)) { updater -> updater.update(featuresValues[feature.name]) } } featureManager.categoricalFactors.filter { !featureManager.isUserFeature(it.name) }.forEach { feature -> UserFactorStorage.applyOnBoth(project, UserFactorDescriptions.categoricalFeatureDescriptor(feature)) { updater -> updater.update(featuresValues[feature.name]) } } } private fun processExplicitSelect(lookup: LookupImpl, element: LookupElement) { processElementSelected(lookup, element) UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.COMPLETION_FINISH_TYPE) { updater -> updater.fireExplicitCompletionPerformed() } val prefixLength = lookup.getPrefixLength(element) UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.PREFIX_LENGTH_ON_COMPLETION) { updater -> updater.fireCompletionPerformed(prefixLength) } val itemPosition = lookup.selectedIndex if (itemPosition != -1) { UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.SELECTED_ITEM_POSITION) { updater -> updater.fireCompletionPerformed(itemPosition) } } if (prefixLength > 1) { val pattern = lookup.itemPattern(element) val isMnemonicsUsed = !element.lookupString.startsWith(pattern) UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.MNEMONICS_USAGE) { updater -> updater.fireCompletionFinished(isMnemonicsUsed) } } } private fun processTypedSelect(lookup: LookupImpl, element: LookupElement) { processElementSelected(lookup, element) UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.COMPLETION_FINISH_TYPE) { updater -> updater.fireTypedSelectPerformed() } } }
apache-2.0
f60d491b968bb9fc9c94b194adf5f90f
42.076271
118
0.699587
4.882805
false
false
false
false
hawaiianmoose/Android-DankBoard
app/src/main/java/com/boomcity/dankboard/TabDataInfo.kt
1
522
package com.boomcity.dankboard class TabDataInfo (tabName: String, tabPosition: Int, var soundClips: MutableList<SoundClip> = arrayListOf()) { var name: String = tabName val position: Int = tabPosition } class TabsData (tabsData: MutableList<TabDataInfo>?) { val tabsList: MutableList<TabDataInfo>? = tabsData fun getTab(tabId: Int) : TabDataInfo? { for (tab in tabsList!!) { if (tab.position == tabId) { return tab } } return null } }
gpl-3.0
dc0701deb39b223aa80b8fae1bc9f5ec
26.526316
111
0.62069
4.110236
false
false
false
false
ktorio/ktor
ktor-network/nix/src/io/ktor/network/sockets/TCPSocketNative.kt
1
1454
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets import io.ktor.network.selector.* import io.ktor.util.network.* import io.ktor.utils.io.* import kotlinx.coroutines.* import platform.posix.* import kotlin.coroutines.* internal class TCPSocketNative( private val descriptor: Int, private val selector: SelectorManager, override val remoteAddress: SocketAddress, override val localAddress: SocketAddress, parent: CoroutineContext = EmptyCoroutineContext ) : Socket, CoroutineScope { private val _context: CompletableJob = Job(parent[Job]) private val selectable: SelectableNative = SelectableNative(descriptor) override val coroutineContext: CoroutineContext = parent + Dispatchers.Unconfined + _context override val socketContext: Job get() = _context override fun attachForReading(channel: ByteChannel): WriterJob = attachForReadingImpl(channel, descriptor, selectable, selector) override fun attachForWriting(channel: ByteChannel): ReaderJob = attachForWritingImpl(channel, descriptor, selectable, selector) override fun close() { _context.complete() _context.invokeOnCompletion { shutdown(descriptor, SHUT_RDWR) // Descriptor is closed by the selector manager selector.notifyClosed(selectable) } } }
apache-2.0
c3a047edd0a43727b23d94ac63361250
32.813953
118
0.729023
4.767213
false
false
false
false
beyondeye/graphkool
graphkool-core/src/test/kotlin/com/beyondeye/graphkool/StartWarsQueryTest.kt
1
12789
package com.beyondeye.graphkool import graphql.GraphQL import io.kotlintest.specs.BehaviorSpec /** * Created by daely on 12/9/2016. */ class StartWarsQueryTest : BehaviorSpec() { init { given("the query 1") { val query = """ query HeroNameQuery { hero { name } } """ //val expected = mapOf("hero" to mapOf("name" to "R2-D2")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Correctly identifies R2-D2 as the hero of the Star Wars Saga") { result.toString() shouldBe "{hero={name=R2-D2}}" } } } given("the query 2") { val query = """ query HeroNameAndFriendsQuery { hero { id name friends { name } } } """ /* val expected = mapOf( "hero" to mapOf( "id" to "2001", "name" to "R2-D2", "friends" to arrayOf( mapOf("name" to "Luke Skywalker"), mapOf("name" to "Han Solo"), mapOf("name" to "Leia Organa") ) ) ) */ `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to query for the ID and friends of R2-D2") { result.toString() shouldBe "{hero={id=2001, name=R2-D2, friends=[{name=Luke Skywalker}, {name=Han Solo}, {name=Leia Organa}]}}" } } } given("the query 3") { val query = """ query NestedQuery { hero { name friends { name appearsIn friends { name } } } } """ val expected = mapOf( "hero" to mapOf("name" to "R2-D2", "friends" to listOf( mapOf( "name" to "Luke Skywalker", "appearsIn" to listOf("NEWHOPE", "EMPIRE", "JEDI"), "friends" to listOf( mapOf("name" to "Han Solo"), mapOf("name" to "Leia Organa"), mapOf("name" to "C-3PO"), mapOf("name" to "R2-D2") ) ), mapOf( "name" to "Han Solo", "appearsIn" to listOf("NEWHOPE", "EMPIRE", "JEDI"), "friends" to listOf( mapOf("name" to "Luke Skywalker"), mapOf("name" to "Leia Organa"), mapOf("name" to "R2-D2") ) ), mapOf( "name" to "Leia Organa", "appearsIn" to listOf("NEWHOPE", "EMPIRE", "JEDI"), "friends" to listOf( mapOf("name" to "Luke Skywalker"), mapOf("name" to "Han Solo"), mapOf("name" to "C-3PO"), mapOf("name" to "R2-D2") ) ) ) ) ) //val expected = mapOf("hero" to mapOf("name" to "R2-D2")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to query for the friends of friends of R2-D2") { result.toString() shouldBe expected.toString() //"{hero={name=R2-D2, friends=[{name=Luke Skywalker, appearsIn=[NEWHOPE, EMPIRE, JEDI], friends=[{name=Han Solo}, {name=Leia Organa}, {name=C-3PO}, {name=R2-D2}]}, {name=Han Solo, appearsIn=[NEWHOPE, EMPIRE, JEDI], friends=[{name=Luke Skywalker}, {name=Leia Organa}, {name=R2-D2}]}, {name=Leia Organa, appearsIn=[NEWHOPE, EMPIRE, JEDI], friends=[{name=Luke Skywalker}, {name=Han Solo}, {name=C-3PO}, {name=R2-D2}]}]}}" } } } given("the query 4") { val query = """ query FetchLukeQuery { human(id: "1000") { name } } """ val expected= mapOf("human" to mapOf("name" to "Luke Skywalker")) //val expected = mapOf("hero" to mapOf("name" to "R2-D2")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to query for Luke Skywalker directly, using his ID") { result.toString() shouldBe expected.toString() } } } given("the query 5") { val query = """ query FetchSomeIDQuery(${'$'}someId: String!) { human(id: ${'$'}someId) { name } } """ val expected = mapOf("human" to mapOf( "name" to "Luke Skywalker" )) val params = mapOf( "someId" to "1000" ) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query,null as Any?, params).data then("Allows us to create a generic query, then use it to fetch Luke Skywalker using his ID") { result.toString() shouldBe expected.toString() } } } given("the query 6") { val query = """ query humanQuery(${'$'}id: String!) { human(id: ${'$'}id) { name } } """ val expected = mapOf("human" to null) val params= mapOf("id" to "not a valid id") //val expected = mapOf("hero" to mapOf("name" to "R2-D2")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query,null as Any?, params).data then("Allows us to create a generic query, then pass an invalid ID to get null back") { result.toString() shouldBe expected.toString() } } } given("the query 7") { val query = """ query FetchLukeAliased { luke: human(id: "1000") { name } } """ val expected = mapOf("luke" to mapOf("name" to "Luke Skywalker")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to query for Luke, changing his key with an alias") { result.toString() shouldBe expected.toString() } } } given("the query 8") { val query = """ query FetchLukeAndLeiaAliased { luke: human(id: "1000") { name } leia: human(id: "1003") { name } } """ val expected = mapOf( "luke" to mapOf("name" to "Luke Skywalker"), "leia" to mapOf("name" to "Leia Organa")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to query for both Luke and Leia, using two root fields and an alias") { result.toString() shouldBe expected.toString() } } } given("the query 9") { val query = """ query DuplicateFields { luke: human(id: "1000") { name homePlanet } leia: human(id: "1003") { name homePlanet } } """ val expected = mapOf( "luke" to mapOf("name" to "Luke Skywalker", "homePlanet" to "Tatooine"), "leia" to mapOf("name" to "Leia Organa", "homePlanet" to "Alderaan")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to query using duplicated content") { result.toString() shouldBe expected.toString() } } } given("the query 10") { val query = """ query UseFragment { luke: human(id: "1000") { ...HumanFragment } leia: human(id: "1003") { ...HumanFragment } } fragment HumanFragment on Human { name homePlanet } """ val expected = mapOf( "luke" to mapOf("name" to "Luke Skywalker", "homePlanet" to "Tatooine"), "leia" to mapOf("name" to "Leia Organa", "homePlanet" to "Alderaan")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to use a fragment to avoid duplicating content") { result.toString() shouldBe expected.toString() } } } given("the query 11") { val query = """ query CheckTypeOfR2 { hero { __typename name } } """ val expected = mapOf("hero" to mapOf("__typename" to "Droid", "name" to "R2-D2")) `when`("run the query") { val result = GraphQL(StarWarsSchema.starWarsSchema).execute(query).data then("Allows us to verify that R2-D2 is a droid") { result.toString() shouldBe expected.toString() } } } } }
apache-2.0
6ecb16fb4d2e8e69d06a7e2ec4452d17
43.873684
485
0.348737
5.719589
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/base/BaseChapterHolder.kt
2
1738
package eu.kanade.tachiyomi.ui.manga.chapter.base import android.view.View import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.util.view.popupMenu open class BaseChapterHolder( view: View, private val adapter: BaseChaptersAdapter<*> ) : FlexibleViewHolder(view, adapter) { fun onDownloadClick(view: View, position: Int) { val item = adapter.getItem(position) as? BaseChapterItem<*, *> ?: return when (item.status) { Download.State.NOT_DOWNLOADED, Download.State.ERROR -> { adapter.clickListener.downloadChapter(position) } else -> { view.popupMenu( R.menu.chapter_download, initMenu = { // Download.State.DOWNLOADED findItem(R.id.delete_download).isVisible = item.status == Download.State.DOWNLOADED // Download.State.DOWNLOADING, Download.State.QUEUE findItem(R.id.cancel_download).isVisible = item.status != Download.State.DOWNLOADED // Download.State.QUEUE findItem(R.id.start_download).isVisible = item.status == Download.State.QUEUE }, onMenuItemClick = { if (itemId == R.id.start_download) { adapter.clickListener.startDownloadNow(position) } else { adapter.clickListener.deleteChapter(position) } } ) } } } }
apache-2.0
16d2bd0c35f0c73bfda029033cbc0ce2
38.5
107
0.551784
5.052326
false
false
false
false
emoji-gen/Emoji-Android
app/src/main/java/moe/pine/emoji/fragment/setting/AddTeamFragment.kt
1
2188
package moe.pine.emoji.fragment.setting import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_setting_add_team.* import moe.pine.emoji.R import moe.pine.emoji.components.common.SoftInputManagerComponent import moe.pine.emoji.components.setting.InputTextWatcherComponent import moe.pine.emoji.components.setting.SettingSaverComponent import moe.pine.emoji.components.setting.TeamInputClearComponent /** * Fragment for add slack team * Created by pine on May 14, 2017. */ class AddTeamFragment : Fragment() { companion object { private val IS_FOCUS_KEY = "isFocus" fun newInstance(isFocus: Boolean = false): AddTeamFragment { val fragment = AddTeamFragment() val arguments = Bundle() arguments.putBoolean(IS_FOCUS_KEY, isFocus) fragment.arguments = arguments return fragment } } private val inputTextWatcher by lazy { InputTextWatcherComponent(this) } private val softInputManager by lazy { SoftInputManagerComponent(this.fragment_setting_add_team) } private val settingSaver by lazy { SettingSaverComponent(this) } private val inputClear by lazy { TeamInputClearComponent(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_setting_add_team, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) this.inputTextWatcher.onActivityCreated(savedInstanceState) this.softInputManager.onActivityCreated(savedInstanceState) this.settingSaver.onActivityCreated(savedInstanceState) this.inputClear.onActivityCreated(savedInstanceState) val isFocus = this.arguments!!.getBoolean(IS_FOCUS_KEY, false) if (isFocus) this.edit_text_setting_team.requestFocus() } override fun onDestroyView() { this.inputClear.onDestroyView() super.onDestroyView() } }
mit
a57d87c55832395245b718a3c292fc29
37.403509
116
0.743144
4.587002
false
false
false
false
cascheberg/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/database/MessageSendLogDatabase.kt
1
11141
package org.thoughtcrime.securesms.database import android.content.ContentValues import android.content.Context import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper import org.thoughtcrime.securesms.database.model.MessageLogEntry import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.CursorUtil import org.thoughtcrime.securesms.util.FeatureFlags import org.thoughtcrime.securesms.util.SqlUtil import org.whispersystems.signalservice.api.crypto.ContentHint import org.whispersystems.signalservice.api.messages.SendMessageResult import org.whispersystems.signalservice.internal.push.SignalServiceProtos import java.util.UUID /** * Stores a 24-hr buffer of all outgoing messages. Used for the retry logic required for sender key. * * General note: This class is actually two tables -- one to store the entry, and another to store all the devices that were sent it. * * The general lifecycle of entries in the store goes something like this: * - Upon sending a message, throw an entry in the 'message table' and throw an entry for each recipient you sent it to in the 'recipient table' * - Whenever you get a delivery receipt, delete the entries in the 'recipient table' * - Whenever there's no more records in the 'recipient table' for a given message, delete the entry in the 'message table' * - Whenever you delete a message, delete the entry in the 'message table' * - Whenever you read an entry from the table, first trim off all the entries that are too old * * Because of all of this, you can be sure that if an entry is in this store, it's safe to resend to someone upon request * * Worth noting that we use triggers + foreign keys to make sure entries in this table are properly cleaned up. Triggers for when you delete a message, and * a cascading delete foreign key between these two tables. */ class MessageSendLogDatabase constructor(context: Context?, databaseHelper: SQLCipherOpenHelper?) : Database(context, databaseHelper) { companion object { @JvmField val CREATE_TABLE: Array<String> = arrayOf(MessageTable.CREATE_TABLE, RecipientTable.CREATE_TABLE) @JvmField val CREATE_INDEXES: Array<String> = MessageTable.CREATE_INDEXES + RecipientTable.CREATE_INDEXES @JvmField val CREATE_TRIGGERS: Array<String> = MessageTable.CREATE_TRIGGERS } private object MessageTable { const val TABLE_NAME = "message_send_log" const val ID = "_id" const val DATE_SENT = "date_sent" const val CONTENT = "content" const val RELATED_MESSAGE_ID = "related_message_id" const val IS_RELATED_MESSAGE_MMS = "is_related_message_mms" const val CONTENT_HINT = "content_hint" const val CREATE_TABLE = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY, $DATE_SENT INTEGER NOT NULL, $CONTENT BLOB NOT NULL, $RELATED_MESSAGE_ID INTEGER DEFAULT -1, $IS_RELATED_MESSAGE_MMS INTEGER DEFAULT 0, $CONTENT_HINT INTEGER NOT NULL ) """ @JvmField val CREATE_INDEXES = arrayOf( "CREATE INDEX message_log_date_sent_index ON $TABLE_NAME ($DATE_SENT)", "CREATE INDEX message_log_related_message_index ON $TABLE_NAME ($RELATED_MESSAGE_ID, $IS_RELATED_MESSAGE_MMS)" ) @JvmField val CREATE_TRIGGERS = arrayOf( """ CREATE TRIGGER msl_sms_delete AFTER DELETE ON ${SmsDatabase.TABLE_NAME} BEGIN DELETE FROM $TABLE_NAME WHERE $RELATED_MESSAGE_ID = old.${SmsDatabase.ID} AND $IS_RELATED_MESSAGE_MMS = 0; END """, """ CREATE TRIGGER msl_mms_delete AFTER DELETE ON ${MmsDatabase.TABLE_NAME} BEGIN DELETE FROM $TABLE_NAME WHERE $RELATED_MESSAGE_ID = old.${MmsDatabase.ID} AND $IS_RELATED_MESSAGE_MMS = 1; END """ ) } private object RecipientTable { const val TABLE_NAME = "message_send_log_recipients" const val ID = "_id" const val MESSAGE_LOG_ID = "message_send_log_id" const val RECIPIENT_ID = "recipient_id" const val DEVICE = "device" const val CREATE_TABLE = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY, $MESSAGE_LOG_ID INTEGER NOT NULL REFERENCES ${MessageTable.TABLE_NAME} (${MessageTable.ID}) ON DELETE CASCADE, $RECIPIENT_ID INTEGER NOT NULL, $DEVICE INTEGER NOT NULL ) """ val CREATE_INDEXES = arrayOf( "CREATE INDEX message_send_log_recipients_recipient_index ON $TABLE_NAME ($RECIPIENT_ID, $DEVICE)" ) } fun insertIfPossible(recipientId: RecipientId, sentTimestamp: Long, sendMessageResult: SendMessageResult, contentHint: ContentHint, relatedMessageId: Long, isRelatedMessageMms: Boolean) { if (!FeatureFlags.senderKey()) return if (sendMessageResult.isSuccess && sendMessageResult.success.content.isPresent) { val recipientDevice = listOf(RecipientDevice(recipientId, sendMessageResult.success.devices)) insert(recipientDevice, sentTimestamp, sendMessageResult.success.content.get(), contentHint, relatedMessageId, isRelatedMessageMms) } } fun insertIfPossible(sentTimestamp: Long, possibleRecipients: List<Recipient>, results: List<SendMessageResult>, contentHint: ContentHint, relatedMessageId: Long, isRelatedMessageMms: Boolean) { if (!FeatureFlags.senderKey()) return val recipientsByUuid: Map<UUID, Recipient> = possibleRecipients.filter(Recipient::hasUuid).associateBy(Recipient::requireUuid, { it }) val recipientsByE164: Map<String, Recipient> = possibleRecipients.filter(Recipient::hasE164).associateBy(Recipient::requireE164, { it }) val recipientDevices: List<RecipientDevice> = results .filter { it.isSuccess && it.success.content.isPresent } .map { result -> val recipient: Recipient = if (result.address.uuid.isPresent) { recipientsByUuid[result.address.uuid.get()]!! } else { recipientsByE164[result.address.number.get()]!! } RecipientDevice(recipient.id, result.success.devices) } val content: SignalServiceProtos.Content = results.first { it.isSuccess && it.success.content.isPresent }.success.content.get() insert(recipientDevices, sentTimestamp, content, contentHint, relatedMessageId, isRelatedMessageMms) } private fun insert(recipients: List<RecipientDevice>, dateSent: Long, content: SignalServiceProtos.Content, contentHint: ContentHint, relatedMessageId: Long, isRelatedMessageMms: Boolean) { val db = databaseHelper.writableDatabase db.beginTransaction() try { val logValues = ContentValues().apply { put(MessageTable.DATE_SENT, dateSent) put(MessageTable.CONTENT, content.toByteArray()) put(MessageTable.CONTENT_HINT, contentHint.type) put(MessageTable.RELATED_MESSAGE_ID, relatedMessageId) put(MessageTable.IS_RELATED_MESSAGE_MMS, if (isRelatedMessageMms) 1 else 0) } val messageLogId: Long = db.insert(MessageTable.TABLE_NAME, null, logValues) recipients.forEach { recipientDevice -> recipientDevice.devices.forEach { device -> val recipientValues = ContentValues() recipientValues.put(RecipientTable.MESSAGE_LOG_ID, messageLogId) recipientValues.put(RecipientTable.RECIPIENT_ID, recipientDevice.recipientId.serialize()) recipientValues.put(RecipientTable.DEVICE, device) db.insert(RecipientTable.TABLE_NAME, null, recipientValues) } } db.setTransactionSuccessful() } finally { db.endTransaction() } } fun getLogEntry(recipientId: RecipientId, device: Int, dateSent: Long): MessageLogEntry? { if (!FeatureFlags.senderKey()) return null trimOldMessages(System.currentTimeMillis(), FeatureFlags.retryRespondMaxAge()) val db = databaseHelper.readableDatabase val table = "${MessageTable.TABLE_NAME} LEFT JOIN ${RecipientTable.TABLE_NAME} ON ${MessageTable.TABLE_NAME}.${MessageTable.ID} = ${RecipientTable.TABLE_NAME}.${RecipientTable.MESSAGE_LOG_ID}" val query = "${MessageTable.DATE_SENT} = ? AND ${RecipientTable.RECIPIENT_ID} = ? AND ${RecipientTable.DEVICE} = ?" val args = SqlUtil.buildArgs(dateSent, recipientId, device) db.query(table, null, query, args, null, null, null).use { cursor -> if (cursor.moveToFirst()) { return MessageLogEntry( recipientId = RecipientId.from(CursorUtil.requireLong(cursor, RecipientTable.RECIPIENT_ID)), dateSent = CursorUtil.requireLong(cursor, MessageTable.DATE_SENT), content = SignalServiceProtos.Content.parseFrom(CursorUtil.requireBlob(cursor, MessageTable.CONTENT)), contentHint = ContentHint.fromType(CursorUtil.requireInt(cursor, MessageTable.CONTENT_HINT)), relatedMessageId = CursorUtil.requireLong(cursor, MessageTable.RELATED_MESSAGE_ID), isRelatedMessageMms = CursorUtil.requireBoolean(cursor, MessageTable.IS_RELATED_MESSAGE_MMS) ) } } return null } fun deleteAllRelatedToMessage(messageId: Long, mms: Boolean) { if (!FeatureFlags.senderKey()) return val db = databaseHelper.writableDatabase val query = "${MessageTable.RELATED_MESSAGE_ID} = ? AND ${MessageTable.IS_RELATED_MESSAGE_MMS} = ?" val args = SqlUtil.buildArgs(messageId, if (mms) 1 else 0) db.delete(MessageTable.TABLE_NAME, query, args) } fun deleteEntryForRecipient(dateSent: Long, recipientId: RecipientId, device: Int) { if (!FeatureFlags.senderKey()) return deleteEntriesForRecipient(listOf(dateSent), recipientId, device) } fun deleteEntriesForRecipient(dateSent: List<Long>, recipientId: RecipientId, device: Int) { if (!FeatureFlags.senderKey()) return val db = databaseHelper.writableDatabase db.beginTransaction() try { val query = """ ${RecipientTable.RECIPIENT_ID} = ? AND ${RecipientTable.DEVICE} = ? AND ${RecipientTable.MESSAGE_LOG_ID} IN ( SELECT ${MessageTable.ID} FROM ${MessageTable.TABLE_NAME} WHERE ${MessageTable.DATE_SENT} IN (${dateSent.joinToString(",")}) )""" val args = SqlUtil.buildArgs(recipientId, device) db.delete(RecipientTable.TABLE_NAME, query, args) val cleanQuery = "${MessageTable.ID} NOT IN (SELECT ${RecipientTable.MESSAGE_LOG_ID} FROM ${RecipientTable.TABLE_NAME})" db.delete(MessageTable.TABLE_NAME, cleanQuery, null) db.setTransactionSuccessful() } finally { db.endTransaction() } } fun deleteAll() { if (!FeatureFlags.senderKey()) return databaseHelper.writableDatabase.delete(MessageTable.TABLE_NAME, null, null) } fun trimOldMessages(currentTime: Long, maxAge: Long) { if (!FeatureFlags.senderKey()) return val db = databaseHelper.writableDatabase val query = "${MessageTable.DATE_SENT} < ?" val args = SqlUtil.buildArgs(currentTime - maxAge) db.delete(MessageTable.TABLE_NAME, query, args) } private data class RecipientDevice(val recipientId: RecipientId, val devices: List<Int>) }
gpl-3.0
264e48e6875204fc10727b2b047eecc8
41.041509
196
0.712952
4.221675
false
false
false
false
retomerz/intellij-community
plugins/settings-repository/src/RepositoryService.kt
3
2806
/* * 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.settingsRepository import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.util.exists import com.intellij.util.io.URLUtil import com.intellij.util.isDirectory import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.createBareRepository import java.io.IOException import java.nio.file.Path import java.nio.file.Paths interface RepositoryService { fun checkUrl(uriString: String, suggestToCreate: Boolean, project: Project? = null): Boolean { val uri = URIish(uriString) val isFile: Boolean if (uri.scheme == URLUtil.FILE_PROTOCOL) { isFile = true } else { isFile = uri.scheme == null && uri.host == null } if (isFile && !checkFileRepo(uriString, project)) { return false } return true } private fun checkFileRepo(url: String, project: Project?): Boolean { val suffix = "/${Constants.DOT_GIT}" val file = Paths.get(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) if (file.exists()) { if (!file.isDirectory()) { //noinspection DialogTitleCapitalization Messages.showErrorDialog(project, "Specified path is not a directory", "Specified Path is Invalid") return false } else if (isValidRepository(file)) { return true } } else if (!file.isAbsolute) { Messages.showErrorDialog(project, icsMessage("specify.absolute.path.dialog.message"), "") return false } if (MessageDialogBuilder .yesNo(icsMessage("init.dialog.title"), icsMessage("init.dialog.message", file)) .yesText("Create") .project(project) .`is`()) { try { createBareRepository(file) return true } catch (e: IOException) { Messages.showErrorDialog(project, icsMessage("init.failed.message", e.message), icsMessage("init.failed.title")) return false } } else { return false } } // must be protected, kotlin bug fun isValidRepository(file: Path): Boolean }
apache-2.0
e614445057dea851bb7c5e9290709368
31.264368
120
0.691019
4.19432
false
false
false
false
MarkusAmshove/Kluent
jvm/src/test/kotlin/org/amshove/kluent/tests/equivalency/ShouldBeEquivalentTo.kt
1
43441
package org.amshove.kluent.tests.equivalency import org.amshove.kluent.internal.ComparisonFailedException import org.amshove.kluent.internal.assertFailsWith import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeEquivalentTo import org.amshove.kluent.shouldNotBeEquivalentTo import org.amshove.kluent.shouldStartWith import org.junit.Test import java.time.LocalDate @ExperimentalStdlibApi class ShouldBeEquivalentTo { @Test fun failShouldBeEquivalentToAsPropertiesAreDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } val team2 = Team("team1").apply { persons = listOf( ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldBeEquivalentTo(team2) } } @Test fun passShouldNotBeEquivalentToAsPropertiesAreDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } // assert team1.shouldNotBeEquivalentTo(team2) { it.compareByProperties() } } @Test fun failShouldBeEquivalentToAsPropertiesAreDifferentForIterables() { // arrange val teams1 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) }, Team("team3").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } ) val teams2 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "") ) }, Team("team3").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } ) // assert assertFailsWith(ComparisonFailedException::class) { teams1.shouldBeEquivalentTo(teams2) { it.compareByProperties() } } } @Test fun passShouldNotBeEquivalentToAsPropertiesAreDifferentForIterables() { // arrange val teams1 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } ) val teams2 = listOf( Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "") ) }, Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } ) // assert teams1.shouldNotBeEquivalentTo(teams2) } @Test fun passShouldBeEquivalentToWithStrictOrderingAsPropertiesAreEqualForIterables() { // arrange val teams1 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "") ) }, Team("team3").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } ) val teams2 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "") ) }, Team("team3").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } ) // assert teams1.shouldBeEquivalentTo(teams2) { it.withStrictOrdering() } } @Test fun passShouldNotBeEquivalentToWithStrictOrderingEvenIfPropertiesAreEqualForIterables() { // arrange val teams1 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "") ) }, Team("team3").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } ) val teams2 = listOf( Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) }, Team("team3").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) }, Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "") ) } ) // assert teams1.shouldNotBeEquivalentTo(teams2) { it.withStrictOrdering() } } @Test fun passShouldBeEquivalentToAsPropertiesAreEqualComparingByProperties() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } // assert team1.shouldBeEquivalentTo(team2) { it.compareByProperties() } } @Test fun failShouldNotBeEquivalentToAsPropertiesAreEqualComparingByProperties() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldNotBeEquivalentTo(team2) { it.compareByProperties() } } } @Test fun failShouldBeEquivalentToAsIncludedPropertyPersonsIsDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK") } ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldBeEquivalentTo(team2) { it.including(Team::persons) } } } @Test fun passShouldNotBeEquivalentToAsIncludedPropertyPersonsIsDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK") } ) } // assert team1.shouldNotBeEquivalentTo(team2) { it.including(Team::persons) } } @Test fun passShouldBeEquivalentToEvenIfExcludedPropertyPersonsIsDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK") } ) } // assert team1.shouldBeEquivalentTo(team2) { it.excluding(Team::persons) } } @Test fun failShouldNotBeEquivalentToEvenIfExcludedPropertyPersonsIsDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK") } ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldNotBeEquivalentTo(team2) { it.excluding(Team::persons) } } } @Test fun failShouldBeEquivalentToEvenIfExcludedPropertyPersonsIsEqual() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK") } ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldBeEquivalentTo(team2) { it.excluding(Team::persons) } } } @Test fun passShouldNotBeEquivalentToEvenIfExcludedPropertyPersonsIsEqual() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK") } ) } // assert team1.shouldNotBeEquivalentTo(team2) { it.excluding(Team::persons) } } @Test fun failShouldBeEquivalentToAsIncludedPropertyNameIsDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Watson"), Person("Marco", "Polo") ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldBeEquivalentTo(team2) { it.including(Team::name) } } } @Test fun passShouldNotBeEquivalentToAsIncludedPropertyNameIsDifferent() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Watson"), Person("Marco", "Polo") ) } // assert team1.shouldNotBeEquivalentTo(team2) { it.including(Team::name) } } @Test fun passShouldBeEquivalentToAsIncludedPropertiesAreEqual() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } // assert team1.shouldBeEquivalentTo(team2) { it.including(Team::persons) } } @Test fun failShouldNotBeEquivalentToAsIncludedPropertiesAreEqual() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) address = Address("Graham Street", "36", "London", "N1 8GJ", "UK").apply { address2 = "Islington" } } ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldNotBeEquivalentTo(team2) { it.including(Team::persons) } } } @Test fun passShouldBeEquivalentToEvenIfPropertiesAreDifferentAsExcludingNestedObjects() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } // assert team1.shouldBeEquivalentTo(team2) { it.excludingNestedObjects() } } @Test fun failShouldNotBeEquivalentToEvenIfPropertiesAreDifferentAsExcludingNestedObjects() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } val team2 = Team("team1").apply { persons = listOf( Person("John", "Johnson"), Person("Marc", "Marcson") ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldNotBeEquivalentTo(team2) { it.excludingNestedObjects() } } } @Test fun failShouldBeEquivalentToEvenIfPropertiesAreEqualAsExcludingNestedObjects() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } // assert assertFailsWith(ComparisonFailedException::class) { team1.shouldBeEquivalentTo(team2) { it.excludingNestedObjects() } } } @Test fun passShouldNotBeEquivalentToEvenIfPropertiesAreEqualAsExcludingNestedObjects() { // arrange val team1 = Team("team1").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } val team2 = Team("team2").apply { persons = listOf( Person("John", "Johnson").apply { address = Address("Mainzerlandstrasse", "200", "Frankfurt am Main", "60327", "Germany") }, Person("Marc", "Marcson").apply { birthDate = LocalDate.of(2020, 2, 1) } ) } // assert team1.shouldNotBeEquivalentTo(team2) { it.excludingNestedObjects() } } @Test fun passShouldBeEquivalentToEvenIfPropertiesAreDifferentAsNotAllowingInfiniteRecursion() { // arrange val a1 = A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }) } } val a2 = A("name1").apply { b = B("name11").apply { c = C(D("name311").apply { name2 = "name3111" }) } } // assert a1.shouldBeEquivalentTo(a2) { it.maxLevelOfRecursion = 3 return@shouldBeEquivalentTo it } } @Test fun failShouldNotBeEquivalentToEvenIfPropertiesAreDifferentAsNotAllowingInfiniteRecursion() { // arrange val a1 = A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }) } } val a2 = A("name1").apply { b = B("name11").apply { c = C(D("name311").apply { name2 = "name3111" }) } } // assert assertFailsWith(ComparisonFailedException::class) { a1.shouldNotBeEquivalentTo(a2) { it.maxLevelOfRecursion = 3 return@shouldNotBeEquivalentTo it } } } @Test fun passShouldNotBeEquivalentToAsPropertiesAreDifferentAndAllowingInfiniteRecursion() { // arrange val a1 = listOf( A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }).apply { name = "name1111" } d = D("name111").apply { Elist = mutableListOf( E().apply { Flist = listOf( F(1), F(2) ) }, E().apply { Flist = listOf( F(3), F(4) ) } ) name2 = "name1111" } } e = "abc" }, A("name2").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name2111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" } } e = "abc" } ) val a2 = listOf( A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" } } e = "abc" }, A("name2").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name3111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" } } e = "abc" } ) // assert a1.shouldNotBeEquivalentTo(a2) { // set the default maxLevelOfRecursion = 2 but allow infinite recursion it.maxLevelOfRecursion = 2 it.allowingInfiniteRecursion() return@shouldNotBeEquivalentTo it } } @Test fun failShouldBeEquivalentToAsPropertiesAreDifferentAndAllowingInfiniteRecursion() { // arrange val a1 = listOf( A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }).apply { name = "name1111" } d = D("name111").apply { Elist = mutableListOf( E().apply { Flist = listOf( F(1), F(2) ) }, E().apply { Flist = listOf( F(3), F(4) ) } ) name2 = "name1111" } } e = "abc" }, A("name2").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name2111" }).apply { name = "name1111" } d = D("name111").apply { Elist = mutableListOf( E().apply { Flist = listOf( F(5), F(6) ) }, E().apply { Flist = listOf( F(7) ) } ) name2 = "name1111" } } e = "abc" } ) val a2 = listOf( A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }).apply { name = "name1111" } d = D("name111").apply { Elist = mutableListOf( E().apply { Flist = listOf( F(1), F(2) ) }, E().apply { Flist = listOf( F(3), F(4) ) } ) name2 = "name1111" } } e = "abc" }, A("name2").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name3111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" Elist = mutableListOf( E().apply { Flist = listOf( F(5), F(6) ) }, E().apply { Flist = listOf( F(7) ) } ) } } e = "abc" } ) // assert try { a1.shouldBeEquivalentTo(a2) { // set the default maxLevelOfRecursion = 2 but allow infinite recursion it.maxLevelOfRecursion = 2 it.allowingInfiniteRecursion() return@shouldBeEquivalentTo it } } catch (e: ComparisonFailedException) { e.message!!.shouldStartWith("Are not equivalent:") e.actual!!.replace("\\s+|\\t|\\n".toRegex(), " ").trim().shouldBeEqualTo( """ A (e = abc, name = name1) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name1111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist ˪----E[0] ˪-----Flist ˪------F[0] (id = 1, name = ) ˪------F[1] (id = 2, name = ) ˪----E[1] ˪-----Flist ˪------F[0] (id = 3, name = ) ˪------F[1] (id = 4, name = ) A (e = abc, name = name2) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name2111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist ˪----E[0] ˪-----Flist ˪------F[0] (id = 5, name = ) ˪------F[1] (id = 6, name = ) ˪----E[1] ˪-----Flist ˪------F[0] (id = 7, name = ) """.replace("\\s+|\\t|\\n".toRegex(), " ").trim() ) e.expected!!.replace("\\s+|\\t|\\n".toRegex(), " ").trim().shouldBeEqualTo( """ A (e = abc, name = name1) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name1111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist ˪----E[0] ˪-----Flist ˪------F[0] (id = 1, name = ) ˪------F[1] (id = 2, name = ) ˪----E[1] ˪-----Flist ˪------F[0] (id = 3, name = ) ˪------F[1] (id = 4, name = ) A (e = abc, name = name2) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name3111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist ˪----E[0] ˪-----Flist ˪------F[0] (id = 5, name = ) ˪------F[1] (id = 6, name = ) ˪----E[1] ˪-----Flist ˪------F[0] (id = 7, name = ) """.replace("\\s+|\\t|\\n".toRegex(), " ").trim() ) } } @Test fun failShouldBeEquivalentToAsAmountOfEntitiesIsDifferent() { // arrange val a1 = listOf( A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" } } e = "abc" }, A("name2").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name2111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" } } e = "abc" } ) val a2 = listOf( A("name1").apply { b = B("name11").apply { c = C(D("name111").apply { name2 = "name1111" }).apply { name = "name1111" } d = D("name111").apply { name2 = "name1111" } } e = "abc" } ) // assert try { a1.shouldBeEquivalentTo(a2) { // set the default maxLevelOfRecursion = 2 but allow infinite recursion it.maxLevelOfRecursion = 2 it.allowingInfiniteRecursion() return@shouldBeEquivalentTo it } } catch (e: ComparisonFailedException) { e.message!!.shouldStartWith("Are not equivalent:") e.actual!!.replace("\\s+|\\t|\\n".toRegex(), " ").trim().shouldBeEqualTo( """ A (e = abc, name = name1) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name1111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist A (e = abc, name = name2) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name2111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist """.replace("\\s+|\\t|\\n".toRegex(), " ").trim() ) e.expected!!.replace("\\s+|\\t|\\n".toRegex(), " ").trim().shouldBeEqualTo( """ A (e = abc, name = name1) ˪-B (name = name11) ˪--C (name = name1111) ˪---D (name = name111, name2 = name1111) ˪----Elist ˪--D (name = name111, name2 = name1111) ˪---Elist """.replace("\\s+|\\t|\\n".toRegex(), " ").trim() ) } } @Test fun shouldFailAsAmountOfPropertiesIsDifferent() { // arrange val a1 = E().apply { Flist = listOf( F(1).apply { name = "name1" }, F(2).apply { name = "name2" } ) } val a2 = E().apply { Flist = listOf( F(1).apply { name = "name1" } ) } // assert try { a1.shouldBeEquivalentTo(a2) } catch (e: ComparisonFailedException) { e.message!!.shouldStartWith("Are not equivalent:") e.actual!!.replace("\\s+|\\t|\\n".toRegex(), " ").trim().shouldBeEqualTo( """ E ˪-Flist ˪--F[0] (id = 1, name = name1) ˪--F[1] (id = 2, name = name2) """.replace("\\s+|\\t|\\n".toRegex(), " ").trim() ) e.expected!!.replace("\\s+|\\t|\\n".toRegex(), " ").trim().shouldBeEqualTo( """ E ˪-Flist ˪--F[0] (id = 1, name = name1) """.replace("\\s+|\\t|\\n".toRegex(), " ").trim() ) } } internal class Team(val name: String) { var persons: List<Person> = listOf() } @Suppress("unused") internal class Person(val firstName: String, val lastName: String) { var birthDate: LocalDate? = null var address: Address? = null } @Suppress("unused") internal class Address( val street: String, val house: String, val city: String, val zipCode: String, val country: String ) { var address2: String? = null } @Suppress("unused") internal class A(val name: String) { var b: B? = null var e: String? = null } @Suppress("unused") internal class B(val name: String) { var c: C? = null var d: D? = null } @Suppress("unused") internal class C(val d: D) { var name: String? = null } @Suppress("unused") internal class D(val name: String) { var Elist: MutableList<E> = mutableListOf() var name2: String? = null } internal class E() { var Flist: List<F> = listOf() } internal class F(var id: Int) { var name: String = "" } }
mit
881f214faa6bc9b31492869da12ecf53
34.198864
111
0.412877
4.523209
false
false
false
false
arnab/adventofcode
src/main/kotlin/aoc2016/day8/BoardGamer.kt
1
2848
package aoc2016.day8 data class Cell(val x: Int, val y: Int, var on: Boolean = false) { fun draw() = if (on) "#" else "-" } data class Board(val size: Pair<Int, Int>) { val cells: List<List<Cell>> by lazy { IntRange(0, size.second - 1).map { x-> IntRange(0, size.first - 1).map { y-> Cell(x, y) } } } // "rect 3x3" private val rectInstrMatcher = Regex("""rect (\d+)x(\d+)""") // "rotate row y=0 by 4" private val rotateRowInstrMatcher = Regex("""rotate row y=(\d+) by (\d+)""") // "rotate column x=1 by 1" private val rotateColInstrMatcher = Regex("""rotate column x=(\d+) by (\d+)""") fun apply(instructionText: String): Board { val rectMatch = rectInstrMatcher.matchEntire(instructionText) if (rectMatch != null) { val (a, b) = rectMatch.destructured applyRectInstruction(a.toInt(), b.toInt()) } val rotateRowMatch = rotateRowInstrMatcher.matchEntire(instructionText) if (rotateRowMatch != null) { val (row, shift) = rotateRowMatch.destructured applyRotateRowInstruction(row.toInt(), shift.toInt()) } val rotateColMatch = rotateColInstrMatcher.matchEntire(instructionText) if (rotateColMatch != null) { val (col, shift) = rotateColMatch.destructured applyRotateColInstruction(col.toInt(), shift.toInt()) } return this } private fun applyRectInstruction(a: Int, b: Int) { IntRange(0, b - 1).forEach { x -> IntRange(0, a - 1).forEach { y -> cells[x][y].on = true } } } private fun applyRotateRowInstruction(row: Int, shift: Int) { val size = cells[row].size val rowOriginal = cells[row].map { it.copy() } cells[row].forEachIndexed { i, cell -> val indexBeingShifted = (size - shift + i) % size cell.on = rowOriginal[indexBeingShifted].on } } private fun applyRotateColInstruction(col: Int, shift: Int) { val size = cells.size val columnOriginal = cells.map { row -> row[col] }.map { it.copy() } cells.forEachIndexed { i, row -> val indexBeingShifted = (size - shift + i) % size cells[i][col].on = columnOriginal[indexBeingShifted].on } } fun draw() { cells.forEach { row -> println() println(row.map(Cell::draw).joinToString(" ")) } } } object BoardGamer { fun run(X: Int, Y: Int, instructions: List<String>): Board { var board = Board(Pair(X, Y)) instructions.forEach { println("After instruction \"$it\":") board = board.apply(it) board.draw() } return board } }
mit
71037a53b5fd2146c8659601c042a343
29.956522
83
0.554073
3.896033
false
false
false
false
ssseasonnn/RxDownload
rxdownload4-recorder/src/main/java/zlc/season/rxdownload4/recorder/RxDownloadRecorder.kt
1
4396
package zlc.season.rxdownload4.recorder import android.annotation.SuppressLint import io.reactivex.Flowable.fromIterable import io.reactivex.Maybe import io.reactivex.android.schedulers.AndroidSchedulers.mainThread import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers.io import zlc.season.claritypotion.ClarityPotion.Companion.clarityPotion import zlc.season.rxdownload4.manager.* import zlc.season.rxdownload4.notification.SimpleNotificationCreator import zlc.season.rxdownload4.task.Task @SuppressLint("CheckResult") object RxDownloadRecorder { val taskDataBase by lazy { TaskDataBase.getInstance(clarityPotion) } /** * Update task extraInfo */ fun update(task: Task, newExtraInfo: String): Maybe<TaskEntity> { return Maybe.just(task) .subscribeOn(io()) .flatMap { taskDataBase.taskDao().update(task.hashCode(), newExtraInfo) } .flatMap { getTask(task) } } fun getTask(url: String): Maybe<TaskEntity> { return getTask(Task(url)) } fun getTask(task: Task): Maybe<TaskEntity> { return taskDataBase.taskDao().get(task.hashCode()) .subscribeOn(io()) .doOnSuccess { it.status.progress = it.progress } } fun getTaskList(vararg url: String): Maybe<List<TaskEntity>> { val tasks = mutableListOf<Task>() url.mapTo(tasks) { Task(it) } return getTaskList(*tasks.toTypedArray()) } fun getTaskList(vararg task: Task): Maybe<List<TaskEntity>> { val ids = mutableListOf<Int>() task.mapTo(ids) { it.hashCode() } return taskDataBase.taskDao().get(*ids.toIntArray()) .subscribeOn(io()) .doOnSuccess { mapResult(it) } } fun getTaskList(page: Int, pageSize: Int): Maybe<List<TaskEntity>> { return taskDataBase.taskDao().page(page * pageSize, pageSize) .subscribeOn(io()) .doOnSuccess { mapResult(it) } } fun getTaskListWithStatus(page: Int, pageSize: Int, vararg status: Status): Maybe<List<TaskEntity>> { return taskDataBase.taskDao().pageWithStatus(page * pageSize, pageSize, *status) .subscribeOn(io()) .doOnSuccess { mapResult(it) } } fun getAllTask(): Maybe<List<TaskEntity>> { return taskDataBase.taskDao().getAll() .subscribeOn(io()) .doOnSuccess { mapResult(it) } } fun getAllTaskWithStatus(vararg status: Status): Maybe<List<TaskEntity>> { return taskDataBase.taskDao().getAllWithStatus(*status) .subscribeOn(io()) .doOnSuccess { mapResult(it) } } fun startAll(callback: () -> Unit = {}) { getAllTaskWithStatus(Paused(), Failed()) .flatMapPublisher { fromIterable(it) } .doOnNext { it.task.createManager().start() } .observeOn(mainThread()) .doOnComplete { callback() } .subscribeBy() } fun stopAll(callback: () -> Unit = {}) { getAllTaskWithStatus(Pending(), Started(), Downloading()) .flatMapPublisher { fromIterable(it) } .doOnNext { it.task.createManager().stop() } .observeOn(mainThread()) .doOnComplete { callback() } .subscribeBy() } fun deleteAll(callback: () -> Unit = {}) { getAllTask() .flatMapPublisher { fromIterable(it) } .doOnNext { it.task.createManager().delete() } .observeOn(mainThread()) .doOnComplete { callback() } .subscribeBy() } private fun mapResult(list: List<TaskEntity>) { list.forEach { it.status.progress = it.progress } } private fun Task.createManager(): TaskManager { return manager( notificationCreator = SimpleNotificationCreator(), recorder = RoomRecorder() ) } }
apache-2.0
6a7305cff3d13bc98c1549a376c8f473
31.330882
105
0.555505
4.852097
false
false
false
false
paplorinc/intellij-community
platform/lang-impl/src/com/intellij/bootRuntime/Controller.kt
1
3214
// 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.bootRuntime import com.intellij.bootRuntime.BundleState.* import com.intellij.bootRuntime.bundles.Local import com.intellij.bootRuntime.bundles.Runtime import com.intellij.bootRuntime.command.Cleanup import com.intellij.bootRuntime.command.RuntimeCommand import com.intellij.bootRuntime.command.CommandFactory import com.intellij.bootRuntime.command.CommandFactory.Type.* import com.intellij.bootRuntime.command.CommandFactory.produce import com.intellij.bootRuntime.command.UseDefault import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.project.Project import com.intellij.ui.components.JBOptionButton import com.intellij.util.ui.UIUtil import java.awt.GridBagConstraints import java.awt.Insets import javax.swing.JButton import javax.swing.SwingUtilities class Controller(val project: Project, val actionPanel:ActionPanel, val model: Model) { init { CommandFactory.initialize(project, this) } fun updateRuntime() { runtimeSelected(model.selectedBundle) } // the fun is supposed to be invoked on the combobox selection fun runtimeSelected(runtime:Runtime) { model.updateBundle(runtime) actionPanel.removeAll() val list = runtimeStateToActions(runtime, model.currentState()).toList() val job = JBOptionButton(list.firstOrNull(), list.subList(1, list.size).toTypedArray()) val constraint = GridBagConstraints() constraint.insets = Insets(0,0,0, 0) constraint.weightx = 1.0 constraint.anchor = GridBagConstraints.WEST val resetButton = JButton(UseDefault(project, this)) resetButton.toolTipText = "Reset boot Runtime to the default one" resetButton.isEnabled = BinTrayUtil.getJdkConfigFilePath().exists() actionPanel.add(resetButton, constraint) val cleanButton = JButton(Cleanup(project, this)) cleanButton.toolTipText = "Remove all installed runtimes" actionPanel.add(cleanButton, constraint ) constraint.anchor = GridBagConstraints.EAST actionPanel.rootPane?.defaultButton = job actionPanel.add(job, constraint) actionPanel.repaint() actionPanel.revalidate() } private fun runtimeStateToActions(runtime:Runtime, currentState: BundleState) : List<RuntimeCommand> { return when (currentState) { REMOTE -> listOf(produce(REMOTE_INSTALL, runtime), produce(DOWNLOAD, runtime)) DOWNLOADED -> listOf(produce(INSTALL, runtime), produce(DELETE, runtime)) EXTRACTED -> listOf(produce(INSTALL, runtime), produce(DELETE, runtime)) UNINSTALLED -> listOf(produce(INSTALL, runtime), produce(DELETE, runtime)) INSTALLED -> listOf(produce(UNINSTALL, runtime)) } } fun add(local: Local) { model.bundles.add(local) model.selectedBundle = local } fun restart() { SwingUtilities.invokeLater { SwingUtilities.getWindowAncestor(actionPanel).dispose() ApplicationManagerEx.getApplicationEx().restart() } } fun noRuntimeSelected() { UIUtil.uiTraverser(actionPanel).filter(JButton::class.java).forEach{b -> b.isEnabled = false} } }
apache-2.0
9bc97dfd240f97bd421d4a0aa81453df
35.11236
140
0.762601
4.325707
false
false
false
false
google/intellij-community
python/src/com/jetbrains/python/testing/doctest/PythonDocTestCommandLineState.kt
6
2790
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.testing.doctest import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.value.* import com.jetbrains.python.PythonHelper import com.jetbrains.python.testing.AbstractPythonLegacyTestRunConfiguration.TestType.* import com.jetbrains.python.testing.PythonTestCommandLineStateBase import java.util.function.Function class PythonDocTestCommandLineState(config: PythonDocTestRunConfiguration, env: ExecutionEnvironment) : PythonTestCommandLineStateBase<PythonDocTestRunConfiguration>(config, env) { override fun getRunner(): PythonHelper = PythonHelper.DOCSTRING /** * *To be deprecated. The part of the legacy implementation based on [GeneralCommandLine].* */ override fun getTestSpecs(): List<String> = listOf(configuration.buildTestSpec()) override fun getTestSpecs(request: TargetEnvironmentRequest): List<Function<TargetEnvironment, String>> = listOf(configuration.buildTestSpec(request)) companion object { /** * *To be deprecated. The part of the legacy implementation based on [GeneralCommandLine].* */ private fun PythonDocTestRunConfiguration.buildTestSpec(): String = when (testType) { TEST_SCRIPT -> scriptName TEST_CLASS -> "$scriptName::$className" TEST_METHOD -> "$scriptName::$className::$methodName" TEST_FOLDER -> if (usePattern() && !pattern.isEmpty()) "$folderName/;$pattern" else "$folderName/" TEST_FUNCTION -> "$scriptName::::$methodName" else -> throw IllegalArgumentException("Unknown test type: $testType") } private fun PythonDocTestRunConfiguration.buildTestSpec(request: TargetEnvironmentRequest): TargetEnvironmentFunction<String> = when (testType) { TEST_SCRIPT -> request.getTargetEnvironmentValueForLocalPath(scriptName) TEST_CLASS -> request.getTargetEnvironmentValueForLocalPath(scriptName) + "::$className" TEST_METHOD -> request.getTargetEnvironmentValueForLocalPath(scriptName) + "::$className::$methodName" TEST_FOLDER -> if (usePattern() && !pattern.isEmpty()) request.getTargetEnvironmentValueForLocalPath(folderName) + "/;$pattern" else request.getTargetEnvironmentValueForLocalPath(folderName) + "/" TEST_FUNCTION -> request.getTargetEnvironmentValueForLocalPath(scriptName) + "::::$methodName" else -> throw IllegalArgumentException("Unknown test type: $testType") } } }
apache-2.0
29150288a9b8d1d01941c262b97461a6
52.673077
140
0.757348
5.157116
false
true
false
false
aquatir/remember_java_api
code-sample-angular-kotlin/code-sample-jwt-token-example/kotlin-backend/src/main/kotlin/codesample/kotlin/jwtexample/security/controller/SecurityController.kt
1
4008
package codesample.kotlin.jwtexample.security.controller import codesample.kotlin.jwtexample.dto.request.LoginRequest import codesample.kotlin.jwtexample.dto.request.AccessTokenByRefreshTokenRequest import codesample.kotlin.jwtexample.dto.response.AccessAndRefreshTokenResponse import codesample.kotlin.jwtexample.security.service.JwtTokenService import codesample.kotlin.jwtexample.service.UserService import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController class SecurityController (private val authenticationManager: AuthenticationManager, private val jwtTokenService: JwtTokenService, private val userService: UserService){ /* This request will not be protected by security */ @PostMapping("/auth") fun auth(@RequestBody loginDto: LoginRequest) : AccessAndRefreshTokenResponse { val authentication = authenticationManager.authenticate( UsernamePasswordAuthenticationToken( loginDto.username, loginDto.password ) ) SecurityContextHolder.getContext().authentication = authentication val accessToken = jwtTokenService.generateAccessToken(authentication) val refreshToken = userService.getRefreshTokenByUsername(loginDto.username) return AccessAndRefreshTokenResponse(accessToken, refreshToken) } /** * Get new access token using refresh token. * * Generally speaking refresh token should be stored somewhere (in DB for example) so that you can invalidate this * token from backend if needed. * * There are however a lot of considerations which should be thought about, e.g. * 1) What will happen if refresh token get stolen? Do we check that consecutive refreshes come from the same IP? Do we check * if user's behavior was suspicious when issuing new access/refresh token? (e.g. if use has tried to call some service * 1000 times during 10 second of access token lifetime this may mean, that user is actually a bot) * 2) Do we trust access token for actions like "change username" (which will change refresh token) or should be * make this actions with n-factor authentication? * 3) Do we log important security information like failed logins / refreshes / username change actions, etc? * 4) etc. * * A little info about token refreshes: * * Image that we have good Alice and evil Bob. Bob has stolen Alice's refresh and access tokens. * * - If the next refresh is issued by Bob, Alice's refresh request will fail (so we raise an exception). * - If the next refresh is issued by Alice, Bob's refresh request will fail (so we raise an exception again). * * In both cases we can at least know that something fishy is going on. * * Also note that this exact schema would also work with a single token ('Same' in terms of security), but it may * be less convenient for automatic refreshes / session prolongation. */ @PostMapping("/auth/refresh") fun authRefresh(@RequestBody accessTokenRequest: AccessTokenByRefreshTokenRequest) : AccessAndRefreshTokenResponse { val username = userService.getUsernameAndCheckRefreshToken(accessTokenRequest.refreshToken) val newAccessToken = jwtTokenService.generateAccessToken(username = username) val newRefreshToken = userService.updateRefreshTokenAndReturnUpdated(username) return AccessAndRefreshTokenResponse( accessToken = newAccessToken, refreshToken = newRefreshToken ) } }
mit
cb24ee72d7ef656a9a816fa2aae51b20
51.064935
129
0.739521
5.287599
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/course_list/interactor/CourseListVisitedInteractor.kt
1
1736
package org.stepik.android.domain.course_list.interactor import io.reactivex.Flowable import io.reactivex.Single import ru.nobird.app.core.model.PagedList import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course.model.SourceTypeComposition import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.visited_courses.model.VisitedCourse import org.stepik.android.domain.visited_courses.repository.VisitedCoursesRepository import javax.inject.Inject class CourseListVisitedInteractor @Inject constructor( private val visitedCoursesRepository: VisitedCoursesRepository, private val courseListInteractor: CourseListInteractor ) { fun getVisitedCourseListItems(): Flowable<PagedList<CourseListItem.Data>> = visitedCoursesRepository .observeVisitedCourses() .flatMapSingle { visitedCourses -> getCourseListItems(visitedCourses.map(VisitedCourse::course)) } fun getCourseListItems( courseId: List<Long>, courseViewSource: CourseViewSource, sourceTypeComposition: SourceTypeComposition = SourceTypeComposition.REMOTE ): Single<PagedList<CourseListItem.Data>> = courseListInteractor.getCourseListItems(courseId, courseViewSource = courseViewSource, sourceTypeComposition = sourceTypeComposition) private fun getCourseListItems(courseIds: List<Long>): Single<PagedList<CourseListItem.Data>> = courseListInteractor .getCourseListItems( courseIds = courseIds, courseViewSource = CourseViewSource.Visited, sourceTypeComposition = SourceTypeComposition.CACHE ) }
apache-2.0
1ff4e4b760e3da31d1702431db24a5cc
42.425
141
0.762097
5.618123
false
false
false
false
allotria/intellij-community
java/java-impl/src/com/intellij/codeInsight/hints/JavaHintUtils.kt
4
13010
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeInsight.completion.CompletionMemory import com.intellij.codeInsight.completion.JavaMethodCallElement import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.util.registry.Registry import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil import com.intellij.psi.impl.source.tree.java.PsiEmptyExpressionImpl import com.intellij.psi.impl.source.tree.java.PsiMethodCallExpressionImpl import com.intellij.psi.impl.source.tree.java.PsiNewExpressionImpl import com.intellij.psi.util.TypeConversionUtil import com.intellij.util.IncorrectOperationException object JavaInlayHintsProvider { fun hints(callExpression: PsiCall): Set<InlayInfo> { if (JavaMethodCallElement.isCompletionMode(callExpression)) { val argumentList = callExpression.argumentList?:return emptySet() val text = argumentList.text if (text == null || !text.startsWith('(') || !text.endsWith(')')) return emptySet() val method = CompletionMemory.getChosenMethod(callExpression)?:return emptySet() val params = method.parameterList.parameters val arguments = argumentList.expressions val limit = JavaMethodCallElement.getCompletionHintsLimit() val trailingOffset = argumentList.textRange.endOffset - 1 val infos = ArrayList<InlayInfo>() var lastIndex = 0 (if (arguments.isEmpty()) listOf(trailingOffset) else arguments.map { inlayOffset(it) }).forEachIndexed { i, offset -> if (i < params.size) { params[i].name.let { infos.add(InlayInfo(it, offset, false, params.size == 1, false)) } lastIndex = i } } if (Registry.`is`("editor.completion.hints.virtual.comma")) { for (i in lastIndex + 1 until minOf(params.size, limit)) { params[i].name.let { infos.add(createHintWithComma(it, trailingOffset)) } lastIndex = i } } if (method.isVarArgs && (arguments.isEmpty() && params.size == 2 || !arguments.isEmpty() && arguments.size == params.size - 1)) { params[params.size - 1].name.let { infos.add(createHintWithComma(it, trailingOffset)) } } else if (Registry.`is`("editor.completion.hints.virtual.comma") && lastIndex < (params.size - 1) || limit == 1 && arguments.isEmpty() && params.size > 1 || limit <= arguments.size && arguments.size < params.size) { infos.add(InlayInfo("...more", trailingOffset, false, false, true)) } return infos.toSet() } if (!isParameterHintsEnabledForLanguage(callExpression.language)) return emptySet() val resolveResult = callExpression.resolveMethodGenerics() val hints = methodHints(callExpression, resolveResult) if (hints.isNotEmpty()) return hints return when (callExpression) { is PsiMethodCallExpressionImpl -> mergedHints(callExpression, callExpression.methodExpression.multiResolve(false)) is PsiNewExpressionImpl -> mergedHints(callExpression, callExpression.constructorFakeReference.multiResolve(false)) else -> emptySet() } } private fun createHintWithComma(parameterName: String, offset: Int): InlayInfo { return InlayInfo(",$parameterName", offset, false, false, true, HintWidthAdjustment(", ", parameterName, 1)) } private fun mergedHints(callExpression: PsiCallExpression, results: Array<out ResolveResult>): Set<InlayInfo> { val resultSet = results .filter { it.element != null } .map { methodHints(callExpression, it) } if (resultSet.isEmpty()) return emptySet() if (resultSet.size == 1) { return resultSet.first() } val chosenMethod: PsiMethod? = CompletionMemory.getChosenMethod(callExpression) if (chosenMethod != null) { val callInfo = callInfo(callExpression, chosenMethod) return hintSet(callInfo, PsiSubstitutor.EMPTY) } //we can show hints for same named parameters of overloaded methods, even if don't know exact method return resultSet.reduce { left, right -> left.intersect(right) } .map { InlayInfo(it.text, it.offset, isShowOnlyIfExistedBefore = true) } .toSet() } private fun methodHints(callExpression: PsiCall, resolveResult: ResolveResult): Set<InlayInfo> { val element = resolveResult.element val substitutor = (resolveResult as? JavaResolveResult)?.substitutor ?: PsiSubstitutor.EMPTY if (element is PsiMethod && isMethodToShow(element, callExpression)) { val info = callInfo(callExpression, element) if (isCallInfoToShow(info)) { return hintSet(info, substitutor) } } return emptySet() } private fun isCallInfoToShow(info: CallInfo): Boolean { val hintsProvider = JavaInlayParameterHintsProvider.getInstance() if (!hintsProvider.ignoreOneCharOneDigitHints.get() && info.allParamsSequential()) { return false } return true } private fun String.decomposeOrderedParams(): Pair<String, Int>? { val firstDigit = indexOfFirst { it.isDigit() } if (firstDigit < 0) return null val prefix = substring(0, firstDigit) try { val number = substring(firstDigit, length).toInt() return prefix to number } catch (e: NumberFormatException) { return null } } private fun CallInfo.allParamsSequential(): Boolean { val paramNames = regularArgs .map { it.parameter.name.decomposeOrderedParams() } .filterNotNull() if (paramNames.size > 1 && paramNames.size == regularArgs.size) { val prefixes = paramNames.map { it.first } if (prefixes.toSet().size != 1) return false val numbers = paramNames.map { it.second } val first = numbers.first() if (first == 0 || first == 1) { return numbers.areSequential() } } return false } private fun hintSet(info: CallInfo, substitutor: PsiSubstitutor): Set<InlayInfo> { val resultSet = mutableSetOf<InlayInfo>() val varargInlay = info.varargsInlay(substitutor) if (varargInlay != null) { resultSet.add(varargInlay) } if (isShowForParamsWithSameType()) { resultSet.addAll(info.sameTypeInlays()) } resultSet.addAll(info.unclearInlays(substitutor)) return resultSet } private fun isShowForParamsWithSameType() = JavaInlayParameterHintsProvider.getInstance().showForParamsWithSameType.get() private fun isMethodToShow(method: PsiMethod, callExpression: PsiCall): Boolean { val params = method.parameterList.parameters if (params.isEmpty()) return false if (params.size == 1) { val hintsProvider = JavaInlayParameterHintsProvider.getInstance() if (!hintsProvider.showForBuilderLikeMethods.get() && isBuilderLike(callExpression, method)) { return false } if (!hintsProvider.showIfMethodNameContainsParameterName.get() && isParamNameContainedInMethodName(params[0], method)) { return false } } return true } private fun isBuilderLike(expression: PsiCall, method: PsiMethod): Boolean { if (expression is PsiNewExpression) return false val returnType = TypeConversionUtil.erasure(method.returnType) ?: return false val calledMethodClassFqn = method.containingClass?.qualifiedName ?: return false return returnType.equalsToText(calledMethodClassFqn) } private fun isParamNameContainedInMethodName(parameter: PsiParameter, method: PsiMethod): Boolean { val parameterName = parameter.name if (parameterName.length > 1) { return method.name.contains(parameterName, ignoreCase = true) } return false } private fun callInfo(callExpression: PsiCall, method: PsiMethod): CallInfo { val params = method.parameterList.parameters val hasVarArg = params.lastOrNull()?.isVarArgs ?: false val regularParamsCount = if (hasVarArg) params.size - 1 else params.size val arguments = callExpression.argumentList?.expressions ?: emptyArray() val regularArgInfos = params .take(regularParamsCount) .zip(arguments) .map { CallArgumentInfo(it.first, it.second) } val varargParam = if (hasVarArg) params.last() else null val varargExpressions = arguments.drop(regularParamsCount) return CallInfo(regularArgInfos, varargParam, varargExpressions) } } private fun List<Int>.areSequential(): Boolean { if (size == 0) throw IncorrectOperationException("List is empty") val ordered = (first()..first() + size - 1).toList() if (ordered.size == size) { return zip(ordered).all { it.first == it.second } } return false } private fun inlayInfo(info: CallArgumentInfo, showOnlyIfExistedBefore: Boolean = false): InlayInfo? { return inlayInfo(info.argument, info.parameter, showOnlyIfExistedBefore) } private fun inlayInfo(callArgument: PsiExpression, methodParam: PsiParameter, showOnlyIfExistedBefore: Boolean = false): InlayInfo? { val paramName = methodParam.name val paramToShow = (if (methodParam.type is PsiEllipsisType) "..." else "") + paramName val offset = inlayOffset(callArgument) return InlayInfo(paramToShow, offset, showOnlyIfExistedBefore) } fun inlayOffset(callArgument: PsiExpression): Int = inlayOffset(callArgument, false) fun inlayOffset(callArgument: PsiExpression, atEnd: Boolean): Int { if (callArgument.textRange.isEmpty) { val next = callArgument.nextSibling as? PsiWhiteSpace if (next != null) return next.textRange.endOffset } return if (atEnd) callArgument.textRange.endOffset else callArgument.textRange.startOffset } private fun shouldShowHintsForExpression(callArgument: PsiElement): Boolean { if (JavaInlayParameterHintsProvider.getInstance().isShowHintWhenExpressionTypeIsClear.get()) return true return when (callArgument) { is PsiLiteralExpression -> true is PsiThisExpression -> true is PsiBinaryExpression -> true is PsiPolyadicExpression -> true is PsiPrefixExpression -> { val tokenType = callArgument.operationTokenType val isLiteral = callArgument.operand is PsiLiteralExpression isLiteral && (JavaTokenType.MINUS == tokenType || JavaTokenType.PLUS == tokenType) } else -> false } } private class CallInfo(val regularArgs: List<CallArgumentInfo>, val varArg: PsiParameter?, val varArgExpressions: List<PsiExpression>) { fun unclearInlays(substitutor: PsiSubstitutor): List<InlayInfo> { val inlays = mutableListOf<InlayInfo>() for (callInfo in regularArgs) { val inlay = when { isErroneousArg(callInfo) -> null shouldShowHintsForExpression(callInfo.argument) -> inlayInfo(callInfo) !callInfo.isAssignable(substitutor) -> inlayInfo(callInfo, showOnlyIfExistedBefore = true) else -> null } inlay?.let { inlays.add(inlay) } } return inlays } fun sameTypeInlays(): List<InlayInfo> { val all = regularArgs.map { it.parameter.typeText() } val duplicated = all.toMutableList() all.distinct().forEach { duplicated.remove(it) } return regularArgs .filterNot { isErroneousArg(it) } .filter { duplicated.contains(it.parameter.typeText()) && it.argument.text != it.parameter.name } .mapNotNull { inlayInfo(it) } } fun isErroneousArg(arg : CallArgumentInfo): Boolean { return arg.argument is PsiEmptyExpressionImpl || arg.argument.prevSibling is PsiEmptyExpressionImpl } fun varargsInlay(substitutor: PsiSubstitutor): InlayInfo? { if (varArg == null) return null var hasUnassignable = false for (expr in varArgExpressions) { if (shouldShowHintsForExpression(expr)) { return inlayInfo(varArgExpressions.first(), varArg) } hasUnassignable = hasUnassignable || !varArg.isAssignable(expr, substitutor) } return if (hasUnassignable) inlayInfo(varArgExpressions.first(), varArg, showOnlyIfExistedBefore = true) else null } } private class CallArgumentInfo(val parameter: PsiParameter, val argument: PsiExpression) { fun isAssignable(substitutor: PsiSubstitutor): Boolean { return parameter.isAssignable(argument, substitutor) } } private fun PsiParameter.isAssignable(argument: PsiExpression, substitutor: PsiSubstitutor = PsiSubstitutor.EMPTY): Boolean { val substitutedType = substitutor.substitute(type) ?: return false if (PsiPolyExpressionUtil.isPolyExpression(argument)) return true return argument.type?.isAssignableTo(substitutedType) ?: false } private fun PsiType.isAssignableTo(parameterType: PsiType): Boolean { return TypeConversionUtil.isAssignable(parameterType, this) } private fun PsiParameter.typeText() = type.canonicalText
apache-2.0
a1665f95aabcd893bcf4b507e34034d7
35.343575
140
0.706457
4.598798
false
false
false
false
fluidsonic/fluid-json
annotation-processor/test-cases/1/output-expected/property/serializedName/CustomJsonCodec.kt
1
2020
package `property`.serializedName import codecProvider.CustomCodingContext import io.fluidsonic.json.AbstractJsonCodec import io.fluidsonic.json.JsonCodingType import io.fluidsonic.json.JsonDecoder import io.fluidsonic.json.JsonEncoder import io.fluidsonic.json.missingPropertyError import io.fluidsonic.json.readBooleanOrNull import io.fluidsonic.json.readByteOrNull import io.fluidsonic.json.readCharOrNull import io.fluidsonic.json.readDoubleOrNull import io.fluidsonic.json.readFloatOrNull import io.fluidsonic.json.readFromMapByElementValue import io.fluidsonic.json.readIntOrNull import io.fluidsonic.json.readLongOrNull import io.fluidsonic.json.readShortOrNull import io.fluidsonic.json.readStringOrNull import io.fluidsonic.json.readValueOfType import io.fluidsonic.json.readValueOfTypeOrNull import io.fluidsonic.json.writeBooleanOrNull import io.fluidsonic.json.writeByteOrNull import io.fluidsonic.json.writeCharOrNull import io.fluidsonic.json.writeDoubleOrNull import io.fluidsonic.json.writeFloatOrNull import io.fluidsonic.json.writeIntOrNull import io.fluidsonic.json.writeIntoMap import io.fluidsonic.json.writeLongOrNull import io.fluidsonic.json.writeMapElement import io.fluidsonic.json.writeShortOrNull import io.fluidsonic.json.writeStringOrNull import io.fluidsonic.json.writeValueOrNull import kotlin.String import kotlin.Unit internal object CustomJsonCodec : AbstractJsonCodec<Custom, CustomCodingContext>() { public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<Custom>): Custom { var _value1: String? = null readFromMapByElementValue { key -> when (key) { "V A L U E 1" -> _value1 = readString() else -> skipValue() } } return Custom( value1 = _value1 ?: missingPropertyError("V A L U E 1") ) } public override fun JsonEncoder<CustomCodingContext>.encode(`value`: Custom): Unit { writeIntoMap { writeMapElement("V A L U E 1", string = value.value1) writeMapElement("V A L U E 2", string = value.value2) } } }
apache-2.0
b244d3a2947520cf8eeb09e3f0e73c7b
33.237288
96
0.815347
4.334764
false
false
false
false
SmokSmog/smoksmog-android
domain/src/test/kotlin/com/antyzero/smoksmog/SmokSmogTest.kt
1
2032
package com.antyzero.smoksmog import com.antyzero.smoksmog.location.Location import com.antyzero.smoksmog.location.Location.Position import com.antyzero.smoksmog.location.LocationProvider import com.antyzero.smoksmog.storage.PersistentStorage import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import org.assertj.core.api.Assertions.assertThat import org.junit.Test import pl.malopolska.smoksmog.Api import pl.malopolska.smoksmog.model.Station import rx.Observable import rx.observers.TestSubscriber class SmokSmogTest { @Test fun nearestStation() { val latitude = 49.617454 val longitude = 20.715333 val testSubscriber = TestSubscriber<Station>() val locationProvider = mock<LocationProvider> { on { location() } doReturn Position(latitude to longitude).observable<Location>() } val api = mock<Api> { on { stationByLocation(latitude, longitude) } doReturn Station( 6, "Nowy Sącz", latitude = latitude.toFloat(), longitude = longitude.toFloat()).observable() } val smokSmog = SmokSmog(api, mock<PersistentStorage> {}, locationProvider) smokSmog.nearestStation().subscribe(testSubscriber) testSubscriber.assertNoErrors() testSubscriber.assertCompleted() testSubscriber.assertValueCount(1) assertThat(testSubscriber.onNextEvents[0].id).isEqualTo(6) } @Test fun locationUnknown() { val testSubscriber = TestSubscriber<Station>() val locationProvider = mock<LocationProvider> { on { location() } doReturn Location.Unknown().observable<Location>() } val smokSmog = SmokSmog(mock<Api> { }, mock<PersistentStorage> { }, locationProvider) smokSmog.nearestStation().subscribe(testSubscriber) testSubscriber.assertNoErrors() testSubscriber.assertCompleted() testSubscriber.assertValueCount(0) } } private fun <T> T.observable() = Observable.just(this)
gpl-3.0
d4be2c4618678d806e485c154e5f8045
35.285714
112
0.708026
4.574324
false
true
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/execution/wsl/WslPath.kt
3
1176
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.wsl import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil data class WslPath(val distributionId: String, val linuxPath: String) { val distribution: WSLDistribution by lazy { WslDistributionManager.getInstance().getOrCreateDistributionByMsId(distributionId) } companion object { @JvmStatic fun parseWindowsUncPath(windowsUncPath : String) : WslPath? { if (!WSLUtil.isSystemCompatible()) return null var path = FileUtil.toSystemDependentName(windowsUncPath) if (!path.startsWith(WSLDistribution.UNC_PREFIX)) return null path = StringUtil.trimStart(path, WSLDistribution.UNC_PREFIX) val index = path.indexOf('\\') if (index <= 0) return null return WslPath(path.substring(0, index), FileUtil.toSystemIndependentName(path.substring(index))) } @JvmStatic fun getDistributionByWindowsUncPath(windowsUncPath : String) : WSLDistribution? = parseWindowsUncPath(windowsUncPath)?.distribution } }
apache-2.0
2d178a645dea37416124b514aff1fe61
42.555556
140
0.755952
4.454545
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/test/kotlin/com/vrem/util/LocaleUtilsTest.kt
1
3721
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <VREMSoftwareDevelopment@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.util import org.junit.Assert.* import org.junit.Test import java.util.* class LocaleUtilsTest { @Test fun testAllCountries() { // execute val actual = allCountries() // validate assertTrue(actual.size >= 2) assertTrue(actual[0].country < actual[actual.size - 1].country) } @Test fun testFindByCountryCode() { // setup val expected = allCountries()[0] // execute val actual = findByCountryCode(expected.country) // validate assertEquals(expected, actual) assertEquals(expected.country, actual.country) assertEquals(expected.displayCountry, actual.displayCountry) assertNotEquals(expected.country, expected.displayCountry) assertNotEquals(actual.country, actual.displayCountry) } @Test fun testFindByCountryCodeWithUnknownCode() { // execute val actual = findByCountryCode("WW") // validate assertEquals(Locale.getDefault(), actual) } @Test fun testToLanguageTag() { assertEquals(Locale.US.language + "_" + Locale.US.country, toLanguageTag(Locale.US)) assertEquals(Locale.ENGLISH.language + "_", toLanguageTag(Locale.ENGLISH)) } @Test fun testFindByLanguageTagWithUnknownTag() { val defaultLocal = Locale.getDefault() assertEquals(defaultLocal, findByLanguageTag(String.EMPTY)) assertEquals(defaultLocal, findByLanguageTag("WW")) assertEquals(defaultLocal, findByLanguageTag("WW_HH_TT")) } @Test fun testFindByLanguageTag() { assertEquals(Locale.SIMPLIFIED_CHINESE, findByLanguageTag(toLanguageTag(Locale.SIMPLIFIED_CHINESE))) assertEquals(Locale.TRADITIONAL_CHINESE, findByLanguageTag(toLanguageTag(Locale.TRADITIONAL_CHINESE))) assertEquals(Locale.ENGLISH, findByLanguageTag(toLanguageTag(Locale.ENGLISH))) } @Test fun testSupportedLanguages() { // setup val expected: Set<Locale> = setOf( BULGARIAN, Locale.SIMPLIFIED_CHINESE, Locale.TRADITIONAL_CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN, Locale.ITALIAN, Locale.JAPANESE, POLISH, PORTUGUESE, SPANISH, RUSSIAN, UKRAINIAN, Locale.getDefault()) // execute val actual = supportedLanguages() // validate assertEquals(expected.size, actual.size) for (locale in expected) { assertTrue(actual.contains(locale)) } } @Test fun testDefaultCountryCode() { assertEquals(Locale.getDefault().country, defaultCountryCode()) } @Test fun testDefaultLanguageTag() { assertEquals(toLanguageTag(Locale.getDefault()), defaultLanguageTag()) } }
gpl-3.0
1d0ab94c222131fc99f537d03809cb60
31.938053
110
0.6466
4.782776
false
true
false
false
zdary/intellij-community
platform/util/ui/src/com/intellij/util/ui/WrapLayout.kt
2
9316
// 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.util.ui import java.awt.Component import java.awt.Container import java.awt.Dimension import java.awt.FlowLayout import javax.swing.JScrollPane import javax.swing.SwingUtilities import kotlin.math.* /** * FlowLayout subclass that fully supports wrapping of components. */ open class WrapLayout : FlowLayout { /** * Constructs a new `WrapLayout` with a left * alignment and a default 5-unit horizontal and vertical gap. */ constructor() : super() /** * Constructs a new `FlowLayout` with the specified * alignment and a default 5-unit horizontal and vertical gap. * The value of the alignment argument must be one of * `WrapLayout`, `WrapLayout`, * or `WrapLayout`. * @param align the alignment value */ constructor(align: Int) : super(align) /** * Creates a new flow layout manager with the indicated alignment * and the indicated horizontal and vertical gaps. * * * The value of the alignment argument must be one of * `WrapLayout`, `WrapLayout`, * or `WrapLayout`. * @param align the alignment value * @param hgap the horizontal gap between components * @param vgap the vertical gap between components */ constructor(align: Int, hgap: Int, vgap: Int) : super(align, hgap, vgap) var fillWidth: Boolean = false /** * Returns the preferred dimensions for this layout given the * *visible* components in the specified target container. * @param target the component which needs to be laid out * @return the preferred dimensions to lay out the * subcomponents of the specified container */ override fun preferredLayoutSize(target: Container): Dimension { return layoutSize(target, true) } /** * Returns the minimum dimensions needed to layout the *visible* * components contained in the specified target container. * @param target the component which needs to be laid out * @return the minimum dimensions to lay out the * subcomponents of the specified container */ override fun minimumLayoutSize(target: Container): Dimension { val minimum = layoutSize(target, false) minimum.width -= hgap + 1 return minimum } /** * Returns the minimum or preferred dimension needed to layout the target * container. * * @param target target to get layout size for * @param preferred should preferred size be calculated * @return the dimension to layout the target container */ private fun layoutSize(target: Container, preferred: Boolean): Dimension { synchronized(target.treeLock) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container // has not yet been calculated so lets ask for the maximum. var container = target while (container.size.width == 0 && container.parent != null) { container = container.parent } var targetWidth = container.size.width if (targetWidth == 0) { targetWidth = Integer.MAX_VALUE } val hgap = hgap val vgap = vgap val insets = target.insets val horizontalInsetsAndGap = insets.left + insets.right + hgap * 2 val maxWidth = targetWidth - horizontalInsetsAndGap // Fit components into the allowed width val dim = Dimension(0, 0) var rowWidth = 0 var rowHeight = 0 val nmembers = target.componentCount for (i in 0 until nmembers) { val m = target.getComponent(i) if (m.isVisible) { val d = if (preferred) preferredSize(m) else m.minimumSize // Can't add the component to current row. Start a new row. if (rowWidth + hgap + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight) rowWidth = 0 rowHeight = 0 } // Add a horizontal gap for all components after the first if (rowWidth != 0) { rowWidth += hgap } rowWidth += d.width rowHeight = max(rowHeight, d.height) } } addRow(dim, rowWidth, rowHeight) dim.width += horizontalInsetsAndGap dim.height += insets.top + insets.bottom + vgap * 2 // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. val scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane::class.java, target) if (scrollPane != null && target.isValid) { dim.width -= hgap + 1 } dim.width = min(dim.width, maxWidth) return dim } } /** * A new row has been completed. Use the dimensions of this row * to update the preferred size for the container. * * @param dim update the width and height when appropriate * @param rowWidth the width of the row to add * @param rowHeight the height of the row to add */ private fun addRow(dim: Dimension, rowWidth: Int, rowHeight: Int) { dim.width = max(dim.width, rowWidth) if (dim.height > 0) { dim.height += vgap } dim.height += rowHeight } override fun layoutContainer(target: Container) { synchronized(target.treeLock) { val insets = target.insets val maxwidth = target.width - (insets.left + insets.right + hgap * 2) val nmembers = target.componentCount var x = 0 var y = insets.top + vgap var rowh = 0 var start = 0 val ltr = target.componentOrientation.isLeftToRight val useBaseline = alignOnBaseline val ascent = IntArray(nmembers) val descent = IntArray(nmembers) for (i in 0 until nmembers) { val m = target.getComponent(i) if (m.isVisible) { val d = preferredSize(m) m.setSize(d.width, d.height) if (useBaseline) { val baseline = m.getBaseline(d.width, d.height) if (baseline >= 0) { ascent[i] = baseline descent[i] = d.height - baseline } else { ascent[i] = -1 } } if (x == 0 || x + d.width <= maxwidth) { if (x > 0) { x += hgap } x += d.width rowh = max(rowh, d.height) } else { rowh = moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, i, ltr, useBaseline, ascent, descent) x = d.width y += vgap + rowh rowh = d.height start = i } } } moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, nmembers, ltr, useBaseline, ascent, descent) } } private fun preferredSize(m: Component) = Dimension(max(m.preferredSize.width, m.minimumSize.width), max(m.preferredSize.height, m.minimumSize.height)) private fun moveComponents(target: Container, _x: Int, y: Int, width: Int, _height: Int, rowStart: Int, rowEnd: Int, ltr: Boolean, useBaseline: Boolean, ascent: IntArray, descent: IntArray): Int { var x = _x var height = _height when (alignment) { LEFT -> x += if (ltr) 0 else width CENTER -> x += width / 2 RIGHT -> x += if (ltr) width else 0 LEADING -> { } TRAILING -> x += width } var maxAscent = 0 var nonBaselineHeight = 0 var baselineOffset = 0 if (useBaseline) { var maxDescent = 0 for (i in rowStart until rowEnd) { val m = target.getComponent(i) if (m.isVisible) { if (ascent[i] >= 0) { maxAscent = max(maxAscent, ascent[i]) maxDescent = max(maxDescent, descent[i]) } else { nonBaselineHeight = max(m.height, nonBaselineHeight) } } } height = max(maxAscent + maxDescent, nonBaselineHeight) baselineOffset = (height - maxAscent - maxDescent) / 2 } var expand = 1.0 if (fillWidth) { var sum = 0.0 for (i in rowStart until rowEnd) { val m = target.getComponent(i) if (m.isVisible) { sum += max(m.preferredSize.width, m.minimumSize.width) } } expand = target.width.toDouble() / sum } for (i in rowStart until rowEnd) { val m = target.getComponent(i) if (m.isVisible) { val cy: Int = if (useBaseline && ascent[i] >= 0) { y + baselineOffset + maxAscent - ascent[i] } else { y + (height - m.height) / 2 } val w = if (fillWidth) floor(max(m.preferredSize.width, m.minimumSize.width) * expand).toInt() else m.width if (ltr) { m.setBounds(x, cy, w, m.height) } else { m.setBounds(target.width - x - w, cy, w, m.height) } x += m.width + hgap } } return height } }
apache-2.0
fc00a51c19f48f94121ac4dff1c1cc17
31.017182
140
0.597145
4.183206
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/blocks/multipart/OutlineRenderUtil.kt
1
4022
package net.ndrei.teslacorelib.blocks.multipart import net.minecraft.block.material.Material import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.RenderGlobal import net.minecraft.util.EnumHand import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.Vec3d import net.minecraftforge.client.event.DrawBlockHighlightEvent import java.awt.Color object OutlineRenderUtil { fun renderDefaultOutline(event: DrawBlockHighlightEvent, part: IBlockPart) = this.renderOutline(event, { offset -> val aabb = part.hitBoxes.fold<IBlockPartHitBox, AxisAlignedBB?>(null) { ab, hb -> if (ab == null) hb.aabb else ab.union(hb.aabb) } ?: return@renderOutline false val stack = when (event.player!!.activeHand ?: EnumHand.MAIN_HAND) { EnumHand.MAIN_HAND -> event.player.heldItemMainhand EnumHand.OFF_HAND -> event.player.heldItemOffhand } val targetState = event.player.world.getBlockState(event.target.blockPos) val color = Color(if (stack.isEmpty) part.getOutlineColor(event.player.world, event.target.blockPos, targetState) else part.getHoverOutlineColor(event.player.world, event.target.blockPos, targetState, event.player, stack) , true) RenderGlobal.drawSelectionBoundingBox(aabb.grow(1.0 / 32.0), //.offset(offset), color.red.toFloat() / 255f, color.green.toFloat() / 255f, color.blue.toFloat() / 255f, color.alpha.toFloat() / 255f) return@renderOutline true }, true, part) fun renderOutline(event: DrawBlockHighlightEvent, renderCallback: (offset: Vec3d) -> Boolean, translateOffset: Boolean = false, part: IBlockPart): Boolean { GlStateManager.enableBlend() GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO) GlStateManager.glLineWidth(2.0f) GlStateManager.disableTexture2D() if (!part.outlineDepthCheck) GlStateManager.disableDepth() GlStateManager.depthMask(false) val blockPos = event.target.blockPos val blockState = event.player.world.getBlockState(blockPos) var rendered = false if ((blockState.material !== Material.AIR) && event.player.world.worldBorder.contains(blockPos)) { val dx = event.player.lastTickPosX + (event.player.posX - event.player.lastTickPosX) * event.partialTicks.toDouble() val dy = event.player.lastTickPosY + (event.player.posY - event.player.lastTickPosY) * event.partialTicks.toDouble() val dz = event.player.lastTickPosZ + (event.player.posZ - event.player.lastTickPosZ) * event.partialTicks.toDouble() val offset = Vec3d(dx, dy, dz).subtractReverse(Vec3d(blockPos.x.toDouble(), blockPos.y.toDouble(), blockPos.z.toDouble())) if (translateOffset) { GlStateManager.pushMatrix() GlStateManager.translate(offset.x, offset.y, offset.z) // val state = event.player.world.getBlockState(event.target.blockPos) // val block = state.block as? IProvideVariantTransform // if (block != null) { // val transform = block.getTransform(state.getPropertyString()).matrix // GlStateManager.multMatrix(transform.toFloatBuffer()) // } } rendered = renderCallback(offset) if (translateOffset) { GlStateManager.popMatrix() } } if (!part.outlineDepthCheck) GlStateManager.enableDepth() GlStateManager.depthMask(true) GlStateManager.enableTexture2D() GlStateManager.disableBlend() return rendered } }
mit
ceb26c7375e419998c9aeb443c9e4905
47.46988
194
0.65266
4.343413
false
false
false
false
macoscope/KetchupLunch
app/src/main/java/com/macoscope/ketchuplunch/model/GooglePlayServices.kt
1
975
package com.macoscope.ketchuplunch.model import android.content.Context import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability class GooglePlayServices(val context: Context) { data class CheckAvaialabilityResult(val isAvailable: Boolean, val connectionStatusCode: Int) fun acquireServices(): CheckAvaialabilityResult { val apiAvailability = GoogleApiAvailability.getInstance() val connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(context) val isAvailable = !apiAvailability.isUserResolvableError(connectionStatusCode) return CheckAvaialabilityResult(isAvailable, connectionStatusCode) } fun isAvailable(): Boolean { val apiAvailability = GoogleApiAvailability.getInstance() val connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(context) return connectionStatusCode == ConnectionResult.SUCCESS } }
apache-2.0
e72ad906e5cdf2d21da9b3f449c0ce77
41.391304
96
0.792821
5.477528
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/fragments/projectpage/FrequentlyAskedQuestionFragment.kt
1
5611
package com.kickstarter.ui.fragments.projectpage import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.res.ResourcesCompat import androidx.core.view.isGone import androidx.core.view.isVisible import com.kickstarter.R import com.kickstarter.databinding.FragmentFrequentlyAskedQuestionBinding import com.kickstarter.libs.BaseFragment import com.kickstarter.libs.Configure import com.kickstarter.libs.MessagePreviousScreenType import com.kickstarter.libs.SimpleDividerItemDecoration import com.kickstarter.libs.qualifiers.RequiresFragmentViewModel import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.models.Project import com.kickstarter.ui.ArgumentsKey import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.MessageCreatorActivity import com.kickstarter.ui.activities.MessagesActivity import com.kickstarter.ui.adapters.FrequentlyAskedQuestionsAdapter import com.kickstarter.ui.data.ProjectData import com.kickstarter.viewmodels.projectpage.FrequentlyAskedQuestionViewModel import rx.android.schedulers.AndroidSchedulers @RequiresFragmentViewModel(FrequentlyAskedQuestionViewModel.ViewModel::class) class FrequentlyAskedQuestionFragment : BaseFragment<FrequentlyAskedQuestionViewModel.ViewModel>(), Configure { private var binding: FragmentFrequentlyAskedQuestionBinding? = null private var fqaAdapter = FrequentlyAskedQuestionsAdapter() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) binding = FragmentFrequentlyAskedQuestionBinding.inflate(inflater, container, false) return binding?.root } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() this.viewModel.outputs.projectFaqList() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding?.answerEmptyStateTv?.isVisible = it.isEmpty() binding?.fqaRecyclerView?.isGone = it.isEmpty() fqaAdapter.takeData(it) } this.viewModel.outputs.bindEmptyState() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding?.answerEmptyStateTv?.isVisible = true binding?.fqaRecyclerView?.isGone = true } binding?.askQuestionButton?.setOnClickListener { this.viewModel.inputs.askQuestionButtonClicked() } this.viewModel.outputs.askQuestionButtonIsGone() .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe { if (it) { getString(R.string.Log_in_to_ask_the_project_creator_directly) } else { getString(R.string.Ask_the_project_creator_directly) }.apply { binding?.answerEmptyStateTv?.text = getString( R.string .Looks_like_there_arent_any_frequently_asked_questions ) + " " + this } binding?.answerEmptyStateSepartor?.isGone = it binding?.askQuestionButton?.isGone = it } this.viewModel.outputs.startComposeMessageActivity() .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe { startComposeMessageActivity(it) } this.viewModel.outputs.startMessagesActivity() .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe { startMessagesActivity(it) } } private fun startComposeMessageActivity(it: Project?) { startActivity( Intent(requireContext(), MessageCreatorActivity::class.java) .putExtra(IntentKey.PROJECT, it) ) } private fun startMessagesActivity(project: Project) { startActivity( Intent(requireContext(), MessagesActivity::class.java) .putExtra(IntentKey.MESSAGE_SCREEN_SOURCE_CONTEXT, MessagePreviousScreenType.CREATOR_BIO_MODAL) .putExtra(IntentKey.PROJECT, project) .putExtra(IntentKey.BACKING, project.backing()) ) } private fun setupRecyclerView() { binding?.fqaRecyclerView?.overScrollMode = View.OVER_SCROLL_NEVER binding?.fqaRecyclerView?.adapter = fqaAdapter ResourcesCompat.getDrawable(resources, R.drawable.divider_grey_300_horizontal, null)?.let { binding?.fqaRecyclerView?.addItemDecoration(SimpleDividerItemDecoration(it)) } } companion object { @JvmStatic fun newInstance(position: Int): FrequentlyAskedQuestionFragment { val fragment = FrequentlyAskedQuestionFragment() val bundle = Bundle() bundle.putInt(ArgumentsKey.PROJECT_PAGER_POSITION, position) fragment.arguments = bundle return fragment } } override fun configureWith(projectData: ProjectData) { this.viewModel?.inputs?.configureWith(projectData) } }
apache-2.0
9bb68de5e4144f155ce3080d9dd3cd30
38.237762
111
0.679023
5.190564
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/fields/implWsDataClassFiledCode.kt
1
2360
package com.intellij.workspaceModel.codegen.fields import com.intellij.workspaceModel.codegen.deft.* import com.intellij.workspaceModel.codegen.isOverride import com.intellij.workspaceModel.codegen.isRefType import com.intellij.workspaceModel.codegen.javaName val Field<*, *>.implWsDataFieldCode: String get() = buildString { if (hasSetter) { if (isOverride && name !in listOf("name", "entitySource")) append(implWsBlockingCodeOverride) else append(implWsDataBlockingCode) } else { if (defaultValue!!.startsWith("=")) { append("var $javaName: ${type.javaType} ${defaultValue}") } else { append("var $javaName: ${type.javaType} = ${defaultValue}") } } } private val Field<*, *>.implWsDataBlockingCode: String get() = implWsDataBlockCode(type, name) private fun Field<*, *>.implWsDataBlockCode(fieldType: ValueType<*>, name: String, isOptional: Boolean = false): String { return when (fieldType) { TInt -> "var $javaName: ${fieldType.javaType} = 0" TBoolean -> "var $javaName: ${fieldType.javaType} = false" TString -> "lateinit var $javaName: String" is TRef -> error("Reference type at EntityData not supported") is TCollection<*, *>, is TMap<*, *> -> { if (fieldType.isRefType()) error("Reference type at EntityData not supported") if (!isOptional) { "lateinit var $javaName: ${fieldType.javaType}" } else { "var $javaName: ${fieldType.javaType}? = null" } } is TOptional<*> -> when (fieldType.type) { TInt, TBoolean, TString -> "var $javaName: ${fieldType.javaType} = null" else -> implWsDataBlockCode(fieldType.type, name, true) } is TBlob<*> -> { if (!isOptional) { "lateinit var $javaName: ${fieldType.javaType}" } else { "var $javaName: ${fieldType.javaType}? = null" } } else -> error("Unsupported field type: $this") } } val Field<*, *>.implWsDataFieldInitializedCode: String get() = when (type) { is TInt, is TBoolean -> "" is TString, is TBlob<*>, is TCollection<*, *>, is TMap<*, *> -> { val capitalizedFieldName = javaName.replaceFirstChar { it.titlecaseChar() } "fun is${capitalizedFieldName}Initialized(): Boolean = ::${javaName}.isInitialized" } else -> error("Unsupported field type: $this") }
apache-2.0
d62531d6a99715b0f218198c904d1d65
35.875
121
0.642797
4.054983
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/DslHighlightingMarker.kt
1
2669
// 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.highlighter.markers import com.intellij.application.options.colors.ColorAndFontOptions import com.intellij.codeHighlighting.Pass import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.ide.DataManager import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement import com.intellij.util.Function import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.highlighter.dsl.DslHighlighterExtension import org.jetbrains.kotlin.idea.highlighter.dsl.isDslHighlightingMarker import org.jetbrains.kotlin.psi.KtClass import javax.swing.JComponent private val navHandler = GutterIconNavigationHandler<PsiElement> { event, element -> val dataContext = (event.component as? JComponent)?.let { DataManager.getInstance().getDataContext(it) } ?: return@GutterIconNavigationHandler val ktClass = element?.parent as? KtClass ?: return@GutterIconNavigationHandler val styleId = ktClass.styleIdForMarkerAnnotation() ?: return@GutterIconNavigationHandler ColorAndFontOptions.selectOrEditColor(dataContext, DslHighlighterExtension.styleOptionDisplayName(styleId), KotlinLanguage.NAME) } private val toolTipHandler = Function<PsiElement, String> { KotlinBundle.message("highlighter.tool.tip.marker.annotation.for.dsl") } fun collectHighlightingColorsMarkers( ktClass: KtClass, result: LineMarkerInfos ) { if (!KotlinLineMarkerOptions.dslOption.isEnabled) return val styleId = ktClass.styleIdForMarkerAnnotation() ?: return val anchor = ktClass.nameIdentifier ?: return result.add( LineMarkerInfo<PsiElement>( anchor, anchor.textRange, createDslStyleIcon(styleId), Pass.LINE_MARKERS, toolTipHandler, navHandler, GutterIconRenderer.Alignment.RIGHT ) ) } private fun KtClass.styleIdForMarkerAnnotation(): Int? { val classDescriptor = toDescriptor() as? ClassDescriptor ?: return null if (classDescriptor.kind != ClassKind.ANNOTATION_CLASS) return null if (!classDescriptor.isDslHighlightingMarker()) return null return DslHighlighterExtension.styleIdByMarkerAnnotation(classDescriptor) }
apache-2.0
533cdb6eb62045f27e129567078986f8
42.064516
158
0.790184
4.783154
false
false
false
false
siosio/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/testUtils.kt
1
6808
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage import com.google.common.collect.HashBiMap import com.intellij.util.containers.BidirectionalMultiMap import com.intellij.workspaceModel.storage.impl.* import com.intellij.workspaceModel.storage.impl.containers.BidirectionalMap import com.intellij.workspaceModel.storage.impl.containers.BidirectionalSetMap import com.intellij.workspaceModel.storage.impl.containers.copy import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import junit.framework.TestCase.* import org.junit.Assert import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.util.function.BiPredicate import kotlin.reflect.full.memberProperties class TestEntityTypesResolver : EntityTypesResolver { private val pluginPrefix = "PLUGIN___" override fun getPluginId(clazz: Class<*>): String? = pluginPrefix + clazz.name override fun resolveClass(name: String, pluginId: String?): Class<*> { Assert.assertEquals(pluginPrefix + name, pluginId) if (name.startsWith("[")) return Class.forName(name) return javaClass.classLoader.loadClass(name) } } object SerializationRoundTripChecker { fun verifyPSerializationRoundTrip(storage: WorkspaceEntityStorage, virtualFileManager: VirtualFileUrlManager): ByteArray { storage as WorkspaceEntityStorageImpl storage.assertConsistency() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val stream = ByteArrayOutputStream() serializer.serializeCache(stream, storage) val byteArray = stream.toByteArray() val deserialized = (serializer.deserializeCache(ByteArrayInputStream(byteArray)) as WorkspaceEntityStorageBuilderImpl).toStorage() deserialized.assertConsistency() assertStorageEquals(storage, deserialized) storage.assertConsistency() return byteArray } private fun assertStorageEquals(expected: WorkspaceEntityStorageImpl, actual: WorkspaceEntityStorageImpl) { // Assert entity data assertEquals(expected.entitiesByType.size(), actual.entitiesByType.size()) for ((clazz, expectedEntityFamily) in expected.entitiesByType.entityFamilies.withIndex()) { val actualEntityFamily = actual.entitiesByType.entityFamilies[clazz] if (expectedEntityFamily == null || actualEntityFamily == null) { assertNull(expectedEntityFamily) assertNull(actualEntityFamily) continue } val expectedEntities = expectedEntityFamily.entities val actualEntities = actualEntityFamily.entities assertOrderedEquals(expectedEntities, actualEntities) { a, b -> a == null && b == null || a != null && b != null && a.equalsIgnoringEntitySource(b) } } // Assert refs assertMapsEqual(expected.refs.oneToOneContainer, actual.refs.oneToOneContainer) assertMapsEqual(expected.refs.oneToManyContainer, actual.refs.oneToManyContainer) assertMapsEqual(expected.refs.abstractOneToOneContainer, actual.refs.abstractOneToOneContainer) assertMapsEqual(expected.refs.oneToAbstractManyContainer, actual.refs.oneToAbstractManyContainer) assertMapsEqual(expected.indexes.virtualFileIndex.entityId2VirtualFileUrl, actual.indexes.virtualFileIndex.entityId2VirtualFileUrl) assertMapsEqual(expected.indexes.virtualFileIndex.vfu2EntityId, actual.indexes.virtualFileIndex.vfu2EntityId) // Just checking that all properties have been asserted assertEquals(4, RefsTable::class.memberProperties.size) // Assert indexes assertBiMultiMap(expected.indexes.softLinks.index, actual.indexes.softLinks.index) assertBiMap(expected.indexes.persistentIdIndex.index, actual.indexes.persistentIdIndex.index) // External index should not be persisted assertTrue(actual.indexes.externalMappings.isEmpty()) // Just checking that all properties have been asserted assertEquals(5, StorageIndexes::class.memberProperties.size) } // Use UsefulTestCase.assertOrderedEquals in case it'd be used in this module private fun <T> assertOrderedEquals(actual: Iterable<T?>, expected: Iterable<T?>, comparator: (T?, T?) -> Boolean) { if (!equals(actual, expected, BiPredicate(comparator))) { val expectedString: String = expected.toString() val actualString: String = actual.toString() Assert.assertEquals("", expectedString, actualString) Assert.fail( "Warning! 'toString' does not reflect the difference.\nExpected: $expectedString\nActual: $actualString") } } private fun <T> equals(a1: Iterable<T?>, a2: Iterable<T?>, predicate: BiPredicate<in T?, in T?>): Boolean { val it1 = a1.iterator() val it2 = a2.iterator() while (it1.hasNext() || it2.hasNext()) { if (!it1.hasNext() || !it2.hasNext() || !predicate.test(it1.next(), it2.next())) { return false } } return true } private fun assertMapsEqual(expected: Map<*, *>, actual: Map<*, *>) { val local = HashMap(expected) for ((key, value) in actual) { val expectedValue = local.remove(key) if (expectedValue == null) { Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", key, value)) } if (expectedValue != value) { Assert.fail( String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, key, value)) } } if (local.isNotEmpty()) { Assert.fail("No mappings found for the following keys: " + local.keys) } } private fun <A, B> assertBiMultiMap(expected: BidirectionalMultiMap<A, B>, actual: BidirectionalMultiMap<A, B>) { val local = expected.copy() for (key in actual.keys) { val value = actual.getValues(key) val expectedValue = local.getValues(key) local.removeKey(key) assertOrderedEquals(expectedValue, value) { a, b -> a == b } } if (!local.isEmpty) { Assert.fail("No mappings found for the following keys: " + local.keys) } } private fun <T> assertBiMap(expected: HashBiMap<EntityId, T>, actual: HashBiMap<EntityId, T>) { val local = HashBiMap.create(expected) for (key in actual.keys) { val value = actual.getValue(key) val expectedValue = local.remove(key) if (expectedValue == null) { Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", key, value)) } if (expectedValue != value) { Assert.fail( String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, key, value)) } } if (local.isNotEmpty()) { Assert.fail("No mappings found for the following keys: " + local.keys) } } }
apache-2.0
cbfb5ef9786ada53ff0b8b0538bdfb58
41.81761
155
0.72547
4.596894
false
false
false
false
vovagrechka/fucking-everything
attic/alraune/alraune-front/src/DocumentCategoryPicker.kt
1
3117
package alraune.front import alraune.shared.AlDocumentCategories import alraune.shared.AlDomid import vgrechka.* import vgrechka.kjs.JQueryPile.byIDNoneOrSingle import vgrechka.kjs.JQueryPile.byIDSingle // TODO:vgrechka Think about garbage collection class DocumentCategoryPicker { val selectID = "c03af235-f18e-48ad-9a68-4ae0e523eff9" val backButtonID = "92c15f06-fd82-4d0a-9445-fd3eb59e8aab" val pathExceptLast = mutableListOf<AlDocumentCategories.Category>() init { var category = AlDocumentCategories.findByIDOrBitch(AlFrontPile.shitFromBack.documentCategoryID) while (true) { pathExceptLast += category val parent = category.parent if (parent == null) break else category = parent } pathExceptLast.reverse() val last = pathExceptLast.last() pathExceptLast.removeAt(pathExceptLast.lastIndex) update() selectJQ().setVal(last.id) } fun update() { val containerJQ = byIDSingle(AlDomid.documentCategoryPickerContainer) containerJQ.html(buildString { val items = pathExceptLast.last().children ln("<div style='display: flex; align-items: center;'>") val pathToShow = pathExceptLast.drop(1) for (step in pathToShow) { ln("<div style='margin-right: 0.5rem;'>${step.title}</div>") } if (pathToShow.isNotEmpty()) { ln("<button class='btn btn-default' style='margin-right: 0.5rem;' id='$backButtonID'>") ln("<i class='fa fa-arrow-left'></i></button>") } if (items.isNotEmpty()) { ln("<select class='form-control' id='$selectID'>") for (item in items) { ln("<option value='${item.id}'>${item.title}</option>") } ln("</select>") } }) selectJQ().on("change") { handleSelectChange() } val backButtonJQ = byIDNoneOrSingle(backButtonID) backButtonJQ?.let { it.on("click") { handleBackButtonClick() } } } private fun handleBackButtonClick() { pathExceptLast.removeAt(pathExceptLast.lastIndex) update() } fun debug_handleBackButtonClick() { handleBackButtonClick() } private fun handleSelectChange() { val categoryID = getSelectedCategoryID() val item = pathExceptLast.last().children.find {it.id == categoryID} ?: wtf("5162f6ed-31bc-4e89-8088-5528b9ea43d5") if (item.children.isNotEmpty()) { pathExceptLast += item update() } } fun getSelectedCategoryID(): String { val categoryID = selectJQ().getVal() ?: wtf("975e6a00-5798-44dd-a704-5e9f47e1e678") return categoryID } fun debug_setSelectValue(categoryID: String) { selectJQ().setVal(categoryID) handleSelectChange() } private fun selectJQ() = byIDSingle(selectID) }
apache-2.0
2b6c5b87a4eeb486aec1a0c2d8b75c5e
27.081081
123
0.58967
4.106719
false
false
false
false
jwren/intellij-community
python/python-psi-impl/src/com/jetbrains/python/inspections/stdlib/PyStdlibInspectionExtension.kt
4
2457
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections.stdlib import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.DUNDER_POST_INIT import com.jetbrains.python.psi.types.PyNamedTupleType import com.jetbrains.python.psi.types.PyNamedTupleType.NAMEDTUPLE_SPECIAL_ATTRIBUTES import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleTypeProvider import com.jetbrains.python.codeInsight.parseStdDataclassParameters import com.jetbrains.python.inspections.PyInspectionExtension import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyReferenceExpression import com.jetbrains.python.psi.types.PyClassLikeType import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext class PyStdlibInspectionExtension : PyInspectionExtension() { override fun ignoreInitNewSignatures(original: PyFunction, complementary: PyFunction): Boolean { return PyNames.TYPE_ENUM == complementary.containingClass?.qualifiedName } override fun ignoreUnresolvedMember(type: PyType, name: String, context: TypeEvalContext): Boolean { if (type is PyClassLikeType) { return type is PyNamedTupleType && ignoredUnresolvedNamedTupleMember(type, name) || type.getAncestorTypes(context).filterIsInstance<PyNamedTupleType>().any { ignoredUnresolvedNamedTupleMember(it, name) } } return false } override fun ignoreProtectedSymbol(expression: PyReferenceExpression, context: TypeEvalContext): Boolean { val qualifier = expression.qualifier return qualifier != null && expression.referencedName in NAMEDTUPLE_SPECIAL_ATTRIBUTES && PyNamedTupleTypeProvider.isNamedTuple(context.getType(qualifier), context) } override fun ignoreMethodParameters(function: PyFunction, context: TypeEvalContext): Boolean { return function.name == "__prepare__" && function.getParameters(context).let { it.size == 3 && !it.any { p -> p.isKeywordContainer || p.isPositionalContainer } } || function.name == DUNDER_POST_INIT && function.containingClass?.let { parseStdDataclassParameters(it, context) != null } == true } private fun ignoredUnresolvedNamedTupleMember(type: PyNamedTupleType, name: String): Boolean { return name == PyNames.SLOTS || type.fields.containsKey(name) } }
apache-2.0
2aa85bf63aba96a8d802e34b74688b11
49.142857
140
0.777371
4.706897
false
false
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/adapters/QuickFilterEventTypeAdapter.kt
1
4473
package com.simplemobiletools.calendar.pro.adapters import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.activities.SimpleActivity import com.simplemobiletools.calendar.pro.extensions.config import com.simplemobiletools.calendar.pro.models.EventType import com.simplemobiletools.commons.extensions.adjustAlpha import com.simplemobiletools.commons.extensions.getProperTextColor import com.simplemobiletools.commons.helpers.LOWER_ALPHA import kotlinx.android.synthetic.main.quick_filter_event_type_view.view.* class QuickFilterEventTypeAdapter( val activity: SimpleActivity, private val allEventTypes: List<EventType>, private val quickFilterEventTypeIds: Set<String>, val callback: () -> Unit ) : RecyclerView.Adapter<QuickFilterEventTypeAdapter.ViewHolder>() { private val activeKeys = HashSet<Long>() private val quickFilterEventTypes = ArrayList<EventType>() private val displayEventTypes = activity.config.displayEventTypes private val textColorActive = activity.getProperTextColor() private val textColorInactive = textColorActive.adjustAlpha(LOWER_ALPHA) private val minItemWidth = activity.resources.getDimensionPixelSize(R.dimen.quick_filter_min_width) private var lastClickTS = 0L init { quickFilterEventTypeIds.forEach { quickFilterEventType -> val eventType = allEventTypes.firstOrNull { eventType -> eventType.id.toString() == quickFilterEventType } ?: return@forEach quickFilterEventTypes.add(eventType) if (displayEventTypes.contains(eventType.id.toString())) { activeKeys.add(eventType.id!!) } } quickFilterEventTypes.sortBy { it.title.lowercase() } } private fun toggleItemSelection(select: Boolean, eventType: EventType, pos: Int) { if (select) { activeKeys.add(eventType.id!!) } else { activeKeys.remove(eventType.id) } notifyItemChanged(pos) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val parentWidth = parent.measuredWidth val nrOfItems = quickFilterEventTypes.size val view = activity.layoutInflater.inflate(R.layout.quick_filter_event_type_view, parent, false) if (nrOfItems * minItemWidth > parentWidth) view.layoutParams.width = minItemWidth else view.layoutParams.width = parentWidth / nrOfItems return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val eventType = quickFilterEventTypes[position] holder.bindView(eventType) } override fun getItemCount() = quickFilterEventTypes.size inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun bindView(eventType: EventType): View { val isSelected = activeKeys.contains(eventType.id) itemView.apply { quick_filter_event_type.text = eventType.title val textColor = if (isSelected) textColorActive else textColorInactive quick_filter_event_type.setTextColor(textColor) val indicatorHeightRes = if (isSelected) R.dimen.quick_filter_active_line_size else R.dimen.quick_filter_inactive_line_size quick_filter_event_type_color.layoutParams.height = resources.getDimensionPixelSize(indicatorHeightRes) quick_filter_event_type_color.setBackgroundColor(eventType.color) // avoid too quick clicks, could cause glitches quick_filter_event_type.setOnClickListener { if (System.currentTimeMillis() - lastClickTS > 300) { lastClickTS = System.currentTimeMillis() viewClicked(!isSelected, eventType) callback() } } } return itemView } private fun viewClicked(select: Boolean, eventType: EventType) { activity.config.displayEventTypes = if (select) { activity.config.displayEventTypes.plus(eventType.id.toString()) } else { activity.config.displayEventTypes.minus(eventType.id.toString()) } toggleItemSelection(select, eventType, adapterPosition) } } }
gpl-3.0
ffc40afa61a83bdac61d7c3d075fad25
41.198113
139
0.687011
4.997765
false
false
false
false
jwren/intellij-community
plugins/package-search/test-src/com/jetbrains/packagesearch/intellij/plugin/PackageSearchTestUtils.kt
2
1238
package com.jetbrains.packagesearch.intellij.plugin import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion internal object PackageSearchTestUtils { fun loadPackageVersionsFromResource(resourcePath: String): List<PackageVersion.Named> = javaClass.classLoader.getResourceAsStream(resourcePath)!! .bufferedReader() .useLines { lines -> lines.filterNot { it.startsWith('#') } .mapIndexed { lineNumber, line -> val parts = line.split(',') check(parts.size == 3) { "Invalid line ${lineNumber + 1}: has ${parts.size} part(s), but we expected to have 3" } val versionName = parts[0] val isStable = parts[1].toBooleanStrictOrNull() ?: error("Line ${lineNumber + 1} has invalid stability: ${parts[1]}") val timestamp = parts[2].toLongOrNull() ?: error("Line ${lineNumber + 1} has an invalid timestamp: ${parts[1]}") PackageVersion.Named(versionName, isStable, timestamp) } .toList() } }
apache-2.0
aee0cfb6eb53964fed4d6bac6592dd27
46.615385
137
0.55412
5.477876
false
false
false
false
ajordens/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RestartStageHandler.kt
1
4896
/* * Copyright 2017 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.q.handler import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.model.PipelineTrigger import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.RestartStage import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.q.Queue import java.time.Clock import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component @Component class RestartStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, private val pendingExecutionService: PendingExecutionService, private val clock: Clock ) : OrcaMessageHandler<RestartStage>, StageBuilderAware { override val messageType = RestartStage::class.java private val log: Logger get() = LoggerFactory.getLogger(javaClass) override fun handle(message: RestartStage) { message.withStage { stage -> if (stage.execution.shouldQueue()) { // this pipeline is already running and has limitConcurrent = true stage.execution.pipelineConfigId?.let { log.info("Queueing restart of {} {} {}", stage.execution.application, stage.execution.name, stage.execution.id) pendingExecutionService.enqueue(it, message) } } else { // If RestartStage is requested for a synthetic stage, operate on its parent val topStage = stage.topLevelStage val startMessage = StartStage(message.executionType, message.executionId, message.application, topStage.id) if (topStage.status.isComplete) { topStage.addRestartDetails(message.user) topStage.reset() restartParentPipelineIfNeeded(message, topStage) topStage.execution.updateStatus(RUNNING) repository.updateStatus(topStage.execution) queue.push(StartStage(startMessage)) } } } } private fun restartParentPipelineIfNeeded(message: RestartStage, topStage: StageExecution) { if (topStage.execution.trigger !is PipelineTrigger) { return } val trigger = topStage.execution.trigger as PipelineTrigger if (trigger.parentPipelineStageId == null) { // Must've been triggered by dependent pipeline, we don't restart those return } // We have a copy of the parent execution, not the live one. So we retrieve the live one. val parentExecution = repository.retrieve(trigger.parentExecution.type, trigger.parentExecution.id) if (!parentExecution.status.isComplete()) { // only attempt to restart the parent pipeline if it's not running return } val parentStage = parentExecution.stageById(trigger.parentPipelineStageId) parentStage.addSkipRestart() repository.storeStage(parentStage) queue.push(RestartStage(trigger.parentExecution, parentStage.id, message.user)) } /** * Inform the parent stage when it restarts that the child is already running */ private fun StageExecution.addSkipRestart() { context["_skipPipelineRestart"] = true } private fun StageExecution.addRestartDetails(user: String?) { context["restartDetails"] = mapOf( "restartedBy" to (user ?: "anonymous"), "restartTime" to clock.millis(), "previousException" to context.remove("exception") ) } private fun StageExecution.reset() { if (status.isComplete) { status = NOT_STARTED startTime = null endTime = null tasks = emptyList() builder().prepareStageForRestart(this) repository.storeStage(this) removeSynthetics() } downstreamStages().forEach { it.reset() } } private fun StageExecution.removeSynthetics() { execution .stages .filter { it.parentStageId == id } .forEach { it.removeSynthetics() repository.removeStage(execution, it.id) } } }
apache-2.0
afd297762e195d033ab26e73464ba6ca
35
121
0.731005
4.50414
false
false
false
false
GunoH/intellij-community
plugins/devkit/devkit-kotlin-tests/testData/inspections/useDPIAwareInsets/UseJBUIInsetsThatCanBeSimplified.kt
2
2401
import com.intellij.util.ui.JBUI import java.awt.Insets class UseJBUIInsetsThatCanBeSimplified { companion object { private val INSETS_CONSTANT_CAN_BE_SIMPLIFIED: Insets = JBUI.<warning descr="Insets creation can be simplified">insets(0)</warning> private val INSETS_CONSTANT_CORRECT1: Insets = JBUI.insets(1, 2, 3, 4) // correct private val INSETS_CONSTANT_CORRECT2: Insets = JBUI.insets(1) // correct private const val ZERO = 0 private const val ONE = 1 } @Suppress("UNUSED_VARIABLE") fun any() { // cases that can be simplified: JBUI.<warning descr="Insets creation can be simplified">insets(0)</warning> val insets1 = JBUI.<warning descr="Insets creation can be simplified">insets(0)</warning> takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(0)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(0, 0)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(1, 1)</warning>) // all the same takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(0, 0, 0, 0)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(1, 1, 1, 1)</warning>) // 1st == 3rd and 2nd == 4th takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(1, 2, 1, 2)</warning>) // 3 zeros takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(1, 0, 0, 0)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(0, 1, 0, 0)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(0, 0, 1, 0)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(0, 0, 0, 1)</warning>) // static import: JBUI.<warning descr="Insets creation can be simplified">insets(0)</warning> // constant used to check expressions evaluation: takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(ONE, ZERO, 0, ZERO)</warning>) takeInsets(JBUI.<warning descr="Insets creation can be simplified">insets(ONE, 2, ONE, 2)</warning>) // correct cases: JBUI.insets(1) JBUI.insets(1, 2) JBUI.insets(1, 1, 0, 0) JBUI.insets(1, 2, 3, 4) } @Suppress("UNUSED_PARAMETER") private fun takeInsets(insets: Insets) { // do nothing } }
apache-2.0
ea71fc48876329f1137129cd73bf74f0
43.462963
135
0.697209
3.823248
false
false
false
false
550609334/Twobbble
app/src/main/java/com/twobbble/tools/RxHelper.kt
1
2902
package com.twobbble.tools import io.reactivex.ObservableTransformer import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * Created by liuzipeng on 2017/2/21. */ class RxHelper { companion object { /** * 输入输出都为List的observable模板 * * @param subscribeThread 订阅的线程 * @param unSubscribeThread 解除订阅的线程 * @param observeThread 结果返回的线程 */ fun <T> listModeThread(subscribeThread: Scheduler? = Schedulers.io(), unSubscribeThread: Scheduler? = Schedulers.io(), observeThread: Scheduler? = AndroidSchedulers.mainThread()): ObservableTransformer<MutableList<T>, MutableList<T>> { return ObservableTransformer { it.onErrorResumeNext(NetExceptionHandler.HttpResponseFunc()) .retry(Constant.RX_RETRY_TIME) .subscribeOn(subscribeThread). unsubscribeOn(unSubscribeThread). observeOn(observeThread) } } /** * 输入输出都为单个对象的observable模板 * * @param subscribeThread 订阅的线程 * @param unSubscribeThread 解除订阅的线程 * @param observeThread 结果返回的线程 */ fun <T> singleModeThread(subscribeThread: Scheduler? = Schedulers.io(), unSubscribeThread: Scheduler? = Schedulers.io(), observeThread: Scheduler? = AndroidSchedulers.mainThread()): ObservableTransformer<T, T> { return ObservableTransformer { it.onErrorResumeNext(NetExceptionHandler.HttpResponseFunc()) .retry(Constant.RX_RETRY_TIME) .subscribeOn(subscribeThread). unsubscribeOn(unSubscribeThread). observeOn(observeThread) } } /** * 输入输出都为单个对象的observable模板 * * @param subscribeThread 订阅的线程 * @param unSubscribeThread 解除订阅的线程 * @param observeThread 结果返回的线程 */ fun <T> singleModeThreadNormal(subscribeThread: Scheduler? = Schedulers.io(), unSubscribeThread: Scheduler? = Schedulers.io(), observeThread: Scheduler? = AndroidSchedulers.mainThread()): ObservableTransformer<T, T> { return ObservableTransformer { it.subscribeOn(subscribeThread). unsubscribeOn(unSubscribeThread). observeOn(observeThread) } } } }
apache-2.0
c0611efbdf3c303fb927fdc652614663
38.985294
147
0.564018
5.502024
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/config/auth/NullAuthenticator.kt
1
899
package com.maubis.scarlet.base.config.auth import android.content.Context import com.maubis.scarlet.base.support.ui.ThemedActivity class NullAuthenticator : IAuthenticator { override fun openLoginActivity(context: Context): Runnable? = null override fun openForgetMeActivity(context: Context): Runnable? = null override fun openTransferDataActivity(context: Context): Runnable? = null override fun openLogoutActivity(context: Context): Runnable? = null override fun logout() {} override fun setup(context: Context) {} override fun userId(context: Context): String? = null override fun isLoggedIn(context: Context): Boolean = false override fun isLegacyLoggedIn(): Boolean = false override fun setPendingUploadListener(listener: IPendingUploadListener?) {} override fun requestSync(forced: Boolean) {} override fun showPendingSync(activity: ThemedActivity) {} }
gpl-3.0
0cf9362e397addc548eed2ed14883493
28.032258
77
0.776418
4.610256
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/SimplifiableCallInspection.kt
2
7982
// 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.inspections.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.receiverType import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class SimplifiableCallInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(callExpression) { val calleeExpression = callExpression.calleeExpression ?: return val (conversion, resolvedCall) = callExpression.findConversionAndResolvedCall() ?: return if (!conversion.callChecker(resolvedCall)) return val replacement = conversion.analyzer(callExpression) ?: return holder.registerProblem( calleeExpression, KotlinBundle.message("0.call.could.be.simplified.to.1", conversion.shortName, replacement), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, SimplifyCallFix(conversion, replacement) ) }) private fun KtCallExpression.findConversionAndResolvedCall(): Pair<Conversion, ResolvedCall<*>>? { val calleeText = calleeExpression?.text ?: return null val resolvedCall: ResolvedCall<*>? by lazy { this.resolveToCall() } for (conversion in conversions) { if (conversion.shortName != calleeText) continue if (resolvedCall?.isCalling(conversion.fqName) == true) { return conversion to resolvedCall!! } } return null } private data class Conversion( val callFqName: String, val analyzer: (KtCallExpression) -> String?, val callChecker: (ResolvedCall<*>) -> Boolean = { true } ) { val fqName = FqName(callFqName) val shortName = fqName.shortName().asString() } companion object { private fun KtCallExpression.singleLambdaExpression(): KtLambdaExpression? { val argument = valueArguments.singleOrNull() ?: return null return (argument as? KtLambdaArgument)?.getLambdaExpression() ?: argument.getArgumentExpression() as? KtLambdaExpression } private fun KtLambdaExpression.singleStatement(): KtExpression? = bodyExpression?.statements?.singleOrNull() private fun KtLambdaExpression.singleLambdaParameterName(): String? { val lambdaParameters = valueParameters return if (lambdaParameters.isNotEmpty()) lambdaParameters.singleOrNull()?.name else "it" } private fun KtExpression.isNameReferenceTo(name: String): Boolean = this is KtNameReferenceExpression && this.getReferencedName() == name private fun KtExpression.isNull(): Boolean = this is KtConstantExpression && this.node.elementType == KtNodeTypes.NULL private val conversions = listOf( Conversion("kotlin.collections.flatMap", fun(callExpression: KtCallExpression): String? { val lambdaExpression = callExpression.singleLambdaExpression() ?: return null val reference = lambdaExpression.singleStatement() ?: return null val lambdaParameterName = lambdaExpression.singleLambdaParameterName() ?: return null if (!reference.isNameReferenceTo(lambdaParameterName)) return null val receiverType = callExpression.receiverType() ?: return null if (KotlinBuiltIns.isPrimitiveArray(receiverType)) return null if (KotlinBuiltIns.isArray(receiverType) && receiverType.arguments.firstOrNull()?.type?.let { KotlinBuiltIns.isArray(it) } != true ) return null return "flatten()" }), Conversion("kotlin.collections.filter", analyzer = fun(callExpression: KtCallExpression): String? { val lambdaExpression = callExpression.singleLambdaExpression() ?: return null val lambdaParameterName = lambdaExpression.singleLambdaParameterName() ?: return null when (val statement = lambdaExpression.singleStatement() ?: return null) { is KtBinaryExpression -> { if (statement.operationToken != KtTokens.EXCLEQ && statement.operationToken != KtTokens.EXCLEQEQEQ) return null val left = statement.left ?: return null val right = statement.right ?: return null if (left.isNameReferenceTo(lambdaParameterName) && right.isNull() || right.isNameReferenceTo(lambdaParameterName) && left.isNull() ) { return "filterNotNull()" } } is KtIsExpression -> { if (statement.isNegated) return null if (!statement.leftHandSide.isNameReferenceTo(lambdaParameterName)) return null val rightTypeReference = statement.typeReference ?: return null val bindingContext = callExpression.analyze(BodyResolveMode.PARTIAL) val rightType = bindingContext[BindingContext.TYPE, rightTypeReference] val resolvedCall = callExpression.getResolvedCall(bindingContext) if (resolvedCall != null && rightType != null) { val resultingElementType = resolvedCall.resultingDescriptor.returnType ?.arguments?.singleOrNull()?.takeIf { !it.isStarProjection }?.type if (resultingElementType != null && !rightType.isSubtypeOf(resultingElementType)) { return null } } return "filterIsInstance<${rightTypeReference.text}>()" } } return null }, callChecker = fun(resolvedCall: ResolvedCall<*>): Boolean { val extensionReceiverType = resolvedCall.extensionReceiver?.type ?: return false return extensionReceiverType.constructor.declarationDescriptor?.defaultType?.isMap(extensionReceiverType.builtIns) == false }) ) } private class SimplifyCallFix(val conversion: Conversion, val replacement: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("simplify.call.fix.text", conversion.shortName, replacement) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return callExpression.replace(KtPsiFactory(callExpression).createExpression(replacement)) } } }
apache-2.0
bb403a109aa84857f27406a3bea7b356
51.860927
158
0.659484
6.019608
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/CoroutineUtils.kt
1
1724
// 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.core.util import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.Runnable import org.jetbrains.kotlin.idea.util.application.getServiceSafe import org.jetbrains.kotlin.idea.util.application.isDispatchThread import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext object EDT : CoroutineDispatcher() { override fun isDispatchNeeded(context: CoroutineContext): Boolean = !isDispatchThread() override fun dispatch(context: CoroutineContext, block: Runnable) { val modalityState = context[ModalityStateElement.Key]?.modalityState ?: ModalityState.defaultModalityState() ApplicationManager.getApplication().invokeLater(block, modalityState) } class ModalityStateElement(val modalityState: ModalityState) : AbstractCoroutineContextElement(Key) { companion object Key : CoroutineContext.Key<ModalityStateElement> } operator fun invoke(project: Project) = this + project.cancelOnDisposal } // job that is cancelled when the project is disposed val Project.cancelOnDisposal: Job get() = this.getServiceSafe<ProjectJob>().sharedJob internal class ProjectJob(project: Project) : Disposable { internal val sharedJob: Job = Job() override fun dispose() { sharedJob.cancel() } }
apache-2.0
73ab5742a7d33ee7f43fab6f576ba00c
39.093023
158
0.793503
4.911681
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt
1
32360
// 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.refactoring.introduce.extractionEngine import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.openapi.util.Key import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.inspections.PublicApiImplicitTypeInspection import org.jetbrains.kotlin.idea.inspections.UseExpressionBodyInspection import org.jetbrains.kotlin.idea.intentions.InfixCallToOrdinaryIntention import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeArgumentsIntention import org.jetbrains.kotlin.idea.refactoring.introduce.* import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.* import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValueBoxer.AsTuple import org.jetbrains.kotlin.idea.refactoring.removeTemplateEntryBracesIfPossible import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.psi.patternMatching.* import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnificationResult.StronglyMatched import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnificationResult.WeaklyMatched import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.isFlexible import java.util.* private fun buildSignature(config: ExtractionGeneratorConfiguration, renderer: DescriptorRenderer): CallableBuilder { val extractionTarget = config.generatorOptions.target if (!extractionTarget.isAvailable(config.descriptor)) { val message = KotlinBundle.message("error.text.can.t.generate.0.1", extractionTarget.targetName, config.descriptor.extractionData.codeFragmentText ) throw BaseRefactoringProcessor.ConflictsInTestsException(listOf(message)) } val builderTarget = when (extractionTarget) { ExtractionTarget.FUNCTION, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION -> CallableBuilder.Target.FUNCTION else -> CallableBuilder.Target.READ_ONLY_PROPERTY } return CallableBuilder(builderTarget).apply { val visibility = config.descriptor.visibility?.value ?: "" fun TypeParameter.isReified() = originalDeclaration.hasModifier(KtTokens.REIFIED_KEYWORD) val shouldBeInline = config.descriptor.typeParameters.any { it.isReified() } val annotations = if (config.descriptor.annotations.isEmpty()) { "" } else { config.descriptor.annotations.joinToString(separator = "\n", postfix = "\n") { renderer.renderAnnotation(it) } } val extraModifiers = config.descriptor.modifiers.map { it.value } + listOfNotNull(if (shouldBeInline) KtTokens.INLINE_KEYWORD.value else null) + listOfNotNull(if (config.generatorOptions.isConst) KtTokens.CONST_KEYWORD.value else null) val modifiers = if (visibility.isNotEmpty()) listOf(visibility) + extraModifiers else extraModifiers modifier(annotations + modifiers.joinToString(separator = " ")) typeParams( config.descriptor.typeParameters.map { val typeParameter = it.originalDeclaration val bound = typeParameter.extendsBound buildString { if (it.isReified()) { append(KtTokens.REIFIED_KEYWORD.value) append(' ') } append(typeParameter.name) if (bound != null) { append(" : ") append(bound.text) } } } ) fun KotlinType.typeAsString() = renderer.renderType(this) config.descriptor.receiverParameter?.let { val receiverType = it.parameterType val receiverTypeAsString = receiverType.typeAsString() receiver(if (receiverType.isFunctionType) "($receiverTypeAsString)" else receiverTypeAsString) } name(config.generatorOptions.dummyName ?: config.descriptor.name) config.descriptor.parameters.forEach { parameter -> param(parameter.name, parameter.parameterType.typeAsString()) } with(config.descriptor.returnType) { if (KotlinBuiltIns.isUnit(this) || isError || extractionTarget == ExtractionTarget.PROPERTY_WITH_INITIALIZER) { noReturnType() } else { returnType(typeAsString()) } } typeConstraints(config.descriptor.typeParameters.flatMap { it.originalConstraints }.map { it.text!! }) } } fun ExtractionGeneratorConfiguration.getSignaturePreview(renderer: DescriptorRenderer) = buildSignature(this, renderer).asString() fun ExtractionGeneratorConfiguration.getDeclarationPattern( descriptorRenderer: DescriptorRenderer = IdeDescriptorRenderers.SOURCE_CODE ): String { val extractionTarget = generatorOptions.target if (!extractionTarget.isAvailable(descriptor)) { throw BaseRefactoringProcessor.ConflictsInTestsException( listOf( KotlinBundle.message("error.text.can.t.generate.0.1", extractionTarget.targetName, descriptor.extractionData.codeFragmentText ) ) ) } return buildSignature(this, descriptorRenderer).let { builder -> builder.transform { for (i in generateSequence(indexOf('$')) { indexOf('$', it + 2) }) { if (i < 0) break insert(i + 1, '$') } } when (extractionTarget) { ExtractionTarget.FUNCTION, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION, ExtractionTarget.PROPERTY_WITH_GETTER -> builder.blockBody("$0") ExtractionTarget.PROPERTY_WITH_INITIALIZER -> builder.initializer("$0") ExtractionTarget.LAZY_PROPERTY -> builder.lazyBody("$0") } builder.asString() } } fun KotlinType.isSpecial(): Boolean { val classDescriptor = this.constructor.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.name.isSpecial || DescriptorUtils.isLocal(classDescriptor) } fun createNameCounterpartMap(from: KtElement, to: KtElement): Map<KtSimpleNameExpression, KtSimpleNameExpression> { return from.collectDescendantsOfType<KtSimpleNameExpression>().zip(to.collectDescendantsOfType<KtSimpleNameExpression>()).toMap() } class DuplicateInfo( val range: KotlinPsiRange, val controlFlow: ControlFlow, val arguments: List<String> ) fun ExtractableCodeDescriptor.findDuplicates(): List<DuplicateInfo> { fun processWeakMatch(match: WeaklyMatched, newControlFlow: ControlFlow): Boolean { val valueCount = controlFlow.outputValues.size val weakMatches = HashMap(match.weakMatches) val currentValuesToNew = HashMap<OutputValue, OutputValue>() fun matchValues(currentValue: OutputValue, newValue: OutputValue): Boolean { if ((currentValue is Jump) != (newValue is Jump)) return false if (currentValue.originalExpressions.zip(newValue.originalExpressions).all { weakMatches[it.first] == it.second }) { currentValuesToNew[currentValue] = newValue weakMatches.keys.removeAll(currentValue.originalExpressions) return true } return false } if (valueCount == 1) { matchValues(controlFlow.outputValues.first(), newControlFlow.outputValues.first()) } else { outer@ for (currentValue in controlFlow.outputValues) for (newValue in newControlFlow.outputValues) { if ((currentValue is ExpressionValue) != (newValue is ExpressionValue)) continue if (matchValues(currentValue, newValue)) continue@outer } } return currentValuesToNew.size == valueCount && weakMatches.isEmpty() } fun getControlFlowIfMatched(match: UnificationResult.Matched): ControlFlow? { val analysisResult = extractionData.copy(originalRange = match.range).performAnalysis() if (analysisResult.status != AnalysisResult.Status.SUCCESS) return null val newControlFlow = analysisResult.descriptor!!.controlFlow if (newControlFlow.outputValues.isEmpty()) return newControlFlow if (controlFlow.outputValues.size != newControlFlow.outputValues.size) return null val matched = when (match) { is StronglyMatched -> true is WeaklyMatched -> processWeakMatch(match, newControlFlow) else -> throw AssertionError("Unexpected unification result: $match") } return if (matched) newControlFlow else null } val unifierParameters = parameters.map { UnifierParameter(it.originalDescriptor, it.parameterType) } val unifier = KotlinPsiUnifier(unifierParameters, true) val scopeElement = getOccurrenceContainer() ?: return Collections.emptyList() val originalTextRange = extractionData.originalRange.getPhysicalTextRange() return extractionData .originalRange .match(scopeElement, unifier) .asSequence() .filter { !(it.range.getPhysicalTextRange().intersects(originalTextRange)) } .mapNotNull { match -> val controlFlow = getControlFlowIfMatched(match) val range = with(match.range) { (elements.singleOrNull() as? KtStringTemplateEntryWithExpression)?.expression?.toRange() ?: this } controlFlow?.let { DuplicateInfo(range, it, unifierParameters.map { param -> match.substitution.getValue(param).text!! }) } } .toList() } private fun ExtractableCodeDescriptor.getOccurrenceContainer(): PsiElement? { return extractionData.duplicateContainer ?: extractionData.targetSibling.parent } private fun makeCall( extractableDescriptor: ExtractableCodeDescriptor, declaration: KtNamedDeclaration, controlFlow: ControlFlow, rangeToReplace: KotlinPsiRange, arguments: List<String> ) { fun insertCall(anchor: PsiElement, wrappedCall: KtExpression): KtExpression? { val firstExpression = rangeToReplace.elements.firstOrNull { it is KtExpression } as? KtExpression if (firstExpression?.isLambdaOutsideParentheses() == true) { val functionLiteralArgument = firstExpression.getStrictParentOfType<KtLambdaArgument>()!! return functionLiteralArgument.moveInsideParenthesesAndReplaceWith(wrappedCall, extractableDescriptor.originalContext) } if (anchor is KtOperationReferenceExpression) { val newNameExpression = when (val operationExpression = anchor.parent as? KtOperationExpression ?: return null) { is KtUnaryExpression -> OperatorToFunctionIntention.convert(operationExpression).second is KtBinaryExpression -> { InfixCallToOrdinaryIntention.convert(operationExpression).getCalleeExpressionIfAny() } else -> null } return newNameExpression?.replaced(wrappedCall) } (anchor as? KtExpression)?.extractableSubstringInfo?.let { return it.replaceWith(wrappedCall) } return anchor.replaced(wrappedCall) } if (rangeToReplace !is KotlinPsiRange.ListRange) return val anchor = rangeToReplace.startElement val anchorParent = anchor.parent!! anchor.nextSibling?.let { from -> val to = rangeToReplace.endElement if (to != anchor) { anchorParent.deleteChildRange(from, to) } } val calleeName = declaration.name?.quoteIfNeeded() val callText = when (declaration) { is KtNamedFunction -> { val argumentsText = arguments.joinToString(separator = ", ", prefix = "(", postfix = ")") val typeArguments = extractableDescriptor.typeParameters.map { it.originalDeclaration.name } val typeArgumentsText = with(typeArguments) { if (isNotEmpty()) joinToString(separator = ", ", prefix = "<", postfix = ">") else "" } "$calleeName$typeArgumentsText$argumentsText" } else -> calleeName } val anchorInBlock = generateSequence(anchor) { it.parent }.firstOrNull { it.parent is KtBlockExpression } val block = (anchorInBlock?.parent as? KtBlockExpression) ?: anchorParent val psiFactory = KtPsiFactory(anchor.project) val newLine = psiFactory.createNewLine() if (controlFlow.outputValueBoxer is AsTuple && controlFlow.outputValues.size > 1 && controlFlow.outputValues .all { it is Initializer } ) { val declarationsToMerge = controlFlow.outputValues.map { (it as Initializer).initializedDeclaration } val isVar = declarationsToMerge.first().isVar if (declarationsToMerge.all { it.isVar == isVar }) { controlFlow.declarationsToCopy.subtract(declarationsToMerge).forEach { block.addBefore(psiFactory.createDeclaration(it.text!!), anchorInBlock) as KtDeclaration block.addBefore(newLine, anchorInBlock) } val entries = declarationsToMerge.map { p -> p.name + (p.typeReference?.let { ": ${it.text}" } ?: "") } anchorInBlock?.replace( psiFactory.createDestructuringDeclaration("${if (isVar) "var" else "val"} (${entries.joinToString()}) = $callText") ) return } } val inlinableCall = controlFlow.outputValues.size <= 1 val unboxingExpressions = if (inlinableCall) { controlFlow.outputValueBoxer.getUnboxingExpressions(callText ?: return) } else { val varNameValidator = NewDeclarationNameValidator(block, anchorInBlock, NewDeclarationNameValidator.Target.VARIABLES) val resultVal = KotlinNameSuggester.suggestNamesByType(extractableDescriptor.returnType, varNameValidator, null).first() block.addBefore(psiFactory.createDeclaration("val $resultVal = $callText"), anchorInBlock) block.addBefore(newLine, anchorInBlock) controlFlow.outputValueBoxer.getUnboxingExpressions(resultVal) } val copiedDeclarations = HashMap<KtDeclaration, KtDeclaration>() for (decl in controlFlow.declarationsToCopy) { val declCopy = psiFactory.createDeclaration<KtDeclaration>(decl.text!!) copiedDeclarations[decl] = block.addBefore(declCopy, anchorInBlock) as KtDeclaration block.addBefore(newLine, anchorInBlock) } if (controlFlow.outputValues.isEmpty()) { anchor.replace(psiFactory.createExpression(callText!!)) return } fun wrapCall(outputValue: OutputValue, callText: String): List<PsiElement> { return when (outputValue) { is ExpressionValue -> { val exprText = if (outputValue.callSiteReturn) { val firstReturn = outputValue.originalExpressions.asSequence().filterIsInstance<KtReturnExpression>().firstOrNull() val label = firstReturn?.getTargetLabel()?.text ?: "" "return$label $callText" } else { callText } Collections.singletonList(psiFactory.createExpression(exprText)) } is ParameterUpdate -> Collections.singletonList( psiFactory.createExpression("${outputValue.parameter.argumentText} = $callText") ) is Jump -> { when { outputValue.elementToInsertAfterCall == null -> Collections.singletonList(psiFactory.createExpression(callText)) outputValue.conditional -> Collections.singletonList( psiFactory.createExpression("if ($callText) ${outputValue.elementToInsertAfterCall.text}") ) else -> listOf( psiFactory.createExpression(callText), newLine, psiFactory.createExpression(outputValue.elementToInsertAfterCall.text!!) ) } } is Initializer -> { val newProperty = copiedDeclarations[outputValue.initializedDeclaration] as KtProperty newProperty.initializer = psiFactory.createExpression(callText) Collections.emptyList() } else -> throw IllegalArgumentException("Unknown output value: $outputValue") } } val defaultValue = controlFlow.defaultOutputValue controlFlow.outputValues .filter { it != defaultValue } .flatMap { wrapCall(it, unboxingExpressions.getValue(it)) } .withIndex() .forEach { val (i, e) = it if (i > 0) { block.addBefore(newLine, anchorInBlock) } block.addBefore(e, anchorInBlock) } defaultValue?.let { if (!inlinableCall) { block.addBefore(newLine, anchorInBlock) } insertCall(anchor, wrapCall(it, unboxingExpressions.getValue(it)).first() as KtExpression)?.removeTemplateEntryBracesIfPossible() } if (anchor.isValid) { anchor.delete() } } private var KtExpression.isJumpElementToReplace: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("IS_JUMP_ELEMENT_TO_REPLACE"), false) private var KtReturnExpression.isReturnForLabelRemoval: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("IS_RETURN_FOR_LABEL_REMOVAL"), false) fun ExtractionGeneratorConfiguration.generateDeclaration( declarationToReplace: KtNamedDeclaration? = null ): ExtractionResult { val psiFactory = KtPsiFactory(descriptor.extractionData.originalFile) fun getReturnsForLabelRemoval() = descriptor.controlFlow.outputValues .flatMapTo(arrayListOf()) { it.originalExpressions.filterIsInstance<KtReturnExpression>() } fun createDeclaration(): KtNamedDeclaration { descriptor.controlFlow.jumpOutputValue?.elementsToReplace?.forEach { it.isJumpElementToReplace = true } getReturnsForLabelRemoval().forEach { it.isReturnForLabelRemoval = true } return with(descriptor.extractionData) { if (generatorOptions.inTempFile) { createTemporaryDeclaration("${getDeclarationPattern()}\n") } else { psiFactory.createDeclarationByPattern( getDeclarationPattern(), PsiChildRange(originalElements.firstOrNull(), originalElements.lastOrNull()) ) } } } fun getReturnArguments(resultExpression: KtExpression?): List<KtExpression> { return descriptor.controlFlow.outputValues .mapNotNull { when (it) { is ExpressionValue -> resultExpression is Jump -> if (it.conditional) psiFactory.createExpression("false") else null is ParameterUpdate -> psiFactory.createExpression(it.parameter.nameForRef) is Initializer -> psiFactory.createExpression(it.initializedDeclaration.name!!) else -> throw IllegalArgumentException("Unknown output value: $it") } } } fun KtExpression.replaceWithReturn(replacingExpression: KtReturnExpression) { descriptor.controlFlow.defaultOutputValue?.let { val boxedExpression = replaced(replacingExpression).returnedExpression!! descriptor.controlFlow.outputValueBoxer.extractExpressionByValue(boxedExpression, it) } } fun getPublicApiInspectionIfEnabled(): PublicApiImplicitTypeInspection? { val project = descriptor.extractionData.project val inspectionProfileManager = ProjectInspectionProfileManager.getInstance(project) val inspectionProfile = inspectionProfileManager.currentProfile val state = inspectionProfile.getToolsOrNull("PublicApiImplicitType", project)?.defaultState ?: return null if (!state.isEnabled || state.level == HighlightDisplayLevel.DO_NOT_SHOW) return null return state.tool.tool as? PublicApiImplicitTypeInspection } fun useExplicitReturnType(): Boolean { if (descriptor.returnType.isFlexible()) return true val inspection = getPublicApiInspectionIfEnabled() ?: return false val targetClass = (descriptor.extractionData.targetSibling.parent as? KtClassBody)?.parent as? KtClassOrObject if ((targetClass != null && targetClass.isLocal) || descriptor.extractionData.isLocal()) return false val visibility = (descriptor.visibility ?: KtTokens.DEFAULT_VISIBILITY_KEYWORD).toVisibility() return when { visibility.isPublicAPI -> true inspection.reportInternal && visibility == DescriptorVisibilities.INTERNAL -> true inspection.reportPrivate && visibility == DescriptorVisibilities.PRIVATE -> true else -> false } } fun adjustDeclarationBody(declaration: KtNamedDeclaration) { val body = declaration.getGeneratedBody() (body.blockExpressionsOrSingle().singleOrNull() as? KtExpression)?.let { if (it.mustBeParenthesizedInInitializerPosition()) { it.replace(psiFactory.createExpressionByPattern("($0)", it)) } } val jumpValue = descriptor.controlFlow.jumpOutputValue if (jumpValue != null) { val replacingReturn = psiFactory.createExpression(if (jumpValue.conditional) "return true" else "return") body.collectDescendantsOfType<KtExpression> { it.isJumpElementToReplace }.forEach { it.replace(replacingReturn) it.isJumpElementToReplace = false } } body.collectDescendantsOfType<KtReturnExpression> { it.isReturnForLabelRemoval }.forEach { it.getTargetLabel()?.delete() it.isReturnForLabelRemoval = false } /* * Sort by descending position so that internals of value/type arguments in calls and qualified types are replaced * before calls/types themselves */ val currentRefs = body .collectDescendantsOfType<KtSimpleNameExpression> { it.resolveResult != null } .sortedByDescending { it.startOffset } currentRefs.forEach { val resolveResult = it.resolveResult!! val currentRef = if (it.isValid) { it } else { body.findDescendantOfType { expr -> expr.resolveResult == resolveResult } ?: return@forEach } val originalRef = resolveResult.originalRefExpr val newRef = descriptor.replacementMap[originalRef] .fold(currentRef as KtElement) { ref, replacement -> replacement(descriptor, ref) } (newRef as? KtSimpleNameExpression)?.resolveResult = resolveResult } if (generatorOptions.target == ExtractionTarget.PROPERTY_WITH_INITIALIZER) return if (body !is KtBlockExpression) throw AssertionError("Block body expected: ${descriptor.extractionData.codeFragmentText}") val firstExpression = body.statements.firstOrNull() if (firstExpression != null) { for (param in descriptor.parameters) { param.mirrorVarName?.let { varName -> body.addBefore(psiFactory.createProperty(varName, null, true, param.name), firstExpression) body.addBefore(psiFactory.createNewLine(), firstExpression) } } } val defaultValue = descriptor.controlFlow.defaultOutputValue val lastExpression = body.statements.lastOrNull() if (lastExpression is KtReturnExpression) return val defaultExpression = if (!generatorOptions.inTempFile && defaultValue != null && descriptor.controlFlow.outputValueBoxer .boxingRequired && lastExpression!!.isMultiLine() ) { val varNameValidator = NewDeclarationNameValidator(body, lastExpression, NewDeclarationNameValidator.Target.VARIABLES) val resultVal = KotlinNameSuggester.suggestNamesByType(defaultValue.valueType, varNameValidator, null).first() body.addBefore(psiFactory.createDeclaration("val $resultVal = ${lastExpression.text}"), lastExpression) body.addBefore(psiFactory.createNewLine(), lastExpression) psiFactory.createExpression(resultVal) } else lastExpression val returnExpression = descriptor.controlFlow.outputValueBoxer.getReturnExpression(getReturnArguments(defaultExpression), psiFactory) ?: return @Suppress("NON_EXHAUSTIVE_WHEN") when (generatorOptions.target) { ExtractionTarget.LAZY_PROPERTY, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION -> { // In the case of lazy property absence of default value means that output values are of OutputValue.Initializer type // We just add resulting expressions without return, since returns are prohibited in the body of lazy property if (defaultValue == null) { body.appendElement(returnExpression.returnedExpression!!) } return } } when { defaultValue == null -> body.appendElement(returnExpression) !defaultValue.callSiteReturn -> lastExpression!!.replaceWithReturn(returnExpression) } if (generatorOptions.allowExpressionBody) { val bodyExpression = body.statements.singleOrNull() val bodyOwner = body.parent as KtDeclarationWithBody val useExpressionBodyInspection = UseExpressionBodyInspection() if (bodyExpression != null && useExpressionBodyInspection.isActiveFor(bodyOwner)) { useExpressionBodyInspection.simplify(bodyOwner, !useExplicitReturnType()) } } } fun insertDeclaration(declaration: KtNamedDeclaration, anchor: PsiElement): KtNamedDeclaration { declarationToReplace?.let { return it.replace(declaration) as KtNamedDeclaration } return with(descriptor.extractionData) { val targetContainer = anchor.parent!! // TODO: Get rid of explicit new-lines in favor of formatter rules val emptyLines = psiFactory.createWhiteSpace("\n\n") if (insertBefore) { (targetContainer.addBefore(declaration, anchor) as KtNamedDeclaration).apply { targetContainer.addBefore(emptyLines, anchor) } } else { (targetContainer.addAfter(declaration, anchor) as KtNamedDeclaration).apply { if (!(targetContainer is KtClassBody && (targetContainer.parent as? KtClass)?.isEnum() == true)) { targetContainer.addAfter(emptyLines, anchor) } } } } } val duplicates = if (generatorOptions.inTempFile) Collections.emptyList() else descriptor.duplicates val anchor = with(descriptor.extractionData) { val targetParent = targetSibling.parent val anchorCandidates = duplicates.mapTo(arrayListOf()) { it.range.elements.first().substringContextOrThis } anchorCandidates.add(targetSibling) if (targetSibling is KtEnumEntry) { anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry }) } val marginalCandidate = if (insertBefore) { anchorCandidates.minByOrNull { it.startOffset }!! } else { anchorCandidates.maxByOrNull { it.startOffset }!! } // Ascend to the level of targetSibling marginalCandidate.parentsWithSelf.first { it.parent == targetParent } } val shouldInsert = !(generatorOptions.inTempFile || generatorOptions.target == ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION) val declaration = createDeclaration().let { if (shouldInsert) insertDeclaration(it, anchor) else it } adjustDeclarationBody(declaration) if (generatorOptions.inTempFile) return ExtractionResult(this, declaration, Collections.emptyMap()) val replaceInitialOccurrence = { val arguments = descriptor.parameters.map { it.argumentText } makeCall(descriptor, declaration, descriptor.controlFlow, descriptor.extractionData.originalRange, arguments) } if (!generatorOptions.delayInitialOccurrenceReplacement) replaceInitialOccurrence() if (shouldInsert) { ShortenReferences.DEFAULT.process(declaration) } if (generatorOptions.inTempFile) return ExtractionResult(this, declaration, emptyMap()) val duplicateReplacers = HashMap<KotlinPsiRange, () -> Unit>().apply { if (generatorOptions.delayInitialOccurrenceReplacement) { put(descriptor.extractionData.originalRange, replaceInitialOccurrence) } putAll(duplicates.map { it.range to { makeCall(descriptor, declaration, it.controlFlow, it.range, it.arguments) } }) } if (descriptor.typeParameters.isNotEmpty()) { for (ref in ReferencesSearch.search(declaration, LocalSearchScope(descriptor.getOccurrenceContainer()!!))) { val typeArgumentList = (ref.element.parent as? KtCallExpression)?.typeArgumentList ?: continue if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(typeArgumentList, false)) { typeArgumentList.delete() } } } if (declaration is KtProperty) { if (declaration.isExtensionDeclaration() && !declaration.isTopLevel) { val receiverTypeReference = (declaration as? KtCallableDeclaration)?.receiverTypeReference receiverTypeReference?.siblings(withItself = false)?.firstOrNull { it.node.elementType == KtTokens.DOT }?.delete() receiverTypeReference?.delete() } if ((declaration.descriptor as? PropertyDescriptor)?.let { DescriptorUtils.isOverride(it) } == true) { val scope = declaration.getResolutionScope() val newName = KotlinNameSuggester.suggestNameByName(descriptor.name) { it != descriptor.name && scope.getAllAccessibleVariables(Name.identifier(it)).isEmpty() } declaration.setName(newName) } } CodeStyleManager.getInstance(descriptor.extractionData.project).reformat(declaration) return ExtractionResult(this, declaration, duplicateReplacers) }
apache-2.0
b940df922e7da9a3f5ff2f39f44e8450
44.900709
158
0.675031
5.693174
false
false
false
false