repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/PackaddCommand.kt | 1 | 1225 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
// Currently support only matchit
class PackaddCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_REQUIRED, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
if (argument == "matchit" || (argument.startsWith("!") && argument.drop(1).trim() == "matchit")) {
injector.optionService.setOption(OptionScope.GLOBAL, "matchit")
}
return ExecutionResult.Success
}
}
| mit |
fcostaa/kotlin-rxjava-android | feature/base/src/main/kotlin/com/github/felipehjcosta/marvelapp/base/di/ApplicationModule.kt | 1 | 358 | package com.github.felipehjcosta.marvelapp.base.di
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class ApplicationModule {
@Singleton
@Provides
fun providesApplicationContext(application: Application): Context = application.applicationContext
}
| mit |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/attentionmechanism/AttentionMechanismLayer.kt | 1 | 2816 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.SoftmaxBase
import com.kotlinnlp.simplednn.core.layers.Layer
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
* The Attention Mechanism Layer Structure.
*
* @property inputArrays the input arrays of the layer
* @param inputType the input array type (default Dense)
* @param params the parameters which connect the input to the output
* @param activation the activation function of the layer (default SoftmaxBase)
*/
internal class AttentionMechanismLayer(
val inputArrays: List<AugmentedArray<DenseNDArray>>,
inputType: LayerType.Input,
override val params: AttentionMechanismLayerParameters,
activation: ActivationFunction? = SoftmaxBase()
) : Layer<DenseNDArray>(
inputArray = AugmentedArray(params.inputSize), // empty array (it should not be used)
inputType = inputType,
outputArray = AugmentedArray(inputArrays.size),
params = params,
activationFunction = activation,
dropout = 0.0
) {
/**
* A matrix containing the attention arrays as rows.
*/
internal val attentionMatrix: AugmentedArray<DenseNDArray> = AugmentedArray(
DenseNDArrayFactory.fromRows(this.inputArrays.map { it.values })
)
/**
* The helper which executes the forward.
*/
override val forwardHelper = AttentionMechanismForwardHelper(layer = this)
/**
* The helper which executes the backward.
*/
override val backwardHelper = AttentionMechanismBackwardHelper(layer = this)
/**
* The helper which calculates the relevance.
*/
override val relevanceHelper: RelevanceHelper? = null
/**
* Initialization: set the activation function of the output array.
*/
init {
require(this.inputArrays.isNotEmpty()) { "The attention sequence cannot be empty." }
require(this.inputArrays.all { it.values.length == this.params.inputSize }) {
"The input arrays must have the expected size (${this.params.inputSize})."
}
if (activation != null)
this.outputArray.setActivation(activation)
}
}
| mpl-2.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/widget/alltime/StatsAllTimeWidgetConfigureActivity.kt | 1 | 979 | package org.wordpress.android.ui.stats.refresh.lists.widget.alltime
import android.os.Bundle
import android.view.MenuItem
import org.wordpress.android.databinding.StatsAllTimeWidgetConfigureActivityBinding
import org.wordpress.android.ui.LocaleAwareActivity
class StatsAllTimeWidgetConfigureActivity : LocaleAwareActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
with(StatsAllTimeWidgetConfigureActivityBinding.inflate(layoutInflater)) {
setContentView(root)
setSupportActionBar(toolbar.toolbarMain)
}
supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
}
| gpl-2.0 |
Applandeo/Material-Calendar-View | library/src/main/java/com/applandeo/materialcalendarview/listeners/OnSelectDateListener.kt | 1 | 295 | package com.applandeo.materialcalendarview.listeners
import java.util.*
/**
* This interface is used to inform DatePicker that user selected any days
*
* Created by Applandeo Team.
*/
interface OnSelectDateListener {
@JvmSuppressWildcards
fun onSelect(calendar: List<Calendar>)
} | apache-2.0 |
DiUS/pact-jvm | core/model/src/main/kotlin/au/com/dius/pact/core/model/Pact.kt | 1 | 2802 | package au.com.dius.pact.core.model
import au.com.dius.pact.core.support.Json
import au.com.dius.pact.core.support.json.JsonValue
/**
* Pact Provider
*/
data class Provider @JvmOverloads constructor (val name: String = "provider") {
companion object {
@JvmStatic
fun fromJson(json: JsonValue): Provider {
if (json is JsonValue.Object && json.has("name") && json["name"] is JsonValue.StringValue) {
val name = Json.toString(json["name"])
return Provider(if (name.isEmpty()) "provider" else name)
}
return Provider("provider")
}
}
}
/**
* Pact Consumer
*/
data class Consumer @JvmOverloads constructor (val name: String = "consumer") {
companion object {
@JvmStatic
fun fromJson(json: JsonValue): Consumer {
if (json is JsonValue.Object && json.has("name") && json["name"] is JsonValue.StringValue) {
val name = Json.toString(json["name"])
return Consumer(if (name.isEmpty()) "consumer" else name)
}
return Consumer("consumer")
}
}
}
/**
* Interface to an interaction between a consumer and a provider
*/
interface Interaction {
/**
* Interaction description
*/
val description: String
/**
* Returns the provider states for this interaction
*/
val providerStates: List<ProviderState>
/**
* Checks if this interaction conflicts with the other one. Used for merging pact files.
*/
fun conflictsWith(other: Interaction): Boolean
/**
* Converts this interaction to a Map
*/
fun toMap(pactSpecVersion: PactSpecVersion): Map<*, *>
/**
* Generates a unique key for this interaction
*/
fun uniqueKey(): String
/**
* Interaction ID. Will only be populated from pacts loaded from a Pact Broker
*/
val interactionId: String?
}
/**
* Interface to a pact
*/
interface Pact<I : Interaction> {
/**
* Returns the provider of the service for the pact
*/
val provider: Provider
/**
* Returns the consumer of the service for the pact
*/
val consumer: Consumer
/**
* Returns all the interactions of the pact
*/
val interactions: List<I>
/**
* The source that this pact was loaded from
*/
val source: PactSource
/**
* Returns a pact with the interactions sorted
*/
fun sortInteractions(): Pact<I>
/**
* Returns a Map representation of this pact for the purpose of generating a JSON document.
*/
fun toMap(pactSpecVersion: PactSpecVersion): Map<String, *>
/**
* If this pact is compatible with the other pact. Pacts are compatible if they have the
* same provider and they are the same type
*/
fun compatibleTo(other: Pact<*>): Boolean
/**
* Merges all the interactions into this Pact
* @param interactions
*/
fun mergeInteractions(interactions: List<*>)
}
| apache-2.0 |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/fragments/devdb/DevDbHelper.kt | 1 | 995 | package forpdateam.ru.forpda.ui.fragments.devdb
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.util.SparseArray
object DevDbHelper {
private val colorFilters = SparseArray<ColorFilter>().apply {
put(1, PorterDuffColorFilter(Color.parseColor("#850113"), PorterDuff.Mode.SRC_IN))
put(2, PorterDuffColorFilter(Color.parseColor("#d50000"), PorterDuff.Mode.SRC_IN))
put(3, PorterDuffColorFilter(Color.parseColor("#ffac00"), PorterDuff.Mode.SRC_IN))
put(4, PorterDuffColorFilter(Color.parseColor("#99cc00"), PorterDuff.Mode.SRC_IN))
put(5, PorterDuffColorFilter(Color.parseColor("#339900"), PorterDuff.Mode.SRC_IN))
}
fun getColorFilter(rating: Int): ColorFilter {
return colorFilters.get(getRatingCode(rating))
}
fun getRatingCode(rating: Int): Int {
return Math.max(Math.round(rating / 2.0f), 1)
}
} | gpl-3.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/suppress/errorRecovery/unresolvedAnnotation.kt | 13 | 129 | // "Suppress 'REDUNDANT_NULLABLE' for fun foo" "true"
// ERROR: Unresolved reference: ann
@ann fun foo(): String?<caret>? = null | apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/code-insight/inspections-k2/tests/test/org/jetbrains/kotlin/idea/k2/intentions/tests/AbstractK2LocalInspectionTest.kt | 1 | 1331 | // 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.k2.intentions.tests
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import org.jetbrains.kotlin.idea.fir.highlighter.KotlinHighLevelDiagnosticHighlightingPass
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.AbstractLocalInspectionTest
import org.jetbrains.kotlin.test.utils.IgnoreTests
import java.io.File
abstract class AbstractK2LocalInspectionTest : AbstractLocalInspectionTest() {
override fun isFirPlugin() = true
override val inspectionFileName: String = ".k2Inspection"
override fun checkForUnexpectedErrors(fileText: String) {}
override fun collectHighlightInfos(): List<HighlightInfo> {
return KotlinHighLevelDiagnosticHighlightingPass.ignoreThisPassInTests { super.collectHighlightInfos() }
}
override fun doTestFor(mainFile: File, inspection: AbstractKotlinInspection, fileText: String) {
IgnoreTests.runTestIfNotDisabledByFileDirective(mainFile.toPath(), IgnoreTests.DIRECTIVES.IGNORE_FIR, "after") {
super.doTestFor(mainFile, inspection, fileText)
}
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/for/nameConflict5.kt | 13 | 199 | internal class A {
fun foo(p: Boolean) {
if (p) {
val i = 10
}
var i = 1
while (i < 1000) {
println(i)
i *= 2
}
}
} | apache-2.0 |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/signin/SignInModule.kt | 1 | 251 | package net.squanchy.signin
import dagger.Module
import dagger.Provides
import net.squanchy.service.repository.AuthService
@Module
internal class SignInModule {
@Provides
fun service(authService: AuthService) = SignInService(authService)
}
| apache-2.0 |
hermantai/samples | kotlin/Mastering-Kotlin-master/Chapter04/src/Player.kt | 1 | 302 | class Player : Movable, Drawable {
override fun move(currentTime: Long) {
// add logic
}
override fun draw() {
// add logic
}
override fun update(currentTime: Long) {
super<Movable>.update(currentTime)
super<Drawable>.update(currentTime)
}
}
| apache-2.0 |
TealCube/facecore | src/main/kotlin/io/pixeloutlaw/minecraft/spigot/hilt/BannerType.kt | 1 | 2756 | /*
* The MIT License
* Copyright © 2015 Pixel Outlaw
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.pixeloutlaw.minecraft.spigot.hilt
import org.bukkit.Material
enum class BannerType(val mat: Material) {
BLACK_BANNER(Material.BLACK_BANNER),
BLACK_WALL_BANNER(Material.BLACK_WALL_BANNER),
BLUE_BANNER(Material.BLUE_BANNER),
BLUE_WALL_BANNER(Material.BLUE_WALL_BANNER),
BROWN_BANNER(Material.BROWN_BANNER),
BROWN_WALL_BANNER(Material.BROWN_WALL_BANNER),
CYAN_BANNER(Material.CYAN_BANNER),
CYAN_WALL_BANNER(Material.CYAN_WALL_BANNER),
GRAY_BANNER(Material.GRAY_BANNER),
GRAY_WALL_BANNER(Material.GRAY_WALL_BANNER),
GREEN_BANNER(Material.GREEN_BANNER),
GREEN_WALL_BANNER(Material.GREEN_WALL_BANNER),
LIGHT_BLUE_BANNER(Material.LIGHT_BLUE_BANNER),
LIGHT_BLUE_WALL_BANNER(Material.LIGHT_BLUE_WALL_BANNER),
LIGHT_GRAY_BANNER(Material.LIGHT_GRAY_BANNER),
LIGHT_GRAY_WALL_BANNER(Material.LIGHT_GRAY_WALL_BANNER),
LIME_BANNER(Material.LIME_BANNER),
LIME_WALL_BANNER(Material.LIME_WALL_BANNER),
MAGENTA_BANNER(Material.MAGENTA_BANNER),
MAGENTA_WALL_BANNER(Material.MAGENTA_WALL_BANNER),
ORANGE_BANNER(Material.ORANGE_BANNER),
ORANGE_WALL_BANNER(Material.ORANGE_WALL_BANNER),
PINK_BANNER(Material.PINK_BANNER),
PINK_WALL_BANNER(Material.PINK_WALL_BANNER),
PURPLE_BANNER(Material.PURPLE_BANNER),
PURPLE_WALL_BANNER(Material.PURPLE_WALL_BANNER),
RED_BANNER(Material.RED_BANNER),
RED_WALL_BANNER(Material.RED_WALL_BANNER),
WHITE_BANNER(Material.WHITE_BANNER),
WHITE_WALL_BANNER(Material.WHITE_WALL_BANNER),
YELLOW_BANNER(Material.YELLOW_BANNER),
YELLOW_WALL_BANNER(Material.YELLOW_WALL_BANNER)
} | isc |
siarhei-luskanau/android-iot-doorbell | app/src/androidTest/kotlin/siarhei/luskanau/iot/doorbell/AppImageListTest.kt | 1 | 1280 | package siarhei.luskanau.iot.doorbell
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavDeepLinkBuilder
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.filters.LargeTest
import org.junit.Rule
import siarhei.luskanau.iot.doorbell.navigation.NavRootDirections
import siarhei.luskanau.iot.doorbell.navigation.NavigationActivity
import kotlin.test.Test
import siarhei.luskanau.iot.doorbell.navigation.R as NavigationR
import siarhei.luskanau.iot.doorbell.ui.imagelist.R as ImageListR
@LargeTest
class AppImageListTest {
@get:Rule
val activityScenarioRule = activityScenarioRule<NavigationActivity>(
intent = NavDeepLinkBuilder(ApplicationProvider.getApplicationContext())
.setGraph(NavigationR.navigation.nav_app)
.setDestination(ImageListR.id.nav_image_list_xml)
.setArguments(
NavRootDirections.actionDoorbellListToImageList(
doorbellId = "doorbellId"
).arguments
)
.createTaskStackBuilder()
.intents
.first()
)
@Test
fun appTest() {
activityScenarioRule.scenario.moveToState(Lifecycle.State.RESUMED)
}
}
| mit |
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 |
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 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveAsMember/moveClassToTopLevelClassAndMakePrivate/before/specificImport.kt | 65 | 61 | import A.X as XX
fun bar(s: String) {
val t: XX = XX()
} | apache-2.0 |
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 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/intentions/destructuringInLambda/noIt.kt | 13 | 149 | data class XY(val x: String, val y: String)
fun convert(xy: XY, foo: (XY) -> String) = foo(xy)
fun foo(xy: XY) = convert(xy) <caret>{ it.x + it.y } | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/FakeKotlinLanguage.kt | 4 | 704 | // 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.util
import com.intellij.lang.Language
/**
* Presense of this class fixes a lot of red code in plugin.xml files, as the correct `KotlinLanguage` class comes in a binary form
* (from the Kotlin compiler).
*
* This is a temporary hack: resolution in plugin descriptor should be fixed, so it searches not only in project classes, but
* also in libraries.
*
* For instance checks, use `org.jetbrains.kotlin.idea.KotlinLanguage`.
*/
@Suppress("unused")
private class FakeKotlinLanguage : Language("kotlin") | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/sequence/psi/streams/positive/location/BetweenChainCallsAfterDot.kt | 13 | 762 | /*
* 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.
*/
import java.util.stream.Stream
fun main(args: Array<String>) {
Stream.<caret>of("abc", "acd", "ef").map({ it.length }).filter { x -> x!! % 2 == 0 }.count()
}
| apache-2.0 |
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 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantOverride/hashCode.kt | 8 | 139 | // PROBLEM: none
interface I {
override fun hashCode(): Int
}
class Test : I {
<caret>override fun hashCode() = super.hashCode()
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/removeSingleLambdaParameter/receiver.kt | 2 | 374 | // "Remove single lambda parameter declaration" "false"
// ACTION: Convert to anonymous function
// ACTION: Convert to multi-line lambda
// ACTION: Enable a trailing comma by default in the formatter
// ACTION: Remove explicit lambda parameter types (may break code)
// ACTION: Rename to _
fun ((Boolean) -> Unit).foo() {}
fun test() {
{ <caret>b: Boolean -> }.foo()
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/highlighterMetaInfo/Labels.kt | 9 | 229 | fun bar(block: () -> Int) = block()
fun foo(): Int {
bar label@ {
return@label 2
}
loop@ for (i in 1..100) {
break@loop
}
loop2@ for (i in 1..100) {
break@loop2
}
return 1
} | apache-2.0 |
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 |
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 |
StephenVinouze/KinApp | core/src/test/kotlin/com/github/stephenvinouze/core/ExampleUnitTest.kt | 1 | 405 | package com.github.stephenvinouze.core
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
class ExampleUnitTest {
@Test
@Throws(Exception::class)
fun addition_isCorrect() {
assertEquals(4, (2 + 2).toLong())
}
} | apache-2.0 |
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 |
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 |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/main/java/com/doctoror/particleswallpaper/userprefs/particlecolor/ParticleColorModuleProvider.kt | 1 | 1025 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.userprefs.particlecolor
import org.koin.dsl.module.module
private const val PARAM_VIEW = 0
fun provideModuleParticleColor() = module {
/*
* Parameter at index 0 must be a ParticleColorPreferenceView.
*/
factory {
ParticleColorPreferencePresenter(
get(),
get(),
get(),
it[PARAM_VIEW]
)
}
}
| apache-2.0 |
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 |
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 |
WilliamHester/Breadit-2 | app/app/src/main/java/me/williamhester/reddit/messages/VotableListMessage.kt | 1 | 190 | package me.williamhester.reddit.messages
import me.williamhester.reddit.models.Votable
/**
* Created by williamhester on 5/8/17.
*/
class VotableListMessage(val votables: List<Votable>)
| apache-2.0 |
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 |
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 |
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 |
sys1yagi/DroiDon | app/src/test/java/com/sys1yagi/mastodon/android/testtool/RxTestSchedulerRule.kt | 1 | 1042 | package com.sys1yagi.mastodon.android.testtool
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.TestScheduler
import org.junit.rules.ExternalResource
/**
* :cool: https://github.com/DroidKaigi/conference-app-2017/blob/master/app/src/test/java/io/github/droidkaigi/confsched2017/util/RxTestSchedulerRule.kt
*/
class RxTestSchedulerRule : ExternalResource() {
val testScheduler: TestScheduler = TestScheduler()
override fun before() {
RxJavaPlugins.reset()
RxJavaPlugins.setInitIoSchedulerHandler { testScheduler }
RxJavaPlugins.setIoSchedulerHandler { testScheduler }
RxAndroidPlugins.reset()
RxAndroidPlugins.setInitMainThreadSchedulerHandler { testScheduler }
RxAndroidPlugins.setMainThreadSchedulerHandler { testScheduler }
}
override fun after() {
RxJavaPlugins.reset()
RxAndroidPlugins.reset()
}
fun triggerActions(){
testScheduler.triggerActions()
}
}
| mit |
drakelord/wire | wire-tests/src/test/proto-kotlin/com/squareup/wire/protos/kotlin/SomeRequest.kt | 1 | 1785 | // Code generated by Wire protocol buffer compiler, do not edit.
// Source file: service_kotlin.proto
package com.squareup.wire.protos.kotlin
import com.squareup.wire.FieldEncoding
import com.squareup.wire.Message
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.ProtoReader
import com.squareup.wire.ProtoWriter
import com.squareup.wire.TagHandler
import kotlin.Deprecated
import kotlin.DeprecationLevel
import kotlin.Int
import kotlin.jvm.JvmField
import okio.ByteString
data class SomeRequest(val unknownFields: ByteString = ByteString.EMPTY) : Message<SomeRequest,
SomeRequest.Builder>(ADAPTER, unknownFields) {
@Deprecated(
message = "Shouldn't be used in Kotlin",
level = DeprecationLevel.HIDDEN
)
override fun newBuilder(): Builder = Builder(this.copy())
class Builder(private val message: SomeRequest) : Message.Builder<SomeRequest, Builder>() {
override fun build(): SomeRequest = message
}
companion object {
@JvmField
val ADAPTER: ProtoAdapter<SomeRequest> = object : ProtoAdapter<SomeRequest>(
FieldEncoding.LENGTH_DELIMITED,
SomeRequest::class.java
) {
override fun encodedSize(value: SomeRequest): Int =
value.unknownFields.size
override fun encode(writer: ProtoWriter, value: SomeRequest) {
writer.writeBytes(value.unknownFields)
}
override fun decode(reader: ProtoReader): SomeRequest {
val unknownFields = reader.forEachTag { tag ->
when (tag) {
else -> TagHandler.UNKNOWN_TAG
}
}
return SomeRequest(
unknownFields = unknownFields
)
}
override fun redact(value: SomeRequest): SomeRequest? = value.copy(
unknownFields = ByteString.EMPTY
)
}
}
}
| apache-2.0 |
google/ground-android | ground/src/main/java/com/google/android/ground/persistence/remote/firestore/schema/MultipleChoiceConverter.kt | 1 | 1438 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote.firestore.schema
import com.google.android.ground.model.task.MultipleChoice
import com.google.android.ground.model.task.Option
import com.google.android.ground.util.Enums.toEnum
import kotlinx.collections.immutable.toPersistentList
internal object MultipleChoiceConverter {
@JvmStatic
fun toMultipleChoice(em: TaskNestedObject): MultipleChoice {
var options: List<Option> = listOf()
if (em.options != null) {
options =
em.options.entries
.sortedBy { it.value.index }
.map { (key, value): Map.Entry<String, OptionNestedObject> ->
OptionConverter.toOption(key, value)
}
}
return MultipleChoice(
options.toPersistentList(),
toEnum(MultipleChoice.Cardinality::class.java, em.cardinality!!)
)
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/variableNameAndType/TopLevel.kt | 13 | 158 |
class Foo
class BarFoo
val f<caret>
// EXIST: { itemText: "foo", tailText: ": Foo (<root>)" }
// ABSENT: { itemText: "foo", tailText: ": BarFoo (<root>)" } | apache-2.0 |
mikepenz/FastAdapter | fastadapter/src/main/java/com/mikepenz/fastadapter/utils/Sort.kt | 1 | 202 | package com.mikepenz.fastadapter.utils
/**
* @author pa.gulko zTrap (14.12.2019)
*/
internal fun <T> MutableList<T>.trySortWith(comparator: Comparator<in T>?) {
comparator?.let { sortWith(it) }
} | apache-2.0 |
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 |
pr0stik/AndroidDev | Anko/KotlinManyLayout/app/src/test/java/com/example/foxy/kotlinmanylayout/ExampleUnitTest.kt | 1 | 358 | package com.example.foxy.kotlinmanylayout
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| gpl-3.0 |
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 |
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 |
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 |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/process/exec/ExecTimeoutException.kt | 2 | 325 | package com.intellij.ide.starter.process.exec
import kotlin.time.Duration
class ExecTimeoutException(private val processName: String,
private val timeout: Duration) : RuntimeException() {
override val message
get() = "Failed to wait for the process `$processName` to complete in $timeout"
} | apache-2.0 |
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 |
JetBrains/intellij-community | plugins/kotlin/idea/tests/testData/resolve/references/DefaultObjectAsReceiverForMemberPropertyInSuperType.kt | 1 | 205 | package t
interface Interface {
val some : Int get() = 1
}
open class A {
companion object Companion : Interface {
}
}
fun test() {
<caret>A.some
}
// REF: companion object of (t).A
| apache-2.0 |
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 |
fancylou/FancyFilePicker | fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/adapter/FilePickerViewPagerAdapter.kt | 1 | 721 | package net.muliba.fancyfilepickerlibrary.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
/**
* Created by fancylou on 10/23/17.
*/
class FilePickerViewPagerAdapter(fm: FragmentManager, val tabs:Array<String>, val fragments:ArrayList<Fragment>) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment? = if(position < fragments.size)
{
fragments[position]
}else {
null
}
override fun getCount(): Int = tabs.size
override fun getPageTitle(position: Int): CharSequence = if (position < tabs.size)
{
tabs[position]
}else{
""
}
} | apache-2.0 |
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 |
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 |
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 |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/feature/Feature.kt | 1 | 10874 | package no.skatteetaten.aurora.boober.feature
import io.fabric8.kubernetes.api.model.HasMetadata
import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler
import no.skatteetaten.aurora.boober.model.AuroraConfigFileType.APP
import no.skatteetaten.aurora.boober.model.AuroraConfigFileType.BASE
import no.skatteetaten.aurora.boober.model.AuroraConfigFileType.ENV
import no.skatteetaten.aurora.boober.model.AuroraConfigFileType.GLOBAL
import no.skatteetaten.aurora.boober.model.AuroraConfigFileType.INCLUDE_ENV
import no.skatteetaten.aurora.boober.model.AuroraContextCommand
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import no.skatteetaten.aurora.boober.model.AuroraResource
import no.skatteetaten.aurora.boober.model.AuroraResourceSource
import no.skatteetaten.aurora.boober.model.ErrorType
import no.skatteetaten.aurora.boober.utils.boolean
import no.skatteetaten.aurora.boober.utils.durationString
import no.skatteetaten.aurora.boober.utils.notBlank
import no.skatteetaten.aurora.boober.utils.oneOf
import no.skatteetaten.aurora.boober.utils.allowedPattern
class FeatureKeyMissingException(
key: String,
keys: Set<String>
) : RuntimeException("The feature context key=$key was not found in the context. keys=$keys")
class FeatureWrongTypeException(
key: String,
throwable: Throwable
) : RuntimeException("The feature context key=$key was not the expected type ${throwable.localizedMessage}", throwable)
typealias FeatureContext = Map<String, Any>
@Suppress("UNCHECKED_CAST")
inline fun <reified T> FeatureContext.getContextKey(key: String): T {
val value = try {
this[key] as T?
} catch (e: Exception) {
throw FeatureWrongTypeException(key, e)
}
return value ?: throw FeatureKeyMissingException(key, this.keys)
}
interface Feature {
fun List<HasMetadata>.generateAuroraResources() = this.map { it.generateAuroraResource() }
fun HasMetadata.generateAuroraResource(header: Boolean = false) = generateResource(this, header)
fun generateResource(content: HasMetadata, header: Boolean = false) =
AuroraResource(content, AuroraResourceSource(this::class.java), header = header)
fun modifyResource(resource: AuroraResource, comment: String) =
resource.sources.add(AuroraResourceSource(this::class.java, comment = comment))
/**
Should this feature run or not.
You can either do this via Spring Conditional annotations to react to the environment,
or you can react on the header and toggle if you are active in that way.
If you look at BuildFeature you will see that it reacts on the Application.type to only enable
itself if the type is development
*/
fun enable(header: AuroraDeploymentSpec): Boolean = true
/**
Return a set of Handlers, see AuroraConfigFieldHandler for details on what a handler is
*/
fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler>
/**
Method to create a context for the given feature
This context will be sent to validate/generate/modify steps
The validationContext flag will let the the context know if the context should only be used for validation
You can throw an exception here and it will be registered as a validation error if you like
*/
fun createContext(spec: AuroraDeploymentSpec, cmd: AuroraContextCommand, validationContext: Boolean):
FeatureContext = emptyMap()
/**
Perform validation of this feature.
If this method throws it will be handled as a single error or multiple errors if ExceptionList
*/
fun validate(adc: AuroraDeploymentSpec, fullValidation: Boolean, context: FeatureContext):
List<Exception> = emptyList()
/**
Generate a set of AuroraResource from this feature
Resource generation of all features are run before the modify step occurs
If this method throws errors other features will still be run.
If any feature has thrown an error the process will stop
use the generateResource method in this interface as a helper to add the correct source
If you have more then one error throw an ExceptionList
*/
fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> = emptySet()
/**
Generate a set of AuroraResource from this feature
Functionally equal to generate except this generation is intended to be run sequentially and not in parallel
*/
fun generateSequentially(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> = emptySet()
/**
Modify generated resources
Resource modification of all features are run before the validate step occurs
If this method throws errors other features will still modify the resources.
If any feature has thrown an error the process will stop
use the modifyResource method in this interface as a helper to add a source to your modification
If you have more then one error throw an ExceptionList
*/
fun modify(adc: AuroraDeploymentSpec, resources: Set<AuroraResource>, context: FeatureContext) = Unit
}
enum class ApplicationPlatform(val baseImageName: String, val baseImageVersion: Int, val insecurePolicy: String) {
java("wingnut11", 2, "None"),
python("rumple39", 2, "None"),
web("wrench16", 1, "Redirect"),
doozer("turbo", 3, "None");
}
enum class TemplateType(
val isGroupIdRequired: Boolean = true,
val auroraGeneratedDeployment: Boolean = true
) {
cronjob(auroraGeneratedDeployment = false),
job(auroraGeneratedDeployment = false),
deploy,
development,
localTemplate(false, false),
template(false, false)
}
enum class DeploymentState {
deploymentConfig,
deployment
}
val AuroraDeploymentSpec.applicationPlatform: ApplicationPlatform get() = this["applicationPlatform"]
val AuroraDeploymentSpec.component: String get() = if (this.applicationPlatform == ApplicationPlatform.web) {
"frontend"
} else {
"backend"
}
class HeaderHandlers private constructor(defaultAppName: String, defaultEnvName: String) {
val handlers: Set<AuroraConfigFieldHandler>
val aboutFileTypes = setOf(GLOBAL, ENV, INCLUDE_ENV)
val appFileTypes = setOf(BASE, APP)
companion object {
fun create(defaultAppName: String, defaultEnvName: String) = HeaderHandlers(defaultAppName, defaultEnvName)
const val GLOBAL_FILE = "globalFile"
const val ENV_FILE = "envFile"
const val BASE_FILE = "baseFile"
}
init {
val validSchemaVersions = listOf("v1")
val envNamePattern = "^[a-z0-9\\-]{0,52}$"
val envNameMessage =
"Environment must consist of lower case alphanumeric characters or '-'. It must be no longer than 52 characters."
handlers = setOf(
AuroraConfigFieldHandler(
"schemaVersion",
validator = { it.oneOf(validSchemaVersions) }
),
AuroraConfigFieldHandler(
"type",
validator = { node -> node.oneOf(TemplateType.values().map { it.toString() }) }
),
// The value for jobs here will be wrong, but we do not use deployState for jobs.
AuroraConfigFieldHandler(
"deployState",
defaultValue = "deploymentConfig",
validator = { node -> node.oneOf(DeploymentState.values().map { it.toString() }) }
),
AuroraConfigFieldHandler(
"applicationPlatform",
defaultValue = "java",
validator = { node -> node.oneOf(ApplicationPlatform.values().map { it.toString() }) }
),
AuroraConfigFieldHandler(
"affiliation", validator = {
it.allowedPattern(
"^[a-z]{1,10}$",
"Affiliation can only contain letters and must be no longer than 10 characters"
)
},
allowedFilesTypes = aboutFileTypes
),
AuroraConfigFieldHandler("segment"),
AuroraConfigFieldHandler("cluster", validator = { it.notBlank("Cluster must be set") }),
AuroraConfigFieldHandler("permissions/admin", allowedFilesTypes = aboutFileTypes),
AuroraConfigFieldHandler("permissions/view", allowedFilesTypes = aboutFileTypes),
AuroraConfigFieldHandler("permissions/edit", allowedFilesTypes = aboutFileTypes),
AuroraConfigFieldHandler("permissions/adminServiceAccount", allowedFilesTypes = aboutFileTypes),
// Max length of OpenShift project names is 63 characters. Project name = affiliation + "-" + envName.
AuroraConfigFieldHandler(
"envName",
validator = { it.allowedPattern(envNamePattern, envNameMessage) },
defaultSource = "folderName",
defaultValue = defaultEnvName,
allowedFilesTypes = setOf(ENV)
),
AuroraConfigFieldHandler(
"name",
defaultValue = defaultAppName,
defaultSource = "fileName",
validator = {
it.allowedPattern(
"^[a-z][-a-z0-9]{0,38}[a-z0-9]$",
"The first character of name must be a letter [a-z] and the last character must be alphanumeric. Total length needs to be no more than 40 characters. The rest of the characters can be alphanumeric or a hyphen.",
false
)
},
allowedFilesTypes = appFileTypes
),
AuroraConfigFieldHandler(
"env/name",
validator = { it.allowedPattern(envNamePattern, envNameMessage, false) },
allowedFilesTypes = setOf(ENV)
),
AuroraConfigFieldHandler(
"env/ttl",
validator = { it.durationString() },
allowedFilesTypes = aboutFileTypes
),
AuroraConfigFieldHandler(
"env/autoDeploy",
validator = { it.boolean() },
defaultValue = false,
allowedFilesTypes = setOf(ENV, APP)
),
AuroraConfigFieldHandler(GLOBAL_FILE, allowedFilesTypes = setOf(BASE, ENV)),
AuroraConfigFieldHandler(ENV_FILE, allowedFilesTypes = setOf(APP), validationSeverity = ErrorType.WARNING),
AuroraConfigFieldHandler(BASE_FILE, allowedFilesTypes = setOf(APP), validationSeverity = ErrorType.WARNING),
AuroraConfigFieldHandler(
"includeEnvFile",
allowedFilesTypes = setOf(ENV),
validationSeverity = ErrorType.WARNING
)
)
}
}
| apache-2.0 |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/channels/ChannelUndeliveredElementTest.kt | 1 | 4708 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.channels
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.test.*
class ChannelUndeliveredElementTest : TestBase() {
@Test
fun testSendSuccessfully() = runTest {
runAllKindsTest { kind ->
val channel = kind.create<Resource> { it.cancel() }
val res = Resource("OK")
launch {
channel.send(res)
}
val ok = channel.receive()
assertEquals("OK", ok.value)
assertFalse(res.isCancelled) // was not cancelled
channel.close()
assertFalse(res.isCancelled) // still was not cancelled
}
}
@Test
fun testRendezvousSendCancelled() = runTest {
val channel = Channel<Resource> { it.cancel() }
val res = Resource("OK")
val sender = launch(start = CoroutineStart.UNDISPATCHED) {
assertFailsWith<CancellationException> {
channel.send(res) // suspends & get cancelled
}
}
sender.cancelAndJoin()
assertTrue(res.isCancelled)
}
@Test
fun testBufferedSendCancelled() = runTest {
val channel = Channel<Resource>(1) { it.cancel() }
val resA = Resource("A")
val resB = Resource("B")
val sender = launch(start = CoroutineStart.UNDISPATCHED) {
channel.send(resA) // goes to buffer
assertFailsWith<CancellationException> {
channel.send(resB) // suspends & get cancelled
}
}
sender.cancelAndJoin()
assertFalse(resA.isCancelled) // it is in buffer, not cancelled
assertTrue(resB.isCancelled) // send was cancelled
channel.cancel() // now cancel the channel
assertTrue(resA.isCancelled) // now cancelled in buffer
}
@Test
fun testUnlimitedChannelCancelled() = runTest {
val channel = Channel<Resource>(Channel.UNLIMITED) { it.cancel() }
val resA = Resource("A")
val resB = Resource("B")
channel.send(resA) // goes to buffer
channel.send(resB) // goes to buffer
assertFalse(resA.isCancelled) // it is in buffer, not cancelled
assertFalse(resB.isCancelled) // it is in buffer, not cancelled
channel.cancel() // now cancel the channel
assertTrue(resA.isCancelled) // now cancelled in buffer
assertTrue(resB.isCancelled) // now cancelled in buffer
}
@Test
fun testConflatedResourceCancelled() = runTest {
val channel = Channel<Resource>(Channel.CONFLATED) { it.cancel() }
val resA = Resource("A")
val resB = Resource("B")
channel.send(resA)
assertFalse(resA.isCancelled)
assertFalse(resB.isCancelled)
channel.send(resB)
assertTrue(resA.isCancelled) // it was conflated (lost) and thus cancelled
assertFalse(resB.isCancelled)
channel.close()
assertFalse(resB.isCancelled) // not cancelled yet, can be still read by receiver
channel.cancel()
assertTrue(resB.isCancelled) // now it is cancelled
}
@Test
fun testSendToClosedChannel() = runTest {
runAllKindsTest { kind ->
val channel = kind.create<Resource> { it.cancel() }
channel.close() // immediately close channel
val res = Resource("OK")
assertFailsWith<ClosedSendChannelException> {
channel.send(res) // send fails to closed channel, resource was not delivered
}
assertTrue(res.isCancelled)
}
}
private suspend fun runAllKindsTest(test: suspend CoroutineScope.(TestChannelKind) -> Unit) {
for (kind in TestChannelKind.values()) {
if (kind.viaBroadcast) continue // does not support onUndeliveredElement
try {
withContext(Job()) {
test(kind)
}
} catch(e: Throwable) {
error("$kind: $e", e)
}
}
}
private class Resource(val value: String) {
private val _cancelled = atomic(false)
val isCancelled: Boolean
get() = _cancelled.value
fun cancel() {
check(!_cancelled.getAndSet(true)) { "Already cancelled" }
}
}
@Test
fun testHandlerIsNotInvoked() = runTest { // #2826
val channel = Channel<Unit> {
expectUnreached()
}
expect(1)
launch {
expect(2)
channel.receive()
}
channel.send(Unit)
finish(3)
}
}
| apache-2.0 |
leafclick/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/issue/GradleIssueChecker.kt | 1 | 718 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.issue
import com.intellij.build.issue.BuildIssueChecker
import com.intellij.openapi.extensions.ExtensionPointName
import org.jetbrains.annotations.ApiStatus
/**
* @author Vladislav.Soroka
*/
@ApiStatus.Experimental
interface GradleIssueChecker : BuildIssueChecker<GradleIssueData> {
companion object {
internal val EP = ExtensionPointName.create<GradleIssueChecker>("org.jetbrains.plugins.gradle.issueChecker")
@JvmStatic
fun getKnownIssuesCheckList(): List<GradleIssueChecker> {
return EP.extensionList
}
}
}
| apache-2.0 |
leafclick/intellij-community | platform/configuration-store-impl/src/ModuleStateStorageManager.kt | 1 | 4600 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.components.*
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleEx
import com.intellij.openapi.module.impl.ModuleManagerImpl
import com.intellij.openapi.module.impl.getModuleNameByFilePath
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.io.FileNotFoundException
import java.nio.file.Path
import java.nio.file.Paths
@ApiStatus.Internal
open class ModuleStateStorageManager(macroSubstitutor: TrackingPathMacroSubstitutor, module: Module) : StateStorageManagerImpl("module", macroSubstitutor, module) {
override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation) = StoragePathMacros.MODULE_FILE
override fun pathRenamed(oldPath: String, newPath: String, event: VFileEvent?) {
try {
super.pathRenamed(oldPath, newPath, event)
}
finally {
val requestor = event?.requestor
if (requestor == null || requestor !is StateStorage /* not renamed as result of explicit rename */) {
val module = componentManager as ModuleEx
val oldName = module.name
module.rename(getModuleNameByFilePath(newPath), false)
(ModuleManager.getInstance(module.project) as? ModuleManagerImpl)?.fireModuleRenamedByVfsEvent(module, oldName)
}
}
}
override fun beforeElementLoaded(element: Element) {
val optionElement = Element("component").setAttribute("name", "DeprecatedModuleOptionManager")
val iterator = element.attributes.iterator()
for (attribute in iterator) {
if (attribute.name != ProjectStateStorageManager.VERSION_OPTION) {
iterator.remove()
optionElement.addContent(Element("option").setAttribute("key", attribute.name).setAttribute("value", attribute.value))
}
}
element.addContent(optionElement)
}
override fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
val componentIterator = elements.iterator()
for (component in componentIterator) {
if (component.getAttributeValue("name") == "DeprecatedModuleOptionManager") {
componentIterator.remove()
for (option in component.getChildren("option")) {
rootAttributes.put(option.getAttributeValue("key"), option.getAttributeValue("value"))
}
break
}
}
// need be last for compat reasons
rootAttributes.put(ProjectStateStorageManager.VERSION_OPTION, "4")
}
override val isExternalSystemStorageEnabled: Boolean
get() = (componentManager as Module?)?.project?.isExternalStorageEnabled ?: false
override fun createFileBasedStorage(path: String, collapsedPath: String, roamingType: RoamingType, rootTagName: String?): StateStorage {
return ModuleFileStorage(this, Paths.get(path), collapsedPath, rootTagName, roamingType, getMacroSubstitutor(collapsedPath), if (roamingType == RoamingType.DISABLED) null else compoundStreamProvider)
}
override fun getFileBasedStorageConfiguration(fileSpec: String) = moduleFileBasedStorageConfiguration
private class ModuleFileStorage(storageManager: ModuleStateStorageManager,
file: Path,
fileSpec: String,
rootElementName: String?,
roamingType: RoamingType,
pathMacroManager: PathMacroSubstitutor? = null,
provider: StreamProvider? = null) : MyFileStorage(storageManager, file, fileSpec, rootElementName, roamingType, pathMacroManager, provider) {
override fun handleVirtualFileNotFound() {
if (storageDataRef.get() == null && !storageManager.isExternalSystemStorageEnabled) {
throw FileNotFoundException(ProjectBundle.message("module.file.does.not.exist.error", file.toString()))
}
}
}
}
private val moduleFileBasedStorageConfiguration = object : FileBasedStorageConfiguration {
override val isUseVfsForWrite: Boolean
get() = true
// use VFS to load module file because it is refreshed and loaded into VFS in any case
override val isUseVfsForRead: Boolean
get() = true
}
| apache-2.0 |
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 |
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 |
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 |
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 |
code-helix/slatekit | src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/core/Patch.kt | 1 | 80 | package slatekit.apis.core
data class Patch(val name:String, val value:String)
| apache-2.0 |
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 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/simple/classObject.kt | 5 | 874 | // FILE: 1.kt
package test
inline fun inline(s: () -> String): String {
return s()
}
class InlineAll {
inline fun inline(s: () -> String): String {
return s()
}
companion object {
inline fun inline(s: () -> String): String {
return s()
}
}
}
// FILE: 2.kt
import test.*
fun testClassObjectCall(): String {
return InlineAll.inline({"classobject"})
}
fun testInstanceCall(): String {
val inlineX = InlineAll()
return inlineX.inline({"instance"})
}
fun testPackageCall(): String {
return inline({"package"})
}
fun box(): String {
if (testClassObjectCall() != "classobject") return "test1: ${testClassObjectCall()}"
if (testInstanceCall() != "instance") return "test2: ${testInstanceCall()}"
if (testPackageCall() != "package") return "test3: ${testPackageCall()}"
return "OK"
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/statementLikeLastExpression.kt | 2 | 634 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
var globalResult = ""
suspend fun suspendWithValue(v: String): String = suspendCoroutineOrReturn { x ->
x.resume(v)
COROUTINE_SUSPENDED
}
fun builder(c: suspend () -> String) {
c.startCoroutine(handleResultContinuation {
globalResult = it
})
}
fun box(): String {
var condition = true
builder {
if (condition) {
suspendWithValue("OK")
} else {
suspendWithValue("fail 1")
}
}
return globalResult
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/callableReference/bound/objectReceiver.kt | 3 | 71 | object Singleton {
fun ok() = "OK"
}
fun box() = (Singleton::ok)() | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/invertIfCondition/notBlock4.kt | 9 | 154 | // AFTER-WARNING: Parameter 'i' is never used
fun foo(b: Boolean) {
<caret>if (b) bar(1) // comment1
else bar(2) // comment2
}
fun bar(i: Int) {} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt | 39 | 155 | fun foo(param: Int): String {
val x = "a1234_"
val y = "-4123a"
val z = "+1243a"
val u = 123
return "ab<selection>123</selection>def"
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/replaceSizeCheckWithIsNotEmpty/list.kt | 10 | 89 | // WITH_STDLIB
fun foo() {
val listOf = listOf(1, 2, 3)
listOf.size<caret> > 0
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/sequence/streams/sequence/terminal/AnyTrue.kt | 13 | 125 | package streams.sequence.terminal
fun main(args: Array<String>) {
//Breakpoint!
sequenceOf(1, 2, 3, 4).any { it == 3 }
} | apache-2.0 |
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 |
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 |
serssp/reakt | reakt/src/main/kotlin/com/github/andrewoma/react/Util.kt | 3 | 369 | package com.github.andrewoma.react
fun check(condition: Boolean, message: String = "Assertion failed"): Unit {
if (!condition) {
throw Exception(message)
}
}
// Like the JS "debugger" statement. Launches the JS debugger
@native
val debugger: Any = noImpl
@native("Reakt.uniqueId") @Suppress("UNUSED_PARAMETER")
fun uniqueId(obj: Any): String = noImpl | mit |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartTest.kt | 1 | 1105 | package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.danar.comm.MsgBolusStart
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class)
class MsgBolusStartTest : DanaRTestBase() {
@Test fun runTest() {
`when`(constraintChecker.applyBolusConstraints(Constraint(anyObject()))).thenReturn(Constraint(0.0))
val packet = MsgBolusStart(injector, 1.0)
// test message decoding
val array = ByteArray(100)
putByteToArray(array, 0, 1)
packet.handleMessage(array)
Assert.assertEquals(true, packet.failed)
putByteToArray(array, 0, 2)
packet.handleMessage(array)
Assert.assertEquals(false, packet.failed)
}
} | agpl-3.0 |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/SubscriptionValidationRequest.kt | 1 | 163 | package com.habitrpg.android.habitica.models
class SubscriptionValidationRequest {
var transaction: Transaction? = null
var sku: String? = null
}
| gpl-3.0 |
Flank/flank | tool/filter/src/main/kotlin/flank/filter/internal/Test.kt | 1 | 1599 | package flank.filter.internal
import flank.filter.ShouldRun
internal object Test {
/**
* TestFilter similar to https://junit.org/junit4/javadoc/4.12/org/junit/runner/manipulation/Filter.html
*
* Annotations are tracked as all annotation filters must match on a test.
*
* @property describe - description of the filter
* @property shouldRun - lambda that returns if a TestMethod should be included in the test run
* **/
data class Filter(
val describe: String,
val shouldRun: ShouldRun,
val isAnnotation: Boolean = false
)
/**
* Supports arguments defined in androidx.test.internal.runner.RunnerArgs
*
* Multiple annotation arguments will result in the intersection.
* https://developer.android.com/reference/android/support/test/runner/AndroidJUnitRunner
* https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run
*/
internal object Target {
object Type {
const val TEST_CLASS = "class"
const val NOT_TEST_CLASS = "notClass"
const val TEST_SIZE = "size"
const val ANNOTATION = "annotation"
const val NOT_ANNOTATION = "notAnnotation"
const val TEST_PACKAGE = "package"
const val NOT_TEST_PACKAGE = "notPackage"
const val TEST_FILE = "testFile"
const val NOT_TEST_FILE = "notTestFile"
}
object Size {
const val LARGE = "large"
const val MEDIUM = "medium"
const val SMALL = "small"
}
}
}
| apache-2.0 |
fabmax/kool | kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/geometry/TriangleMeshGeometry.kt | 1 | 1522 | package de.fabmax.kool.physics.geometry
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.physics.MemoryStack
import de.fabmax.kool.physics.Physics
import de.fabmax.kool.physics.toPxVec3
import de.fabmax.kool.scene.geometry.IndexedVertexList
import physx.PxTriangleMeshGeometry
actual class TriangleMeshGeometry actual constructor(triangleMesh: TriangleMesh, scale: Vec3f) : CommonTriangleMeshGeometry(triangleMesh), CollisionGeometry {
override val pxGeometry: PxTriangleMeshGeometry
init {
Physics.checkIsLoaded()
MemoryStack.stackPush().use { mem ->
val s = scale.toPxVec3(mem.createPxVec3())
val r = mem.createPxQuat(0f, 0f, 0f, 1f)
val meshScale = mem.createPxMeshScale(s, r)
pxGeometry = PxTriangleMeshGeometry(triangleMesh.pxTriangleMesh, meshScale)
}
if (triangleMesh.releaseWithGeometry) {
if (triangleMesh.refCnt > 0) {
// PxTriangleMesh starts with a ref count of 1, only increment it if this is not the first
// geometry which uses it
triangleMesh.pxTriangleMesh.acquireReference()
}
triangleMesh.refCnt++
}
}
actual constructor(geometry: IndexedVertexList) : this(TriangleMesh(geometry))
override fun dispose(ctx: KoolContext) {
super.dispose(ctx)
if (triangleMesh.releaseWithGeometry) {
triangleMesh.pxTriangleMesh.release()
}
}
} | apache-2.0 |
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 |
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 |
siosio/intellij-community | plugins/kotlin/maven/tests/test/org/jetbrains/kotlin/idea/maven/KotlinMavenImportingTestCase.kt | 1 | 1867 | // 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.maven
import com.intellij.testFramework.RunAll
import com.intellij.util.ThrowableRunnable
import org.jetbrains.idea.maven.MavenImportingTestCase
import org.jetbrains.kotlin.config.ResourceKotlinRootType
import org.jetbrains.kotlin.config.SourceKotlinRootType
import org.jetbrains.kotlin.config.TestResourceKotlinRootType
import org.jetbrains.kotlin.config.TestSourceKotlinRootType
import org.jetbrains.kotlin.idea.test.KotlinSdkCreationChecker
abstract class KotlinMavenImportingTestCase : MavenImportingTestCase() {
private var sdkCreationChecker: KotlinSdkCreationChecker? = null
override fun setUp() {
super.setUp()
sdkCreationChecker = KotlinSdkCreationChecker()
}
override fun tearDown() {
RunAll.runAll(
ThrowableRunnable<Throwable> { sdkCreationChecker!!.removeNewKotlinSdk() },
ThrowableRunnable<Throwable> { super.tearDown() },
)
}
protected fun assertKotlinSources(moduleName: String, vararg expectedSources: String) {
doAssertContentFolders(moduleName, SourceKotlinRootType, *expectedSources)
}
protected fun assertKotlinResources(moduleName: String, vararg expectedSources: String) {
doAssertContentFolders(moduleName, ResourceKotlinRootType, *expectedSources)
}
protected fun assertKotlinTestSources(moduleName: String, vararg expectedSources: String) {
doAssertContentFolders(moduleName, TestSourceKotlinRootType, *expectedSources)
}
protected fun assertKotlinTestResources(moduleName: String, vararg expectedSources: String) {
doAssertContentFolders(moduleName, TestResourceKotlinRootType, *expectedSources)
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/combineEmptyStrings.kt | 4 | 60 | fun main(args: Array<String>){
val x = "" +<caret> ""
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/classToPackageFacade/AChild.kt | 5 | 37 | class AChild : A() {
fun j() {}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/annotations/ParameterAnnotation6.kt | 2 | 256 | // FIR_COMPARISON
val v = 1
enum class class InlineOption {
A, B
}
annotation class inlineOptions(val x: InlineOption)
fun foo(@inlineOptions(InlineOp<caret>) a: Int) { }
// INVOCATION_COUNT: 1
// EXIST: InlineOption
// ABSENT: String
// ABSENT: v
| apache-2.0 |
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 |
DevPicon/kotlin-workshop-androidtitlan | app/src/main/java/pe/devpicon/android/kotlinworkshopapp/data/mapper/CraftDataMapper.kt | 1 | 564 | package pe.devpicon.android.kotlinworkshopapp.data.mapper
import pe.devpicon.android.kotlinworkshopapp.data.entity.CraftEntity
import pe.devpicon.android.kotlinworkshopapp.mvp.model.CraftModel
/**
* Created by Armando on 7/5/2017.
*/
class CraftDataMapper {
fun mapFromEntity(craftEntity: CraftEntity): CraftModel = CraftModel(
craftEntity.name,
craftEntity.creator,
craftEntity.quantity,
craftEntity.state,
craftEntity.country,
craftEntity.imageUrl,
craftEntity.story)
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/property/valOnLibType.kt | 4 | 135 | // "Create extension property 'Int.foo'" "true"
// WITH_RUNTIME
class A<T>(val n: T)
fun test() {
val a: A<Int> = 2.<caret>foo
}
| apache-2.0 |
siosio/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/MarkdownNotifier.kt | 1 | 1864 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
object MarkdownNotifier {
val NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("Markdown")
fun notifyNetworkProblems(project: Project) {
NOTIFICATION_GROUP.createNotification(
MarkdownBundle.message("markdown.google.import.network.problems.msg"),
NotificationType.ERROR
).notify(project)
}
fun notifyPandocDetected(project: Project) {
NOTIFICATION_GROUP.createNotification(
MarkdownBundle.message("markdown.settings.pandoc.notification.detected"),
NotificationType.INFORMATION
).notify(project)
}
fun notifyPandocNotDetected(project: Project) {
NOTIFICATION_GROUP.createNotification(
MarkdownBundle.message("markdown.settings.pandoc.notification.not.detected"),
NotificationType.WARNING
).notify(project)
}
fun notifyPandocDetectionFailed(project: Project, @NlsSafe msg: String) {
NOTIFICATION_GROUP.createNotification(msg, NotificationType.ERROR).notify(project)
}
fun notifyIfConvertFailed(project: Project, @NlsSafe msg: String) {
NOTIFICATION_GROUP.createNotification(msg, NotificationType.ERROR).notify(project)
}
fun notifyOfSuccessfulExport(project: Project, @NlsSafe msg: String) {
NOTIFICATION_GROUP.createNotification(msg, NotificationType.INFORMATION).notify(project)
}
fun notifyAboutConversionWarning(project: Project, @NlsSafe msg: String) {
NOTIFICATION_GROUP.createNotification(msg, NotificationType.WARNING).notify(project)
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonMergeUtilTest.kt | 28 | 3717 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.comparison
class ComparisonMergeUtilTest : ComparisonMergeUtilTestBase() {
fun testSimpleCases() {
chars {
("" - "" - "")
("" - "" - "").matching()
changes()
test()
}
chars {
("xyz" - "xyz" - "xyz")
(" " - " " - " ").matching()
changes()
test()
}
chars {
("" - "" - "x")
("" - "" - "-").matching()
changes(mod(0, 0, 0, 0, 0, 1))
test()
}
chars {
("x" - "yx" - "x")
(" " - "- " - " ").matching()
test()
}
chars {
("x" - "xy" - "x")
(" " - " -" - " ").matching()
test()
}
chars {
("xyz" - "xYz" - "xyz")
(" - " - " - " - " - ").matching()
test()
}
chars {
("xyz" - "XyZ" - "xyz")
("- -" - "- -" - "- -").matching()
test()
}
}
fun testConflictTYpes() {
chars {
("abcd" - "abcd" - "abXcd")
(" " - " " - " - ").matching()
test()
}
chars {
("abXcd" - "abcd" - "abXcd")
(" - " - " " - " - ").matching()
test()
}
chars {
("abcd" - "abXcd" - "abXcd")
(" " - " - " - " - ").matching()
test()
}
chars {
("abcd" - "abXcd" - "abcd")
(" " - " - " - " ").matching()
test()
}
chars {
("abcd" - "abXcd" - "abYcd")
(" " - " - " - " - ").matching()
test()
}
chars {
("abXcd" - "abXcd" - "abYcd")
(" - " - " - " - " - ").matching()
test()
}
chars {
("abYcd" - "abXcd" - "abYcd")
(" - " - " - " - " - ").matching()
test()
}
chars {
("abYcd" - "abXcd" - "abZcd")
(" - " - " - " - " - ").matching()
test()
}
chars {
("abXcd" - "abcd" - "abYcd")
(" - " - " " - " - ").matching()
test()
}
}
fun testBoundaryConflicts() {
chars {
("abcd" - "abcd" - "abcdx")
(" " - " " - " -").matching()
test()
}
chars {
("abcd" - "abcdx" - "abcdx")
(" " - " -" - " -").matching()
test()
}
chars {
("abcd" - "abcdx" - "abcdy")
(" " - " -" - " -").matching()
test()
}
chars {
("abcdz" - "abcdx" - "abcdy")
(" -" - " -" - " -").matching()
test()
}
chars {
("xabcd" - "abcd" - "abcd")
("- " - " " - " ").matching()
test()
}
chars {
("xabcd" - "yabcd" - "abcd")
("- " - "- " - " ").matching()
test()
}
chars {
("abcd" - "yabcd" - "abcd")
(" " - "- " - " ").matching()
test()
}
}
fun testMultipleChanges() {
chars {
("XXbXcXXeX" - "XyXzXXnXkX" - "XqXXeXrXX")
(" - - - " - " - - - - " - " - - - ").matching()
test()
}
chars {
("Ax" - "z" - "zA")
("--" - "-" - "--").matching()
test()
}
chars {
("ayz" - "xyz" - "xyq")
("- -" - "- -" - "- -").matching()
test()
}
}
}
| apache-2.0 |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/models/FavoriteResponse.kt | 1 | 321 | package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class FavoriteResponse(
@JsonProperty("user_favorite") val userFavorite: Boolean
) | mit |
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 |
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 |
pengwei1024/sampleShare | kotlin-basic/src/delegate/NotNullExample.kt | 1 | 387 | package delegate
import kotlin.properties.Delegates
/**
* Created by pengwei on 2017/8/7.
*/
class User {
var name: String by Delegates.notNull()
fun init(name: String) {
this.name = name
}
}
fun main(args: Array<String>) {
val user = User()
print(user.name)
// user.name -> IllegalStateException
// user.init("Carl")
// println(user.name)
}
| apache-2.0 |
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 |
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 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/booleanLiteralArgument/booleanLiteral.kt | 13 | 164 | // HIGHLIGHT: GENERIC_ERROR_OR_WARNING
// FIX: Add 'c =' to argument
fun foo(a: Boolean, b: Boolean, c: Boolean) {}
fun test() {
foo(true, true, true<caret>)
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/detectProperties/GetterWithSideEffect3.kt | 13 | 162 | class C {
var x = ""
fun getX(): String {
println("getter invoked")
return x
}
fun setX(x: String) {
this.x = x
}
}
| apache-2.0 |
androidx/androidx | compose/ui/ui/src/test/kotlin/androidx/compose/ui/input/key/KeyInputModifierTest.kt | 3 | 2170 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.key
import androidx.compose.testutils.first
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.InspectableValue
import androidx.compose.ui.platform.ValueElement
import androidx.compose.ui.platform.isDebugInspectorInfoEnabled
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
class KeyInputModifierTest {
@Before
fun before() {
isDebugInspectorInfoEnabled = true
}
@After
fun after() {
isDebugInspectorInfoEnabled = false
}
@Test
fun testInspectorValueForKeyEvent() {
val onKeyEvent: (KeyEvent) -> Boolean = { true }
val modifier = Modifier.onKeyEvent(onKeyEvent).first() as InspectableValue
assertThat(modifier.nameFallback).isEqualTo("onKeyEvent")
assertThat(modifier.valueOverride).isNull()
assertThat(modifier.inspectableElements.asIterable()).containsExactly(
ValueElement("onKeyEvent", onKeyEvent)
)
}
@Test
fun testInspectorValueForPreviewKeyEvent() {
val onPreviewKeyEvent: (KeyEvent) -> Boolean = { true }
val modifier = Modifier.onPreviewKeyEvent(onPreviewKeyEvent).first() as InspectableValue
assertThat(modifier.nameFallback).isEqualTo("onPreviewKeyEvent")
assertThat(modifier.valueOverride).isNull()
assertThat(modifier.inspectableElements.asIterable()).containsExactly(
ValueElement("onPreviewKeyEvent", onPreviewKeyEvent)
)
}
}
| apache-2.0 |
tommykw/Musical | app/src/main/java/com/github/tommykw/musical/di/MainActivityModule.kt | 1 | 356 | package com.github.tommykw.musical.di
import com.github.tommykw.musical.ui.MainActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Suppress("unused")
@Module
abstract class MainActivityModule {
@ContributesAndroidInjector(modules = [FragmentBuildersModule::class])
abstract fun contributeMainActivity(): MainActivity
} | mit |