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
charleskorn/batect
app/src/journeyTest/kotlin/batect/journeytests/ContainerWithDependencyJourneyTest.kt
1
1896
/* Copyright 2017-2020 Charles Korn. 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 batect.journeytests import batect.journeytests.testutils.ApplicationRunner import batect.journeytests.testutils.itCleansUpAllContainersItCreates import batect.journeytests.testutils.itCleansUpAllNetworksItCreates import batect.testutils.createForGroup import batect.testutils.on import batect.testutils.runBeforeGroup import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.containsSubstring import com.natpryce.hamkrest.equalTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object ContainerWithDependencyJourneyTest : Spek({ describe("a task with a container with a dependency") { val runner by createForGroup { ApplicationRunner("container-with-dependency") } on("running that task") { val result by runBeforeGroup { runner.runApplication(listOf("the-task")) } it("displays the output from that task") { assertThat(result.output, containsSubstring("Status code for request: 200")) } it("returns the exit code from that task") { assertThat(result.exitCode, equalTo(0)) } itCleansUpAllContainersItCreates { result } itCleansUpAllNetworksItCreates { result } } } })
apache-2.0
charleskorn/batect
app/src/main/kotlin/batect/cli/options/OptionParser.kt
1
6305
/* Copyright 2017-2020 Charles Korn. 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 batect.cli.options import batect.cli.options.defaultvalues.DefaultValueProvider import batect.cli.options.defaultvalues.StandardFlagOptionDefaultValueProvider import batect.cli.options.defaultvalues.StaticDefaultValueProvider class OptionParser { private val options = mutableSetOf<OptionDefinition>() private val optionNames = mutableMapOf<String, OptionDefinition>() fun parseOptions(args: Iterable<String>): OptionsParsingResult { var argIndex = 0 while (argIndex < args.count()) { when (val optionParsingResult = parseOption(args, argIndex)) { is OptionParsingResult.ReadOption -> argIndex += optionParsingResult.argumentsConsumed is OptionParsingResult.InvalidOption -> return OptionsParsingResult.InvalidOptions(optionParsingResult.message) is OptionParsingResult.NoOption -> return checkDefaults(argIndex) } } return checkDefaults(argIndex) } private fun parseOption(args: Iterable<String>, currentIndex: Int): OptionParsingResult { val arg = args.elementAt(currentIndex) val argName = arg.substringBefore("=") val option = optionNames[argName] if (option == null) { if (argName.startsWith("-")) { return OptionParsingResult.InvalidOption("Invalid option '$argName'. Run './batect --help' for a list of valid options.") } else { return OptionParsingResult.NoOption } } return option.parse(args.drop(currentIndex)) } private fun checkDefaults(argumentsConsumed: Int): OptionsParsingResult { options.forEach { when (val result = it.checkDefaultValue()) { is DefaultApplicationResult.Failed -> return OptionsParsingResult.InvalidOptions("The default value for the ${it.longOption} option is invalid: ${result.message}") } } return OptionsParsingResult.ReadOptions(argumentsConsumed) } fun addOption(option: OptionDefinition) { if (optionNames.containsKey(option.longOption)) { throw IllegalArgumentException("An option with the name '${option.longName}' has already been added.") } if (option.shortOption != null && optionNames.containsKey(option.shortOption)) { throw IllegalArgumentException("An option with the name '${option.shortName}' has already been added.") } options.add(option) optionNames[option.longOption] = option if (option.shortOption != null) { optionNames[option.shortOption] = option } } fun getOptions(): Set<OptionDefinition> = options } interface OptionParserContainer { val optionParser: OptionParser fun valueOption(group: OptionGroup, longName: String, description: String, shortName: Char? = null) = valueOption(group, longName, description, ValueConverters::string, shortName) fun <V> valueOption(group: OptionGroup, longName: String, description: String, valueConverter: (String) -> ValueConversionResult<V>, shortName: Char? = null) = valueOption(group, longName, description, StaticDefaultValueProvider<V?>(null), valueConverter, shortName) fun valueOption(group: OptionGroup, longName: String, description: String, defaultValue: String, shortName: Char? = null) = valueOption(group, longName, description, defaultValue, ValueConverters::string, shortName) fun <StorageType, ValueType : StorageType> valueOption(group: OptionGroup, longName: String, description: String, defaultValue: StorageType, valueConverter: (String) -> ValueConversionResult<ValueType>, shortName: Char? = null) = valueOption(group, longName, description, StaticDefaultValueProvider(defaultValue), valueConverter, shortName) fun valueOption(group: OptionGroup, longName: String, description: String, defaultValueProvider: DefaultValueProvider<String>, shortName: Char? = null) = valueOption(group, longName, description, defaultValueProvider, ValueConverters::string, shortName) fun <StorageType, ValueType : StorageType> valueOption(group: OptionGroup, longName: String, description: String, defaultValueProvider: DefaultValueProvider<StorageType>, valueConverter: (String) -> ValueConversionResult<ValueType>, shortName: Char? = null) = ValueOption(group, longName, description, defaultValueProvider, valueConverter, shortName) fun flagOption(group: OptionGroup, longName: String, description: String, shortName: Char? = null) = flagOption(group, longName, description, StandardFlagOptionDefaultValueProvider, shortName) fun flagOption(group: OptionGroup, longName: String, description: String, defaultValueProvider: DefaultValueProvider<Boolean>, shortName: Char? = null) = FlagOption(group, longName, description, defaultValueProvider, shortName) fun mapOption(group: OptionGroup, longName: String, description: String, shortName: Char? = null) = MapOption(group, longName, description, shortName) fun mapOption(group: OptionGroup, longName: String, description: String, valueFormatForHelp: String, shortName: Char? = null) = MapOption(group, longName, description, shortName, valueFormatForHelp) } sealed class OptionsParsingResult { data class ReadOptions(val argumentsConsumed: Int) : OptionsParsingResult() data class InvalidOptions(val message: String) : OptionsParsingResult() } sealed class OptionParsingResult { data class ReadOption(val argumentsConsumed: Int) : OptionParsingResult() data class InvalidOption(val message: String) : OptionParsingResult() object NoOption : OptionParsingResult() }
apache-2.0
stoyicker/dinger
data/src/main/kotlin/data/tinder/recommendation/RecommendationProcessedFileDaoDelegate.kt
1
2062
package data.tinder.recommendation import data.database.CollectibleDaoDelegate import domain.recommendation.DomainRecommendationProcessedFile internal class RecommendationProcessedFileDaoDelegate( private val processedFileDao: RecommendationProcessedFileDao, private val photoProcessedFileDao: RecommendationPhoto_ProcessedFileDao, private val albumProcessedFileDao: RecommendationSpotifyAlbum_ProcessedFileDao) : CollectibleDaoDelegate<String, DomainRecommendationProcessedFile>() { override fun selectByPrimaryKey(primaryKey: String) = processedFileDao.selectProcessedFileByUrl(primaryKey).firstOrNull()?.let { return DomainRecommendationProcessedFile( widthPx = it.widthPx, url = it.url, heightPx = it.heightPx) } ?: DomainRecommendationProcessedFile.NONE override fun insertResolved(source: DomainRecommendationProcessedFile) = processedFileDao.insertProcessedFile(RecommendationUserPhotoProcessedFileEntity( widthPx = source.widthPx, url = source.url, heightPx = source.heightPx)) fun insertResolvedForPhotoId( photoId: String, processedFiles: Iterable<DomainRecommendationProcessedFile>) = processedFiles.forEach { insertResolved(it) photoProcessedFileDao.insertPhoto_ProcessedFile( RecommendationUserPhotoEntity_RecommendationUserPhotoProcessedFileEntity( recommendationUserPhotoEntityId = photoId, recommendationUserPhotoProcessedFileEntityUrl = it.url)) } fun insertResolvedForAlbumId( albumId: String, processedFiles: Iterable<DomainRecommendationProcessedFile>) = processedFiles.forEach { insertResolved(it) albumProcessedFileDao.insertSpotifyAlbum_ProcessedFile( RecommendationUserSpotifyThemeTrackAlbumEntity_RecommendationUserPhotoProcessedFileEntity( recommendationUserSpotifyThemeTrackAlbumEntityId = albumId, recommendationUserPhotoProcessedFileEntityUrl = it.url)) } }
mit
nrizzio/Signal-Android
core-util/src/main/java/org/signal/core/util/concurrent/TracedThreads.kt
2
443
package org.signal.core.util.concurrent import java.util.concurrent.ConcurrentHashMap /** * A container for keeping track of the caller stack traces of the threads we care about. * * Note: This should only be used for debugging. To keep overhead minimal, not much effort has been put into ensuring this map is 100% accurate. */ internal object TracedThreads { val callerStackTraces: MutableMap<Long, Throwable> = ConcurrentHashMap() }
gpl-3.0
androidx/androidx
health/health-services-client/src/main/java/androidx/health/services/client/data/MilestoneMarkerSummary.kt
3
4023
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client.data import androidx.health.services.client.proto.DataProto import androidx.health.services.client.proto.DataProto.AchievedExerciseGoal import androidx.health.services.client.proto.DataProto.MilestoneMarkerSummary.SummaryMetricsEntry import java.time.Duration import java.time.Instant /** * The summary of metrics and state from the previously achieved milestone marker [ExerciseGoal]. */ @Suppress("ParcelCreator") public class MilestoneMarkerSummary( /** Returns the time at which this milestone marker started being tracked. */ public val startTime: Instant, /** Returns the time at which this milestone marker was reached. */ public val endTime: Instant, /** * Returns the total elapsed time for which the exercise was active during this milestone, i.e. * started but not paused. */ public val activeDuration: Duration, /** The [ExerciseGoal] that triggered this milestone summary. */ public val achievedGoal: ExerciseGoal<out Number>, /** * Returns the [DataPointContainer] for aggregated metrics tracked between [startTime] and * [endTime] i.e. during the duration of this milestone. This summary will only contain * [DataPoint]s for [AggregateDataType]s. */ public val summaryMetrics: DataPointContainer, ) { internal constructor( proto: DataProto.MilestoneMarkerSummary ) : this( Instant.ofEpochMilli(proto.startTimeEpochMs), Instant.ofEpochMilli(proto.endTimeEpochMs), Duration.ofMillis(proto.activeDurationMs), ExerciseGoal.fromProto(proto.achievedGoal.exerciseGoal), DataPointContainer(proto.summaryMetricsList.map { DataPoint.fromProto(it.aggregateDataPoint) }) ) internal val proto: DataProto.MilestoneMarkerSummary = DataProto.MilestoneMarkerSummary.newBuilder() .setStartTimeEpochMs(startTime.toEpochMilli()) .setEndTimeEpochMs(endTime.toEpochMilli()) .setActiveDurationMs(activeDuration.toMillis()) .setAchievedGoal(AchievedExerciseGoal.newBuilder().setExerciseGoal(achievedGoal.proto)) .addAllSummaryMetrics( summaryMetrics.cumulativeDataPoints .map { SummaryMetricsEntry.newBuilder() .setDataType(it.dataType.proto) .setAggregateDataPoint(it.proto) .build() } // Sorting to ensure equals() works correctly. .sortedBy { it.dataType.name } ) .addAllSummaryMetrics( summaryMetrics.statisticalDataPoints .map { SummaryMetricsEntry.newBuilder() .setDataType(it.dataType.proto) .setAggregateDataPoint(it.proto) .build() } // Sorting to ensure equals() works correctly. .sortedBy { it.dataType.name } ) .build() override fun toString(): String = "MilestoneMarkerSummary(" + "startTime=$startTime, " + "endTime=$endTime, " + "achievedGoal=$achievedGoal, " + "summaryMetrics=$summaryMetrics)" }
apache-2.0
androidx/androidx
room/room-common/src/main/java/androidx/room/RewriteQueriesToDropUnusedColumns.kt
3
2693
/* * 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.room /** * When present, [RewriteQueriesToDropUnusedColumns] annotation will cause Room to * rewrite your [Query] methods such that only the columns that are used in the response are * queried from the database. * * This annotation is useful if you don't need all columns returned in a query but also don't * want to spell out their names in the query projection. * * For example, if you have a `User` class with 10 fields and want to return only * the `name` and `lastName` fields in a POJO, you could write the query like this: * * ``` * @Dao * interface MyDao { * @Query("SELECT * FROM User") * public fun getAll(): List<NameAndLastName> * } * * data class NameAndLastName ( * val name: String, * val lastName: String * ) * ``` * * Normally, Room would print a [RoomWarnings.CURSOR_MISMATCH] warning since the query result * has additional columns that are not used in the response. You can annotate the method with * [RewriteQueriesToDropUnusedColumns] to inform Room to rewrite your query at compile time to * avoid fetching extra columns. * * ``` * @Dao * interface MyDao { * @RewriteQueriesToDropUnusedColumns * @Query("SELECT * FROM User") * fun getAll(): List<NameAndLastName> * } * ``` * * At compile time, Room will convert this query to `SELECT name, lastName FROM (SELECT * * FROM User)` which gets flattened by **Sqlite** to `SELECT name, lastName FROM User`. * * When the annotation is used on a [Dao] method annotated with [Query], it will only * affect that query. You can put the annotation on the [Dao] annotated class/interface or * the [Database] annotated class where it will impact all methods in the dao / database * respectively. * * Note that Room will not rewrite the query if it has multiple columns that have the same name as * it does not yet have a way to distinguish which one is necessary. */ @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) public annotation class RewriteQueriesToDropUnusedColumns
apache-2.0
androidx/androidx
compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/AppBarSamples.kt
3
15788
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.BottomAppBar import androidx.compose.material3.BottomAppBarDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp /** * A sample for a simple use of small [TopAppBar]. * * The top app bar here does not react to any scroll events in the content under it. */ @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun SimpleTopAppBar() { Scaffold( topBar = { TopAppBar( title = { Text( "Simple TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } } ) }, content = { innerPadding -> LazyColumn( contentPadding = innerPadding, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } } ) } /** * A sample for a simple use of [CenterAlignedTopAppBar]. * * The top app bar here does not react to any scroll events in the content under it. */ @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun SimpleCenterAlignedTopAppBar() { Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text( "Centered TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } } ) }, content = { innerPadding -> LazyColumn( contentPadding = innerPadding, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } } ) } /** * A sample for a pinned small [TopAppBar]. * * The top app bar here is pinned to its location and changes its container color when the content * under it is scrolled. */ @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun PinnedTopAppBar() { val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { TopAppBar( title = { Text( "TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, actions = { // RowScope here, so these icons will be placed horizontally IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) }, content = { innerPadding -> LazyColumn( contentPadding = innerPadding, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } } ) } /** * A sample for a small [TopAppBar] that collapses when the content is scrolled up, and * appears when the content scrolled down. */ @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun EnterAlwaysTopAppBar() { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { TopAppBar( title = { Text( "TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) }, content = { innerPadding -> LazyColumn( contentPadding = innerPadding, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } } ) } /** * A sample for a [MediumTopAppBar] that collapses when the content is scrolled up, and * appears when the content is completely scrolled back down. */ @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun ExitUntilCollapsedMediumTopAppBar() { val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { MediumTopAppBar( title = { Text( "Medium TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) }, content = { innerPadding -> LazyColumn( contentPadding = innerPadding, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } } ) } /** * A sample for a [LargeTopAppBar] that collapses when the content is scrolled up, and * appears when the content is completely scrolled back down. */ @OptIn(ExperimentalMaterial3Api::class) @Preview @Sampled @Composable fun ExitUntilCollapsedLargeTopAppBar() { val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { LargeTopAppBar( title = { Text( "Large TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) }, content = { innerPadding -> LazyColumn( contentPadding = innerPadding, verticalArrangement = Arrangement.spacedBy(8.dp) ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) } } } ) } @Preview @Sampled @Composable fun SimpleBottomAppBar() { BottomAppBar { IconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Filled.Menu, contentDescription = "Localized description") } } } @Preview @Sampled @Composable fun BottomAppBarWithFAB() { BottomAppBar( actions = { IconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Filled.Check, contentDescription = "Localized description") } IconButton(onClick = { /* doSomething() */ }) { Icon( Icons.Filled.Edit, contentDescription = "Localized description", ) } }, floatingActionButton = { FloatingActionButton( onClick = { /* do something */ }, containerColor = BottomAppBarDefaults.bottomAppBarFabColor, elevation = FloatingActionButtonDefaults.bottomAppBarFabElevation() ) { Icon(Icons.Filled.Add, "Localized description") } } ) }
apache-2.0
bibaev/stream-debugger-plugin
src/main/java/com/intellij/debugger/streams/trace/impl/handler/type/ArrayTypeImpl.kt
1
1009
/* * 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.debugger.streams.trace.impl.handler.type /** * @author Vitaliy.Bibaev */ class ArrayTypeImpl(override val elementType: GenericType, toName: (String) -> String, private val toDefaultValue: (String) -> String) : ClassTypeImpl(toName.invoke(elementType.variableTypeName), toDefaultValue("1")), ArrayType { override fun sizedDeclaration(size: String): String = toDefaultValue(size) }
apache-2.0
willjgriff/android-ethereum-wallet
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/transactions/TransactionsController.kt
1
3359
package com.github.willjgriff.ethereumwallet.ui.screens.transactions import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.willjgriff.ethereumwallet.R import com.github.willjgriff.ethereumwallet.ethereum.transactions.model.DomainTransaction import com.github.willjgriff.ethereumwallet.mvp.BaseMvpControllerKotlin import com.github.willjgriff.ethereumwallet.ui.navigation.NavigationToolbarListener import com.github.willjgriff.ethereumwallet.ui.screens.transactions.adapters.TransactionsAdapter import com.github.willjgriff.ethereumwallet.ui.screens.transactions.di.injectPresenter import com.github.willjgriff.ethereumwallet.ui.screens.transactions.mvp.TransactionsPresenter import com.github.willjgriff.ethereumwallet.ui.screens.transactions.mvp.TransactionsView import com.github.willjgriff.ethereumwallet.ui.utils.inflate import com.github.willjgriff.ethereumwallet.ui.utils.listdecorator.EvenPaddingDecorator import com.jakewharton.rxbinding2.view.RxView import kotlinx.android.synthetic.main.controller_transactions.view.* import javax.inject.Inject /** * Created by williamgriffiths on 11/04/2017. */ class TransactionsController : BaseMvpControllerKotlin<TransactionsView, TransactionsPresenter>(), TransactionsView { override val mvpView: TransactionsView get() = this @Inject lateinit override var presenter: TransactionsPresenter private val TRANSACTIONS_LIST_ITEM_TOP_BOTTOM_PADDING_DP = 16 private val TRANSACTIONS_LIST_ITEM_LEFT_RIGHT_PADDING_DP = 8 private val transactionsAdapter: TransactionsAdapter = TransactionsAdapter() init { injectPresenter() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_transactions) setNavigationToolbarListener() bindViews(view) setupTransactionsList(view) return view } private fun bindViews(view: View) { val clearTxsButton = view.controller_transactions_clear_transactions val selectSearchRange = view.controller_transactions_search_in_range presenter.setObservables(RxView.clicks(clearTxsButton), RxView.clicks(selectSearchRange)) } private fun setNavigationToolbarListener() { val navigationToolbarListener = targetController if (navigationToolbarListener is NavigationToolbarListener) { navigationToolbarListener.setToolbarTitle(applicationContext?.getString(R.string.controller_transactions_title) ?: "") } } private fun setupTransactionsList(view: View) { view.controller_transactions_recycler_view.apply { layoutManager = LinearLayoutManager(applicationContext) adapter = transactionsAdapter addItemDecoration(EvenPaddingDecorator(TRANSACTIONS_LIST_ITEM_TOP_BOTTOM_PADDING_DP, TRANSACTIONS_LIST_ITEM_LEFT_RIGHT_PADDING_DP)) } } override fun addTransaction(transaction: DomainTransaction) { transactionsAdapter.addTransaction(transaction) } override fun clearTransactions() { transactionsAdapter.transactions = mutableListOf() } override fun displayRangeDialog() { SelectBlockRangeAlertDialog(activity!!).show() } }
apache-2.0
percolate/percolate-java-sdk
api/src/test/java/com/percolate/sdk/api/request/comment/CommentRequestTest.kt
1
805
package com.percolate.sdk.api.request.comment import com.percolate.sdk.api.BaseApiTest import com.percolate.sdk.dto.Comment import org.junit.Assert import org.junit.Test class CommentRequestTest : BaseApiTest() { @Test fun testGet() { val comments = percolateApi .comments() .get(CommentParams()) .execute() .body(); val commentsList = comments?.comments Assert.assertNotNull(commentsList) Assert.assertEquals(3, commentsList!!.size.toLong()) } @Test fun testCreate() { val commentData = percolateApi .comments() .create(Comment()) .execute() .body(); Assert.assertNotNull(commentData?.comment) } }
bsd-3-clause
codebutler/odyssey
retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/storage/StorageProviderRegistry.kt
1
1592
/* * GameLibraryProviderRegistry.kt * * Copyright (C) 2017 Retrograde Project * * 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.codebutler.retrograde.lib.storage import android.content.Context import android.content.SharedPreferences import com.codebutler.retrograde.lib.library.db.entity.Game class StorageProviderRegistry(context: Context, val providers: Set<StorageProvider>) { companion object { const val PREF_NAME = "storage_providers" } private val providersByScheme = mapOf(*providers.map { provider -> provider.uriSchemes.map { scheme -> scheme to provider } }.flatten().toTypedArray()) private val prefs: SharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) val enabledProviders: Iterable<StorageProvider> get() = providers.filter { prefs.getBoolean(it.id, it.enabledByDefault) } fun getProvider(game: Game) = providersByScheme[game.fileUri.scheme]!! }
gpl-3.0
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/openal/templates/AL_EXT_FLOAT32.kt
1
431
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.openal.templates import org.lwjgl.generator.* import org.lwjgl.openal.* val AL_EXT_FLOAT32 = "EXTFloat32".nativeClassAL("EXT_FLOAT32") { documentation = "Native bindings to the $extensionName extension." IntConstant( "Buffer formats.", "FORMAT_MONO_FLOAT32"..0x10010, "FORMAT_STEREO_FLOAT32"..0x10011 ) }
bsd-3-clause
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mcp/at/psi/mixins/impl/AtEntryImplMixin.kt
1
1365
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at.psi.mixins.impl import com.demonwav.mcdev.platform.mcp.at.AtElementFactory import com.demonwav.mcdev.platform.mcp.at.psi.mixins.AtEntryMixin import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode abstract class AtEntryImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), AtEntryMixin { override fun setEntry(entry: String) { replace(AtElementFactory.createEntry(project, entry)) } override fun setKeyword(keyword: AtElementFactory.Keyword) { this.keyword.replace(AtElementFactory.createKeyword(project, keyword)) } override fun setClassName(className: String) { this.className.replace(AtElementFactory.createClassName(project, className)) } override fun setFieldName(fieldName: String) { val newField = AtElementFactory.createFieldName(project, fieldName) replaceMember(newField) } override fun setFunction(function: String) { val atFunction = AtElementFactory.createFunction(project, function) replaceMember(atFunction) } override fun setAsterisk() { val asterisk = AtElementFactory.createAsterisk(project) replaceMember(asterisk) } }
mit
wealthfront/magellan
magellan-library/src/main/java/com/wealthfront/magellan/transitions/NoAnimationTransition.kt
1
345
package com.wealthfront.magellan.transitions import android.view.View import com.wealthfront.magellan.Direction public class NoAnimationTransition : MagellanTransition { override fun interrupt() {} override fun animate(from: View?, to: View, direction: Direction, onAnimationEndCallback: () -> Unit) { onAnimationEndCallback() } }
apache-2.0
inorichi/tachiyomi-extensions
src/pt/mangayabu/src/eu/kanade/tachiyomi/extension/pt/mangayabu/MangaYabu.kt
1
7507
package eu.kanade.tachiyomi.extension.pt.mangayabu import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.FormBody import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import java.text.ParseException import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class MangaYabu : ParsedHttpSource() { // Hardcode the id because the language wasn't specific. override val id: Long = 7152688036023311164 override val name = "MangaYabu!" override val baseUrl = "https://mangayabu.top" override val lang = "pt-BR" override val supportsLatest = true override val client: OkHttpClient = network.client.newBuilder() .connectTimeout(2, TimeUnit.MINUTES) .readTimeout(2, TimeUnit.MINUTES) .writeTimeout(2, TimeUnit.MINUTES) .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("User-Agent", USER_AGENT) .add("Origin", baseUrl) .add("Referer", baseUrl) override fun popularMangaRequest(page: Int): Request = GET(baseUrl, headers) override fun popularMangaSelector(): String = "#main div.row:contains(Populares) div.carousel div.card > a" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { val tooltip = element.select("div.card-image.mango-hover").first()!! title = Jsoup.parse(tooltip.attr("data-tooltip")).select("span b").first()!!.text() thumbnail_url = element.select("img").first()!!.attr("src") setUrlWithoutDomain(element.attr("href")) } override fun popularMangaNextPageSelector(): String? = null override fun fetchLatestUpdates(page: Int): Observable<MangasPage> { return super.fetchLatestUpdates(page) .map { MangasPage(it.mangas.distinctBy { m -> m.url }, it.hasNextPage) } } override fun latestUpdatesRequest(page: Int): Request = GET(baseUrl, headers) override fun latestUpdatesSelector() = "#main div.row:contains(Lançamentos) div.card" override fun latestUpdatesFromElement(element: Element): SManga = SManga.create().apply { title = element.select("div.card-content h4").first()!!.text().withoutFlags() thumbnail_url = element.select("div.card-image img").first()!!.attr("src") url = mapChapterToMangaUrl(element.select("div.card-image > a").first()!!.attr("href")) } override fun latestUpdatesNextPageSelector(): String? = null override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val form = FormBody.Builder() .add("action", "data_fetch") .add("search_keyword", query) .build() val newHeaders = headers.newBuilder() .add("X-Requested-With", "XMLHttpRequest") .add("Content-Length", form.contentLength().toString()) .add("Content-Type", form.contentType().toString()) .build() return POST("$baseUrl/wp-admin/admin-ajax.php", newHeaders, form) } override fun searchMangaSelector() = "ul.popup-list div.row > div.col.s4 a.search-links" override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply { val thumbnail = element.select("img").first()!! title = thumbnail.attr("alt").withoutFlags() thumbnail_url = thumbnail.attr("src") setUrlWithoutDomain(element.attr("href")) } override fun searchMangaNextPageSelector(): String? = null override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.manga-column") return SManga.create().apply { title = document.select("div.manga-info > h1").first()!!.text() status = infoElement.select("div.manga-column:contains(Status:)").first()!! .textWithoutLabel() .toStatus() genre = infoElement.select("div.manga-column:contains(Gêneros:)").first()!! .textWithoutLabel() description = document.select("div.manga-info").first()!!.text() .substringAfter(title) .trim() thumbnail_url = document.select("div.manga-index div.mango-hover img")!! .attr("src") } } override fun chapterListSelector() = "div.manga-info:contains(Capítulos) div.manga-chapters div.single-chapter" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { name = element.select("a").first()!!.text().substringAfter("–").trim() date_upload = element.select("small")!!.text().toDate() setUrlWithoutDomain(element.select("a").first()!!.attr("href")) } override fun pageListParse(document: Document): List<Page> { return document.select("div.image-navigator img.slideit") .mapIndexed { i, element -> Page(i, document.location(), element.attr("abs:src")) } } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { val newHeaders = headersBuilder() .set("Referer", page.url) .build() return GET(page.imageUrl!!, newHeaders) } /** * Some mangas doesn't use the same slug from the chapter url, and * since the site doesn't have a proper popular list yet, we have * to deal with some exceptions and map them to the correct * slug manually. * * It's a bad solution, but it's a working one for now. */ private fun mapChapterToMangaUrl(chapterUrl: String): String { val chapterSlug = chapterUrl .substringBefore("-capitulo") .substringAfter("ler/") return "/manga/" + (SLUG_EXCEPTIONS[chapterSlug] ?: chapterSlug) } private fun String.toDate(): Long { return try { DATE_FORMATTER.parse(this)?.time ?: 0L } catch (e: ParseException) { 0L } } private fun String.toStatus() = when (this) { "Em lançamento" -> SManga.ONGOING "Completo" -> SManga.COMPLETED else -> SManga.UNKNOWN } private fun String.withoutFlags(): String = replace(FLAG_REGEX, "").trim() private fun Element.textWithoutLabel(): String = text()!!.substringAfter(":").trim() companion object { private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36" private val FLAG_REGEX = "\\((Pt[-/]br|Scan)\\)".toRegex(RegexOption.IGNORE_CASE) private val DATE_FORMATTER by lazy { SimpleDateFormat("dd/MM/yy", Locale.ENGLISH) } private val SLUG_EXCEPTIONS = mapOf( "the-promised-neverland-yakusoku-no-neverland" to "yakusoku-no-neverland-the-promised-neverland" ) } }
apache-2.0
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/market/dto/MarketServicesViewType.kt
1
1628
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.market.dto import com.google.gson.annotations.SerializedName import kotlin.Int enum class MarketServicesViewType( val value: Int ) { @SerializedName("1") CARDS(1), @SerializedName("2") ROWS(2); }
mit
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/user/UserFragment.kt
1
17318
package com.intfocus.template.dashboard.user import android.app.Activity.RESULT_CANCELED import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Typeface import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.support.v4.content.FileProvider import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.PopupWindow import android.widget.RelativeLayout import com.bumptech.glide.Glide import com.bumptech.glide.request.target.BitmapImageViewTarget import com.google.gson.Gson import com.intfocus.template.ConfigConstants import com.intfocus.template.R import com.intfocus.template.constant.Params.USER_BEAN import com.intfocus.template.constant.Params.USER_NUM import com.intfocus.template.constant.ToastColor import com.intfocus.template.dashboard.feedback.FeedbackActivity import com.intfocus.template.dashboard.mine.activity.AlterPasswordActivity import com.intfocus.template.dashboard.mine.activity.FavoriteArticleActivity import com.intfocus.template.dashboard.mine.activity.SettingActivity import com.intfocus.template.dashboard.mine.activity.ShowPushMessageActivity import com.intfocus.template.general.net.ApiException import com.intfocus.template.general.net.CodeHandledSubscriber import com.intfocus.template.general.net.RetrofitUtil import com.intfocus.template.login.LoginActivity import com.intfocus.template.model.response.login.RegisterResult import com.intfocus.template.model.response.mine_page.UserInfoResult import com.intfocus.template.subject.one.UserContract import com.intfocus.template.subject.one.UserImpl import com.intfocus.template.subject.one.UserPresenter import com.intfocus.template.ui.BaseFragment import com.intfocus.template.util.ActionLogUtil import com.intfocus.template.util.DisplayUtil import com.intfocus.template.util.ImageUtil.* import com.intfocus.template.util.PageLinkManage import com.intfocus.template.util.ToastUtils import kotlinx.android.synthetic.main.activity_dashboard.* import kotlinx.android.synthetic.main.fragment_user.* import kotlinx.android.synthetic.main.item_mine_user_top.* import kotlinx.android.synthetic.main.items_single_value.* import kotlinx.android.synthetic.main.yh_custom_user.* import java.io.File /** * Created by liuruilin on 2017/6/7. */ class UserFragment : BaseFragment(), UserContract.View { override lateinit var presenter: UserContract.Presenter lateinit var mUserInfoSP: SharedPreferences lateinit var mUserSP: SharedPreferences var rootView: View? = null var gson = Gson() var userNum: String? = null /* 请求识别码 */ private val CODE_GALLERY_REQUEST = 0xa0 private val CODE_CAMERA_REQUEST = 0xa1 private val CODE_RESULT_REQUEST = 0xa2 private var rl_logout_confirm: RelativeLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) UserPresenter(UserImpl.getInstance(), this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mUserSP = ctx.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE) if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_user, container, false) presenter.loadData(ctx) } return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val mTypeFace = Typeface.createFromAsset(ctx.assets, "ALTGOT2N.TTF") tv_login_number.typeface = mTypeFace tv_report_number.typeface = mTypeFace tv_beyond_number.typeface = mTypeFace initView() initShow() } override fun onResume() { super.onResume() if (ConfigConstants.USER_CUSTOM) { refreshData() } } fun initView() { userNum = activity!!.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE).getString(USER_NUM, "") requestUserData() iv_user_icon.setOnClickListener { if (ConfigConstants.HEAD_ICON_UPLOAD_SUPPORT) { showIconSelectPopWindow() } } rl_password_alter.setOnClickListener { startPassWordAlterActivity() } rl_issue.setOnClickListener { startIssueActivity() } rl_setting.setOnClickListener { startSettingActivity() } rl_favorite.setOnClickListener { startFavoriteActivity() } rl_message.setOnClickListener { startMessageActivity() } rl_logout.setOnClickListener { showLogoutPopupWindow() } rl_user_location.setOnClickListener { if (ConfigConstants.USER_GROUP_CONTENT) { startUserLocationPage() } } } private fun requestUserData() { RetrofitUtil.getHttpService(ctx).getUserInfo(userNum) .compose(RetrofitUtil.CommonOptions<UserInfoResult>()) .subscribe(object : CodeHandledSubscriber<UserInfoResult>() { override fun onError(apiException: ApiException?) { ToastUtils.show(ctx, apiException!!.displayMessage) } override fun onBusinessNext(mUserInfo: UserInfoResult?) { tv_user_name.text = mUserInfo!!.data!!.user_name tv_user_role.text = mUserInfo.data!!.role_name tv_mine_user_num_value.text = mUserInfo.data!!.user_num tv_mine_user_group_value.text = mUserInfo.data!!.group_name Glide.with(ctx) .load(mUserInfo.data!!.gravatar) .asBitmap() .placeholder(R.drawable.face_default) .error(R.drawable.face_default) .override(DisplayUtil.dip2px(ctx, 60f), DisplayUtil.dip2px(ctx, 60f)) .into(object : BitmapImageViewTarget(iv_user_icon) { override fun setResource(resource: Bitmap?) { val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(ctx.resources, resource) circularBitmapDrawable.isCircular = true iv_user_icon.setImageDrawable(circularBitmapDrawable) } }) } override fun onCompleted() { } }) } private fun initShow() { setViewVisible(ll_single_value, ConfigConstants.USER_CUSTOM) // setViewVisible(ll_yh_custom_user, ConfigConstants.USER_CUSTOM) setViewVisible(rl_favorite, ConfigConstants.USER_CUSTOM) // setViewVisible(rl_message, ConfigConstants.USER_CUSTOM) setViewVisible(rl_password_alter, ConfigConstants.USER_CUSTOM) setViewVisible(iv_mine_user_group_arrow, ConfigConstants.USER_GROUP_CONTENT) } private fun setViewVisible(view: View, show: Boolean) { if (show) { view.visibility = View.VISIBLE } else { view.visibility = View.GONE } } private fun refreshData() { RetrofitUtil.getHttpService(ctx).getUserInfo(userNum) .compose(RetrofitUtil.CommonOptions<UserInfoResult>()) .subscribe(object : CodeHandledSubscriber<UserInfoResult>() { override fun onError(apiException: ApiException?) { ToastUtils.show(ctx, apiException!!.displayMessage) } override fun onBusinessNext(mUserInfo: UserInfoResult?) { tv_login_number.text = mUserInfo!!.data!!.login_duration tv_report_number.text = mUserInfo.data!!.browse_report_count tv_beyond_number.text = mUserInfo.data!!.surpass_percentage.toString() } override fun onCompleted() { } }) } override fun dataLoaded(data: UserInfoResult) { val user = data.data tv_user_name.text = user!!.user_name tv_login_number.text = user.login_duration tv_report_number.text = user.browse_report_count tv_mine_user_num_value.text = user.user_num tv_beyond_number.text = user.surpass_percentage.toString() tv_user_role.text = user.role_name tv_mine_user_group_value.text = user.group_name Glide.with(ctx) .load(user.gravatar) .asBitmap() .placeholder(R.drawable.face_default) .error(R.drawable.face_default) .override(DisplayUtil.dip2px(ctx, 60f), DisplayUtil.dip2px(ctx, 60f)) .into(object : BitmapImageViewTarget(iv_user_icon) { override fun setResource(resource: Bitmap?) { val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(ctx.resources, resource) circularBitmapDrawable.isCircular = true iv_user_icon.setImageDrawable(circularBitmapDrawable) } }) } private fun startPassWordAlterActivity() { val intent = Intent(ctx, AlterPasswordActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) ActionLogUtil.actionLog("点击/个人信息/修改密码") } private fun startFavoriteActivity() { val intent = Intent(activity, FavoriteArticleActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) } private fun startMessageActivity() { val intent = Intent(activity, ShowPushMessageActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) } private fun startIssueActivity() { val intent = Intent(activity, FeedbackActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) } private fun startSettingActivity() { val intent = Intent(activity, SettingActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) } private fun startUserLocationPage() { RetrofitUtil.getHttpService(ctx).getRegister("sypc_000103") .compose(RetrofitUtil.CommonOptions()) .subscribe(object : CodeHandledSubscriber<RegisterResult>() { override fun onError(apiException: ApiException) { ToastUtils.show(ctx, "功能开发中") } override fun onBusinessNext(data: RegisterResult) { if (data.data!!.contains("http")) { PageLinkManage.pageLink(ctx!!, "归属部门", data.data!!) } else { ToastUtils.show(ctx, data.data!!) } } override fun onCompleted() {} }) } /** * 退出登录选择窗 */ private fun showLogoutPopupWindow() { val contentView = LayoutInflater.from(ctx).inflate(R.layout.popup_logout, null) //设置弹出框的宽度和高度 val popupWindow = PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) popupWindow.isFocusable = true// 取得焦点 //注意 要是点击外部空白处弹框消息 那么必须给弹框设置一个背景色 不然是不起作用的 popupWindow.setBackgroundDrawable(BitmapDrawable()) //点击外部消失 popupWindow.isOutsideTouchable = true //设置可以点击 popupWindow.isTouchable = true popupWindow.animationStyle = R.style.anim_popup_bottombar popupWindow.showAtLocation(this.view, Gravity.BOTTOM, 0, contentView.height) rl_logout_confirm = contentView.findViewById(R.id.rl_logout_confirm) rl_logout_confirm!!.setOnClickListener { // 取消 popupWindow.dismiss() // 确认退出 presenter.logout(ctx) } contentView.findViewById<RelativeLayout>(R.id.rl_cancel).setOnClickListener { // 取消 popupWindow.dismiss() } contentView.findViewById<RelativeLayout>(R.id.rl_popup_logout_background).setOnClickListener { // 点击背景半透明区域 popupWindow.dismiss() } } /** * 退出登录成功 */ override fun logoutSuccess() { val intent = Intent(activity, LoginActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) RetrofitUtil.destroyInstance() activity!!.finish() } /** * 吐司错误信息 */ override fun showErrorMsg(errorMsg: String) { ToastUtils.show(ctx, errorMsg) } /** * 吐司成功信息 */ override fun showSuccessMsg(msg: String) { ToastUtils.show(ctx, msg, ToastColor.SUCCESS) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // 用户没有选择图片,返回 if (resultCode == RESULT_CANCELED) { ToastUtils.show(ctx, "取消") return } when (requestCode) { CODE_GALLERY_REQUEST -> { val cropIntent = launchSystemImageCrop(ctx, data!!.data) startActivityForResult(cropIntent, CODE_RESULT_REQUEST) } CODE_CAMERA_REQUEST -> { val cropIntent: Intent val tempFile = File(Environment.getExternalStorageDirectory(), "icon.jpg") if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val photoURI = FileProvider.getUriForFile(ctx, "com.intfocus.template.fileprovider", tempFile) cropIntent = launchSystemImageCrop(ctx, photoURI) } else { cropIntent = launchSystemImageCrop(ctx, Uri.fromFile(tempFile)) } startActivityForResult(cropIntent, CODE_RESULT_REQUEST) } else -> { } } if (data != null) { setImageToHeadView() } super.onActivityResult(requestCode, resultCode, data) } /** * 显示头像选择菜单 */ private fun showIconSelectPopWindow() { val contentView = LayoutInflater.from(ctx).inflate(R.layout.popup_mine_icon_select, null) //设置弹出框的宽度和高度 val popupWindow = PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) popupWindow.isFocusable = true// 取得焦点 //注意 要是点击外部空白处弹框消息 那么必须给弹框设置一个背景色 不然是不起作用的 // todo bug 验证最新bitmap 创建 popupWindow.setBackgroundDrawable(BitmapDrawable()) //点击外部消失 popupWindow.isOutsideTouchable = true //设置可以点击 popupWindow.isTouchable = true popupWindow.showAtLocation(activity!!.toolBar, Gravity.BOTTOM, 0, 0) contentView.findViewById<RelativeLayout>(R.id.rl_camera).setOnClickListener { // 打开相机 startActivityForResult(launchCamera(ctx), CODE_CAMERA_REQUEST) popupWindow.dismiss() } contentView.findViewById<RelativeLayout>(R.id.rl_gallery).setOnClickListener { // 打开相册 startActivityForResult(getGallery(), CODE_GALLERY_REQUEST) popupWindow.dismiss() } contentView.findViewById<RelativeLayout>(R.id.rl_cancel).setOnClickListener { // 取消 popupWindow.dismiss() } contentView.findViewById<RelativeLayout>(R.id.rl_popup_icon_background).setOnClickListener { // 点击背景半透明区域 popupWindow.dismiss() } ActionLogUtil.actionLog("点击/个人信息/设置头像") } /** * 提取保存裁剪之后的图片数据,并设置头像部分的View */ private fun setImageToHeadView() { val imgPath = Environment.getExternalStorageDirectory().toString() + "/icon.jpg" val bitmap = BitmapFactory.decodeFile(imgPath) if (bitmap != null) { iv_user_icon.setImageBitmap(makeRoundCorner(bitmap)) presenter.uploadUserIcon(ctx, bitmap, imgPath) } } }
gpl-3.0
pandiaraj44/react-native
packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/AndroidConfiguration.kt
1
753
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react import com.android.build.gradle.BaseExtension import org.gradle.api.Project fun Project.configureDevPorts(androidExt: BaseExtension) { val devServerPort = project.properties["reactNativeDevServerPort"]?.toString() ?: "8081" val inspectorProxyPort = project.properties["reactNativeInspectorProxyPort"]?.toString() ?: devServerPort androidExt.buildTypes.all { it.resValue("integer", "react_native_dev_server_port", devServerPort) it.resValue("integer", "react_native_inspector_proxy_port", inspectorProxyPort) } }
bsd-3-clause
felipebz/sonar-plsql
zpa-core/src/main/kotlin/org/sonar/plugins/plsqlopen/api/annotations/Priority.kt
1
994
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.annotations enum class Priority { INFO, MINOR, MAJOR, CRITICAL, BLOCKER }
lgpl-3.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/full/text/FTWindowPsiImpl.kt
1
892
/* * Copyright (C) 2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.psi.impl.full.text import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import uk.co.reecedunn.intellij.plugin.xpath.ast.full.text.FTWindow class FTWindowPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), FTWindow
apache-2.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/completion/providers/XPathKindTestProvider.kt
1
4575
/* * Copyright (C) 2019 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.completion.providers import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import uk.co.reecedunn.intellij.plugin.core.completion.CompletionProviderEx import uk.co.reecedunn.intellij.plugin.intellij.lang.XPathSpec import uk.co.reecedunn.intellij.plugin.xpath.completion.lookup.XPathInsertText import uk.co.reecedunn.intellij.plugin.xpath.completion.lookup.XPathKeywordLookup import uk.co.reecedunn.intellij.plugin.xpath.completion.property.XPathCompletionProperty object XPathKindTestProvider : CompletionProviderEx { private val XPATH_10_KIND_TESTS = listOf( XPathKeywordLookup("comment", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("processing-instruction", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("processing-instruction", XPathInsertText.PARAMS_NAME_STRING), XPathKeywordLookup("text", XPathInsertText.EMPTY_PARAMS) ) private val XPATH_20_WD_2003_KIND_TESTS = listOf( XPathKeywordLookup("attribute", XPathInsertText.PARAMS_SCHEMA_CONTEXT), XPathKeywordLookup("comment", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("document-node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("document-node", XPathInsertText.PARAMS_ROOT_ELEMENT), XPathKeywordLookup("element", XPathInsertText.PARAMS_SCHEMA_CONTEXT), XPathKeywordLookup("namespace-node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("processing-instruction", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("processing-instruction", XPathInsertText.PARAMS_NAME_STRING), XPathKeywordLookup("text", XPathInsertText.EMPTY_PARAMS) ) private val XPATH_20_REC_KIND_TESTS = listOf( XPathKeywordLookup("attribute", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("attribute", XPathInsertText.PARAMS_WILDCARD), XPathKeywordLookup("attribute", XPathInsertText.PARAMS_NAME), XPathKeywordLookup("attribute", XPathInsertText.PARAMS_WILDCARD_AND_TYPE), XPathKeywordLookup("attribute", XPathInsertText.PARAMS_NAME_AND_TYPE), XPathKeywordLookup("comment", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("document-node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("document-node", XPathInsertText.PARAMS_ROOT_ELEMENT), XPathKeywordLookup("element", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("element", XPathInsertText.PARAMS_WILDCARD), XPathKeywordLookup("element", XPathInsertText.PARAMS_NAME), XPathKeywordLookup("element", XPathInsertText.PARAMS_WILDCARD_AND_TYPE), XPathKeywordLookup("element", XPathInsertText.PARAMS_NAME_AND_TYPE), XPathKeywordLookup("namespace-node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("node", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("processing-instruction", XPathInsertText.EMPTY_PARAMS), XPathKeywordLookup("processing-instruction", XPathInsertText.PARAMS_NAME), XPathKeywordLookup("processing-instruction", XPathInsertText.PARAMS_NAME_STRING), XPathKeywordLookup("schema-attribute", XPathInsertText.PARAMS_NAME), XPathKeywordLookup("schema-element", XPathInsertText.PARAMS_NAME), XPathKeywordLookup("text", XPathInsertText.EMPTY_PARAMS) ) override fun apply(element: PsiElement, context: ProcessingContext, result: CompletionResultSet) { when (context[XPathCompletionProperty.XPATH_VERSION]) { XPathSpec.REC_1_0_19991116 -> result.addAllElements(XPATH_10_KIND_TESTS) XPathSpec.WD_2_0_20030502 -> result.addAllElements(XPATH_20_WD_2003_KIND_TESTS) else -> result.addAllElements(XPATH_20_REC_KIND_TESTS) } } }
apache-2.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathLocalUnionType.kt
1
957
/* * Copyright (C) 2017, 2019-2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.ast.xpath import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType /** * An XPath 4.0 ED and XQuery 4.0 ED `LocalUnionType` node in the XPath/XQuery AST. */ interface XPathLocalUnionType : PsiElement, XdmItemType { val memberTypes: Sequence<XdmItemType> }
apache-2.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/full/text/FTPrimaryWithOptions.kt
1
819
/* * Copyright (C) 2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.ast.full.text import com.intellij.psi.PsiElement /** * An XQuery Full Text 1.0 `FTPrimaryWithOptions` node in the XQuery AST. */ interface FTPrimaryWithOptions : PsiElement
apache-2.0
rhdunn/xquery-intellij-plugin
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/XdmEmptySequence.kt
1
1043
/* * Copyright (C) 2019 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding object XdmEmptySequence { private var instance: XdmValue? = null fun getInstance(classLoader: ClassLoader): XdmValue { if (instance == null) { val `class` = classLoader.loadClass("net.sf.saxon.s9api.XdmEmptySequence") instance = XdmValue(`class`.getMethod("getInstance").invoke(null), `class`) } return instance!! } }
apache-2.0
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/course_revenue/reducer/CourseBenefitsMonthlyReducer.kt
1
3208
package org.stepik.android.presentation.course_revenue.reducer import org.stepik.android.domain.course_revenue.model.CourseBenefitByMonthListItem import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.State import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.Message import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.Action import ru.nobird.android.core.model.concatWithPagedList import ru.nobird.android.presentation.redux.reducer.StateReducer import javax.inject.Inject class CourseBenefitsMonthlyReducer @Inject constructor() : StateReducer<State, Message, Action> { override fun reduce(state: State, message: Message): Pair<State, Set<Action>> = when (message) { is Message.FetchCourseBenefitsByMonthsSuccess -> { when (state) { is State.Loading -> { val courseBenefitsMonthlyState = if (message.courseBenefitByMonthListDataItems.isEmpty()) { State.Empty } else { State.Content(message.courseBenefitByMonthListDataItems, message.courseBenefitByMonthListDataItems) } courseBenefitsMonthlyState to emptySet() } is State.Content -> { val resultingList = state.courseBenefitByMonthListDataItems.concatWithPagedList(message.courseBenefitByMonthListDataItems) state.copy(courseBenefitByMonthListDataItems = resultingList, courseBenefitByMonthListItems = resultingList) to emptySet() } else -> null } } is Message.FetchCourseBenefitsByMonthsFailure -> { when (state) { is State.Loading -> State.Error to emptySet() is State.Content -> state to emptySet() else -> null } } is Message.FetchCourseBenefitsByMonthNext -> { if (state is State.Content) { if (state.courseBenefitByMonthListDataItems.hasNext && state.courseBenefitByMonthListItems.last() !is CourseBenefitByMonthListItem.Placeholder) { state.copy(courseBenefitByMonthListItems = state.courseBenefitByMonthListItems + CourseBenefitByMonthListItem.Placeholder) to setOf(Action.FetchCourseBenefitsByMonths(message.courseId, state.courseBenefitByMonthListDataItems.page + 1)) } else { null } } else { null } } is Message.TryAgain -> { if (state is State.Error) { State.Loading to setOf(Action.FetchCourseBenefitsByMonths(message.courseId)) } else { null } } } ?: state to emptySet() }
apache-2.0
pkleimann/livingdoc
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioFixtureModel.kt
3
2648
package org.livingdoc.engine.execution.examples.scenarios import org.livingdoc.api.fixtures.scenarios.After import org.livingdoc.api.fixtures.scenarios.Before import org.livingdoc.api.fixtures.scenarios.Step import org.livingdoc.engine.execution.examples.scenarios.matching.ScenarioStepMatcher import org.livingdoc.engine.execution.examples.scenarios.matching.ScenarioStepMatcher.MatchingResult import org.livingdoc.engine.execution.examples.scenarios.matching.StepTemplate import java.lang.reflect.Method import kotlin.reflect.KClass internal class ScenarioFixtureModel( val fixtureClass: Class<*> ) { val beforeMethods: List<Method> val afterMethods: List<Method> val stepMethods: List<Method> val stepTemplateToMethod: Map<StepTemplate, Method> private val stepMatcher: ScenarioStepMatcher init { // method analysis val beforeMethods = mutableListOf<Method>() val afterMethods = mutableListOf<Method>() val stepMethods = mutableListOf<Method>() fixtureClass.declaredMethods.forEach { method -> if (method.isAnnotatedWith(Before::class)) beforeMethods.add(method) if (method.isAnnotatedWith(After::class)) afterMethods.add(method) if (method.isAnnotatedWith(Step::class)) stepMethods.add(method) if (method.isAnnotatedWith(Step.Steps::class)) stepMethods.add(method) } // before and after methods are ordered alphanumerically to make execution order more intuitive this.beforeMethods = beforeMethods.sortedBy { it.name } this.afterMethods = afterMethods.sortedBy { it.name } this.stepMethods = stepMethods // step alias analysis val stepAliases = mutableSetOf<String>() val stepTemplateToMethod = mutableMapOf<StepTemplate, Method>() stepMethods.forEach { method -> method.getAnnotationsByType(Step::class.java) .flatMap { it.value.asIterable() } .forEach { alias -> stepAliases.add(alias) stepTemplateToMethod[StepTemplate.parse(alias)] = method } } this.stepTemplateToMethod = stepTemplateToMethod this.stepMatcher = ScenarioStepMatcher(stepTemplateToMethod.keys.toList()) } fun getMatchingStepTemplate(step: String): MatchingResult = stepMatcher.match(step) fun getStepMethod(template: StepTemplate): Method = stepTemplateToMethod[template]!! private fun Method.isAnnotatedWith(annotationClass: KClass<out Annotation>): Boolean { return this.isAnnotationPresent(annotationClass.java) } }
apache-2.0
robfletcher/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteTaskHandlerTest.kt
1
13081
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.NoopRegistry import com.netflix.spinnaker.orca.DefaultStageResolver import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.events.TaskComplete import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.model.TaskExecutionImpl import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.SkipStage import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.buildTasks import com.netflix.spinnaker.orca.q.get import com.netflix.spinnaker.orca.q.multiTaskStage import com.netflix.spinnaker.orca.q.rollingPushStage import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher object CompleteTaskHandlerTest : SubjectSpek<CompleteTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val publisher: ApplicationEventPublisher = mock() val clock = fixedClock() val stageResolver = DefaultStageResolver(StageDefinitionBuildersProvider(emptyList())) subject(GROUP) { CompleteTaskHandler(queue, repository, DefaultStageDefinitionBuilderFactory(stageResolver), ContextParameterProcessor(), publisher, clock, NoopRegistry()) } fun resetMocks() = reset(queue, repository, publisher) setOf(SUCCEEDED, SKIPPED).forEach { successfulStatus -> describe("when a task completes with $successfulStatus status") { given("the stage contains further tasks") { val pipeline = pipeline { stage { type = multiTaskStage.type multiTaskStage.buildTasks(this) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", successfulStatus, successfulStatus ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage( check { it.tasks.first().apply { assertThat(status).isEqualTo(successfulStatus) assertThat(endTime).isEqualTo(clock.millis()) } } ) } it("runs the next task") { verify(queue) .push( StartTask( message.executionType, message.executionId, message.application, message.stageId, "2" ) ) } it("publishes an event") { verify(publisher).publishEvent( check<TaskComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.taskId).isEqualTo(message.taskId) assertThat(it.status).isEqualTo(successfulStatus) } ) } } given("the stage is complete") { val pipeline = pipeline { stage { type = singleTaskStage.type singleTaskStage.buildTasks(this) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", SUCCEEDED, SUCCEEDED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage( check { it.tasks.last().apply { assertThat(status).isEqualTo(SUCCEEDED) assertThat(endTime).isEqualTo(clock.millis()) } } ) } it("emits an event to signal the stage is complete") { verify(queue) .push( CompleteStage( message.executionType, message.executionId, message.application, message.stageId ) ) } } given("the task is the end of a rolling push loop") { val pipeline = pipeline { stage { refId = "1" type = rollingPushStage.type rollingPushStage.buildTasks(this) } } and("when the task returns REDIRECT") { val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1").id, "4", REDIRECT, REDIRECT ) beforeGroup { pipeline.stageByRef("1").apply { tasks[0].status = SUCCEEDED tasks[1].status = SUCCEEDED tasks[2].status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("repeats the loop") { verify(queue).push( check<StartTask> { assertThat(it.taskId).isEqualTo("2") } ) } it("resets the status of the loop tasks") { verify(repository).storeStage( check { assertThat(it.tasks[1..3].map(TaskExecution::getStatus)).allMatch { it == NOT_STARTED } } ) } it("does not publish an event") { verifyZeroInteractions(publisher) } } } } } setOf(TERMINAL, CANCELED, STOPPED).forEach { status -> describe("when a task completes with $status status") { val pipeline = pipeline { stage { type = multiTaskStage.type multiTaskStage.buildTasks(this) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", status, status ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage( check { it.tasks.first().apply { assertThat(status).isEqualTo(status) assertThat(endTime).isEqualTo(clock.millis()) } } ) } it("fails the stage") { verify(queue).push( CompleteStage( message.executionType, message.executionId, message.application, message.stageId ) ) } it("does not run the next task") { verify(queue, never()).push(any<RunTask>()) } it("publishes an event") { verify(publisher).publishEvent( check<TaskComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.taskId).isEqualTo(message.taskId) assertThat(it.status).isEqualTo(status) } ) } } } describe("when a task should complete parent stage") { val task = fun(isStageEnd: Boolean): TaskExecution { val task = TaskExecutionImpl() task.isStageEnd = isStageEnd return task } it("is last task in stage") { subject.shouldCompleteStage(task(true), SUCCEEDED, SUCCEEDED) == true subject.shouldCompleteStage(task(false), SUCCEEDED, SUCCEEDED) == false } it("did not originally complete with FAILED_CONTINUE") { subject.shouldCompleteStage(task(false), TERMINAL, TERMINAL) == true subject.shouldCompleteStage(task(false), FAILED_CONTINUE, TERMINAL) == true subject.shouldCompleteStage(task(false), FAILED_CONTINUE, FAILED_CONTINUE) == false } } describe("manual skip behavior") { given("a stage with a manual skip flag") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.buildTasks(this) context["manualSkip"] = true } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1").id, "1", SKIPPED, SKIPPED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("skips the stage") { verify(queue).push(SkipStage(pipeline.stageByRef("1"))) } } given("a stage whose parent has a manual skip flag") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.buildTasks(this) context["manualSkip"] = true stage { refId = "1<1" type = singleTaskStage.type singleTaskStage.buildTasks(this) } } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1<1").id, "1", SKIPPED, SKIPPED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("skips the parent stage") { verify(queue).push(SkipStage(pipeline.stageByRef("1"))) } } } })
apache-2.0
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/addressBook/AddressBookViewModel.kt
1
1771
package com.marknkamau.justjava.ui.addressBook import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.marknjunge.core.data.model.Address import com.marknjunge.core.data.model.Resource import com.marknjunge.core.data.model.User import com.marknjunge.core.data.repository.UsersRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AddressBookViewModel @Inject constructor(private val usersRepository: UsersRepository) : ViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> = _loading private val _user = MutableLiveData<Resource<User>>() val user: LiveData<Resource<User>> = _user fun getAddresses() { viewModelScope.launch { _loading.value = true usersRepository.getCurrentUser().collect { _user.value = it } _loading.value = false } } fun addAddress(address: Address): LiveData<Resource<Address>> { val liveData = MutableLiveData<Resource<Address>>() viewModelScope.launch { _loading.value = true liveData.value = usersRepository.addAddress(address) _loading.value = false } return liveData } fun deleteAddress(address: Address): LiveData<Resource<Unit>> { val livedata = MutableLiveData<Resource<Unit>>() viewModelScope.launch { _loading.value = true livedata.value = usersRepository.deleteAddress(address) _loading.value = false } return livedata } }
apache-2.0
hitoshura25/Media-Player-Omega-Android
common_view/src/main/java/com/vmenon/mpo/view/activity/BaseActivity.kt
1
1495
package com.vmenon.mpo.view.activity import android.content.Context import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.google.android.material.navigation.NavigationView import com.vmenon.mpo.navigation.domain.NavigationController import com.vmenon.mpo.system.domain.Logger import javax.inject.Inject abstract class BaseActivity<COMPONENT : Any> : AppCompatActivity() { lateinit var component: COMPONENT @Inject protected lateinit var navigationController: NavigationController @Inject protected lateinit var logger: Logger override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) component = setupComponent(applicationContext) inject(component) } fun requireContentView() = getContentView()!! fun requireLoadingView() = getLoadingView()!! abstract fun getContentView(): View? abstract fun getLoadingView(): View? abstract fun drawerLayout(): DrawerLayout? abstract fun navigationView(): NavigationView? protected abstract fun setupComponent(context: Context): COMPONENT protected abstract fun inject(component: COMPONENT) protected inline fun <reified VIEW_MODEL : ViewModel> viewModel(): Lazy<VIEW_MODEL> = lazy { ViewModelProvider(this)[VIEW_MODEL::class.java] } }
apache-2.0
GDGLima/CodeLab-Kotlin-Infosoft-2017
Infosoft2017/app/src/main/java/com/emedinaa/infosoft2017/ui/adapterskt/EventAdapterK.kt
1
1811
package com.emedinaa.infosoft2017.ui.adapterskt import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.emedinaa.infosoft2017.R import com.emedinaa.infosoft2017.helpers.formatDate import com.emedinaa.infosoft2017.model.EntityK import kotlinx.android.synthetic.main.row_event.view.* /** * Created by emedinaa on 3/09/17. */ class EventAdapterK(val events:List<EntityK.EventK>, val context: Context): RecyclerView.Adapter<EventAdapterK.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textViewHour: TextView = view.textViewHour val textViewTitle: TextView = view.textViewTitle val textSpeaker: TextView = view.textSpeaker val textViewDate: TextView = view.textViewDate } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) return ViewHolder(layoutInflater.inflate(R.layout.row_event, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val title: String = events[position].titulo!! val sb = StringBuilder() sb.append(events[position].horario_inicio).append("-").append(events[position].horario_fin) val hour: String? = sb.toString() val speaker:String=events[position].expositor_nombre val date:String =events[position].fecha holder.textViewHour.text = hour holder.textViewTitle.text = title holder.textSpeaker.text = speaker holder.textViewDate.text = formatDate(date) } override fun getItemCount(): Int { return events.size } }
apache-2.0
realm/realm-java
realm/realm-library/src/androidTest/kotlin/io/realm/RealmModelManagedSetTester.kt
1
23512
/* * Copyright 2021 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm import io.realm.entities.* import io.realm.kotlin.createObject import io.realm.rule.BlockingLooperThread import java.lang.IllegalArgumentException import kotlin.reflect.KFunction1 import kotlin.reflect.KFunction2 import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 import kotlin.test.* /** * Generic tester for Realm models types of managed sets. * * It delegates the validation of managed realm models to the ManagedSetTester class, as it will validate all the paths, * whereas in this test we validate Realm models specific cases. */ class RealmModelManagedSetTester<T : Any>( private val testerName: String, private val setFieldName: String, private val setFieldClass: Class<T>, private val realmAnyType: RealmAny.Type? = null, private val setGetter: KFunction1<SetAllTypes, RealmSet<T>>, private val setSetter: KFunction2<SetAllTypes, RealmSet<T>, Unit>, private val managedSetGetter: KProperty1<SetContainerClass, RealmSet<T>>, private val managedCollectionGetter: KProperty1<SetContainerClass, RealmList<T>>, private val unmanagedInitializedSet: List<T?>, private val unmanagedNotPresentValue: T, private val toArrayManaged: ToArrayManaged<T>, private val insertObjects: (realm: Realm, objects: List<T?>) -> List<T?>, private val deleteObjects: (objects: List<T?>) -> Unit, private val nullable: Boolean, private val equalsTo: (expected: T?, value: T?) -> Boolean, private val primaryKeyAllTypesSetProperty: KMutableProperty1<SetAllTypesPrimaryKey, RealmSet<T>> ) : SetTester { private lateinit var managedTester: ManagedSetTester<T> private lateinit var config: RealmConfiguration private lateinit var looperThread: BlockingLooperThread private lateinit var realm: Realm private lateinit var managedInitializedSet: List<T?> private lateinit var managedNotPresentValue: T private fun initAndAssertEmptySet(realm: Realm = this.realm): RealmSet<T> { val allTypesObject = createAllTypesManagedContainerAndAssert(realm, "unmanaged") assertNotNull(allTypesObject) val set = setGetter.call(allTypesObject) assertTrue(set.isEmpty()) return set } override fun toString(): String = "RealmModelManagedSet-${testerName}" override fun setUp(config: RealmConfiguration, looperThread: BlockingLooperThread) { this.config = config this.looperThread = looperThread this.realm = Realm.getInstance(config) realm.executeTransaction { transactionRealm -> managedInitializedSet = insertObjects(transactionRealm, unmanagedInitializedSet) managedNotPresentValue = insertObjects(transactionRealm, listOf<T?>(unmanagedNotPresentValue))[0]!! } this.managedTester = ManagedSetTester( testerName = testerName, setFieldClass = setFieldClass, setFieldName = setFieldName, realmAnyType = realmAnyType, setGetter = setGetter, setSetter = setSetter, managedSetGetter = managedSetGetter, managedCollectionGetter = managedCollectionGetter, initializedSet = managedInitializedSet, notPresentValue = managedNotPresentValue, toArrayManaged = toArrayManaged, nullable = nullable, equalsTo = equalsTo, primaryKeyAllTypesSetProperty = primaryKeyAllTypesSetProperty ) this.managedTester.setUp(config, looperThread) } override fun tearDown() { managedTester.tearDown() this.realm.close() } override fun isManaged() = managedTester.isManaged() override fun isValid() = managedTester.isValid() override fun isFrozen() = managedTester.isFrozen() override fun size() = managedTester.size() override fun isEmpty() = managedTester.isEmpty() override fun requiredConstraints() = Unit // Not tested override fun contains() { managedTester.contains() // Test with unmanaged realm objects val set = initAndAssertEmptySet() realm.executeTransaction { // Check throws exception when unmanaged values are passed assertFailsWith<IllegalArgumentException>("Unmanaged objects not permitted") { set.contains(unmanagedNotPresentValue) } if (!nullable) { assertFailsWith<java.lang.NullPointerException>("Set does not support null values") { assertFalse(set.contains(null)) } } } // Test with object from another realm accessTransactionRealmInLooperThread { looperRealm -> val value = insertObjects(looperRealm, listOf<T?>(unmanagedNotPresentValue))[0] assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.contains(value) } } } override fun iterator() = managedTester.iterator() override fun toArray() = managedTester.toArray() override fun toArrayWithParameter() = managedTester.toArrayWithParameter() override fun dynamic() { if (realmAnyType != null) { dynamicRealmAnyTest() } else { dynamicObjectTest() } } private fun toDynamicRealmAny(realm: DynamicRealm, value: RealmAny): RealmAny { val id = value.asRealmModel(DogPrimaryKey::class.java).id return RealmAny.valueOf(realm.where(DogPrimaryKey.CLASS_NAME).equalTo(DogPrimaryKey.ID, id).findFirst()!!) } private fun dynamicRealmAnyTest() { // Create a set from a immutable schema context val set = initAndAssertEmptySet() realm.executeTransaction { set.addAll(unmanagedInitializedSet) } val dynamicRealm = DynamicRealm.getInstance(realm.configuration) val dynamicObject: DynamicRealmObject = dynamicRealm.where(SetAllTypes.NAME) .equalTo(AllTypes.FIELD_STRING, "unmanaged").findFirst()!! val dynamicSet: RealmSet<RealmAny> = dynamicObject.getRealmSet(setFieldName, setFieldClass) as RealmSet<RealmAny> // Access the previous set from a mutable context assertEquals(3, dynamicSet.size) // Update the set with a new value dynamicRealm.executeTransaction { dynamicSet.add(toDynamicRealmAny(dynamicRealm, unmanagedNotPresentValue as RealmAny)) } assertEquals(4, dynamicSet.size) // Try to replace the whole set by a new one dynamicRealm.executeTransaction { dynamicObject.setRealmSet(setFieldName, RealmSet<RealmAny>().apply { add(toDynamicRealmAny(dynamicRealm, unmanagedNotPresentValue as RealmAny)) }) } assertEquals(1, dynamicObject.getRealmSet(setFieldName, setFieldClass).size) // Validate that set is properly represented as a String managedTester.validateToString(dynamicObject, dynamicSet) dynamicRealm.close() } private fun dynamicObjectTest() { // Create a set from a immutable schema context val set = initAndAssertEmptySet() realm.executeTransaction { set.addAll(unmanagedInitializedSet) } val dynamicRealm = DynamicRealm.getInstance(realm.configuration) val dynamicObject: DynamicRealmObject = dynamicRealm.where(SetAllTypes.NAME).equalTo(AllTypes.FIELD_STRING, "unmanaged").findFirst()!! val dynamicSet = dynamicObject.getRealmSet(setFieldName) // Access the previous set from a mutable context set.forEach { value -> if (RealmObject.isValid(value as DogPrimaryKey)) { val managedObject = dynamicRealm.where(DogPrimaryKey.CLASS_NAME).equalTo(DogPrimaryKey.ID, (value as DogPrimaryKey).id) .findFirst()!! assertTrue(dynamicSet.contains(managedObject)) } } // Update the set with a new value dynamicRealm.executeTransaction { val notPresentManaged = dynamicRealm.where(DogPrimaryKey.CLASS_NAME) .equalTo(DogPrimaryKey.ID, (unmanagedNotPresentValue as DogPrimaryKey).id).findFirst()!! dynamicSet.add(notPresentManaged) } set.plus(unmanagedNotPresentValue).forEach { value -> if (RealmObject.isValid(value as DogPrimaryKey)) { val managedObject = dynamicRealm.where(DogPrimaryKey.CLASS_NAME).equalTo(DogPrimaryKey.ID, (value as DogPrimaryKey).id) .findFirst()!! assertTrue(dynamicSet.contains(managedObject)) } } // Try to replace the whole set by a new one dynamicRealm.executeTransaction { val notPresentManaged = dynamicRealm.where(DogPrimaryKey.CLASS_NAME) .equalTo(DogPrimaryKey.ID, (unmanagedNotPresentValue as DogPrimaryKey).id).findFirst()!! dynamicObject.setRealmSet(setFieldName, RealmSet<DynamicRealmObject>().apply { add(notPresentManaged) }) } assertEquals(1, dynamicObject.get<RealmSet<T>>(setFieldName).size) // Validate that set is properly represented as a String managedTester.validateToString(dynamicObject, dynamicSet) dynamicRealm.close() } override fun add() { // Test with managed objects managedTester.add() // Test with unmanaged objects val set = initAndAssertEmptySet() realm.executeTransaction { // Adding a value for the first time returns true unmanagedInitializedSet.forEach { value -> assertTrue(set.add(value)) } // Adding an existing value returns false unmanagedInitializedSet.forEach { value -> assertFalse(set.add(value)) } } // Test with object from another realm accessTransactionRealmInLooperThread { looperRealm -> val value = insertObjects(looperRealm, listOf<T?>(unmanagedNotPresentValue))[0] assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.add(value) } } assertTrue(set.containsAll(managedInitializedSet)) } override fun remove() { managedTester.remove() // Test with unmanaged realm objects val set = initAndAssertEmptySet() realm.executeTransaction { // Check throws exception when unmanaged values are passed assertFailsWith<IllegalArgumentException>("Unmanaged objects not permitted") { set.remove(unmanagedNotPresentValue) } } // Test with object from another realm accessTransactionRealmInLooperThread { looperRealm -> val value = insertObjects(looperRealm, listOf<T?>(unmanagedNotPresentValue))[0] assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.remove(value) } } } override fun insert() { // This specific test case needs unmanaged objects on PK models realm.executeTransaction { deleteObjects(managedInitializedSet) } // Call with unmanaged objects managedTester.doInsertTest(unmanagedInitializedSet) } override fun insertList() { // This specific test case needs unmanaged objects on PK models realm.executeTransaction { deleteObjects(managedInitializedSet) } // Call with unmanaged objects managedTester.doInsertListTest(unmanagedInitializedSet) } override fun insertOrUpdate() { managedTester.insertOrUpdate() } override fun insertOrUpdateList() { managedTester.insertOrUpdate() } override fun copyToRealm() { // This specific test case needs unmanaged objects on PK models realm.executeTransaction { deleteObjects(managedInitializedSet) } // Call with unmanaged objects managedTester.doCopyToRealmTest(unmanagedInitializedSet) } override fun copyToRealmOrUpdate() { managedTester.copyToRealmOrUpdate() } override fun containsAll() { // Test with managed realm objects managedTester.containsAll() // Test with unmanaged realm objects val set = initAndAssertEmptySet() realm.executeTransaction { // Check throws exception when unmanaged values are passed assertFailsWith<IllegalArgumentException>("Collection with unmanaged objects not permitted") { set.containsAll(unmanagedInitializedSet) } if (!nullable) { // Checks it does not contain nulls assertFailsWith<java.lang.NullPointerException>("Set does not support null values") { assertFalse(set.containsAll(listOf(null))) } } } // Test with objects from another realm accessTransactionRealmInLooperThread { looperRealm -> val values = insertObjects(looperRealm, unmanagedInitializedSet) assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.containsAll(values) } } } override fun addAll() { // Test with managed objects managedTester.addAll() val set = initAndAssertEmptySet() realm.executeTransaction { transactionRealm -> // Changes after adding collection if (!nullable) { assertFailsWith<java.lang.NullPointerException>("Cannot add null values into this set") { set.addAll(listOf(null)) } } assertTrue(set.addAll(unmanagedInitializedSet)) assertEquals(unmanagedInitializedSet.size, set.size) // Does not change if we add the same data assertFalse(set.addAll(unmanagedInitializedSet)) assertEquals(unmanagedInitializedSet.size, set.size) // Does not change if we add itself to it assertFalse(set.addAll(set)) assertEquals(unmanagedInitializedSet.size, set.size) // Does not change if we add an empty collection assertFalse(set.addAll(listOf())) assertEquals(unmanagedInitializedSet.size, set.size) // Throws when adding a collection of a different type val somethingEntirelyDifferent = unmanagedInitializedSet.map { Pair(it, it) } assertFailsWith<ClassCastException> { set.addAll(somethingEntirelyDifferent as Collection<T>) } // Does not change if we add the same data from a managed set val sameValuesManagedSet = managedSetGetter.get(transactionRealm.createObject()) assertNotNull(sameValuesManagedSet) assertTrue(sameValuesManagedSet.addAll(unmanagedInitializedSet)) assertFalse(set.addAll(sameValuesManagedSet as Collection<T>)) assertEquals(unmanagedInitializedSet.size, set.size) // Does not change if we add an empty RealmSet val emptyManagedSet = managedSetGetter.get(transactionRealm.createObject()) assertTrue(emptyManagedSet.isEmpty()) assertFalse(set.addAll(emptyManagedSet)) assertEquals(unmanagedInitializedSet.size, set.size) // Changes after adding a managed set containing other values val notPresentValueSet = managedSetGetter.get(transactionRealm.createObject()) assertNotNull(notPresentValueSet) notPresentValueSet.add(unmanagedNotPresentValue) assertTrue(set.addAll(notPresentValueSet as Collection<T>)) assertEquals(unmanagedInitializedSet.size + notPresentValueSet.size, set.size) // Does not change after adding a managed list with the same elements set.clear() set.addAll(unmanagedInitializedSet) val sameValuesManagedList = managedCollectionGetter.call(transactionRealm.createObject<SetContainerClass>()) sameValuesManagedList.addAll(unmanagedInitializedSet) assertFalse(set.addAll(sameValuesManagedList)) assertTrue(set.containsAll(sameValuesManagedList)) // Changes after adding a managed list with other elements val differentValuesManagedList = managedCollectionGetter.call(transactionRealm.createObject<SetContainerClass>()) differentValuesManagedList.addAll(listOf(unmanagedNotPresentValue)) assertTrue(set.addAll(differentValuesManagedList)) assertTrue(set.containsAll(differentValuesManagedList)) // Does not change after adding an empty managed list set.clear() assertTrue(set.addAll(unmanagedInitializedSet)) val emptyValuesManagedList = managedCollectionGetter.call(transactionRealm.createObject<SetContainerClass>()) assertFalse(set.addAll(emptyValuesManagedList)) assertEquals(unmanagedInitializedSet.size, set.size) // Fails if passed null according to Java Set interface assertFailsWith<NullPointerException> { set.addAll(TestHelper.getNull()) } } // Test with objects from another realm accessTransactionRealmInLooperThread { looperRealm -> val values = insertObjects(looperRealm, unmanagedInitializedSet) assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.addAll(values) } } } override fun retainAll() { // Test with managed realm objects managedTester.retainAll() // Test with unmanaged realm objects val set = initAndAssertEmptySet() realm.executeTransaction { // Check throws exception when unmanaged values are passed assertFailsWith<IllegalArgumentException>("Collection with unmanaged objects not permitted") { set.retainAll(unmanagedInitializedSet) } if (!nullable) { // Check throws exception when null values are passed assertFailsWith<java.lang.NullPointerException>("Collections with nulls are not permitted") { set.retainAll(listOf(null)) } } } // Test with objects from another realm accessTransactionRealmInLooperThread { looperRealm -> val values = insertObjects(looperRealm, unmanagedInitializedSet) assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.retainAll(values) } } } override fun removeAll() { // Test with managed realm objects managedTester.removeAll() // Test with unmanaged realm objects val set = initAndAssertEmptySet() realm.executeTransaction { // Check throws exception when unmanaged values are passed assertFailsWith<IllegalArgumentException>("Collection with unmanaged objects not permitted") { set.removeAll(unmanagedInitializedSet) } if (!nullable) { // Check throws exception when null values are passed assertFailsWith<java.lang.NullPointerException>("Collections with nulls are not permitted") { set.removeAll(listOf(null)) } } } // Test with objects from another realm accessTransactionRealmInLooperThread { looperRealm -> val values = insertObjects(looperRealm, unmanagedInitializedSet) assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { set.removeAll(values) } } } override fun clear() = managedTester.clear() override fun freeze() = managedTester.freeze() override fun setters() { managedTester.setters() accessTransactionRealmInLooperThread { looperRealm -> val alternativeObject = createAllTypesManagedContainerAndAssert(looperRealm, "alternativeObject", true) val alternativeSet = RealmSet<T>().init(managedInitializedSet) assertFailsWith<IllegalArgumentException>("Cannot pass values from another Realm") { setSetter(alternativeObject, alternativeSet) } } } override fun addRealmChangeListener() = Unit override fun addSetChangeListener() = Unit override fun removeSetChangeListener() = Unit override fun removeRealmChangeListener() = Unit override fun hasListeners() = Unit override fun aggregations() { if (realmAnyType == null) { // Aggregations on RealmAny type are not supported val set = initAndAssertEmptySet() realm.executeTransaction { set.addAll(managedInitializedSet) } assertEquals(VALUE_AGE_HELLO, set.min(DogPrimaryKey.AGE)) assertEquals(VALUE_AGE_BYE, set.max(DogPrimaryKey.AGE)) assertEquals((VALUE_AGE_HELLO + VALUE_AGE_BYE) / 2.toDouble(), set.average(DogPrimaryKey.AGE)) assertEquals(VALUE_AGE_HELLO + VALUE_AGE_BYE, set.sum(DogPrimaryKey.AGE)) assertEquals(VALUE_BIRTHDAY_HELLO, set.minDate(DogPrimaryKey.BIRTHDAY)) assertEquals(VALUE_BIRTHDAY_BYE, set.maxDate(DogPrimaryKey.BIRTHDAY)) // Delete all should clear the set and remove all objects from the set realm.executeTransaction { set.addAll(managedInitializedSet) assertEquals(managedInitializedSet.size, set.size) set.deleteAllFromRealm() assertTrue(set.isEmpty()) for (element in managedInitializedSet) { assertFalse(RealmObject.isValid(element as RealmModel)) } } } else { // Aggregations on RealmAny type are not supported managedTester.aggregations() } } private fun accessTransactionRealmInLooperThread(block: (looperRealm: Realm) -> Unit) { // Test with objects from another realm looperThread.runBlocking { Realm.getInstance(realm.configuration).use { looperRealm -> looperRealm.executeTransaction { block(looperRealm) } } looperThread.testComplete() } } }
apache-2.0
square/wire
wire-library/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt
1
2812
/* * Copyright 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import com.squareup.wire.internal.FieldOrOneOfBinding import com.squareup.wire.internal.RuntimeMessageAdapter import java.io.IOException internal class MessageTypeAdapter<M : Message<M, B>, B : Message.Builder<M, B>>( private val messageAdapter: RuntimeMessageAdapter<M, B>, private val jsonAdapters: List<TypeAdapter<Any?>> ) : TypeAdapter<M>() { private val nameToField = mutableMapOf<String, JsonField<M, B>>() .also { map -> for (index in jsonAdapters.indices) { val fieldBinding = messageAdapter.fieldBindingsArray[index] val jsonField = JsonField(jsonAdapters[index], fieldBinding) map[messageAdapter.jsonNames[index]] = jsonField val alternateName = messageAdapter.jsonAlternateNames[index] if (alternateName != null) { map[alternateName] = jsonField } } } @Throws(IOException::class) override fun write(out: JsonWriter, message: M?) { out.beginObject() messageAdapter.writeAllFields( message = message, jsonAdapters = jsonAdapters, redactedFieldsAdapter = null ) { name, value, jsonAdapter -> out.name(name) jsonAdapter.write(out, value) } out.endObject() } @Throws(IOException::class) override fun read(input: JsonReader): M { val builder = messageAdapter.newBuilder() input.beginObject() while (input.hasNext()) { val name = input.nextName() val jsonField = nameToField[name] if (jsonField == null) { input.skipValue() continue } val value = jsonField.adapter.read(input) // "If a value is missing in the JSON-encoded data or if its value is null, it will be // interpreted as the appropriate default value when parsed into a protocol buffer." if (value == null) continue jsonField.fieldBinding.set(builder, value) } input.endObject() return builder.build() } data class JsonField<M : Message<M, B>, B : Message.Builder<M, B>>( val adapter: TypeAdapter<Any?>, val fieldBinding: FieldOrOneOfBinding<M, B> ) }
apache-2.0
realm/realm-java
realm/realm-annotations-processor/src/main/java/io/realm/processor/nameconverter/PascalCaseConverter.kt
1
1232
/* * Copyright 2018 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.processor.nameconverter /** * Converter that converts input to "PascalCase". */ class PascalCaseConverter : NameConverter { private val tokenizer = WordTokenizer() override fun convert(name: String): String { val words = tokenizer.split(name) val output = StringBuilder() for (i in words.indices) { val word = words[i].toLowerCase() val codepoint = word.codePointAt(0) output.appendCodePoint(Character.toUpperCase(codepoint)) output.append(word.substring(Character.charCount(codepoint))) } return output.toString() } }
apache-2.0
realm/realm-java
realm/realm-library/src/androidTest/kotlin/io/realm/entities/RealmAnyDefaultNonPK.kt
1
870
/* * Copyright 2020 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.entities import io.realm.RealmAny import io.realm.RealmObject open class RealmAnyDefaultNonPK : RealmObject() { companion object { const val FIELD_REALM_ANY = "realmAny" } var realmAny: RealmAny? = RealmAny.valueOf(RealmAnyNotIndexed()) }
apache-2.0
Unpublished/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/root/DeleteFileCommand.kt
2
1777
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.root import com.amaze.filemanager.file_operations.exceptions.ShellNotRunningException import com.amaze.filemanager.filesystem.RootHelper import com.amaze.filemanager.filesystem.root.base.IRootCommand object DeleteFileCommand : IRootCommand() { /** * Recursively removes a path with it's contents (if any) * * @return boolean whether file was deleted or not */ @Throws(ShellNotRunningException::class) fun deleteFile(path: String): Boolean { val mountPoint = MountPathCommand.mountPath(path, MountPathCommand.READ_WRITE) val result = runShellCommandToList( "rm -rf \"${RootHelper.getCommandLineString(path)}\"" ) mountPoint?.let { MountPathCommand.mountPath(it, MountPathCommand.READ_ONLY) } return result.isNotEmpty() } }
gpl-3.0
PolymerLabs/arcs
java/arcs/core/host/ArcHostContextParticle.kt
1
10851
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.host import arcs.core.common.toArcId import arcs.core.data.Annotation import arcs.core.data.Capabilities import arcs.core.data.Capability.Ttl import arcs.core.data.CollectionType import arcs.core.data.EntityType import arcs.core.data.Plan import arcs.core.data.Schema import arcs.core.data.SchemaSerializer import arcs.core.data.SingletonType import arcs.core.data.expression.deserializeExpression import arcs.core.data.expression.serialize import arcs.core.data.toSchema import arcs.core.entity.Reference import arcs.core.host.api.Particle import arcs.core.host.generated.AbstractArcHostContextParticle import arcs.core.host.generated.ArcHostContextPlan import arcs.core.storage.CapabilitiesResolver import arcs.core.storage.StorageKeyManager import arcs.core.type.Tag import arcs.core.type.Type import arcs.core.util.plus import arcs.core.util.traverse import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Job import kotlinx.coroutines.joinAll import kotlinx.coroutines.withContext typealias ArcHostContextParticle_HandleConnections = AbstractArcHostContextParticle.HandleConnection typealias ArcHostContextParticle_Particles = AbstractArcHostContextParticle.ParticleSchema typealias ArcHostContextParticle_PlanHandle = AbstractArcHostContextParticle.PlanHandle /** * An implicit [Particle] that lives within the [ArcHost] and used as a utility class to * serialize/deserialize [ArcHostContext] information from [Plan.Handle]s. It does not live in an * Arc or participate in normal [Particle] lifecycle. */ class ArcHostContextParticle( private val hostId: String, private val handleManager: HandleManager, private val storageKeyManager: StorageKeyManager, private val serializer: SchemaSerializer<String> ) : AbstractArcHostContextParticle() { /** * Given an [ArcHostContext], convert these types to Arc Schema types, and write them to the * appropriate handles. See `ArcHostContext.arcs` for schema definitions. */ suspend fun writeArcHostContext( context: arcs.core.host.ArcHostContext ) = onHandlesReady { try { handles.planHandles.clear() val connections = context.particles.flatMap { it.planParticle.handles.map { (handleName, handle) -> val planHandle = ArcHostContextParticle_PlanHandle( storageKey = handle.handle.storageKey.toString(), type = handle.handle.type.tag.name, schema = serializer.serialize(handle.handle.type.toSchema()) ) // Write Plan.Handle handles.planHandles.store(planHandle).join() ArcHostContextParticle_HandleConnections( connectionName = handleName, planHandle = handles.planHandles.createReference(planHandle), storageKey = handle.storageKey.toString(), mode = handle.mode.name, type = handle.type.tag.name, ttl = handle.ttl.minutes.toDouble(), expression = handle.expression?.serialize() ?: "", schema = serializer.serialize(handle.type.toSchema()) ) } } // Write Plan.HandleConnection handles.handleConnections.clear() connections.map { handles.handleConnections.store(it) }.joinAll() val particles = context.particles.map { ArcHostContextParticle_Particles( particleName = it.planParticle.particleName, location = it.planParticle.location, particleState = it.particleState.toString(), consecutiveFailures = it.consecutiveFailureCount.toDouble(), handles = connections.map { connection -> handles.handleConnections.createReference(connection) }.toSet() ) } // Write Plan.Particle + ParticleContext handles.particles.clear() particles.map { handles.particles.store(it) }.joinAll() val arcHostContext = AbstractArcHostContextParticle.ArcHostContext( arcId = context.arcId, hostId = hostId, arcState = context.arcState.toString(), particles = particles.map { handles.particles.createReference(it) }.toSet() ) handles.arcHostContext.clear() handles.arcHostContext.store(arcHostContext).join() } catch (e: Exception) { // TODO: retry? throw IllegalStateException("Unable to serialize ${context.arcId} for $hostId", e) } } /** * Reads [ArcHostContext] from serialized representation as Arcs Schema types. See * `ArcHostContext.arcs' for Schema definitions. NOTE: This is more complex than it needs * to be because references are not supported yet in schema2kotlin, and so this information * is stored in de-normalized format. */ suspend fun readArcHostContext( arcHostContext: arcs.core.host.ArcHostContext ): arcs.core.host.ArcHostContext? = onHandlesReady { val arcId = arcHostContext.arcId try { // TODO(cromwellian): replace with .query(arcId, hostId) when queryHandles are efficient val arcStateEntity = handles.arcHostContext.fetch() ?: return@onHandlesReady null val particles = arcStateEntity.particles.map { requireNotNull(it.dereference()) { "Invalid particle reference when deserialising arc $arcId for host $hostId" } }.map { particleEntity -> val handlesMap = createHandlesMap( arcId, particleEntity.particleName, particleEntity.handles ) ParticleContext( Plan.Particle(particleEntity.particleName, particleEntity.location, handlesMap), ParticleState.fromString(particleEntity.particleState), particleEntity.consecutiveFailures.toInt() ) } return@onHandlesReady ArcHostContext( arcId, particles.toMutableList(), initialArcState = ArcState.fromString(arcStateEntity.arcState) ) } catch (e: Exception) { throw IllegalStateException("Unable to deserialize $arcId for $hostId", e) } } private suspend inline fun <T> onHandlesReady( coroutineContext: CoroutineContext = handles.dispatcher, crossinline block: suspend () -> T ): T { val onReadyJobs = mapOf( "particles" to Job(), "arcHostContext" to Job(), "handleConnections" to Job(), "planHandles" to Job() ) handles.particles.onReady { onReadyJobs["particles"]?.complete() } handles.arcHostContext.onReady { onReadyJobs["arcHostContext"]?.complete() } handles.handleConnections.onReady { onReadyJobs["handleConnections"]?.complete() } handles.planHandles.onReady { onReadyJobs["planHandles"]?.complete() } onReadyJobs.values.joinAll() return withContext(coroutineContext) { block() } } suspend fun close() { handleManager.close() } private suspend fun createHandlesMap( arcId: String, particleName: String, handles: Set<Reference<ArcHostContextParticle_HandleConnections>> ) = handles.map { handle -> requireNotNull(handle.dereference()) { "HandleConnection couldn't be dereferenced for arcId $arcId, particle $particleName" } }.map { handle -> val planHandle = requireNotNull(requireNotNull(handle.planHandle).dereference()) { "PlanHandle couldn't be dereferenced for arcId $arcId, particle $handle.connectionName" } handle.connectionName to Plan.HandleConnection( Plan.Handle( storageKeyManager.parse(planHandle.storageKey), fromTag(arcId, serializer.deserialize(planHandle.schema), planHandle.type), emptyList() ), HandleMode.valueOf(handle.mode), fromTag(arcId, serializer.deserialize(handle.schema), handle.type), if (handle.ttl != Ttl.TTL_INFINITE.toDouble()) { listOf(Annotation.createTtl("$handle.ttl minutes")) } else { emptyList() }, handle.expression.ifEmpty { null }?.let { it.deserializeExpression() } ) }.toSet().associateBy({ it.first }, { it.second }) /** * Using instantiated particle to obtain [Schema] objects through their * associated [EntitySpec], reconstruct an associated [Type] object. */ fun fromTag(arcId: String, schema: Schema, tag: String): Type { return when (Tag.valueOf(tag)) { Tag.Singleton -> SingletonType(EntityType(schema)) Tag.Collection -> CollectionType(EntityType(schema)) Tag.Entity -> EntityType(schema) else -> throw IllegalArgumentException( "Illegal Tag $tag when deserializing ArcHostContext with ArcId '$arcId'" ) } } /** * When recipe2plan is finished, the 'Plan' to serialize/deserialize ArcHost information * will be code-genned, and this method will mostly go away, in combination with * the move away from denormalized schemas to schema definitions using references. */ fun createArcHostContextPersistencePlan( capability: Capabilities, arcId: String ): Plan.Partition { val resolver = CapabilitiesResolver( CapabilitiesResolver.Options(arcId.toArcId()) ) /* * Because query() isn't efficient yet, we don't store all serializations under a * single key in the recipe, but per-arcId. * TODO: once efficient queries exist, remove and use recipe2plan key */ val arcHostContextKey = resolver.createStorageKey( capability, EntityType(AbstractArcHostContextParticle.ArcHostContext.SCHEMA), "${hostId}_arcState" ) val particlesKey = resolver.createStorageKey( capability, EntityType(ArcHostContextParticle_Particles.SCHEMA), "${hostId}_arcState_particles" ) val handleConnectionsKey = resolver.createStorageKey( capability, EntityType(ArcHostContextParticle_HandleConnections.SCHEMA), "${hostId}_arcState_handleConnections" ) val planHandlesKey = resolver.createStorageKey( capability, EntityType(ArcHostContextParticle_PlanHandle.SCHEMA), "${hostId}_arcState_planHandles" ) // replace keys with per-arc created ones. val allStorageKeyLens = Plan.Particle.handlesLens.traverse() + Plan.HandleConnection.handleLens + Plan.Handle.storageKeyLens val particle = allStorageKeyLens.mod(ArcHostContextPlan.particles.first()) { storageKey -> val keyString = storageKey.toKeyString() when { "arcHostContext" in keyString -> arcHostContextKey "particles" in keyString -> particlesKey "handleConnections" in keyString -> handleConnectionsKey "planHandles" in keyString -> planHandlesKey else -> storageKey } } return Plan.Partition(arcId, hostId, listOf(particle)) } }
bsd-3-clause
PolymerLabs/arcs
javatests/arcs/core/host/NoOpArcHost.kt
1
1247
package arcs.core.host import arcs.core.common.ArcId import arcs.core.data.Plan /** Fake [ArcHost] used in Tests */ class NoOpArcHost(override val hostId: String) : ArcHost { /** Property used to test [pause] and [unpause] methods. */ var isPaused = false override suspend fun registeredParticles(): List<ParticleIdentifier> = emptyList() override suspend fun startArc(partition: Plan.Partition) = Unit override suspend fun stopArc(partition: Plan.Partition) = Unit override suspend fun lookupArcHostStatus(partition: Plan.Partition): ArcState = ArcState.Indeterminate override suspend fun isHostForParticle(particle: Plan.Particle): Boolean = false override suspend fun pause() { require(!isPaused) { "Can only pause an ArcHost that is currently unpaused." } isPaused = true } override suspend fun unpause() { require(isPaused) { "Can only unpause an ArcHost that is currently paused." } isPaused = false } override suspend fun waitForArcIdle(arcId: String) = Unit override suspend fun addOnArcStateChange( arcId: ArcId, block: ArcStateChangeCallback ): ArcStateChangeRegistration = throw NotImplementedError("Method not implemented for NoOpArcHost.") }
bsd-3-clause
PolymerLabs/arcs
javatests/arcs/core/storage/LocalStorageEndpointTest.kt
1
2573
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage import arcs.core.crdt.CrdtData import arcs.core.crdt.CrdtEntity import arcs.core.crdt.CrdtOperation import arcs.core.crdt.CrdtSingleton import arcs.core.crdt.VersionMap import arcs.core.data.util.toReferencable import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @OptIn(ExperimentalCoroutinesApi::class) @RunWith(JUnit4::class) class LocalStorageEndpointTest { @Test fun endpoint_idle_delegatesToStore() = runTest { val mock = mock<ActiveStore<*, CrdtOperation, *>>() val endpoint = LocalStorageEndpoint(mock, 0) endpoint.idle() verify(mock, times(1)).idle() } @Test fun endpoint_proxyMessage_delegatesToStoreAndCopiesId() = runTest { val mock = mock<ActiveStore<CrdtData, CrdtOperation, Any?>>() val endpoint = LocalStorageEndpoint(mock, 10) endpoint.onProxyMessage(DUMMY_PROXY_MESSAGE) verify(mock, times(1)).onProxyMessage(DUMMY_PROXY_MESSAGE.copy(id = 10)) } @Test fun endpoint_close_removesStoreCallback() = runTest { val mock = mock<ActiveStore<*, CrdtOperation, *>>() val endpoint = LocalStorageEndpoint(mock, 12) endpoint.close() verify(mock, times(1)).off(12) } private fun runTest(block: suspend CoroutineScope.() -> Unit): Unit = runBlockingTest { block() } companion object { val DUMMY_PROXY_MESSAGE = ProxyMessage.ModelUpdate<CrdtData, CrdtOperation, Any?>( model = CrdtEntity.Data( singletons = mapOf( "a" to CrdtSingleton<CrdtEntity.Reference>( VersionMap("alice" to 1), CrdtEntity.ReferenceImpl("AAA".toReferencable().id) ), "b" to CrdtSingleton<CrdtEntity.Reference>( VersionMap("bob" to 1), CrdtEntity.ReferenceImpl("BBB".toReferencable().id) ) ), collections = mapOf(), versionMap = VersionMap("Bar" to 2), creationTimestamp = 971, expirationTimestamp = -1 ), id = 1 ) } }
bsd-3-clause
onoderis/failchat
src/main/kotlin/failchat/chat/badge/BadgeStorage.kt
2
453
package failchat.chat.badge import java.util.concurrent.ConcurrentHashMap class BadgeStorage : BadgeFinder { private val badgesMap: MutableMap<BadgeOrigin, Map<out Any, Badge>> = ConcurrentHashMap() override fun findBadge(origin: BadgeOrigin, badgeId: Any): Badge? { return badgesMap.get(origin)?.get(badgeId) } fun putBadges(origin: BadgeOrigin, badges: Map<out Any, Badge>) { badgesMap.put(origin, badges) } }
gpl-3.0
raflop/kotlin-android-presentation
samples/openid/app/src/main/java/com/example/rlopatka/openidsample/UsersApi.kt
1
2094
package com.example.rlopatka.openidsample import com.google.gson.annotations.SerializedName import io.reactivex.Observable import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET /** * Created by rlopatka on 30.10.2017. */ interface UsersApi { @GET("userinfo") fun getCurrentUser(): Observable<User> } interface ApiFactory { fun <TApi> create(apiClass: Class<TApi>): TApi } object TokenReference { var token: String = "" } class ApiHeadersInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val builder = request.newBuilder() builder.addHeader("Authorization", "Bearer ${TokenReference.token}") return chain.proceed(builder.build()) } } class RetrofitApiFactory: ApiFactory { private var retrofit: Retrofit init { val httpClient = OkHttpClient.Builder() .addInterceptor(ApiHeadersInterceptor()) .build() this.retrofit = Retrofit.Builder() .client(httpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://kotlin-android-presentation.eu.auth0.com/") .build() } override fun <TApi> create(apiClass: Class<TApi>): TApi { return retrofit.create(apiClass) } } class UserApiClient(apiFactory: ApiFactory) { private val api: UsersApi by lazy { apiFactory.create(UsersApi::class.java) } fun getCurrentUser(): Observable<User> { return api.getCurrentUser() } } class User { @SerializedName("sub") var userId: String = "" @SerializedName("nickname") var userName: String = "" @SerializedName("email") var email: String = "" @SerializedName("updated_at") var updatedAt: String = "" }
gpl-3.0
Maccimo/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/base/scripting/projectStructure/ScriptDependenciesInfo.kt
4
5399
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.scripting.projectStructure import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.* import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle import org.jetbrains.kotlin.idea.base.scripting.ScriptingTargetPlatformDetector import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.dependencies.KotlinScriptSearchScope import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.TargetPlatformVersion import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class ScriptDependenciesInfo(override val project: Project) : IdeaModuleInfo, BinaryModuleInfo { abstract val sdk: Sdk? override val name = Name.special("<Script dependencies>") override val displayedName: String get() = KotlinBaseScriptingBundle.message("script.dependencies") override fun dependencies(): List<IdeaModuleInfo> = listOfNotNull(this, sdk?.let { SdkInfo(project, it) }) // NOTE: intentionally not taking corresponding script info into account // otherwise there is no way to implement getModuleInfo override fun hashCode() = project.hashCode() override fun equals(other: Any?): Boolean = other is ScriptDependenciesInfo && this.project == other.project override val moduleOrigin: ModuleOrigin get() = ModuleOrigin.LIBRARY override val sourcesModuleInfo: SourceForBinaryModuleInfo? get() = ScriptDependenciesSourceInfo.ForProject(project) override val platform: TargetPlatform get() = JvmPlatforms.unspecifiedJvmPlatform // TODO(dsavvinov): choose proper TargetVersion override val analyzerServices: PlatformDependentAnalyzerServices get() = JvmPlatformAnalyzerServices override val moduleContentScope: GlobalSearchScope get() = KotlinScriptSearchScope(project, contentScope) class ForFile( project: Project, val scriptFile: VirtualFile, val scriptDefinition: ScriptDefinition ) : ScriptDependenciesInfo(project), LanguageSettingsOwner { override val sdk: Sdk? get() = ScriptConfigurationManager.getInstance(project).getScriptSdk(scriptFile) override val languageVersionSettings: LanguageVersionSettings get() = ScriptingTargetPlatformDetector.getLanguageVersionSettings(project, scriptFile, scriptDefinition) override val targetPlatformVersion: TargetPlatformVersion get() = ScriptingTargetPlatformDetector.getTargetPlatformVersion(project, scriptFile, scriptDefinition) override val contentScope: GlobalSearchScope get() { // TODO: this is not very efficient because KotlinSourceFilterScope already checks if the files are in scripts classpath return KotlinSourceFilterScope.libraryClasses( ScriptConfigurationManager.getInstance(project).getScriptDependenciesClassFilesScope(scriptFile), project ) } } // we do not know which scripts these dependencies are class ForProject(project: Project) : ScriptDependenciesInfo(project) { override val sdk: Sdk? get() { return ScriptConfigurationManager.getInstance(project).getFirstScriptsSdk() } override val contentScope: GlobalSearchScope get() { return KotlinSourceFilterScope.libraryClasses( ScriptConfigurationManager.getInstance(project).getAllScriptsDependenciesClassFilesScope(), project ) } companion object { fun createIfRequired(project: Project, moduleInfos: List<IdeaModuleInfo>): IdeaModuleInfo? = if (moduleInfos.any { gradleApiPresentInModule(it) }) ForProject(project) else null private fun gradleApiPresentInModule(moduleInfo: IdeaModuleInfo) = moduleInfo is JvmLibraryInfo && moduleInfo.library.safeAs<LibraryEx>()?.isDisposed != true && moduleInfo.getLibraryRoots().any { // TODO: it's ugly ugly hack as Script (Gradle) SDK has to be provided in case of providing script dependencies. // So far the indication of usages of script dependencies by module is `gradleApi` // Note: to be deleted with https://youtrack.jetbrains.com/issue/KTIJ-19276 it.contains("gradle-api") } } } }
apache-2.0
blindpirate/gradle
build-logic-commons/gradle-plugin/src/main/kotlin/gradlebuild/testcleanup/TestFilesCleanupRootPlugin.kt
1
3172
/* * Copyright 2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.testcleanup import gradlebuild.testcleanup.extension.TestFilesCleanupBuildServiceRootExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.reporting.Reporting import org.gradle.api.tasks.testing.Test import org.gradle.build.event.BuildEventsListenerRegistry import org.gradle.kotlin.dsl.* import org.gradle.kotlin.dsl.support.serviceOf import java.io.File class TestFilesCleanupRootPlugin : Plugin<Project> { override fun apply(project: Project) { require(project.rootProject == project) { "This plugin should be applied to root project!" } val globalExtension = project.extensions.create<TestFilesCleanupBuildServiceRootExtension>("testFilesCleanupRoot") project.gradle.taskGraph.whenReady { val testFilesCleanupService = project.gradle.sharedServices.registerIfAbsent("testFilesCleanupBuildService", TestFilesCleanupService::class.java) { parameters.rootBuildDir.set(project.buildDir) parameters.projectStates.putAll(globalExtension.projectStates) parameters.cleanupRunnerStep.set(globalExtension.cleanupRunnerStep) parameters.testPathToBinaryResultsDirs.set(allTasks.filterIsInstance<Test>().associate { it.path to it.binaryResultsDirectory.get().asFile }) val taskPathToReports = [email protected] .associate { it.path to it.genericHtmlReports() + it.findTraceJson() } .filter { it.value.isNotEmpty() } parameters.taskPathToReports.set(globalExtension.taskPathToReports.map { taskPathToReportsInExtension -> (taskPathToReportsInExtension.keys + taskPathToReports.keys).associateWith { taskPathToReportsInExtension.getOrDefault(it, emptyList()) + taskPathToReports.getOrDefault(it, emptyList()) } }) } project.gradle.serviceOf<BuildEventsListenerRegistry>().onTaskCompletion(testFilesCleanupService) } } private fun Task.findTraceJson(): List<File> { if (this !is Test) { return emptyList() } // e.g. build/test-results/embeddedIntegTest/trace.json return listOf(project.buildDir.resolve("test-results/$name/trace.json")) } private fun Task.genericHtmlReports() = when (this) { is Reporting<*> -> listOf(this.reports["html"].outputLocation.get().asFile) else -> emptyList() } }
apache-2.0
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/action/motion/leftright/MotionRightMatchCharActionTest.kt
1
1354
/* * 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 org.jetbrains.plugins.ideavim.action.motion.leftright import com.maddyhome.idea.vim.command.VimStateMachine import org.jetbrains.plugins.ideavim.VimTestCase class MotionRightMatchCharActionTest : VimTestCase() { fun `test move and repeat`() { doTest( "fx;", "hello ${c}x hello x hello", "hello x hello ${c}x hello", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } fun `test move and repeat twice`() { doTest( "fx;;", "${c}hello x hello x hello x hello", "hello x hello x hello ${c}x hello", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } fun `test move and repeat two`() { doTest( "fx2;", "${c}hello x hello x hello x hello", "hello x hello x hello ${c}x hello", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } fun `test move and repeat three`() { doTest( "fx3;", "${c}hello x hello x hello x hello x hello", "hello x hello x hello x hello ${c}x hello", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) } }
mit
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/stubs/types/RustEnumItemStubElementType.kt
1
664
package org.rust.lang.core.stubs.types import com.intellij.psi.stubs.StubIndexKey import org.rust.lang.core.psi.RustEnumItem import org.rust.lang.core.psi.RustItem import org.rust.lang.core.psi.impl.RustEnumItemImpl import org.rust.lang.core.stubs.RustItemStub import org.rust.lang.core.stubs.index.RustStructOrEnumIndex class RustEnumItemStubElementType(debugName: String) : RustItemStubElementType<RustEnumItem>(debugName) { override fun createPsi(stub: RustItemStub): RustEnumItem = RustEnumItemImpl(stub, this) override val additionalIndexKeys: Array<StubIndexKey<String, RustItem>> get() = arrayOf(RustStructOrEnumIndex.KEY) }
mit
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/data/remote/api/theme/ThemeParser.kt
1
7324
package forpdateam.ru.forpda.model.data.remote.api.theme import android.util.Log import android.util.Pair import forpdateam.ru.forpda.entity.remote.others.pagination.Pagination import forpdateam.ru.forpda.entity.remote.theme.* import forpdateam.ru.forpda.model.data.remote.ParserPatterns import forpdateam.ru.forpda.model.data.remote.parser.BaseParser import forpdateam.ru.forpda.model.data.storage.IPatternProvider import java.util.regex.Matcher class ThemeParser( private val patternProvider: IPatternProvider ) : BaseParser() { private val scope = ParserPatterns.Topic fun parsePage(response: String, argUrl: String, hatOpen: Boolean = false, pollOpen: Boolean = false): ThemePage = ThemePage().also { page -> page.isHatOpen = hatOpen page.isPollOpen = pollOpen page.url = argUrl patternProvider .getPattern(scope.scope, scope.scroll_anchor) .matcher(argUrl) .findAll { page.addAnchor(it.group(1)) } patternProvider .getPattern(scope.scope, scope.topic_id) .matcher(response) .findOnce { page.forumId = it.group(1).toInt() page.id = it.group(2).toInt() } page.pagination = Pagination.parseForum(response) patternProvider .getPattern(scope.scope, scope.title) .matcher(response) .findOnce { page.title = it.group(1).fromHtml() page.desc = it.group(2).fromHtml() } patternProvider .getPattern(scope.scope, scope.already_in_fav) .matcher(response) .findOnce { page.isInFavorite = true patternProvider .getPattern(scope.scope, scope.fav_id) .matcher(response) .findOnce { page.favId = it.group(1).toInt() } } var attachMatcher: Matcher? = null val posts = patternProvider .getPattern(scope.scope, scope.posts) .matcher(response) .map { matcher -> ThemePost().apply { topicId = page.id forumId = page.forumId id = matcher.group(1).toInt() date = matcher.group(5) number = matcher.group(6).toInt() isOnline = matcher.group(7).contains("green") matcher.group(8).also { avatar = if (!it.isEmpty()) "https://s.4pda.to/forum/uploads/$it" else it } nick = matcher.group(9).fromHtml() userId = matcher.group(10).toInt() isCurator = matcher.group(11) != null groupColor = matcher.group(12) group = matcher.group(13) canMinusRep = !matcher.group(14).isEmpty() reputation = matcher.group(15) canPlusRep = !matcher.group(16).isEmpty() canReport = !matcher.group(17).isEmpty() canEdit = !matcher.group(18).isEmpty() canDelete = !matcher.group(19).isEmpty() page.canQuote = !matcher.group(20).isEmpty() canQuote = page.canQuote body = matcher.group(21) attachMatcher = attachMatcher?.reset(body) ?: patternProvider .getPattern(scope.scope, scope.attached_images) .matcher(body) attachMatcher ?.findAll { attachImages.add(Pair("https://${it.group(1)}", it.group(2))) } } /*if (isCurator() && getUserId() == ClientHelper.getUserId()) page.setCurator(true);*/ } page.posts.addAll(posts) patternProvider .getPattern(scope.scope, scope.poll_main) .matcher(response) .findOnce { matcher -> val isResult = matcher.group().contains("<img") val poll = Poll() poll.isResult = isResult poll.title = matcher.group(1).fromHtml() val questions = patternProvider .getPattern(scope.scope, scope.poll_questions) .matcher(matcher.group(2)) .map { PollQuestion().apply { title = it.group(1).fromHtml() val items = patternProvider .getPattern(scope.scope, scope.poll_question_item) .matcher(it.group(2)) .map { PollQuestionItem().apply { if (!isResult) { type = it.group(1) name = it.group(2).fromHtml() value = it.group(3).toInt() title = it.group(4).fromHtml() } else { title = it.group(5).fromHtml() votes = it.group(6).toInt() percent = java.lang.Float.parseFloat(it.group(7).replace(",", ".")) } } } this.questionItems.addAll(items) } } poll.questions.addAll(questions) patternProvider .getPattern(scope.scope, scope.poll_buttons) .matcher(matcher.group(4)) .findAll { val value = it.group(1) when { value.contains("Голосовать") -> poll.voteButton = true value.contains("результаты") -> poll.showResultsButton = true value.contains("пункты опроса") -> poll.showPollButton = true } } poll.votesCount = matcher.group(3).toInt() page.poll = poll } return page } }
gpl-3.0
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/widgets/BadgedImageView.kt
1
7042
package org.wordpress.android.widgets import android.content.Context import android.graphics.Bitmap import android.graphics.Bitmap.Config.ARGB_8888 import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Paint.ANTI_ALIAS_FLAG import android.graphics.Paint.Style import android.graphics.PorterDuff.Mode.CLEAR import android.graphics.PorterDuffXfermode import android.graphics.drawable.Drawable import android.util.AttributeSet import androidx.annotation.DrawableRes import androidx.appcompat.widget.AppCompatImageView import org.wordpress.android.R import org.wordpress.android.util.DisplayUtils /** * A ImageView that can draw a badge at the corner of its view. * The main difference between this implementation and others commonly found online, is that this one uses * Porter/Duff Compositing to create a transparent space between the badge background and the view. */ class BadgedImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatImageView(context, attrs, defStyleAttr) { companion object { const val DEFAULT_BADGE_BACKGROUND_SIZE = 16f const val DEFAULT_BADGE_BACKGROUND_BORDER_WIDTH = 0f const val DEFAULT_BADGE_ICON_SIZE = 16f const val DEFAULT_BADGE_HORIZONTAL_OFFSET = 0f const val DEFAULT_BADGE_VERTICAL_OFFSET = 0f } var badgeBackground: Drawable? = null set(value) { field = value invalidate() } var badgeBackgroundSize: Float = 0f set(value) { field = value invalidate() } var badgeBackgroundBorderWidth: Float = 0f set(value) { field = value invalidate() } var badgeIcon: Drawable? = null set(value) { field = value invalidate() } var badgeIconSize: Float = 0f set(value) { field = value invalidate() } var badgeHorizontalOffset: Float = 0f set(value) { field = value invalidate() } var badgeVerticalOffset: Float = 0f set(value) { field = value invalidate() } init { val styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.BadgedImageView) badgeBackground = styledAttributes.getDrawable( R.styleable.BadgedImageView_badgeBackground ) badgeBackgroundSize = styledAttributes.getDimension( R.styleable.BadgedImageView_badgeBackgroundSize, DisplayUtils.dpToPx(context, DEFAULT_BADGE_BACKGROUND_SIZE.toInt()).toFloat() ) badgeBackgroundBorderWidth = styledAttributes.getDimension( R.styleable.BadgedImageView_badgeBackgroundBorderWidth, DisplayUtils.dpToPx(context, DEFAULT_BADGE_BACKGROUND_BORDER_WIDTH.toInt()).toFloat() ) badgeIcon = styledAttributes.getDrawable( R.styleable.BadgedImageView_badgeIcon ) badgeIconSize = styledAttributes.getDimension( R.styleable.BadgedImageView_badgeIconSize, DisplayUtils.dpToPx(context, DEFAULT_BADGE_ICON_SIZE.toInt()).toFloat() ) badgeHorizontalOffset = styledAttributes.getDimension( R.styleable.BadgedImageView_badgeHorizontalOffset, DisplayUtils.dpToPx(context, DEFAULT_BADGE_HORIZONTAL_OFFSET.toInt()).toFloat() ) badgeVerticalOffset = styledAttributes.getDimension( R.styleable.BadgedImageView_badgeVerticalOffset, DisplayUtils.dpToPx(context, DEFAULT_BADGE_VERTICAL_OFFSET.toInt()).toFloat() ) styledAttributes.recycle() } private val paint = Paint(ANTI_ALIAS_FLAG) private val eraserPaint = Paint(ANTI_ALIAS_FLAG).apply { color = Color.TRANSPARENT style = Style.FILL_AND_STROKE strokeWidth = badgeBackgroundBorderWidth xfermode = PorterDuffXfermode(CLEAR) } private var tempCanvasBitmap: Bitmap? = null private var tempCanvas: Canvas? = null private var invalidated = true fun setBadgeBackground(@DrawableRes badgeBackgroundResId: Int) { badgeBackground = context.getDrawable(badgeBackgroundResId) } fun setBadgeIcon(@DrawableRes badgeIconResId: Int) { badgeIcon = context.getDrawable(badgeIconResId) } override fun invalidate() { invalidated = true super.invalidate() } override fun onSizeChanged(width: Int, height: Int, oldWidht: Int, oldHeight: Int) { super.onSizeChanged(width, height, oldWidht, oldHeight) val sizeChanged = width != oldWidht || height != oldHeight val isValid = width > 0 && height > 0 if (isValid && (tempCanvas == null || sizeChanged)) { tempCanvasBitmap = Bitmap.createBitmap( width + badgeBackgroundSize.toInt() / 2, height + badgeBackgroundSize.toInt() / 2, ARGB_8888 ) tempCanvas = tempCanvasBitmap?.let { Canvas(it) } invalidated = true } } override fun onDraw(canvas: Canvas) { if (invalidated) { tempCanvas?.let { clearCanvas(it) super.onDraw(it) drawBadge(it) } invalidated = false } if (!invalidated) { tempCanvasBitmap?.let { canvas.drawBitmap(it, 0f, 0f, paint) } } } private fun clearCanvas(canvas: Canvas) { canvas.drawColor(Color.TRANSPARENT, CLEAR) } private fun drawBadge(canvas: Canvas) { val x = pivotX + width / 2f - badgeBackgroundSize / 2f + badgeHorizontalOffset val y = pivotY + height / 2f - badgeBackgroundSize / 2f + badgeVerticalOffset drawBadgeSpace(canvas, x, y) drawBadgeBackground(canvas, x, y) drawBadgeIcon(canvas, x, y) } private fun drawBadgeSpace(canvas: Canvas, x: Float, y: Float) { canvas.drawCircle(x, y, badgeBackgroundSize / 2f + badgeBackgroundBorderWidth, eraserPaint) } private fun drawBadgeBackground(canvas: Canvas, x: Float, y: Float) { if (badgeBackground != null) { badgeBackground?.setBounds(0, 0, badgeBackgroundSize.toInt(), badgeBackgroundSize.toInt()) canvas.save() canvas.translate(x - badgeBackgroundSize / 2f, y - badgeBackgroundSize / 2f) badgeBackground?.draw(canvas) canvas.restore() } } private fun drawBadgeIcon(canvas: Canvas, x: Float, y: Float) { if (badgeIcon != null) { badgeIcon?.setBounds(0, 0, badgeIconSize.toInt(), badgeIconSize.toInt()) canvas.save() canvas.translate(x - badgeIconSize / 2f, y - badgeIconSize / 2f) badgeIcon?.draw(canvas) canvas.restore() } } }
gpl-2.0
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/EditorBloggingPromptsViewModel.kt
1
1679
package org.wordpress.android.ui.posts import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.first import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.bloggingprompts.BloggingPromptsStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named class EditorBloggingPromptsViewModel @Inject constructor( private val bloggingPromptsStore: BloggingPromptsStore, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) : ScopedViewModel(bgDispatcher) { private val _onBloggingPromptLoaded = MutableLiveData<Event<EditorLoadedPrompt>>() val onBloggingPromptLoaded: LiveData<Event<EditorLoadedPrompt>> = _onBloggingPromptLoaded private var isStarted = false fun start(site: SiteModel, bloggingPromptId: Int) { if (bloggingPromptId < 0) { return } if (isStarted) { return } isStarted = true loadPrompt(site, bloggingPromptId) } private fun loadPrompt(site: SiteModel, promptId: Int) = launch { val prompt = bloggingPromptsStore.getPromptById(site, promptId).first().model prompt?.let { _onBloggingPromptLoaded.postValue(Event(EditorLoadedPrompt(promptId, it.content, BLOGGING_PROMPT_TAG))) } } data class EditorLoadedPrompt(val promptId: Int, val content: String, val tag: String) } internal const val BLOGGING_PROMPT_TAG = "dailyprompt"
gpl-2.0
mdaniel/intellij-community
plugins/kotlin/run-configurations/junit/src/org/jetbrains/kotlin/idea/junit/framework/JUnit4KotlinTestFramework.kt
5
2233
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.junit.framework import com.intellij.execution.junit.JUnitUtil import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.siyeh.ig.junit.JUnitCommonClassNames import org.jetbrains.kotlin.idea.testIntegration.framework.AbstractKotlinTestFramework import org.jetbrains.kotlin.idea.testIntegration.framework.KotlinTestFramework.Companion.KOTLIN_TEST_TEST import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.utils.addToStdlib.safeAs class JUnit4KotlinTestFramework : AbstractKotlinTestFramework() { override val markerClassFqn: String = JUnitUtil.TEST_ANNOTATION override val disabledTestAnnotation: String = "org.junit.Ignore" override fun isTestClass(declaration: KtClassOrObject): Boolean { return super.isTestClass(declaration) && CachedValuesManager.getCachedValue(declaration) { CachedValueProvider.Result.create(isJUnit4TestClass(declaration), PsiModificationTracker.MODIFICATION_COUNT) } } override fun isTestMethod(declaration: KtNamedFunction): Boolean { return when { !super.isTestMethod(declaration) -> false declaration.annotationEntries.isEmpty() -> false else -> isJUnit4TestMethod(declaration) } } private fun isJUnit4TestMethod(declaration: KtNamedFunction): Boolean { return isAnnotated(declaration, setOf(JUnitCommonClassNames.ORG_JUNIT_TEST, KOTLIN_TEST_TEST)) } private fun isJUnit4TestClass(declaration: KtClassOrObject): Boolean { if (declaration.safeAs<KtClass>()?.isInner() == true) { return false } else if (declaration.isTopLevel() && isAnnotated(declaration, JUnitUtil.RUN_WITH)) { return true } return declaration.declarations .asSequence() .filterIsInstance<KtNamedFunction>() .any { isJUnit4TestMethod(it) } } }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/references/KtReference.kt
5
1539
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.references import com.intellij.psi.PsiMember import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.references.fe10.base.KtFe10Reference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice import org.jetbrains.kotlin.util.slicedMap.Slices val FE10_BINDING_RESOLVE_TO_DESCRIPTORS: ReadOnlySlice<KtReference, Collection<DeclarationDescriptor>> = Slices.createSimpleSlice() fun KtReference.resolveToDescriptors(bindingContext: BindingContext): Collection<DeclarationDescriptor> { return when (this) { is KtFe10Reference -> resolveToDescriptors(bindingContext) is KtDefaultAnnotationArgumentReference -> { when (val declaration = resolve()) { is KtDeclaration -> listOfNotNull(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration]) is PsiMember -> listOfNotNull(declaration.getJavaOrKotlinMemberDescriptor()) else -> emptyList() } } else -> { bindingContext[FE10_BINDING_RESOLVE_TO_DESCRIPTORS, this]?.let { return it } error("Reference $this should be KtFe10Reference but was ${this::class}") } } }
apache-2.0
micolous/metrodroid
src/androidTest/java/au/id/micolous/metrodroid/test/BaseInstrumentedTestPlatform.kt
1
3350
/* * BaseInstrumentedTestPlatform.kt * * Copyright 2018-2019 Michael Farrell <[email protected]> * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.test import android.content.Context import android.content.res.AssetManager import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import au.id.micolous.metrodroid.MetrodroidApplication import au.id.micolous.metrodroid.util.Preferences import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith import java.io.DataInputStream import java.io.InputStream actual fun <T> runAsync(block: suspend () -> T) { runBlocking { block() } } @RunWith(AndroidJUnit4::class) actual abstract class BaseInstrumentedTestPlatform { val context : Context get() = InstrumentationRegistry.getInstrumentation().context /** * Sets the Android and Java locales to a different language * and country. Does not clean up after execution, and should * only be used in tests. * * @param languageTag ITEF BCP-47 language tag string */ actual fun setLocale(languageTag: String) { LocaleTools.setLocale(languageTag, context.resources) } /** * Sets the system language used by [MetrodroidApplication] resources. * * This is needed for things that call * [au.id.micolous.metrodroid.multi.Localizer.localizeString]. * * @param languageTag ITEF BCP-47 language tag string */ fun setAndroidLanguage(languageTag: String?) { val l = languageTag?.let { LocaleTools.compatLocaleForLanguageTag(it) } LocaleTools.setResourcesLocale(l, MetrodroidApplication.instance.resources) } /** * Sets a boolean preference. * @param preference Key to the preference * @param value Desired state of the preference. */ private fun setBooleanPref(preference: String, value: Boolean) { val prefs = Preferences.getSharedPreferences() prefs.edit() .putBoolean(preference, value) .apply() } actual fun showRawStationIds(state: Boolean) { setBooleanPref(Preferences.PREF_SHOW_RAW_IDS, state) } actual fun showLocalAndEnglish(state: Boolean) { setBooleanPref(Preferences.PREF_SHOW_LOCAL_AND_ENGLISH, state) } actual fun loadAssetSafe(path: String) : InputStream? { try { return DataInputStream(context.assets.open(path, AssetManager.ACCESS_RANDOM)) } catch (e: Exception) { return null } } actual fun listAsset(path: String) : List <String>? = context.assets.list(path)?.toList() val isUnitTest get() = false }
gpl-3.0
ianhanniballake/ContractionTimer
mobile/src/main/java/com/ianhanniballake/contractiontimer/notification/NotificationUpdateReceiver.kt
1
15093
package com.ianhanniballake.contractiontimer.notification import android.app.AlarmManager import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import android.preference.PreferenceManager import android.provider.BaseColumns import android.text.format.DateUtils import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.RemoteInput import androidx.core.content.ContextCompat import com.ianhanniballake.contractiontimer.BuildConfig import com.ianhanniballake.contractiontimer.R import com.ianhanniballake.contractiontimer.appwidget.AppWidgetToggleReceiver import com.ianhanniballake.contractiontimer.extensions.goAsync import com.ianhanniballake.contractiontimer.provider.ContractionContract import com.ianhanniballake.contractiontimer.ui.MainActivity import com.ianhanniballake.contractiontimer.ui.Preferences import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * BroadcastReceiver which updates the ongoing notification */ class NotificationUpdateReceiver : BroadcastReceiver() { companion object { private const val TAG = "NotificationUpdate" private const val NOTIFICATION_ID = 0 private const val NOTIFICATION_CHANNEL = "timing" fun updateNotification(context: Context) { GlobalScope.launch { update(context) } } private suspend fun update(context: Context) = withContext(Dispatchers.IO) { NoteTranslucentActivity.checkServiceState(context) val notificationManager = NotificationManagerCompat.from(context) val preferences = PreferenceManager.getDefaultSharedPreferences(context) val notificationsEnabled = preferences.getBoolean( Preferences.NOTIFICATION_ENABLE_PREFERENCE_KEY, context.resources.getBoolean(R.bool.pref_notification_enable_default)) if (!notificationsEnabled) { if (BuildConfig.DEBUG) Log.d(TAG, "Notifications disabled, cancelling notification") notificationManager.cancel(NOTIFICATION_ID) return@withContext } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(context) } val projection = arrayOf(BaseColumns._ID, ContractionContract.Contractions.COLUMN_NAME_START_TIME, ContractionContract.Contractions.COLUMN_NAME_END_TIME, ContractionContract.Contractions.COLUMN_NAME_NOTE) val selection = ContractionContract.Contractions.COLUMN_NAME_START_TIME + ">?" val averagesTimeFrame = preferences.getString( Preferences.AVERAGE_TIME_FRAME_PREFERENCE_KEY, context.getString(R.string.pref_average_time_frame_default))!!.toLong() val timeCutoff = System.currentTimeMillis() - averagesTimeFrame val selectionArgs = arrayOf(timeCutoff.toString()) val data = context.contentResolver.query( ContractionContract.Contractions.CONTENT_URI, projection, selection, selectionArgs, null) if (data == null || !data.moveToFirst()) { if (BuildConfig.DEBUG) Log.d(TAG, "No data found, cancelling notification") notificationManager.cancel(NOTIFICATION_ID) data?.close() return@withContext } // Set an alarm to update the notification after first start time + average time frame amount of time // This ensures that if no contraction has started since then (likely, otherwise we would have been called in // the mean time) we will fail the above check as there will be no contractions within the average time period // and the notification will be cancelled val startTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME) val lastStartTime = data.getLong(startTimeColumnIndex) val autoCancelIntent = Intent(context, NotificationUpdateReceiver::class.java) val autoCancelPendingIntent = PendingIntent.getBroadcast(context, 0, autoCancelIntent, 0) val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(autoCancelPendingIntent) // We don't need to wake up the device as it doesn't matter if the notification is cancelled until the device // is woken up alarmManager.set( AlarmManager.RTC, lastStartTime + averagesTimeFrame, autoCancelPendingIntent ) // Build the notification if (BuildConfig.DEBUG) Log.d(TAG, "Building Notification") val builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) val publicBuilder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) builder.setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(context, R.color.primary)) .setCategory(NotificationCompat.CATEGORY_ALARM) publicBuilder.setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(context, R.color.primary)) .setCategory(NotificationCompat.CATEGORY_ALARM) val contentIntent = Intent(context, MainActivity::class.java).apply { addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME ) putExtra(MainActivity.LAUNCHED_FROM_NOTIFICATION_EXTRA, true) } val pendingIntent = PendingIntent.getActivity(context, 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(pendingIntent) publicBuilder.setContentIntent(pendingIntent) val wearableExtender = NotificationCompat.WearableExtender() // Determine whether a contraction is currently ongoing val endTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME) val contractionOngoing = data.isNull(endTimeColumnIndex) val startStopIntent = Intent(context, AppWidgetToggleReceiver::class.java) startStopIntent.putExtra(AppWidgetToggleReceiver.WIDGET_NAME_EXTRA, "notification") val startStopPendingIntent = PendingIntent.getBroadcast(context, 0, startStopIntent, PendingIntent.FLAG_UPDATE_CURRENT) if (contractionOngoing) { builder.setContentTitle(context.getString(R.string.notification_timing)) publicBuilder.setContentTitle(context.getString(R.string.notification_timing)) builder.addAction(R.drawable.ic_notif_action_stop, context.getString(R.string.appwidget_contraction_stop), startStopPendingIntent) wearableExtender.addAction(NotificationCompat.Action(R.drawable.ic_wear_action_stop, context.getString(R.string.appwidget_contraction_stop), startStopPendingIntent)) } else { builder.setContentTitle(context.getString(R.string.app_name)) publicBuilder.setContentTitle(context.getString(R.string.app_name)) builder.addAction(R.drawable.ic_notif_action_start, context.getString(R.string.appwidget_contraction_start), startStopPendingIntent) wearableExtender.addAction(NotificationCompat.Action(R.drawable.ic_wear_action_start, context.getString(R.string.appwidget_contraction_start), startStopPendingIntent)) } // See if there is a note and build a page if it exists val noteColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_NOTE) val note = data.getString(noteColumnIndex) val hasNote = note?.isNotBlank() == true // Fill in the 'when', which will be used to show live progress via the chronometer feature val time = if (contractionOngoing) data.getLong(startTimeColumnIndex) else data.getLong(endTimeColumnIndex) builder.setWhen(time) publicBuilder.setWhen(time) builder.setUsesChronometer(true) publicBuilder.setUsesChronometer(true) // Get the average duration and frequency var averageDuration = 0.0 var averageFrequency = 0.0 var numDurations = 0 var numFrequencies = 0 while (!data.isAfterLast) { val startTime = data.getLong(startTimeColumnIndex) if (!data.isNull(endTimeColumnIndex)) { val endTime = data.getLong(endTimeColumnIndex) val curDuration = endTime - startTime averageDuration = (curDuration + numDurations * averageDuration) / (numDurations + 1) numDurations++ } if (data.moveToNext()) { val prevContractionStartTime = data.getLong(startTimeColumnIndex) val curFrequency = startTime - prevContractionStartTime averageFrequency = (curFrequency + numFrequencies * averageFrequency) / (numFrequencies + 1) numFrequencies++ } } val averageDurationInSeconds = (averageDuration / 1000).toLong() val formattedAverageDuration = DateUtils.formatElapsedTime(averageDurationInSeconds) val averageFrequencyInSeconds = (averageFrequency / 1000).toLong() val formattedAverageFrequency = DateUtils.formatElapsedTime(averageFrequencyInSeconds) val contentText = context.getString(R.string.notification_content_text, formattedAverageDuration, formattedAverageFrequency) val bigTextWithoutNote = context.getString(R.string.notification_big_text, formattedAverageDuration, formattedAverageFrequency) val bigText = if (hasNote) { context.getString(R.string.notification_big_text_with_note, formattedAverageDuration, formattedAverageFrequency, note) } else { bigTextWithoutNote } builder.setContentText(contentText) .setStyle(NotificationCompat.BigTextStyle().bigText(bigText)) publicBuilder.setContentText(contentText) .setStyle(NotificationCompat.BigTextStyle().bigText(bigTextWithoutNote)) // Close the cursor data.close() // Create a separate page for the averages as the big text is not shown on Android Wear in chronometer mode val averagePage = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setContentTitle(context.getString(R.string.notification_second_page_title)) .setStyle( NotificationCompat.InboxStyle() .setBigContentTitle(context.getString(R.string.notification_second_page_title)) .addLine( context.getString( R.string.notification_second_page_duration, formattedAverageDuration ) ) .addLine( context.getString( R.string.notification_second_page_frequency, formattedAverageFrequency ) ) ) .build() wearableExtender.addPage(averagePage) if (hasNote) { val notePage = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setContentTitle(context.getString(R.string.detail_note_label)) .setContentText(note) .setStyle( NotificationCompat.BigTextStyle() .setBigContentTitle(context.getString(R.string.detail_note_label)) .bigText(note) ) .build() wearableExtender.addPage(notePage) } // Add 'Add Note'/'Edit Note' action val noteIconResId = if (hasNote) R.drawable.ic_notif_action_edit else R.drawable.ic_notif_action_add val wearIconResId = if (hasNote) R.drawable.ic_wear_action_edit else R.drawable.ic_wear_action_add val noteTitle = if (hasNote) context.getString(R.string.note_dialog_title_edit) else context.getString(R.string.note_dialog_title_add) val noteIntent = Intent(context, NoteTranslucentActivity::class.java) val notePendingIntent = PendingIntent.getActivity(context, 0, noteIntent, 0) val remoteInput = RemoteInput.Builder(Intent.EXTRA_TEXT).setLabel(noteTitle).build() builder.addAction(noteIconResId, noteTitle, notePendingIntent) wearableExtender.addAction(NotificationCompat.Action.Builder(wearIconResId, noteTitle, notePendingIntent).addRemoteInput(remoteInput).build()) val publicNotification = publicBuilder.build() builder.setPublicVersion(publicNotification) val notification = builder.extend(wearableExtender).build() notificationManager.notify(NOTIFICATION_ID, notification) } @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel(context: Context) { val notificationManager = context.getSystemService( NotificationManager::class.java) val channel = NotificationChannel(NOTIFICATION_CHANNEL, context.getString(R.string.notification_timing), NotificationManager.IMPORTANCE_LOW) channel.setShowBadge(false) notificationManager.createNotificationChannel(channel) } } override fun onReceive(context: Context, intent: Intent?) = goAsync { update(context) } }
bsd-3-clause
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/impl/GridImpl.kt
2
22250
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.gridLayout.impl import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.checkTrue import com.intellij.ui.dsl.gridLayout.* import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import java.awt.Insets import java.awt.Rectangle import java.util.* import javax.swing.JComponent import kotlin.math.max import kotlin.math.min @ApiStatus.Internal internal class GridImpl : Grid { override val resizableColumns = mutableSetOf<Int>() override val resizableRows = mutableSetOf<Int>() override val columnsGaps = mutableListOf<HorizontalGaps>() override val rowsGaps = mutableListOf<VerticalGaps>() val visible: Boolean get() = cells.any { it.visible } private val layoutData = LayoutData() private val cells = mutableListOf<Cell>() fun register(component: JComponent, constraints: Constraints) { if (!isEmpty(constraints)) { throw UiDslException("Some cells are occupied already: $constraints") } cells.add(ComponentCell(constraints, component)) } fun registerSubGrid(constraints: Constraints): Grid { if (!isEmpty(constraints)) { throw UiDslException("Some cells are occupied already: $constraints") } val result = GridImpl() cells.add(GridCell(constraints, result)) return result } fun unregister(component: JComponent): Boolean { val iterator = cells.iterator() for (cell in iterator) { when (cell) { is ComponentCell -> { if (cell.component == component) { iterator.remove() return true } } is GridCell -> { if (cell.content.unregister(component)) { return true } } } } return false } fun getPreferredSizeData(parentInsets: Insets): PreferredSizeData { calculatePreferredLayoutData() val outsideGaps = layoutData.getOutsideGaps(parentInsets) return PreferredSizeData(Dimension(layoutData.preferredWidth + outsideGaps.width, layoutData.preferredHeight + outsideGaps.height), outsideGaps ) } /** * Calculates [layoutData] and layouts all components */ fun layout(width: Int, height: Int, parentInsets: Insets) { calculatePreferredLayoutData() val outsideGaps = layoutData.getOutsideGaps(parentInsets) // Recalculate LayoutData for requested size with corrected insets calculateLayoutDataStep2(width - outsideGaps.width) calculateLayoutDataStep3() calculateLayoutDataStep4(height - outsideGaps.height) layout(outsideGaps.left, outsideGaps.top) } /** * Layouts components */ fun layout(x: Int, y: Int) { for (layoutCellData in layoutData.visibleCellsData) { val bounds = calculateBounds(layoutCellData, x, y) when (val cell = layoutCellData.cell) { is ComponentCell -> { cell.component.bounds = bounds } is GridCell -> { cell.content.layout(bounds.x, bounds.y) } } } } /** * Collects PreCalculationData for all components (including sub-grids) and applies size groups */ private fun collectPreCalculationData(): Map<JComponent, PreCalculationData> { val result = mutableMapOf<JComponent, PreCalculationData>() collectPreCalculationData(result) val widthGroups = result.values.groupBy { it.constraints.widthGroup } for ((widthGroup, preCalculationDataList) in widthGroups) { if (widthGroup == null) { continue } val maxWidth = preCalculationDataList.maxOf { it.calculatedPreferredSize.width } for (preCalculationData in preCalculationDataList) { preCalculationData.calculatedPreferredSize.width = maxWidth } } return result } private fun collectPreCalculationData(preCalculationDataMap: MutableMap<JComponent, PreCalculationData>) { for (cell in cells) { when (cell) { is ComponentCell -> { val component = cell.component if (!component.isVisible) { continue } val componentMinimumSize = component.minimumSize val componentPreferredSize = component.preferredSize preCalculationDataMap[component] = PreCalculationData(componentMinimumSize, componentPreferredSize, cell.constraints) } is GridCell -> { cell.content.collectPreCalculationData(preCalculationDataMap) } } } } /** * Calculates [layoutData] for preferred size */ private fun calculatePreferredLayoutData() { val preCalculationDataMap = collectPreCalculationData() calculateLayoutDataStep1(preCalculationDataMap) calculateLayoutDataStep2(layoutData.preferredWidth) calculateLayoutDataStep3() calculateLayoutDataStep4(layoutData.preferredHeight) calculateOutsideGaps(layoutData.preferredWidth, layoutData.preferredHeight) } /** * Step 1 of [layoutData] calculations */ private fun calculateLayoutDataStep1(preCalculationDataMap: Map<JComponent, PreCalculationData>) { layoutData.columnsSizeCalculator.reset() val visibleCellsData = mutableListOf<LayoutCellData>() var columnsCount = 0 var rowsCount = 0 for (cell in cells) { val preferredSize: Dimension when (cell) { is ComponentCell -> { val component = cell.component if (!component.isVisible) { continue } val preCalculationData = preCalculationDataMap[component] preferredSize = preCalculationData!!.calculatedPreferredSize } is GridCell -> { val grid = cell.content if (!grid.visible) { continue } grid.calculateLayoutDataStep1(preCalculationDataMap) preferredSize = Dimension(grid.layoutData.preferredWidth, 0) } } val layoutCellData: LayoutCellData with(cell.constraints) { layoutCellData = LayoutCellData(cell = cell, preferredSize = preferredSize, columnGaps = HorizontalGaps( left = columnsGaps.getOrNull(x)?.left ?: 0, right = columnsGaps.getOrNull(x + width - 1)?.right ?: 0), rowGaps = VerticalGaps( top = rowsGaps.getOrNull(y)?.top ?: 0, bottom = rowsGaps.getOrNull(y + height - 1)?.bottom ?: 0) ) columnsCount = max(columnsCount, x + width) rowsCount = max(rowsCount, y + height) } visibleCellsData.add(layoutCellData) layoutData.columnsSizeCalculator.addConstraint(cell.constraints.x, cell.constraints.width, layoutCellData.cellPaddedWidth) } layoutData.visibleCellsData = visibleCellsData layoutData.preferredWidth = layoutData.columnsSizeCalculator.calculatePreferredSize() layoutData.dimension.setSize(columnsCount, rowsCount) } /** * Step 2 of [layoutData] calculations */ private fun calculateLayoutDataStep2(width: Int) { layoutData.columnsCoord = layoutData.columnsSizeCalculator.calculateCoords(width, resizableColumns) for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell if (cell is GridCell) { cell.content.calculateLayoutDataStep2(layoutData.getFullPaddedWidth(layoutCellData)) } } } /** * Step 3 of [layoutData] calculations */ private fun calculateLayoutDataStep3() { layoutData.rowsSizeCalculator.reset() layoutData.baselineData.reset() for (layoutCellData in layoutData.visibleCellsData) { val constraints = layoutCellData.cell.constraints layoutCellData.baseline = null when (val cell = layoutCellData.cell) { is ComponentCell -> { if (!isSupportedBaseline(constraints)) { continue } val componentWidth = layoutData.getPaddedWidth(layoutCellData) + constraints.visualPaddings.width val baseline: Int if (componentWidth >= 0) { baseline = cell.constraints.componentHelper?.getBaseline(componentWidth, layoutCellData.preferredSize.height) ?: cell.component.getBaseline(componentWidth, layoutCellData.preferredSize.height) // getBaseline changes preferredSize, at least for JLabel layoutCellData.preferredSize.height = cell.component.preferredSize.height } else { baseline = -1 } if (baseline >= 0) { layoutCellData.baseline = baseline layoutData.baselineData.registerBaseline(layoutCellData, baseline) } } is GridCell -> { val grid = cell.content grid.calculateLayoutDataStep3() layoutCellData.preferredSize.height = grid.layoutData.preferredHeight if (grid.layoutData.dimension.height == 1 && isSupportedBaseline(constraints)) { // Calculate baseline for grid val gridBaselines = VerticalAlign.values() .mapNotNull { var result: Pair<VerticalAlign, RowBaselineData>? = null if (it != VerticalAlign.FILL) { val baselineData = grid.layoutData.baselineData.get(it) if (baselineData != null) { result = Pair(it, baselineData) } } result } if (gridBaselines.size == 1) { val (verticalAlign, gridBaselineData) = gridBaselines[0] val baseline = calculateBaseline(layoutCellData.preferredSize.height, verticalAlign, gridBaselineData) layoutCellData.baseline = baseline layoutData.baselineData.registerBaseline(layoutCellData, baseline) } } } } } for (layoutCellData in layoutData.visibleCellsData) { val constraints = layoutCellData.cell.constraints val height = if (layoutCellData.baseline == null) layoutCellData.gapHeight - layoutCellData.cell.constraints.visualPaddings.height + layoutCellData.preferredSize.height else { val rowBaselineData = layoutData.baselineData.get(layoutCellData) rowBaselineData!!.height } // Cell height including gaps and excluding visualPaddings layoutData.rowsSizeCalculator.addConstraint(constraints.y, constraints.height, height) } layoutData.preferredHeight = layoutData.rowsSizeCalculator.calculatePreferredSize() } /** * Step 4 of [layoutData] calculations */ private fun calculateLayoutDataStep4(height: Int) { layoutData.rowsCoord = layoutData.rowsSizeCalculator.calculateCoords(height, resizableRows) for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell if (cell is GridCell) { val subGridHeight = if (cell.constraints.verticalAlign == VerticalAlign.FILL) layoutData.getFullPaddedHeight(layoutCellData) else cell.content.layoutData.preferredHeight cell.content.calculateLayoutDataStep4(subGridHeight) } } } private fun calculateOutsideGaps(width: Int, height: Int) { var left = 0 var right = 0 var top = 0 var bottom = 0 for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell // Update visualPaddings val component = (cell as? ComponentCell)?.component val layout = component?.layout as? GridLayout if (layout != null && component.getClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS) != false) { val preferredSizeData = layout.getPreferredSizeData(component) cell.constraints.visualPaddings = preferredSizeData.outsideGaps } val bounds = calculateBounds(layoutCellData, 0, 0) when (cell) { is ComponentCell -> { left = min(left, bounds.x) top = min(top, bounds.y) right = max(right, bounds.x + bounds.width - width) bottom = max(bottom, bounds.y + bounds.height - height) } is GridCell -> { cell.content.calculateOutsideGaps(bounds.width, bounds.height) val outsideGaps = cell.content.layoutData.outsideGaps left = min(left, bounds.x - outsideGaps.left) top = min(top, bounds.y - outsideGaps.top) right = max(right, bounds.x + bounds.width + outsideGaps.right - width) bottom = max(bottom, bounds.y + bounds.height + outsideGaps.bottom - height) } } } layoutData.outsideGaps = Gaps(top = -top, left = -left, bottom = bottom, right = right) } fun getConstraints(component: JComponent): Constraints? { for (cell in cells) { when(cell) { is ComponentCell -> { if (cell.component == component) { return cell.constraints } } is GridCell -> { val constraints = cell.content.getConstraints(component) if (constraints != null) { return constraints } } } } return null } /** * Calculate bounds for [layoutCellData] */ private fun calculateBounds(layoutCellData: LayoutCellData, offsetX: Int, offsetY: Int): Rectangle { val cell = layoutCellData.cell val constraints = cell.constraints val visualPaddings = constraints.visualPaddings val paddedWidth = layoutData.getPaddedWidth(layoutCellData) val fullPaddedWidth = layoutData.getFullPaddedWidth(layoutCellData) val x = layoutData.columnsCoord[constraints.x] + constraints.gaps.left + layoutCellData.columnGaps.left - visualPaddings.left + when (constraints.horizontalAlign) { HorizontalAlign.LEFT -> 0 HorizontalAlign.CENTER -> (fullPaddedWidth - paddedWidth) / 2 HorizontalAlign.RIGHT -> fullPaddedWidth - paddedWidth HorizontalAlign.FILL -> 0 } val fullPaddedHeight = layoutData.getFullPaddedHeight(layoutCellData) val paddedHeight = if (constraints.verticalAlign == VerticalAlign.FILL) fullPaddedHeight else min(fullPaddedHeight, layoutCellData.preferredSize.height - visualPaddings.height) val y: Int val baseline = layoutCellData.baseline if (baseline == null) { y = layoutData.rowsCoord[constraints.y] + layoutCellData.rowGaps.top + constraints.gaps.top - visualPaddings.top + when (constraints.verticalAlign) { VerticalAlign.TOP -> 0 VerticalAlign.CENTER -> (fullPaddedHeight - paddedHeight) / 2 VerticalAlign.BOTTOM -> fullPaddedHeight - paddedHeight VerticalAlign.FILL -> 0 } } else { val rowBaselineData = layoutData.baselineData.get(layoutCellData)!! val rowHeight = layoutData.getHeight(layoutCellData) y = layoutData.rowsCoord[constraints.y] + calculateBaseline(rowHeight, constraints.verticalAlign, rowBaselineData) - baseline } return Rectangle(offsetX + x, offsetY + y, paddedWidth + visualPaddings.width, paddedHeight + visualPaddings.height) } /** * Calculates baseline for specified [height] */ private fun calculateBaseline(height: Int, verticalAlign: VerticalAlign, rowBaselineData: RowBaselineData): Int { return rowBaselineData.maxAboveBaseline + when (verticalAlign) { VerticalAlign.TOP -> 0 VerticalAlign.CENTER -> (height - rowBaselineData.height) / 2 VerticalAlign.BOTTOM -> height - rowBaselineData.height VerticalAlign.FILL -> 0 } } private fun isEmpty(constraints: Constraints): Boolean { for (cell in cells) { with(cell.constraints) { if (constraints.x + constraints.width > x && x + width > constraints.x && constraints.y + constraints.height > y && y + height > constraints.y ) { return false } } } return true } } /** * Data that collected before layout/preferred size calculations */ private class LayoutData { // // Step 1 // var visibleCellsData = emptyList<LayoutCellData>() val columnsSizeCalculator = ColumnsSizeCalculator() var preferredWidth = 0 /** * Maximum indexes of occupied cells excluding hidden components */ val dimension = Dimension() // // Step 2 // var columnsCoord = emptyArray<Int>() // // Step 3 // val rowsSizeCalculator = ColumnsSizeCalculator() var preferredHeight = 0 val baselineData = BaselineData() // // Step 4 // var rowsCoord = emptyArray<Int>() // // After Step 4 (for preferred size only) // /** * Extra gaps that guarantee no visual clippings (like focus rings). * Calculated for preferred size and this value is used for enlarged container as well. * [GridLayout] takes into account [outsideGaps] for in following cases: * 1. Preferred size is increased when needed to avoid clipping * 2. Layout content can be moved a little from left/top corner to avoid clipping * 3. In parents that also use [GridLayout]: aligning by visual padding is corrected according [outsideGaps] together with insets, * so components in parent and this container are aligned together */ var outsideGaps = Gaps.EMPTY fun getPaddedWidth(layoutCellData: LayoutCellData): Int { val fullPaddedWidth = getFullPaddedWidth(layoutCellData) return if (layoutCellData.cell.constraints.horizontalAlign == HorizontalAlign.FILL) fullPaddedWidth else min(fullPaddedWidth, layoutCellData.preferredSize.width - layoutCellData.cell.constraints.visualPaddings.width) } fun getFullPaddedWidth(layoutCellData: LayoutCellData): Int { val constraints = layoutCellData.cell.constraints return columnsCoord[constraints.x + constraints.width] - columnsCoord[constraints.x] - layoutCellData.gapWidth } fun getHeight(layoutCellData: LayoutCellData): Int { val constraints = layoutCellData.cell.constraints return rowsCoord[constraints.y + constraints.height] - rowsCoord[constraints.y] } fun getFullPaddedHeight(layoutCellData: LayoutCellData): Int { return getHeight(layoutCellData) - layoutCellData.gapHeight } fun getOutsideGaps(parentInsets: Insets): Gaps { return Gaps( top = max(outsideGaps.top, parentInsets.top), left = max(outsideGaps.left, parentInsets.left), bottom = max(outsideGaps.bottom, parentInsets.bottom), right = max(outsideGaps.right, parentInsets.right), ) } } /** * For sub-grids height of [preferredSize] calculated on late steps of [LayoutData] calculations */ private data class LayoutCellData(val cell: Cell, val preferredSize: Dimension, val columnGaps: HorizontalGaps, val rowGaps: VerticalGaps) { /** * Calculated on step 3 */ var baseline: Int? = null val gapWidth: Int get() = cell.constraints.gaps.width + columnGaps.width val gapHeight: Int get() = cell.constraints.gaps.height + rowGaps.height /** * Cell width including gaps and excluding visualPaddings */ val cellPaddedWidth: Int get() = preferredSize.width + gapWidth - cell.constraints.visualPaddings.width } private sealed class Cell(val constraints: Constraints) { abstract val visible: Boolean } private class ComponentCell(constraints: Constraints, val component: JComponent) : Cell(constraints) { override val visible: Boolean get() = component.isVisible } private class GridCell(constraints: Constraints, val content: GridImpl) : Cell(constraints) { override val visible: Boolean get() = content.visible } /** * Contains baseline data for rows, see [Constraints.baselineAlign] */ private class BaselineData { private val rowBaselineData = mutableMapOf<Int, MutableMap<VerticalAlign, RowBaselineData>>() fun reset() { rowBaselineData.clear() } fun registerBaseline(layoutCellData: LayoutCellData, baseline: Int) { val constraints = layoutCellData.cell.constraints checkTrue(isSupportedBaseline(constraints)) val rowBaselineData = getOrCreate(layoutCellData) rowBaselineData.maxAboveBaseline = max(rowBaselineData.maxAboveBaseline, baseline + layoutCellData.rowGaps.top + constraints.gaps.top - constraints.visualPaddings.top) rowBaselineData.maxBelowBaseline = max(rowBaselineData.maxBelowBaseline, layoutCellData.preferredSize.height - baseline + layoutCellData.rowGaps.bottom + constraints.gaps.bottom - constraints.visualPaddings.bottom) } /** * Returns data for single available row */ fun get(verticalAlign: VerticalAlign): RowBaselineData? { checkTrue(rowBaselineData.size <= 1) return rowBaselineData.firstNotNullOfOrNull { it.value }?.get(verticalAlign) } fun get(layoutCellData: LayoutCellData): RowBaselineData? { val constraints = layoutCellData.cell.constraints return rowBaselineData[constraints.y]?.get(constraints.verticalAlign) } private fun getOrCreate(layoutCellData: LayoutCellData): RowBaselineData { val constraints = layoutCellData.cell.constraints val mapByAlign = rowBaselineData.getOrPut(constraints.y) { EnumMap(VerticalAlign::class.java) } return mapByAlign.getOrPut(constraints.verticalAlign) { RowBaselineData() } } } /** * Max sizes for a row which include all gaps and exclude paddings */ private data class RowBaselineData(var maxAboveBaseline: Int = 0, var maxBelowBaseline: Int = 0) { val height: Int get() = maxAboveBaseline + maxBelowBaseline } private fun isSupportedBaseline(constraints: Constraints): Boolean { return constraints.baselineAlign && constraints.verticalAlign != VerticalAlign.FILL && constraints.height == 1 } @ApiStatus.Internal internal class PreCalculationData(val minimumSize: Dimension, val preferredSize: Dimension, val constraints: Constraints) { /** * Preferred size based on minimum/preferred sizes and size groups */ var calculatedPreferredSize = Dimension(max(minimumSize.width, preferredSize.width), max(minimumSize.height, preferredSize.height)) } @ApiStatus.Internal internal data class PreferredSizeData(val preferredSize: Dimension, val outsideGaps: Gaps)
apache-2.0
GunoH/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/diff/impl/incrementalMerge/MergeBuilderTest.kt
8
5617
/* * 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.openapi.diff.impl.incrementalMerge import com.intellij.diff.DiffTestCase import com.intellij.diff.comparison.ComparisonMergeUtil import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.comparison.iterables.DiffIterableUtil.fair import com.intellij.diff.util.MergeRange import com.intellij.diff.util.Range import com.intellij.openapi.util.TextRange class MergeBuilderTest : DiffTestCase() { fun testEqual() { test(1, 1, 1) { addLeft(TextRange(0, 1), TextRange(0, 1)) addRight(TextRange(0, 1), TextRange(0, 1)) } } fun testWholeConflict() { test(1, 2, 3) { addExpected(TextRange(0, 1), TextRange(0, 2), TextRange(0, 3)) } } fun testTailInsert() { test(1, 1, 2) { val range = TextRange(0, 1) addLeft(range, range) addRight(range, range) addExpected(TextRange(1, 1), TextRange(1, 1), TextRange(1, 2)) } } fun testSameInsertsConflicts1() { test(2, 1, 2) { val base = TextRange(0, 1) val version = TextRange(1, 2) addLeft(base, version) addRight(base, version) addExpected(TextRange(0, 1), TextRange(0, 0), TextRange(0, 1)) } } fun testSameInsertsConflicts2() { test(2, 2, 2) { val base = TextRange(1, 2) val version = TextRange(0, 1) addLeft(base, version) addRight(base, version) addExpected(TextRange(0, 0), TextRange(0, 1), TextRange(0, 0)) addExpected(TextRange(1, 2), TextRange(2, 2), TextRange(1, 2)) } } fun testHeadInsert() { test(1, 1, 2) { val range = TextRange(0, 1) addRight(range, TextRange(1, 2)) addLeft(range, range) addExpected(TextRange(0, 0), TextRange(0, 0), TextRange(0, 1)) } } fun testOneSideChange() { test(3, 2, 2) { addRight(TextRange(0, 2), TextRange(0, 2)) addLeft(TextRange(1, 2), TextRange(2, 3)) addExpected(TextRange(0, 2), TextRange(0, 1), TextRange(0, 1)) } } fun testNotAllignedConflict() { test(3, 4, 3) { addLeft(TextRange(1, 3), TextRange(0, 2)) addRight(TextRange(2, 4), TextRange(1, 3)) addExpected(TextRange(0, 1), TextRange(0, 2), TextRange(0, 1)) addExpected(TextRange(2, 3), TextRange(3, 4), TextRange(2, 3)) } } fun testBug() { test(3, 2, 1) { addRight(TextRange(0, 1), TextRange(0, 1)) addLeft(TextRange(0, 2), TextRange(0, 2)) addExpected(TextRange(1, 3), TextRange(1, 2), TextRange(1, 1)) } } fun testMultiChanges() { test(10, 10, 7) { addLeft(TextRange(1, 8), TextRange(1, 8)) addRight(TextRange(1, 2), TextRange(0, 1)) addRight(TextRange(3, 4), TextRange(1, 2)) addRight(TextRange(4, 5), TextRange(3, 4)) addRight(TextRange(6, 7), TextRange(5, 6)) addLeft(TextRange(9, 10), TextRange(9, 10)) addExpected(TextRange(0, 1), TextRange(0, 1), TextRange(0, 0)) addExpected(TextRange(2, 3), TextRange(2, 3), TextRange(1, 1)) addExpected(TextRange(4, 4), TextRange(4, 4), TextRange(2, 3)) addExpected(TextRange(5, 6), TextRange(5, 6), TextRange(4, 5)) addExpected(TextRange(7, 10), TextRange(7, 10), TextRange(6, 7)) } } fun testNoIntersection() { test(3, 5, 3) { addLeft(TextRange(0, 1), TextRange(0, 1)) addRight(TextRange(0, 2), TextRange(0, 2)) addLeft(TextRange(3, 5), TextRange(1, 3)) addRight(TextRange(4, 5), TextRange(2, 3)) addExpected(TextRange(1, 2), TextRange(1, 4), TextRange(1, 2)) } } private fun test(leftCount: Int, baseCount: Int, rightCount: Int, block: Test.() -> Unit) { val test = Test(leftCount, baseCount, rightCount) block(test) test.check() } private inner class Test(val leftCount: Int, val baseCount: Int, val rightCount: Int) { private val leftUnchanged: MutableList<Range> = mutableListOf() private val rightUnchanged: MutableList<Range> = mutableListOf() private val expected: MutableList<MergeRange> = mutableListOf() fun addLeft(base: TextRange, left: TextRange) { leftUnchanged += Range(base.startOffset, base.endOffset, left.startOffset, left.endOffset) } fun addRight(base: TextRange, right: TextRange) { rightUnchanged += Range(base.startOffset, base.endOffset, right.startOffset, right.endOffset) } fun addExpected(left: TextRange, base: TextRange, right: TextRange) { expected += MergeRange(left.startOffset, left.endOffset, base.startOffset, base.endOffset, right.startOffset, right.endOffset) } fun check() { val left = fair(DiffIterableUtil.createUnchanged(leftUnchanged, baseCount, leftCount)) val right = fair(DiffIterableUtil.createUnchanged(rightUnchanged, baseCount, rightCount)) val actual = ComparisonMergeUtil.buildSimple(left, right, CANCELLATION) assertEquals(expected, actual) } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MergeElseIfIntention.kt
3
1484
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.psi.* class MergeElseIfIntention : SelfTargetingIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("merge.else.if") ) { override fun isApplicableTo(element: KtIfExpression, caretOffset: Int): Boolean { val elseBody = element.`else` ?: return false val nestedIf = elseBody.nestedIf() ?: return false return nestedIf.`else` == null } override fun applyTo(element: KtIfExpression, editor: Editor?) { val nestedIf = element.`else`?.nestedIf() ?: return val condition = nestedIf.condition ?: return val nestedBody = nestedIf.then ?: return val factory = KtPsiFactory(element) element.`else`?.replace( factory.createExpressionByPattern("if ($0) $1", condition, nestedBody) ) } companion object { private fun KtExpression.nestedIf() = if (this is KtBlockExpression) { this.statements.singleOrNull() as? KtIfExpression } else { null } } }
apache-2.0
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/DeleteNamedLayoutActionGroup.kt
2
1086
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.actions import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.toolWindow.ToolWindowDefaultLayoutManager class DeleteNamedLayoutActionGroup : ActionGroup(), DumbAware { private val childrenCache = NamedLayoutListBasedCache<AnAction> { name -> if ( name != ToolWindowDefaultLayoutManager.DEFAULT_LAYOUT_NAME && name != ToolWindowDefaultLayoutManager.getInstance().activeLayoutName ) { DeleteNamedLayoutAction(name) } else { null } }.apply { dependsOnActiveLayout = true } override fun getChildren(e: AnActionEvent?): Array<AnAction> = childrenCache.getCachedOrUpdatedArray(AnAction.EMPTY_ARRAY) override fun getActionUpdateThread() = ActionUpdateThread.BGT }
apache-2.0
helloworld1/FreeOTPPlus
app/src/main/java/org/fedorahosted/freeotp/util/TokenImageViewExtensions.kt
1
1390
package org.fedorahosted.freeotp.util import android.widget.ImageView import com.amulyakhare.textdrawable.TextDrawable import com.amulyakhare.textdrawable.util.ColorGenerator import com.bumptech.glide.Glide import org.fedorahosted.freeotp.R import org.fedorahosted.freeotp.data.OtpToken import org.liberty.android.freeotp.token_images.TokenImage import org.liberty.android.freeotp.token_images.matchToken fun ImageView.setTokenImage(token: OtpToken) { when { token.imagePath != null -> { Glide.with(this) .load(token.imagePath) .placeholder(R.drawable.logo) .into(this) } !token.issuer.isNullOrBlank() -> { matchIssuerWithTokenThumbnail(token)?.let { setImageResource(it) } ?: run { val tokenText = token.issuer?.substring(0, 1) ?: "" val color = ColorGenerator.MATERIAL.getColor(tokenText) val tokenTextDrawable = TextDrawable.builder().buildRoundRect(tokenText, color, 10) setImageDrawable(tokenTextDrawable) } } else -> { setImageResource(R.drawable.logo) } } } private fun matchIssuerWithTokenThumbnail(token: OtpToken): Int? { return TokenImage.values().firstOrNull { it.matchToken(token.issuer, token.label) }?.resource }
apache-2.0
ledboot/Toffee
app/src/main/java/com/ledboot/toffee/widget/refreshLoadView/BaseViewHolder.kt
1
1547
package com.ledboot.toffee.widget.refreshLoadView import android.util.SparseArray import android.view.View import android.widget.Adapter import android.widget.AdapterView import androidx.annotation.IdRes import androidx.databinding.ViewDataBinding import androidx.databinding.library.baseAdapters.BR import androidx.recyclerview.widget.RecyclerView /** * Created by Gwynn on 17/10/16. */ class BaseViewHolder<T> : RecyclerView.ViewHolder { constructor(binding: ViewDataBinding) : this(binding.root) { this.binding = binding } constructor(itemView: View) : super(itemView) protected var binding: ViewDataBinding? = null private var views: SparseArray<View> = SparseArray() var mAdapter: BaseQuickAdapter<*, *>? = null public fun setVisible(@IdRes viewId: Int, visible: Boolean): BaseViewHolder<T> { var view: View = getView(viewId) view.visibility = if (visible) View.VISIBLE else View.INVISIBLE return this } public fun <T : View> getView(@IdRes viewId: Int): T { var view = views.get(viewId) if (view == null) { view = itemView.findViewById(viewId) views.put(viewId, view) } return view as T } public fun setAdapter(@IdRes viewId: Int, adapter: Adapter): BaseViewHolder<T> { val view = getView<AdapterView<*>>(viewId) view.adapter = adapter return this } fun bind(data: T) { binding!!.setVariable(BR.item, data) binding!!.executePendingBindings() } }
apache-2.0
jk1/Intellij-idea-mail
src/main/kotlin/github/jk1/smtpidea/ui/EnumRadioGroup.kt
1
848
package github.jk1.smtpidea.ui import javax.swing.ButtonGroup import javax.swing.AbstractButton import java.util.HashMap /** * Radio button group mapped to enum set. Simplifies * UI control bindings for enum-typed configuration properties. */ class EnumRadioGroup<T> : ButtonGroup(){ private var mapping: MutableMap<T, AbstractButton> = HashMap<T, AbstractButton>() public fun add(b: AbstractButton, value: T) { super.add(b) mapping.put(value, b) } public fun getSelected(): T { for (entry in mapping.entrySet()) { if (entry.getValue().isSelected()) { return entry.getKey() } } throw IllegalStateException("No selected value found for EnumRadioGroup") } public fun setSelected(value: T): Unit = mapping.get(value)?.setSelected(true) }
gpl-2.0
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/LocalVariableDeclarationSideOnlyInspection.kt
1
4830
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.demonwav.mcdev.util.findContainingClass import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiLocalVariable import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class LocalVariableDeclarationSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of local variable declaration annotated with @SideOnly" override fun buildErrorString(vararg infos: Any): String { val error = infos[0] as Error return error.getErrorString(*SideOnlyUtil.getSubArray(infos)) } override fun getStaticDescription() = "A variable whose class declaration is annotated with @SideOnly for one side cannot be declared in a class" + " or method that does not match the same side." override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val variableClass = infos[3] as PsiClass return if (variableClass.isWritable) { RemoveAnnotationInspectionGadgetsFix(variableClass, "Remove @SideOnly annotation from variable class declaration") } else { null } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitLocalVariable(variable: PsiLocalVariable) { val psiClass = variable.findContainingClass() ?: return if (!SideOnlyUtil.beginningCheck(variable)) { return } val type = variable.type as? PsiClassType ?: return val variableClass = type.resolve() ?: return val variableSide = SideOnlyUtil.getSideForClass(variableClass) if (variableSide === Side.NONE || variableSide === Side.INVALID) { return } val containingClassSide = SideOnlyUtil.getSideForClass(psiClass) val methodSide = SideOnlyUtil.checkElementInMethod(variable) var classAnnotated = false if (containingClassSide !== Side.NONE && containingClassSide !== Side.INVALID) { if (variableSide !== containingClassSide) { registerVariableError( variable, Error.VAR_CROSS_ANNOTATED_CLASS, variableSide.annotation, containingClassSide.annotation, variableClass ) } classAnnotated = true } if (methodSide === Side.INVALID) { return } if (variableSide !== methodSide) { if (methodSide === Side.NONE) { if (!classAnnotated) { registerVariableError( variable, Error.VAR_UNANNOTATED_METHOD, variableSide.annotation, methodSide.annotation, variableClass ) } } else { registerVariableError( variable, Error.VAR_CROSS_ANNOTATED_METHOD, variableSide.annotation, methodSide.annotation, variableClass ) } } } } } enum class Error { VAR_CROSS_ANNOTATED_CLASS { override fun getErrorString(vararg infos: Any): String { return "A local variable whose class is annotated with ${infos[0]} cannot be used in a class annotated with ${infos[1]}" } }, VAR_CROSS_ANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "A local variable whose class is annotated with ${infos[0]} cannot be used in a method annotated with ${infos[1]}" } }, VAR_UNANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "A local variable whose class is annotated with ${infos[0]} cannot be used in an un-annotated method." } }; abstract fun getErrorString(vararg infos: Any): String } }
mit
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_texture_storage_multisample.kt
4
2200
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_texture_storage_multisample = "ARBTextureStorageMultisample".nativeClassGL("ARB_texture_storage_multisample") { documentation = """ Native bindings to the $registryLink extension. The ${ARB_texture_storage.link} extension and OpenGL 4.2 introduced the concept of immutable texture objects. With these objects, once their data store has been sized and allocated, it could not be resized for the lifetime of the objects (although its content could be updated). OpenGL implementations may be able to take advantage of the knowledge that the underlying data store of certain objects cannot be deleted or otherwise reallocated without destruction of the whole object (normally, a much heavier weight and less frequent operation). Immutable storage for all types of textures besides multisample and buffer textures was introduced by ARB_texture_storage. For completeness, this extension introduces immutable storage for multisampled textures. Requires ${GL42.core} or ${ARB_texture_storage.link}. ${GL43.promoted} """ reuse(GL43C, "TexStorage2DMultisample") reuse(GL43C, "TexStorage3DMultisample") var src = GL43["TexStorage2DMultisample"] DependsOn("GL_EXT_direct_state_access")..void( "TextureStorage2DMultisampleEXT", "DSA version of #TexStorage2DMultisample().", GLuint("texture", "the texture object"), src["target"], src["samples"], src["internalformat"], src["width"], src["height"], src["fixedsamplelocations"] ) src = GL43["TexStorage3DMultisample"] DependsOn("GL_EXT_direct_state_access")..void( "TextureStorage3DMultisampleEXT", "DSA version of #TexStorage3DMultisample().", GLuint("texture", "the texture object"), src["target"], src["samples"], src["internalformat"], src["width"], src["height"], src["depth"], src["fixedsamplelocations"] ) }
bsd-3-clause
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/INTEL_blackhole_render.kt
4
1005
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val INTEL_blackhole_render = "INTELBlackholeRender".nativeClassGL("INTEL_blackhole_render", postfix = INTEL) { documentation = """ Native bindings to the $registryLink extension. The purpose of this extension is to allow an application to disable all rendering operations emitted to the GPU through the OpenGL rendering commands ({@code Draw*}, {@code DispatchCompute*}, {@code BlitFramebuffer}, etc...). Changes to the OpenGL pipeline are not affected. New preprocessor {@code \#defines} are added to the OpenGL Shading Language: ${codeBlock(""" \#define GL_INTEL_blackhole_render 1""")} Requires ${GL30.core}. """ IntConstant( "Accepted by the {@code target} parameter of Enable, Disable, IsEnabled.", "BLACKHOLE_RENDER_INTEL"..0x83FC ) }
bsd-3-clause
lucasgcampos/kotlin-for-android-developers
KotlinAndroid/app/src/main/java/com/lucasgcampos/kotlinandroid/extensions/DatabaseExtensions.kt
1
727
package com.lucasgcampos.kotlinandroid.extensions import android.database.sqlite.SQLiteDatabase import org.jetbrains.anko.db.MapRowParser import org.jetbrains.anko.db.SelectQueryBuilder fun <T : Any> SelectQueryBuilder.parseList( parser: (Map<String, Any>) -> T): List<T> = parseList(object : MapRowParser<T> { override fun parseRow(columns: Map<String, Any>): T = parser(columns) }) fun <T : Any> SelectQueryBuilder.parseOpt(parser: (Map<String, Any>) -> T): T? = parseOpt(object : MapRowParser<T> { override fun parseRow(columns: Map<String, Any>): T = parser(columns) }) fun SQLiteDatabase.clear(tableName: String) { execSQL("delete from $tableName") }
mit
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/OutflowSlicer.kt
6
12480
// 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.slicer import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector.Access import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.util.parentOfType import com.intellij.slicer.SliceUsage import com.intellij.usageView.UsageInfo import com.intellij.util.Processor import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.jumps.ReturnValueInstruction import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingElement import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReadWriteAccessDetector import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class OutflowSlicer( element: KtElement, processor: Processor<in SliceUsage>, parentUsage: KotlinSliceUsage ) : Slicer(element, processor, parentUsage) { override fun processChildren(forcedExpressionMode: Boolean) { if (forcedExpressionMode) { (element as? KtExpression)?.let { processExpression(it) } return } when (element) { is KtProperty -> processVariable(element) is KtParameter -> processVariable(element) is KtFunction -> processFunction(element) is KtPropertyAccessor -> { if (element.isGetter) { processVariable(element.property) } } is KtTypeReference -> { val declaration = element.parent require(declaration is KtCallableDeclaration) require(element == declaration.receiverTypeReference) if (declaration.isExpectDeclaration()) { declaration.resolveToDescriptorIfAny() ?.actualsForExpected() ?.forEach { val actualDeclaration = (it as? DeclarationDescriptorWithSource)?.toPsi() (actualDeclaration as? KtCallableDeclaration)?.receiverTypeReference?.passToProcessor() } } when (declaration) { is KtFunction -> { processExtensionReceiverUsages(declaration, declaration.bodyExpression, mode) } is KtProperty -> { //TODO: process only one of them or both depending on the usage type processExtensionReceiverUsages(declaration, declaration.getter?.bodyExpression, mode) processExtensionReceiverUsages(declaration, declaration.setter?.bodyExpression, mode) } } } is KtExpression -> processExpression(element) } } private fun processVariable(variable: KtCallableDeclaration) { val withDereferences = parentUsage.params.showInstanceDereferences val accessKind = if (withDereferences) AccessKind.READ_OR_WRITE else AccessKind.READ_ONLY fun processVariableAccess(usageInfo: UsageInfo) { val refElement = usageInfo.element ?: return if (refElement !is KtExpression) { if (refElement.parentOfType<PsiComment>() == null) { refElement.passToProcessor() } return } if (refElement.parent is KtValueArgumentName) return // named argument reference is not a read or write val refExpression = KtPsiUtil.safeDeparenthesize(refElement) if (withDereferences) { refExpression.processDereferences() } if (!withDereferences || KotlinReadWriteAccessDetector.INSTANCE.getExpressionAccess(refExpression) == Access.Read) { refExpression.passToProcessor() } } var searchScope = analysisScope if (variable is KtParameter) { if (!canProcessParameter(variable)) return //TODO val callable = variable.ownerFunction as? KtCallableDeclaration if (callable != null) { if (callable.isExpectDeclaration()) { variable.resolveToDescriptorIfAny() ?.actualsForExpected() ?.forEach { (it as? DeclarationDescriptorWithSource)?.toPsi()?.passToProcessor() } } val parameterIndex = variable.parameterIndex() callable.forEachOverridingElement(scope = analysisScope) { _, overridingMember -> when (overridingMember) { is KtCallableDeclaration -> { val parameters = overridingMember.valueParameters check(parameters.size == callable.valueParameters.size) parameters[parameterIndex].passToProcessor() } is PsiMethod -> { val parameters = overridingMember.parameterList.parameters val shift = if (callable.receiverTypeReference != null) 1 else 0 check(parameters.size == callable.valueParameters.size + shift) parameters[parameterIndex + shift].passToProcessor() } else -> { // not supported } } true } if (callable is KtNamedFunction) { // references to parameters of inline function can be outside analysis scope searchScope = LocalSearchScope(callable) } } } processVariableAccesses(variable, searchScope, accessKind, ::processVariableAccess) } private fun processFunction(function: KtFunction) { processCalls(function, includeOverriders = false, CallSliceProducer) } private fun processExpression(expression: KtExpression) { val expressionWithValue = when (expression) { is KtFunctionLiteral -> expression.parent as KtLambdaExpression else -> expression } expressionWithValue.processPseudocodeUsages { pseudoValue, instruction -> when (instruction) { is WriteValueInstruction -> { if (!pseudoValue.processIfReceiverValue(instruction, mode)) { instruction.target.accessedDescriptor?.toPsi()?.passToProcessor() } } is ReadValueInstruction -> { pseudoValue.processIfReceiverValue(instruction, mode) } is CallInstruction -> { if (!pseudoValue.processIfReceiverValue(instruction, mode)) { val parameterDescriptor = instruction.arguments[pseudoValue] ?: return@processPseudocodeUsages val parameter = parameterDescriptor.toPsi() if (parameter != null) { parameter.passToProcessorInCallMode(instruction.element) } else { val function = parameterDescriptor.containingDeclaration as? FunctionDescriptor ?: return@processPseudocodeUsages if (function.isImplicitInvokeFunction()) { processImplicitInvokeCall(instruction, parameterDescriptor) } } } } is ReturnValueInstruction -> { val subroutine = instruction.subroutine if (subroutine is KtNamedFunction) { val (newMode, callElement) = mode.popInlineFunctionCall(subroutine) if (newMode != null) { callElement?.passToProcessor(newMode) return@processPseudocodeUsages } } subroutine.passToProcessor() } is MagicInstruction -> { when (instruction.kind) { MagicKind.NOT_NULL_ASSERTION, MagicKind.CAST -> instruction.outputValue.element?.passToProcessor() else -> { } } } } } } private fun processImplicitInvokeCall(instruction: CallInstruction, parameterDescriptor: ValueParameterDescriptor) { val receiverPseudoValue = instruction.receiverValues.entries.singleOrNull()?.key ?: return val receiverExpression = receiverPseudoValue.element as? KtExpression ?: return val bindingContext = receiverExpression.analyze(BodyResolveMode.PARTIAL) var receiverType = bindingContext.getType(receiverExpression) var receiver: PsiElement = receiverExpression if (receiverType == null && receiverExpression is KtReferenceExpression) { val targetDescriptor = bindingContext[BindingContext.REFERENCE_TARGET, receiverExpression] if (targetDescriptor is CallableDescriptor) { receiverType = targetDescriptor.returnType receiver = targetDescriptor.toPsi() ?: return } } if (receiverType == null || !receiverType.isFunctionType) return val isExtension = receiverType.isExtensionFunctionType val shift = if (isExtension) 1 else 0 val parameterIndex = parameterDescriptor.index - shift val newMode = if (parameterIndex >= 0) mode.withBehaviour(LambdaParameterInflowBehaviour(parameterIndex)) else mode.withBehaviour(LambdaReceiverInflowBehaviour) receiver.passToProcessor(newMode) } private fun processDereferenceIfNeeded( expression: KtExpression, pseudoValue: PseudoValue, instr: InstructionWithReceivers ) { if (!parentUsage.params.showInstanceDereferences) return val receiver = instr.receiverValues[pseudoValue] val resolvedCall = when (instr) { is CallInstruction -> instr.resolvedCall is ReadValueInstruction -> (instr.target as? AccessTarget.Call)?.resolvedCall else -> null } ?: return if (receiver != null && resolvedCall.dispatchReceiver == receiver) { processor.process(KotlinSliceDereferenceUsage(expression, parentUsage, mode)) } } private fun KtExpression.processPseudocodeUsages(processor: (PseudoValue, Instruction) -> Unit) { val pseudocode = pseudocodeCache[this] ?: return val pseudoValue = pseudocode.getElementValue(this) ?: return pseudocode.getUsages(pseudoValue).forEach { processor(pseudoValue, it) } } private fun KtExpression.processDereferences() { processPseudocodeUsages { pseudoValue, instr -> when (instr) { is ReadValueInstruction -> processDereferenceIfNeeded(this, pseudoValue, instr) is CallInstruction -> processDereferenceIfNeeded(this, pseudoValue, instr) } } } }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/completion/tests/testData/basic/multifile/CallablesInExcludedPackage/CallablesInExcludedPackage.dependency2.kt
13
87
package notExcludedPackage fun someOtherFunction() { } val someOtherProperty: Int = 5
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/inlineClass/inlineClassDeprecated.kt
9
94
// "Replace with '@JvmInline value'" "true" // WITH_STDLIB <caret>inline class IC(val i: Int)
apache-2.0
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedDiffPreview.kt
1
7775
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.actions.diff import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.tools.combined.* import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper import com.intellij.openapi.vcs.changes.DiffPreviewUpdateProcessor import com.intellij.openapi.vcs.changes.DiffRequestProcessorWithProducers import com.intellij.openapi.vcs.changes.EditorTabPreviewBase import com.intellij.openapi.vcs.changes.actions.diff.CombinedDiffPreviewModel.Companion.prepareCombinedDiffModelRequests import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ExpandableItemsHandler import com.intellij.util.containers.isEmpty import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.Delegates import org.jetbrains.annotations.NonNls import java.util.stream.Stream import javax.swing.JComponent import javax.swing.JTree.TREE_MODEL_PROPERTY import kotlin.streams.toList @JvmField internal val COMBINED_DIFF_PREVIEW_TAB_NAME = Key.create<() -> @NlsContexts.TabTitle String>("combined_diff_preview_tab_name") class CombinedDiffPreviewVirtualFile(sourceId: String) : CombinedDiffVirtualFile(sourceId, "") abstract class CombinedDiffPreview(protected val tree: ChangesTree, targetComponent: JComponent, isOpenEditorDiffPreviewWithSingleClick: Boolean, needSetupOpenPreviewListeners: Boolean, parentDisposable: Disposable) : EditorTabPreviewBase(tree.project, parentDisposable) { constructor(tree: ChangesTree, parentDisposable: Disposable) : this(tree, tree, false, false, parentDisposable) override val previewFile: VirtualFile by lazy { CombinedDiffPreviewVirtualFile(tree.id) } override val updatePreviewProcessor get() = model protected val model by lazy { createModel().also { model -> model.context.putUserData(COMBINED_DIFF_PREVIEW_TAB_NAME, ::getCombinedDiffTabTitle) project.service<CombinedDiffModelRepository>().registerModel(tree.id, model) } } override fun updatePreview(fromModelRefresh: Boolean) { super.updatePreview(fromModelRefresh) if (isPreviewOpen()) { FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(previewFile) } } init { escapeHandler = Runnable { closePreview() returnFocusToTree() } if (needSetupOpenPreviewListeners) { installListeners(tree, isOpenEditorDiffPreviewWithSingleClick) installNextDiffActionOn(targetComponent) } UIUtil.putClientProperty(tree, ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true) installCombinedDiffModelListener() } private fun installCombinedDiffModelListener() { tree.addPropertyChangeListener(TREE_MODEL_PROPERTY) { if (model.ourDisposable.isDisposed) return@addPropertyChangeListener val changes = model.getSelectedOrAllChangesStream().toList() if (changes.isNotEmpty()) { model.refresh(true) model.reset(prepareCombinedDiffModelRequests(project, changes)) } } } open fun returnFocusToTree() = Unit override fun isPreviewOnDoubleClickAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnDoubleClickAllowed() override fun isPreviewOnEnterAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnEnterAllowed() protected abstract fun createModel(): CombinedDiffPreviewModel protected abstract fun getCombinedDiffTabTitle(): String override fun updateDiffAction(event: AnActionEvent) { event.presentation.isVisible = event.isFromActionToolbar || event.presentation.isEnabled } override fun getCurrentName(): String? = model.selected?.presentableName override fun hasContent(): Boolean = model.requests.isNotEmpty() internal fun getFileSize(): Int = model.requests.size protected val ChangesTree.id: @NonNls String get() = javaClass.name + "@" + Integer.toHexString(hashCode()) private fun isCombinedPreviewAllowed() = Registry.`is`("enable.combined.diff") } abstract class CombinedDiffPreviewModel(protected val tree: ChangesTree, requests: Map<CombinedBlockId, DiffRequestProducer>, parentDisposable: Disposable) : CombinedDiffModelImpl(tree.project, requests, parentDisposable), DiffPreviewUpdateProcessor, DiffRequestProcessorWithProducers { var selected by Delegates.equalVetoingObservable<Wrapper?>(null) { change -> if (change != null) { selectChangeInTree(change) scrollToChange(change) } } companion object { @JvmStatic fun prepareCombinedDiffModelRequests(project: Project, changes: List<Wrapper>): Map<CombinedBlockId, DiffRequestProducer> { return changes .asSequence() .mapNotNull { wrapper -> wrapper.createProducer(project) ?.let { CombinedPathBlockId(wrapper.filePath, wrapper.fileStatus, wrapper.tag) to it } }.toMap() } } override fun collectDiffProducers(selectedOnly: Boolean): ListSelection<DiffRequestProducer> { return ListSelection.create(requests.values.toList(), selected?.createProducer(project)) } abstract fun getAllChanges(): Stream<out Wrapper> protected abstract fun getSelectedChanges(): Stream<out Wrapper> protected open fun showAllChangesForEmptySelection(): Boolean { return true } override fun clear() { init() } override fun refresh(fromModelRefresh: Boolean) { if (ourDisposable.isDisposed) return val selectedChanges = getSelectedOrAllChangesStream().toList() val selectedChange = selected?.let { prevSelected -> selectedChanges.find { it == prevSelected } } if (fromModelRefresh && selectedChange == null && selected != null && context.isWindowFocused && context.isFocusedInWindow) { // Do not automatically switch focused viewer if (selectedChanges.size == 1 && getAllChanges().anyMatch { it: Wrapper -> selected == it }) { selected?.run(::selectChangeInTree) // Restore selection if necessary } return } val newSelected = when { selectedChanges.isEmpty() -> null selectedChange == null -> selectedChanges[0] else -> selectedChange } newSelected?.let { context.putUserData(COMBINED_DIFF_SCROLL_TO_BLOCK, CombinedPathBlockId(it.filePath, it.fileStatus, it.tag)) } selected = newSelected } internal fun getSelectedOrAllChangesStream(): Stream<out Wrapper> { return if (getSelectedChanges().isEmpty() && showAllChangesForEmptySelection()) getAllChanges() else getSelectedChanges() } private fun scrollToChange(change: Wrapper) { context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?.selectDiffBlock(CombinedPathBlockId(change.filePath, change.fileStatus, change.tag), ScrollPolicy.DIFF_BLOCK, false) } open fun selectChangeInTree(change: Wrapper) { ChangesBrowserBase.selectObjectWithTag(tree, change.userObject, change.tag) } override fun getComponent(): JComponent = throw UnsupportedOperationException() //only for splitter preview }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/kotlin/KKKK/jjk_.kt
150
30
fun jjk() { JJK().test() }
apache-2.0
tinmegali/android_achitecture_components_sample
app/src/main/java/com/tinmegali/myweather/web/ApiError.kt
1
117
package com.tinmegali.myweather.web data class ApiError( val statusCode: Int, val message: String? )
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/android/intention/addActivityToManifest/insideBody.kt
14
192
// INTENTION_CLASS: org.jetbrains.kotlin.android.intention.AddActivityToManifest // NOT_AVAILABLE package com.myapp import android.app.Activity class MyActivity : Activity() { <caret> }
apache-2.0
tinmegali/android_achitecture_components_sample
app/src/main/java/com/tinmegali/myweather/data/WeatherDAO.kt
1
800
package com.tinmegali.myweather.data import android.arch.lifecycle.LiveData import android.arch.persistence.room.* import com.tinmegali.myweather.models.WeatherMain @Dao interface WeatherDAO { @Insert( onConflict = OnConflictStrategy.REPLACE ) fun insert( w: WeatherMain ) @Delete fun remove( w: WeatherMain ) @Query( "SELECT * FROM weather " + "ORDER BY id DESC LIMIT 1" ) fun findLast(): LiveData<WeatherMain> @Query("SELECT * FROM weather " + "WHERE city LIKE :city " + "ORDER BY date DESC LIMIT 1") fun findByCity(city: String ): LiveData<WeatherMain> @Query("SELECT * FROM weather " + "WHERE date < :date " + "ORDER BY date ASC LIMIT 1" ) fun findByDate( date: Long ): List<WeatherMain> }
apache-2.0
sanjoydesk/FrameworkBenchmarks
frameworks/Kotlin/hexagon/src/main/kotlin/co/there4/hexagon/Benchmark.kt
1
2812
package co.there4.hexagon import co.there4.hexagon.rest.crud import co.there4.hexagon.serialization.convertToMap import co.there4.hexagon.serialization.serialize import co.there4.hexagon.web.* import co.there4.hexagon.web.servlet.ServletServer import kotlinx.html.* import java.net.InetAddress.getByName as address import java.time.LocalDateTime.now import java.util.concurrent.ThreadLocalRandom import javax.servlet.annotation.WebListener // DATA CLASSES internal data class Message(val message: String = "Hello, World!") internal data class Fortune(val _id: Int, val message: String) internal data class World(val _id: Int, val id: Int = _id, val randomNumber: Int = rnd()) // CONSTANTS private val CONTENT_TYPE_JSON = "application/json" private val QUERIES_PARAM = "queries" // UTILITIES internal fun rnd() = ThreadLocalRandom.current().nextInt(DB_ROWS) + 1 private fun World.strip(): Map<*, *> = this.convertToMap().filterKeys { it != "_id" } private fun World.toJson(): String = this.strip().serialize() private fun List<World>.toJson(): String = this.map(World::strip).serialize() private fun Exchange.hasQueryCount() = request[QUERIES_PARAM] == null private fun Exchange.getDb() { val worlds = (1..getQueries()).map { findWorld() }.filterNotNull() ok(if (hasQueryCount()) worlds[0].toJson() else worlds.toJson(), CONTENT_TYPE_JSON) } private fun listFortunes() = (findFortunes() + Fortune(0, "Additional fortune added at request time.")) .sortedBy { it.message } // HANDLERS private fun Exchange.getUpdates() { val worlds = (1..getQueries()).map { val id = rnd() val newWorld = World(id, id) replaceWorld(newWorld) newWorld } ok(if (hasQueryCount()) worlds[0].toJson() else worlds.toJson(), CONTENT_TYPE_JSON) } private fun Exchange.getQueries() = try { val queries = request[QUERIES_PARAM]?.toInt() ?: 1 when { queries < 1 -> 1 queries > 500 -> 500 else -> queries } } catch (ex: NumberFormatException) { 1 } fun benchmarkRoutes(srv: Router = server) { srv.before { response.addHeader("Server", "Servlet/3.1") response.addHeader("Transfer-Encoding", "chunked") response.addHeader("Date", httpDate(now())) } srv.get("/plaintext") { ok("Hello, World!", "text/plain") } srv.get("/json") { ok(Message().serialize(), CONTENT_TYPE_JSON) } srv.get("/fortunes") { template("fortunes.html", "fortunes" to listFortunes()) } srv.get("/db") { getDb() } srv.get("/query") { getDb() } srv.get("/update") { getUpdates() } } @WebListener class Web : ServletServer () { override fun init() { benchmarkRoutes(this) } } fun main(args: Array<String>) { benchmarkRoutes() run() }
bsd-3-clause
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter7/7.9.KClass.kt
1
421
package com.packt.chapter7 import kotlin.reflect.KClass fun gettingAKClass() { val name = "George" val kclass: KClass<String> = name::class val kclass2: KClass<String> = String::class val kclass3 = Class.forName("com.packt.MyType").kotlin } fun oneKClassPerType() { val kclass1: KClass<String> = "harry"::class val kclass2: KClass<String> = "victoria"::class val kclass3: KClass<String> = String::class }
mit
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/models/Thumbnail.kt
1
2851
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.shared.models import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import android.media.ThumbnailUtils import android.os.Parcelable import androidx.annotation.DrawableRes import de.dreier.mytargets.shared.utils.RoundedAvatarDrawable import de.dreier.mytargets.shared.utils.toByteArray import kotlinx.android.parcel.IgnoredOnParcel import kotlinx.android.parcel.Parcelize import timber.log.Timber import java.io.File import java.util.* @Parcelize class Thumbnail(val data: ByteArray) : Parcelable { @IgnoredOnParcel val roundDrawable: Drawable by lazy { val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size) if (bitmap == null) { Timber.w("Invalid bitmap data provided: %s", Arrays.asList(data).toString()) val dummyBitmap = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888) return@lazy RoundedAvatarDrawable(dummyBitmap) } RoundedAvatarDrawable(bitmap) } companion object { /** * Constant used to indicate the dimension of micro thumbnail. */ private const val TARGET_SIZE_MICRO_THUMBNAIL = 96 fun from(bitmap: Bitmap): Thumbnail { val thumbnail = ThumbnailUtils.extractThumbnail( bitmap, TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL, ThumbnailUtils.OPTIONS_RECYCLE_INPUT ) return Thumbnail(thumbnail.toByteArray()) } fun from(imageFile: File): Thumbnail { val thumbnail = ThumbnailUtils .extractThumbnail( BitmapFactory.decodeFile(imageFile.path), TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL ) ?: Bitmap.createBitmap( TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL, Bitmap.Config.RGB_565 ) return Thumbnail(thumbnail.toByteArray()) } fun from(context: Context, @DrawableRes resId: Int): Thumbnail { return from(BitmapFactory.decodeResource(context.resources, resId)) } } }
gpl-2.0
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration10.kt
1
999
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.base.db.migrations import androidx.sqlite.db.SupportSQLiteDatabase import androidx.room.migration.Migration object Migration10 : Migration(9, 10) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE BOW ADD COLUMN limbs TEXT DEFAULT ''") database.execSQL("ALTER TABLE BOW ADD COLUMN sight TEXT DEFAULT ''") database.execSQL("ALTER TABLE BOW ADD COLUMN draw_weight TEXT DEFAULT ''") } }
gpl-2.0
airbnb/epoxy
kotlinsample/src/main/java/com/airbnb/epoxy/kotlinsample/models/ItemViewBindingDataClass.kt
1
723
package com.airbnb.epoxy.kotlinsample.models import com.airbnb.epoxy.kotlinsample.R import com.airbnb.epoxy.kotlinsample.databinding.DataClassViewBindingItemBinding import com.airbnb.epoxy.kotlinsample.helpers.ViewBindingKotlinModel // This does not require annotations or annotation processing. // The data class is required to generated equals/hashcode which Epoxy needs for diffing. // Views are easily declared via property delegates data class ItemViewBindingDataClass( val title: String ) : ViewBindingKotlinModel<DataClassViewBindingItemBinding>(R.layout.data_class_view_binding_item) { override fun DataClassViewBindingItemBinding.bind() { title.text = [email protected] } }
apache-2.0
airbnb/epoxy
epoxy-adapter/src/main/java/com/airbnb/epoxy/stickyheader/StickyHeaderCallbacks.kt
1
1114
package com.airbnb.epoxy.stickyheader import android.view.View import androidx.recyclerview.widget.RecyclerView /** * Adds sticky headers capabilities to any [RecyclerView.Adapter] * combined with [StickyHeaderLinearLayoutManager]. */ interface StickyHeaderCallbacks { /** * Return true if the view at the specified [position] needs to be sticky * else false. */ fun isStickyHeader(position: Int): Boolean //region Optional callbacks /** * Callback to adjusts any necessary properties of the [stickyHeader] view * that is being used as a sticky, eg. elevation. * Default behaviour is no-op. * * [teardownStickyHeaderView] will be called sometime after this method * and before any other calls to this method go through. */ fun setupStickyHeaderView(stickyHeader: View) = Unit /** * Callback to revert any properties changed in [setupStickyHeaderView]. * Default behaviour is no-op. * * Called after [setupStickyHeaderView]. */ fun teardownStickyHeaderView(stickyHeader: View) = Unit //endregion }
apache-2.0
flesire/ontrack
ontrack-service/src/test/java/net/nemerosa/ontrack/service/labels/LabelProviderServiceIT.kt
1
12595
package net.nemerosa.ontrack.service.labels import net.nemerosa.ontrack.it.AbstractDSLTestSupport import net.nemerosa.ontrack.model.labels.* import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.test.TestUtils.uid import org.junit.Before import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertNull class LabelProviderServiceIT : AbstractDSLTestSupport() { @Autowired private lateinit var labelProviderService: LabelProviderService @Autowired private lateinit var testCountLabelProvider: TestCountLabelProvider @Autowired private lateinit var testCustomLabelProvider: TestCustomLabelProvider @Before fun setup() { testCountLabelProvider.reset() testCustomLabelProvider.reset() } @Test fun `Provided labels for a project`() { project { collectLabels() // Checks that labels have been provided val labelCategory = name.substring(0..1) val labelName = name.substring(0..2) val label = labels.find { it.category == labelCategory && it.name == labelName } assertNotNull(label) { assertEquals( TestAbbrevLabelProvider::class.qualifiedName, it.computedBy?.id ) assertEquals( "Name label", it.computedBy?.name ) } } } @Test fun `Provided labels updates at project level`() { project { // Configuration of the labels testCountLabelProvider.range = 1..3 // Collects of labels collectLabels() // Checks the provided labels assertEquals( listOf("1", "2", "3"), labels.filter { it.category == "count" }.map { it.name } ) assertEquals( 1, labels.filter { it.computedBy?.name == "Name label" }.size ) // Reconfiguration of the labels testCountLabelProvider.range = 2..5 // Collects of labels collectLabels() // Checks the provided labels assertEquals( listOf("2", "3", "4", "5"), labels.filter { it.category == "count" }.map { it.name } ) assertEquals( 1, labels.filter { it.computedBy?.name == "Name label" }.size ) } } @Test fun `Provided labels updates at global level`() { // Enabling the custom labelling (with default description) val name = uid("N") testCustomLabelProvider.labelName = name project { // Collects of labels collectLabels() // Checks the provided custom labels val label = labels.find { it.category == "custom" && it.name == name } assertNotNull(label) { // Default description assertEquals("Custom label for custom:$name", it.description) } // Changing the description testCustomLabelProvider.labelDescription = { _, _ -> "Test description" } // Recollecting the labels collectLabels() // Checks the provided custom labels val newLabel = labels.find { it.category == "custom" && it.name == name } assertNotNull(newLabel) { // Default description assertEquals("Test description", it.description) } } } @Test fun `Overriding manual labels with automated ones without any existing association`() { // Creating a manual label (and random name) val manualLabel = label(category = "custom") // Not computed assertNull(manualLabel.computedBy, "Manual label is not computed") // Configures the custom provider so that it provides the name cat/name testCustomLabelProvider.labelName = manualLabel.name // For a given project project { // Auto collection collectLabels() // Gets the custom labels for this project val labels = this.labels.filter { it.category == "custom" } // Checks that we have 1 label and that it is provided assertEquals(1, labels.size) val label = labels[0] assertEquals(manualLabel.name, label.name) assertEquals(TestCustomLabelProvider::class.qualifiedName, label.computedBy?.id) } // Checks that the manual label is now computed val label = labelManagementService.getLabel(manualLabel.id) assertEquals(manualLabel.name, label.name) assertEquals(TestCustomLabelProvider::class.qualifiedName, label.computedBy?.id) } @Test fun `Overriding manual labels with automated ones with existing association`() { // Creating a manual label (and random name) val manualLabel = label(category = "custom") // Not computed assertNull(manualLabel.computedBy, "Manual label is not computed") // Configures the custom provider so that it provides the name cat/name testCustomLabelProvider.labelName = manualLabel.name // For a given project project { // Associates the manual label to this project labels += manualLabel // Auto collection collectLabels() // Gets the custom labels for this project val labels = this.labels.filter { it.category == "custom" } // Checks that we have 1 label and that it is provided assertEquals(1, labels.size) val label = labels[0] assertEquals(manualLabel.name, label.name) assertEquals(TestCustomLabelProvider::class.qualifiedName, label.computedBy?.id) } // Checks that the manual label is now computed val label = labelManagementService.getLabel(manualLabel.id) assertEquals(manualLabel.name, label.name) assertEquals(TestCustomLabelProvider::class.qualifiedName, label.computedBy?.id) } @Test fun `Providers can steal other providers labels`() { // Configuring the custom provider so that it uses the same cat/name than the count provider testCustomLabelProvider.labelCustom = "count" testCustomLabelProvider.labelName = "1" // Project to test with project { // Collecting the labels collectLabels() // Only 1 label with category = count val labels = this.labels.filter { it.category == "count" } assertEquals(1, labels.size) val label = labels[0] assertEquals("count", label.category) assertEquals("1", label.name) assertNotNull(label.computedBy, "Label is computed") } } @Test fun `Trying to create a manual label over an automated one is not allowed`() { project { collectLabels() // Assert the automated label is created val createdLabel = asAdmin().call { labelManagementService.labels.find { it.category == "count" } } assertNotNull(createdLabel) { assertEquals("1", it.name) assertNotNull(it.computedBy) } // Attempting to create manual similar label assertFailsWith<LabelCategoryNameAlreadyExistException> { label(category = "count", name = "1") } } } @Test fun `Trying to update a manual label over an automated one is not allowed`() { project { collectLabels() // Assert the automated label is created val createdLabel = asAdmin().call { labelManagementService.labels.find { it.category == "count" } } assertNotNull(createdLabel) { assertEquals("1", it.name) assertNotNull(it.computedBy) } // Attempting to update manual similar label assertFailsWith<LabelNotEditableException> { asAdmin().execute { labelManagementService.updateLabel( createdLabel.id, LabelForm( category = "count", name = "1", description = "Just a test", color = "#FF0000" ) ) } } } } @Test fun `Trying to delete a manual label over an automated one is not allowed`() { project { collectLabels() // Assert the automated label is created val createdLabel = asAdmin().call { labelManagementService.labels.find { it.category == "count" } } assertNotNull(createdLabel) { assertEquals("1", it.name) assertNotNull(it.computedBy) } // Attempting to update manual similar label assertFailsWith<LabelNotEditableException> { asAdmin().execute { labelManagementService.deleteLabel( createdLabel.id ) } } } } @Configuration class LabelProviderServiceITConfig { @Bean fun testCountLabelProvider(): TestLabelProvider = TestCountLabelProvider() @Bean fun testAbbrevLabelProvider(): TestLabelProvider = TestAbbrevLabelProvider() @Bean fun testCustomLabelProvider(): TestLabelProvider = TestCustomLabelProvider() } private fun Project.collectLabels() { asAdmin().execute { labelProviderService.collectLabels(this) } } } abstract class TestLabelProvider : LabelProvider { override val isEnabled: Boolean = true } class TestCountLabelProvider : TestLabelProvider() { var range: IntRange = 1..1 override val name: String = "Count label" override fun getLabelsForProject(project: Project): List<LabelForm> { return range.map { count -> LabelForm( category = "count", name = count.toString(), description = "Count $count", color = "#00FF00" ) } } fun reset() { range = 1..1 } } class TestAbbrevLabelProvider : TestLabelProvider() { override val name: String = "Name label" override fun getLabelsForProject(project: Project): List<LabelForm> { return listOf( LabelForm( category = project.name.substring(0..1), name = project.name.substring(0..2), description = "Abbreviation for ${project.name.substring(0..2)}", color = "#FF0000" ) ) } } class TestCustomLabelProvider : TestLabelProvider() { var labelCustom: String? = "custom" var labelName: String? = null var labelDescription: (category: String?, name: String) -> String = { category, name -> "Custom label for $category:$name" } override val name: String = "Custom label" fun reset() { labelCustom = "custom" labelName = null labelDescription = { category, name -> "Custom label for $category:$name" } } override fun getLabelsForProject(project: Project): List<LabelForm> { return labelName?.let { listOf( LabelForm( category = labelCustom, name = it, description = labelDescription(labelCustom, it), color = "#0000FF" ) ) } ?: emptyList() } }
mit
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/ButtonStyle.kt
1
610
package com.slack.api.model.kotlin_extension.block.element enum class ButtonStyle { /** * Primary gives buttons a green outline and text, ideal for affirmation or confirmation actions. primary should * only be used for one button within a set. */ PRIMARY { override val value: String? = "primary" }, /** * Danger gives buttons a red outline and text, and should be used when the action is destructive. Use danger even * more sparingly than primary. */ DANGER { override val value: String? = "danger" }; abstract val value: String? }
mit
DemonWav/MinecraftDevIntelliJ
src/test/kotlin/com/demonwav/mcdev/platform/mixin/shadow/BaseShadowTest.kt
1
2354
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.shadow import com.demonwav.mcdev.framework.ProjectBuilder import com.demonwav.mcdev.platform.mixin.BaseMixinTest import org.junit.jupiter.api.BeforeEach abstract class BaseShadowTest : BaseMixinTest() { protected var mixins: ProjectBuilder.() -> Unit = {} protected abstract fun createMixins() @BeforeEach fun setupProject() { createMixins() buildProject { dir("test") { java( "MixinBase.java", """ package test; public class MixinBase { // Static private static final String privateStaticFinalString = ""; private static String privateStaticString = ""; protected static final String protectedStaticFinalString = ""; protected static String protectedStaticString = ""; static final String packagePrivateStaticFinalString = ""; static String packagePrivateStaticString = ""; public static final String publicStaticFinalString = ""; public static String publicStaticString = ""; // Non-static private final String privateFinalString = ""; private String privateString = ""; protected final String protectedFinalString = ""; protected String protectedString = ""; final String packagePrivateFinalString = ""; String packagePrivateString = ""; public final String publicFinalString = ""; public String publicString = ""; // Bad shadows protected String wrongAccessor = ""; protected final String noFinal = ""; public final String twoIssues = ""; } """, configure = false ) mixins() } } } }
mit
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/forge/insight/ForgeImplicitUsageProvider.kt
1
1339
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.insight import com.demonwav.mcdev.platform.forge.inspections.simpleimpl.SimpleImplUtil import com.demonwav.mcdev.platform.forge.util.ForgeConstants import com.demonwav.mcdev.util.extendsOrImplements import com.intellij.codeInsight.daemon.ImplicitUsageProvider import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod class ForgeImplicitUsageProvider : ImplicitUsageProvider { override fun isImplicitUsage(element: PsiElement) = isCoreMod(element) || isNetworkMessageOrHandler(element) private fun isCoreMod(element: PsiElement): Boolean { return element is PsiClass && element.extendsOrImplements(ForgeConstants.CORE_MOD_INTERFACE) } private fun isNetworkMessageOrHandler(element: PsiElement): Boolean { if (element !is PsiMethod || element.isConstructor && element.hasParameters()) { return false } val containingClass = element.containingClass ?: return false return SimpleImplUtil.isMessageOrHandler(containingClass) } override fun isImplicitRead(element: PsiElement) = false override fun isImplicitWrite(element: PsiElement) = false }
mit
esafirm/android-playground
app/src/main/java/com/esafirm/androidplayground/webview/HostSonicRuntime.kt
1
1725
package com.esafirm.androidplayground.webview import android.content.Context import android.os.Environment import com.tencent.sonic.sdk.SonicRuntime import com.tencent.sonic.sdk.SonicSessionClient import java.io.File import java.io.InputStream class HostSonicRuntime(context: Context) : SonicRuntime(context) { override fun log(tag: String, level: Int, message: String) { } override fun getCookie(url: String): String? { return null } override fun setCookie(url: String, cookies: List<String>): Boolean { return false } /** * @return User's UA */ override fun getUserAgent(): String { return "" } /** * @return the ID of user. */ override fun getCurrentUserAccount(): String { return "" } override fun isSonicUrl(url: String): Boolean { return false } override fun createWebResourceResponse(mimeType: String, encoding: String, data: InputStream, headers: Map<String, String>): Any? { return null } override fun isNetworkValid(): Boolean { return false } override fun showToast(text: CharSequence, duration: Int) { } override fun postTaskToThread(task: Runnable, delayMillis: Long) { } override fun notifyError(client: SonicSessionClient, url: String, errorCode: Int) {} /** * @return the file path which is used to save Sonic caches. */ override fun getSonicCacheDir(): File { val path = Environment.getExternalStorageDirectory().absolutePath + File.separator + "sonic/" val file = File(path.trim { it <= ' ' }) if (!file.exists()) { file.mkdir() } return file } }
mit
aahlenst/spring-boot
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/messaging/amqp/receiving/custom/MyMessageConverter.kt
10
1114
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.boot.docs.messaging.amqp.receiving.custom import org.springframework.amqp.core.Message import org.springframework.amqp.core.MessageProperties import org.springframework.amqp.support.converter.MessageConverter internal class MyMessageConverter : MessageConverter { override fun toMessage(`object`: Any, messageProperties: MessageProperties): Message { return Message(byteArrayOf()) } override fun fromMessage(message: Message): Any { return Any() } }
apache-2.0
google/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/run/runConfigurationTestUtil.kt
2
3845
// 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.run import com.intellij.execution.Executor import com.intellij.execution.Location import com.intellij.execution.PsiLocation import com.intellij.execution.RunManagerEx import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.configurations.JavaCommandLine import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunProfile import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiElement import com.intellij.testFramework.MapDataContext import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.junit.Assert fun getJavaRunParameters(configuration: RunConfiguration): JavaParameters { val state = configuration.getState(MockExecutor, ExecutionEnvironmentBuilder.create(configuration.project, MockExecutor, MockProfile).build()) Assert.assertNotNull(state) Assert.assertTrue(state is JavaCommandLine) configuration.checkConfiguration() return (state as JavaCommandLine).javaParameters!! } fun createConfigurationFromElement(element: PsiElement, save: Boolean = false): RunConfiguration { val dataContext = MapDataContext() dataContext.put(Location.DATA_KEY, PsiLocation(element.project, element)) val runnerAndConfigurationSettings = ConfigurationContext.getFromContext(dataContext, ActionPlaces.UNKNOWN).configuration ?: error("no runnerAndConfigurationSettings for $element [${element.safeAs<KtNamedFunction>()?.fqName?.asString()}]") if (save) { RunManagerEx.getInstanceEx(element.project).setTemporaryConfiguration(runnerAndConfigurationSettings) } return runnerAndConfigurationSettings.configuration } fun createLibraryWithLongPaths(project: Project): Library { val maxCommandlineLengthWindows = 24500 val maxFilenameLengthWindows = 245 return runWriteAction { val modifiableModel = ProjectLibraryTable.getInstance(project).modifiableModel val library = try { modifiableModel.createLibrary("LibraryWithLongPaths", null) } finally { modifiableModel.commit() } with(library.modifiableModel) { for (i in 0..maxCommandlineLengthWindows / maxFilenameLengthWindows) { val tmpFile = VirtualFileManager.constructUrl( LocalFileSystem.getInstance().protocol, FileUtil.createTempDirectory("file$i", "a".repeat(maxFilenameLengthWindows)).path ) addRoot(tmpFile, OrderRootType.CLASSES) } commit() } return@runWriteAction library } } private object MockExecutor : DefaultRunExecutor() { override fun getId() = EXECUTOR_ID } private object MockProfile : RunProfile { override fun getState(executor: Executor, env: ExecutionEnvironment) = null override fun getIcon() = null override fun getName() = "unknown" }
apache-2.0
DroidsOnRoids/DroidsMap
app/src/main/java/pl/droidsonroids/droidsmap/feature/office/business_logic/OfficeEntity.kt
1
485
package pl.droidsonroids.droidsmap.feature.office.business_logic import pl.droidsonroids.droidsmap.model.Entity data class OfficeEntity( val centerLatitude: Double = 0.0, val centerLongitude: Double = 0.0, val topLeftCornerLatitude: Double = 0.0, val topLeftCornerLongitude: Double = 0.0, val mapViewportBearing: Double = 0.0, val translatedMapViewportBearing: Double = 0.0, val mapViewportConstraint: Double = 0.0 ) : Entity()
mit
denzelby/telegram-bot-bumblebee
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/security/exception/UnprivilegedExecutionException.kt
2
234
package com.github.bumblebee.security.exception class UnprivilegedExecutionException : RuntimeException { constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause) }
mit
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/textField.kt
1
4412
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder import com.intellij.openapi.Disposable import com.intellij.openapi.observable.properties.ObservableMutableProperty import com.intellij.openapi.observable.util.* import com.intellij.openapi.ui.validation.DialogValidation import com.intellij.openapi.ui.validation.forTextComponent import com.intellij.openapi.ui.validation.trimParameter import com.intellij.ui.dsl.ValidationException import com.intellij.ui.dsl.builder.impl.CellImpl.Companion.installValidationRequestor import com.intellij.ui.dsl.catchValidationException import com.intellij.ui.dsl.stringToInt import com.intellij.ui.dsl.validateIntInRange import com.intellij.ui.layout.* import com.intellij.util.containers.map2Array import org.jetbrains.annotations.ApiStatus import javax.swing.JTextField import javax.swing.text.JTextComponent import kotlin.reflect.KMutableProperty0 import com.intellij.openapi.observable.util.whenTextChangedFromUi as whenTextChangedFromUiImpl /** * Columns for text components with tiny width. Used for [Row.intTextField] by default */ const val COLUMNS_TINY = 6 /** * Columns for text components with short width */ const val COLUMNS_SHORT = 18 /** * Columns for text components with medium width */ const val COLUMNS_MEDIUM = 25 const val COLUMNS_LARGE = 36 fun <T : JTextComponent> Cell<T>.bindText(property: ObservableMutableProperty<String>): Cell<T> { installValidationRequestor(property) return applyToComponent { bind(property) } } fun <T : JTextComponent> Cell<T>.bindText(prop: KMutableProperty0<String>): Cell<T> { return bindText(prop.toMutableProperty()) } fun <T : JTextComponent> Cell<T>.bindText(getter: () -> String, setter: (String) -> Unit): Cell<T> { return bindText(MutableProperty(getter, setter)) } fun <T : JTextComponent> Cell<T>.bindText(prop: MutableProperty<String>): Cell<T> { return bind(JTextComponent::getText, JTextComponent::setText, prop) } fun <T : JTextComponent> Cell<T>.bindIntText(property: ObservableMutableProperty<Int>): Cell<T> { installValidationRequestor(property) val stringProperty = property .backwardFilter { component.isIntInRange(it) } .toStringIntProperty() return applyToComponent { bind(stringProperty) } } fun <T : JTextComponent> Cell<T>.bindIntText(prop: MutableProperty<Int>): Cell<T> { return bindText({ prop.get().toString() }, { value -> catchValidationException { prop.set(component.getValidatedIntValue(value)) } }) } fun <T : JTextComponent> Cell<T>.bindIntText(prop: KMutableProperty0<Int>): Cell<T> { return bindIntText(prop.toMutableProperty()) } fun <T : JTextComponent> Cell<T>.bindIntText(getter: () -> Int, setter: (Int) -> Unit): Cell<T> { return bindIntText(MutableProperty(getter, setter)) } fun <T : JTextComponent> Cell<T>.text(text: String): Cell<T> { component.text = text return this } /** * Minimal width of text field in chars * * @see COLUMNS_TINY * @see COLUMNS_SHORT * @see COLUMNS_MEDIUM * @see COLUMNS_LARGE */ fun <T : JTextField> Cell<T>.columns(columns: Int) = apply { component.columns(columns) } fun <T : JTextField> T.columns(columns: Int) = apply { this.columns = columns } @Throws(ValidationException::class) private fun JTextComponent.getValidatedIntValue(value: String): Int { val result = stringToInt(value) val range = getClientProperty(DSL_INT_TEXT_RANGE_PROPERTY) as? IntRange range?.let { validateIntInRange(result, it) } return result } private fun JTextComponent.isIntInRange(value: Int): Boolean { val range = getClientProperty(DSL_INT_TEXT_RANGE_PROPERTY) as? IntRange return range == null || value in range } fun <T : JTextComponent> Cell<T>.trimmedTextValidation(vararg validations: DialogValidation.WithParameter<() -> String>) = textValidation(*validations.map2Array { it.trimParameter() }) fun <T : JTextComponent> Cell<T>.textValidation(vararg validations: DialogValidation.WithParameter<() -> String>) = validation(*validations.map2Array { it.forTextComponent() }) @ApiStatus.Experimental fun <T: JTextComponent> Cell<T>.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit): Cell<T> { return applyToComponent { whenTextChangedFromUiImpl(parentDisposable, listener) } }
apache-2.0
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/lucius/psi/Number.kt
1
210
package org.jetbrains.yesod.lucius.psi /** * @author Leyla H */ import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode class Number(node: ASTNode) : ASTWrapperPsiElement(node)
apache-2.0
JetBrains/intellij-community
java/java-impl-refactorings/src/com/intellij/refactoring/extractMethod/newImpl/MethodExtractor.kt
1
14174
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.refactoring.extractMethod.newImpl import com.intellij.codeInsight.Nullability import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.ide.util.PropertiesComponent import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.WriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.wm.WindowManager import com.intellij.psi.* import com.intellij.psi.util.PsiEditorUtil import com.intellij.refactoring.HelpID import com.intellij.refactoring.JavaRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.ExtractMethodDialog import com.intellij.refactoring.extractMethod.ExtractMethodHandler import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.addSiblingAfter import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.guessMethodName import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.replacePsiRange import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.findAllOptionsToExtract import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.selectOptionWithTargetClass import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.withFilteredAnnotations import com.intellij.refactoring.extractMethod.newImpl.inplace.ExtractMethodPopupProvider import com.intellij.refactoring.extractMethod.newImpl.inplace.InplaceMethodExtractor import com.intellij.refactoring.extractMethod.newImpl.inplace.extractInDialog import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.ConflictsUtil import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.NonNls import java.util.concurrent.CompletableFuture data class ExtractedElements(val callElements: List<PsiElement>, val method: PsiMethod) class MethodExtractor { fun doExtract(file: PsiFile, range: TextRange) { val editor = PsiEditorUtil.findEditor(file) ?: return if (EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled) { val activeExtractor = InplaceMethodExtractor.getActiveExtractor(editor) if (activeExtractor != null) { activeExtractor.restartInDialog() } else { findAndSelectExtractOption(editor, file, range)?.thenApply { options -> runInplaceExtract(editor, range, options) } } } else { findAndSelectExtractOption(editor, file, range)?.thenApply { options -> extractInDialog(options.targetClass, options.elements, "", JavaRefactoringSettings.getInstance().EXTRACT_STATIC_METHOD) } } } private fun findAndSelectExtractOption(editor: Editor, file: PsiFile, range: TextRange): CompletableFuture<ExtractOptions>? { try { if (!CommonRefactoringUtil.checkReadOnlyStatus(file.project, file)) return null val elements = ExtractSelector().suggestElementsToExtract(file, range) if (elements.isEmpty()) { throw ExtractException(RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"), file) } val allOptionsToExtract: List<ExtractOptions> = computeWithAnalyzeProgress<List<ExtractOptions>, ExtractException>(file.project) { findAllOptionsToExtract(elements) } return selectOptionWithTargetClass(editor, allOptionsToExtract) } catch (e: ExtractException) { val message = JavaRefactoringBundle.message("extract.method.error.prefix") + " " + (e.message ?: "") CommonRefactoringUtil.showErrorHint(file.project, editor, message, ExtractMethodHandler.getRefactoringName(), HelpID.EXTRACT_METHOD) showError(editor, e.problems) return null } } private fun <T, E: Exception> computeWithAnalyzeProgress(project: Project, throwableComputable: ThrowableComputable<T, E>): T { return ProgressManager.getInstance().run(object : Task.WithResult<T, E>(project, JavaRefactoringBundle.message("dialog.title.analyze.code.fragment.to.extract"), true) { override fun compute(indicator: ProgressIndicator): T { return ReadAction.compute(throwableComputable) } }) } private fun runInplaceExtract(editor: Editor, range: TextRange, options: ExtractOptions){ val project = options.project val popupSettings = createInplaceSettingsPopup(options) val guessedNames = suggestSafeMethodNames(options) val methodName = guessedNames.first() val suggestedNames = guessedNames.takeIf { it.size > 1 }.orEmpty() executeRefactoringCommand(project) { val inplaceExtractor = InplaceMethodExtractor(editor, range, options.targetClass, popupSettings, methodName) inplaceExtractor.extractAndRunTemplate(LinkedHashSet(suggestedNames)) } } val ExtractOptions.targetClass: PsiClass get() = anchor.containingClass ?: throw IllegalStateException() private fun suggestSafeMethodNames(options: ExtractOptions): List<String> { val unsafeNames = guessMethodName(options) val safeNames = unsafeNames.filterNot { name -> hasConflicts(options.copy(methodName = name)) } if (safeNames.isNotEmpty()) return safeNames val baseName = unsafeNames.firstOrNull() ?: "extracted" val generatedNames = sequenceOf(baseName) + generateSequence(1) { seed -> seed + 1 }.map { number -> "$baseName$number" } return generatedNames.filterNot { name -> hasConflicts(options.copy(methodName = name)) }.take(1).toList() } private fun hasConflicts(options: ExtractOptions): Boolean { val (_, method) = prepareRefactoringElements(options) val conflicts = MultiMap<PsiElement, String>() ConflictsUtil.checkMethodConflicts(options.anchor.containingClass, null, method, conflicts) return ! conflicts.isEmpty } private fun createInplaceSettingsPopup(options: ExtractOptions): ExtractMethodPopupProvider { val analyzer = CodeFragmentAnalyzer(options.elements) val optionsWithStatic = ExtractMethodPipeline.withForcedStatic(analyzer, options) val makeStaticAndPassFields = optionsWithStatic?.inputParameters?.size != options.inputParameters.size val showStatic = !options.isStatic && optionsWithStatic != null val defaultStatic = if (!makeStaticAndPassFields) JavaRefactoringSettings.getInstance().EXTRACT_STATIC_METHOD else false val hasAnnotation = options.dataOutput.nullability != Nullability.UNKNOWN && options.dataOutput.type !is PsiPrimitiveType val annotationAvailable = ExtractMethodHelper.isNullabilityAvailable(options) return ExtractMethodPopupProvider( annotateDefault = if (hasAnnotation && annotationAvailable) needsNullabilityAnnotations(options.project) else null, makeStaticDefault = if (showStatic) defaultStatic else null, staticPassFields = makeStaticAndPassFields ) } fun executeRefactoringCommand(project: Project, command: () -> Unit) { CommandProcessor.getInstance().executeCommand(project, command, ExtractMethodHandler.getRefactoringName(), null) } fun replaceElements(sourceElements: List<PsiElement>, callElements: List<PsiElement>, anchor: PsiMember, method: PsiMethod): ExtractedElements { return WriteAction.compute<ExtractedElements, Throwable> { val addedMethod = anchor.addSiblingAfter(method) as PsiMethod val replacedCallElements = replacePsiRange(sourceElements, callElements) ExtractedElements(replacedCallElements, addedMethod) } } fun extractMethod(extractOptions: ExtractOptions): ExtractedElements { val elementsToExtract = prepareRefactoringElements(extractOptions) return replaceElements(extractOptions.elements, elementsToExtract.callElements, extractOptions.anchor, elementsToExtract.method) } fun doTestExtract( doRefactor: Boolean, editor: Editor, isConstructor: Boolean?, isStatic: Boolean?, returnType: PsiType?, newNameOfFirstParam: String?, targetClass: PsiClass?, @PsiModifier.ModifierConstant visibility: String?, vararg disabledParameters: Int ): Boolean { val project = editor.project ?: return false val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return false val range = ExtractMethodHelper.findEditorSelection(editor) ?: return false val elements = ExtractSelector().suggestElementsToExtract(file, range) if (elements.isEmpty()) throw ExtractException("Nothing to extract", file) val analyzer = CodeFragmentAnalyzer(elements) val allOptionsToExtract = findAllOptionsToExtract(elements) var options = allOptionsToExtract.takeIf { targetClass != null }?.find { option -> option.anchor.containingClass == targetClass } ?: allOptionsToExtract.find { option -> option.anchor.containingClass !is PsiAnonymousClass } ?: allOptionsToExtract.first() options = options.copy(methodName = "newMethod") if (isConstructor != options.isConstructor){ options = ExtractMethodPipeline.asConstructor(analyzer, options) ?: throw ExtractException("Fail", elements.first()) } if (! options.isStatic && isStatic == true) { options = ExtractMethodPipeline.withForcedStatic(analyzer, options) ?: throw ExtractException("Fail", elements.first()) } if (newNameOfFirstParam != null) { options = options.copy( inputParameters = listOf(options.inputParameters.first().copy(name = newNameOfFirstParam)) + options.inputParameters.drop(1) ) } if (returnType != null) { options = options.copy(dataOutput = options.dataOutput.withType(returnType)) } if (disabledParameters.isNotEmpty()) { options = options.copy( disabledParameters = options.inputParameters.filterIndexed { index, _ -> index in disabledParameters }, inputParameters = options.inputParameters.filterIndexed { index, _ -> index !in disabledParameters } ) } if (visibility != null) { options = options.copy(visibility = visibility) } if (options.anchor.containingClass?.isInterface == true) { options = ExtractMethodPipeline.adjustModifiersForInterface(options.copy(visibility = PsiModifier.PRIVATE)) } if (doRefactor) { extractMethod(options) } return true } fun showError(editor: Editor, ranges: List<TextRange>) { val project = editor.project ?: return if (ranges.isEmpty()) return val highlightManager = HighlightManager.getInstance(project) ranges.forEach { textRange -> highlightManager.addRangeHighlight(editor, textRange.startOffset, textRange.endOffset, EditorColors.SEARCH_RESULT_ATTRIBUTES, true, null) } WindowManager.getInstance().getStatusBar(project).info = RefactoringBundle.message("press.escape.to.remove.the.highlighting") } fun prepareRefactoringElements(extractOptions: ExtractOptions): ExtractedElements { val dependencies = withFilteredAnnotations(extractOptions) val factory = PsiElementFactory.getInstance(dependencies.project) val codeBlock = BodyBuilder(factory) .build( dependencies.elements, dependencies.flowOutput, dependencies.dataOutput, dependencies.inputParameters, dependencies.disabledParameters, dependencies.requiredVariablesInside ) val method = SignatureBuilder(dependencies.project) .build( dependencies.anchor.context, dependencies.elements, dependencies.isStatic, dependencies.visibility, dependencies.typeParameters, dependencies.dataOutput.type.takeIf { !dependencies.isConstructor }, dependencies.methodName, dependencies.inputParameters, dependencies.dataOutput.annotations, dependencies.thrownExceptions, dependencies.anchor ) method.body?.replace(codeBlock) if (needsNullabilityAnnotations(dependencies.project) && ExtractMethodHelper.isNullabilityAvailable(dependencies)) { updateMethodAnnotations(method, dependencies.inputParameters) } val callElements = CallBuilder(dependencies.elements.first()).createCall(method, dependencies) return ExtractedElements(callElements, method) } private fun needsNullabilityAnnotations(project: Project): Boolean { return PropertiesComponent.getInstance(project).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, true) } companion object { private val LOG = Logger.getInstance(MethodExtractor::class.java) @NonNls const val refactoringId: String = "refactoring.extract.method" internal fun sendRefactoringDoneEvent(extractedMethod: PsiMethod) { val data = RefactoringEventData() data.addElement(extractedMethod) extractedMethod.project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringDone(refactoringId, data) } internal fun sendRefactoringStartedEvent(elements: Array<PsiElement>) { val project = elements.firstOrNull()?.project ?: return val data = RefactoringEventData() data.addElements(elements) val publisher = project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) publisher.refactoringStarted(refactoringId, data) } } }
apache-2.0
raybritton/json-query
lib/src/main/kotlin/com/raybritton/jsonquery/ext/String+Misc.kt
1
360
package com.raybritton.jsonquery.ext fun String.replaceLast(oldValue: String, newValue: String, ignoreCase: Boolean = false): String { val index = lastIndexOf(oldValue, ignoreCase = ignoreCase) return if (index < 0) this else this.replaceRange(index, index + oldValue.length, newValue) } fun String?.wrap() = if (this == null) "null" else "\"$this\""
apache-2.0
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/PatternStoreScreen.kt
2
10883
package io.github.chrislo27.rhre3.screen import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.utils.Align import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.entity.Entity import io.github.chrislo27.rhre3.entity.model.ModelEntity import io.github.chrislo27.rhre3.entity.model.special.TextureEntity import io.github.chrislo27.rhre3.patternstorage.FileStoredPattern import io.github.chrislo27.rhre3.patternstorage.PatternStorage import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.rhre3.track.Remix import io.github.chrislo27.rhre3.util.JsonHandler import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.ui.Button import io.github.chrislo27.toolboks.ui.ImageLabel import io.github.chrislo27.toolboks.ui.TextField import io.github.chrislo27.toolboks.ui.TextLabel import java.io.ByteArrayOutputStream import java.nio.charset.Charset import java.util.* class PatternStoreScreen(main: RHRE3Application, val editor: Editor, val pattern: FileStoredPattern?, val entities: List<Entity>?) : ToolboksScreen<RHRE3Application, PatternStoreScreen>(main) { companion object { private const val ALLOW_SAME_NAMES = true private val JSON_SERIALIZER: ObjectMapper by lazy { JsonHandler.createObjectMapper(failOnUnknown = false, prettyPrinted = false) } fun entitiesToJson(remix: Remix, entities: List<Entity>, prettyPrinted: Boolean = true): String { val array = JsonHandler.OBJECT_MAPPER.createArrayNode() val oldBounds: Map<Entity, Rectangle> = entities.associateWith { Rectangle(it.bounds) } val baseX: Float = entities.minByOrNull { it.bounds.x }?.bounds?.x ?: 0f val baseY: Int = entities.minByOrNull { it.bounds.y }?.bounds?.y?.toInt() ?: 0 entities.forEach { it.updateBounds { it.bounds.x -= baseX it.bounds.y -= baseY } } val texturesStored: MutableSet<String> = mutableSetOf() entities.forEach { entity -> val node = array.addObject() node.put("type", entity.jsonType) if (entity is TextureEntity) { val hash = entity.textureHash if (hash != null && hash !in texturesStored) { val texture = remix.textureCache[hash] if (texture != null) { node.put("_textureData_hash", hash) node.put("_textureData_data", Base64.getEncoder().encode(ByteArrayOutputStream().also { baos -> Remix.writeTexture(baos, texture) }.toByteArray()).toString(Charset.forName("UTF-8"))) texturesStored += hash } } } entity.saveData(node) } // Restore bounds entities.forEach { it.updateBounds { it.bounds.set(oldBounds[it]) } } return if (prettyPrinted) JsonHandler.toJson(array) else JSON_SERIALIZER.writeValueAsString(array) } fun jsonToEntities(remix: Remix, json: String): List<Entity> { return (JsonHandler.OBJECT_MAPPER.readTree(json) as ArrayNode).map { node -> Entity.getEntityFromType(node["type"]?.asText(null) ?: return@map null, node as ObjectNode, remix)?.also { it.readData(node) // Load textures if necessary val texHashNode = node["_textureData_hash"] val texDataNode = node["_textureData_data"] if (texHashNode != null && texDataNode != null) { val texHash = texHashNode.asText() if (!remix.textureCache.containsKey(texHash)) { try { val bytes = Base64.getDecoder().decode(texDataNode.asText().toByteArray(Charset.forName("UTF-8"))) remix.textureCache[texHash] = Texture(Pixmap(bytes, 0, bytes.size)) } catch (e: Exception) { e.printStackTrace() } } } } ?: Remix.createMissingEntitySubtitle(remix, node[ModelEntity.JSON_DATAMODEL]?.textValue() ?: "null", node["beat"]?.floatValue() ?: 0f, node["track"]?.floatValue() ?: 0f, node["width"]?.floatValue() ?: 1f, node["height"]?.floatValue()?.coerceAtLeast(1f) ?: 1f) }.filterNotNull() } } override val stage: GenericStage<PatternStoreScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) private val button: Button<PatternStoreScreen> private lateinit var textField: TextField<PatternStoreScreen> init { stage.titleLabel.text = if (pattern != null) "screen.patternStore.edit.title" else "screen.patternStore.title" stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_pattern_store")) stage.backButton.visible = true stage.onBackButtonClick = { main.screen = ScreenRegistry["editor"] } val palette = main.uiPalette stage.centreStage.elements += TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(screenY = 0.75f, screenHeight = 0.15f) this.isLocalizationKey = true this.text = "screen.patternStore.enterName" } val alreadyExists = TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(screenY = 0.15f, screenHeight = 0.15f) this.isLocalizationKey = true this.text = "screen.patternStore.alreadyExists" this.visible = false } stage.centreStage.elements += alreadyExists if (pattern != null) { stage.bottomStage.elements += Button(palette.copy(highlightedBackColor = Color(1f, 0f, 0f, 0.5f), clickedBackColor = Color(1f, 0.5f, 0.5f, 0.5f)), stage.bottomStage, stage.bottomStage).apply { val backBtnLoc = [email protected] this.location.set(1f - backBtnLoc.screenX - backBtnLoc.screenWidth, backBtnLoc.screenY, backBtnLoc.screenWidth, backBtnLoc.screenHeight) this.addLabel(ImageLabel(palette, this, this.stage).apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_x")) }) this.leftClickAction = { _, _ -> main.screen = PatternDeleteScreen(main, editor, pattern, this@PatternStoreScreen) } } } button = Button(palette, stage.bottomStage, stage.bottomStage).apply { this.location.set(screenX = 0.25f, screenWidth = 0.5f) this.addLabel(TextLabel(palette, this, this.stage).apply { this.isLocalizationKey = true this.text = "screen.patternStore.button" }) this.leftClickAction = { _, _ -> if (pattern == null) { val entities = entities!! PatternStorage.addPattern(FileStoredPattern(UUID.randomUUID(), textField.text.trim(), entitiesToJson(entities.first().remix, entities))) .persist() } else { PatternStorage.deletePattern(pattern) .addPattern(FileStoredPattern(pattern.uuid, textField.text.trim(), pattern.data)) .persist() } editor.stage.updateSelected() main.screen = ScreenRegistry["editor"] } this.enabled = false } val charsRemaining = TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.isLocalizationKey = false this.text = "0 / ?" this.textAlign = Align.right this.fontScaleMultiplier = 0.75f this.location.set(screenX = 0.25f, screenWidth = 0.5f, screenY = 0.4125f, screenHeight = 0.1f) } stage.centreStage.elements += charsRemaining textField = object : TextField<PatternStoreScreen>(palette, stage.centreStage, stage.centreStage) { init { characterLimit = PatternStorage.MAX_PATTERN_NAME_SIZE } override fun onEnterPressed(): Boolean { if (text.isNotBlank()) { button.onLeftClick(0f, 0f) return true } return false } override fun onRightClick(xPercent: Float, yPercent: Float) { super.onRightClick(xPercent, yPercent) text = "" } override fun onTextChange(oldText: String) { super.onTextChange(oldText) val trimmed = text.trim() val already = PatternStorage.patterns.values.any { it !== pattern && it.name == trimmed } button.enabled = trimmed.isNotEmpty() && (ALLOW_SAME_NAMES || !already) alreadyExists.visible = already charsRemaining.text = "${trimmed.length} / ${PatternStorage.MAX_PATTERN_NAME_SIZE}" } }.apply { this.location.set(screenY = 0.5f, screenHeight = 0.1f, screenX = 0.25f, screenWidth = 0.5f) this.canPaste = true this.canInputNewlines = false this.background = true this.hasFocus = true onTextChange("") } stage.centreStage.elements += textField stage.bottomStage.elements += button if (entities?.size == 0) error("Entities are empty") stage.updatePositions() textField.apply { if (pattern != null) { text = pattern.name this.caret = text.length + 1 } } } override fun tickUpdate() { } override fun dispose() { } }
gpl-3.0
allotria/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/StartupManagerTest.kt
1
2117
// 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.ide import com.intellij.ide.startup.impl.StartupManagerImpl import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.DumbServiceImpl import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.startup.StartupActivity import com.intellij.testFramework.* import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.rules.InMemoryFsRule import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @Suppress("UsePropertyAccessSyntax") class StartupManagerTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @JvmField @Rule val fsRule = InMemoryFsRule() @Test(timeout = 5_000) //@Test() fun runAfterOpenedMustBeDumbAware() { val done = CountDownLatch(1) val project = ProjectManagerEx.getInstanceEx().openProject(fsRule.fs.getPath("/p"), createTestOpenProjectOptions().copy(beforeOpen = { project -> val startupManager = StartupManagerImpl.getInstance(project) as StartupManagerImpl assertThat(startupManager.postStartupActivityPassed()).isFalse() val dumbService = DumbService.getInstance(project) as DumbServiceImpl ExtensionTestUtil.maskExtensions(StartupActivity.POST_STARTUP_ACTIVITY, listOf(StartupActivity.DumbAware { runInEdtAndWait { dumbService.isDumb = true } assertThat(dumbService.isDumb).isTrue() }, StartupActivity.DumbAware { startupManager.runAfterOpened { assertThat(dumbService.isDumb).isTrue() done.countDown() } }), project, fireEvents = false) assertThat(startupManager.postStartupActivityPassed()).isFalse() true }))!! try { done.await(1, TimeUnit.SECONDS) } finally { PlatformTestUtil.forceCloseProjectWithoutSaving(project) } } }
apache-2.0
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/CancellableContinuationResumeCloseStressTest.kt
1
1911
/* * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.atomicfu.* import org.junit.* import java.util.concurrent.* import kotlin.test.* import kotlin.test.Test class CancellableContinuationResumeCloseStressTest : TestBase() { @get:Rule public val dispatcher = ExecutorRule(2) private val startBarrier = CyclicBarrier(3) private val doneBarrier = CyclicBarrier(2) private val nRepeats = 1_000 * stressTestMultiplier private val closed = atomic(false) private var returnedOk = false @Test @Suppress("BlockingMethodInNonBlockingContext") fun testStress() = runTest { repeat(nRepeats) { closed.value = false returnedOk = false val job = testJob() startBarrier.await() job.cancel() // (1) cancel job job.join() // check consistency doneBarrier.await() if (returnedOk) { assertFalse(closed.value, "should not have closed resource -- returned Ok") } else { assertTrue(closed.value, "should have closed resource -- was cancelled") } } } private fun CoroutineScope.testJob(): Job = launch(dispatcher, start = CoroutineStart.ATOMIC) { val ok = resumeClose() // might be cancelled assertEquals("OK", ok) returnedOk = true } private suspend fun resumeClose() = suspendCancellableCoroutine<String> { cont -> dispatcher.executor.execute { startBarrier.await() // (2) resume at the same time cont.resume("OK") { close() } doneBarrier.await() } startBarrier.await() // (3) return at the same time } fun close() { assertFalse(closed.getAndSet(true)) } }
apache-2.0
JetBrains/teamcity-dnx-plugin
plugin-dotnet-common/src/main/kotlin/jetbrains/buildServer/dotnet/ToolBitness.kt
1
90
package jetbrains.buildServer.dotnet enum class ToolBitness { Any, X64, X86 }
apache-2.0
googlemaps/android-places-ktx
places-ktx/src/main/java/com/google/android/libraries/places/ktx/api/net/FindCurrentPlaceRequest.kt
1
1346
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.places.ktx.api.net import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest /** * Builds a new [FindCurrentPlaceRequest]. * * @param placeFields the fields of the places to be returned * @param actions the actions to apply to the [FindCurrentPlaceRequest.Builder] * * @return the constructed [FindCurrentPlaceRequest] */ public inline fun findCurrentPlaceRequest( placeFields: List<Place.Field>, noinline actions: (FindCurrentPlaceRequest.Builder.() -> Unit)? = null ): FindCurrentPlaceRequest { val request = FindCurrentPlaceRequest.builder(placeFields) actions?.let { request.apply(it) } return request.build() }
apache-2.0
zdary/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/classstore/ClassDefinition.kt
10
6296
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.classstore import com.intellij.diagnostic.hprof.parser.Type import org.jetbrains.annotations.NonNls import java.util.function.LongUnaryOperator class ClassDefinition(val name: String, val id: Long, val superClassId: Long, val classLoaderId: Long, val instanceSize: Int, val superClassOffset: Int, val refInstanceFields: Array<InstanceField>, private val primitiveInstanceFields: Array<InstanceField>, val constantFields: LongArray, val objectStaticFields: Array<StaticField>, val primitiveStaticFields: Array<StaticField>) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ClassDefinition if (id != other.id) return false if (id == 0L && other.id == 0L) { return name == other.name } return true } val prettyName: String get() = computePrettyName(name) companion object { const val OBJECT_PREAMBLE_SIZE = 8 const val ARRAY_PREAMBLE_SIZE = 12 @NonNls fun computePrettyName(name: String): String { if (!name.startsWith('[')) return name var arraySymbolsCount = 0 while (name.length > arraySymbolsCount && name[arraySymbolsCount] == '[') arraySymbolsCount++ if (name.length <= arraySymbolsCount) { // Malformed name return name } val arrayType: Char = name[arraySymbolsCount] val arrayString: String = "[]".repeat(arraySymbolsCount) return when (arrayType) { 'B' -> "byte$arrayString" 'C' -> "char$arrayString" 'D' -> "double$arrayString" 'F' -> "float$arrayString" 'I' -> "int$arrayString" 'J' -> "long$arrayString" 'L' -> "${name.substring(arraySymbolsCount + 1, name.length - 1)}$arrayString" 'S' -> "short$arrayString" 'Z' -> "boolean$arrayString" else -> name } } val CLASS_FIELD = InstanceField("<class>", -1, Type.OBJECT) } fun getSuperClass(classStore: ClassStore): ClassDefinition? { return when (superClassId) { 0L -> null else -> classStore[superClassId.toInt()] } } override fun hashCode(): Int = id.hashCode() fun isArray(): Boolean = name[0] == '[' fun isPrimitiveArray(): Boolean = isArray() && name.length == 2 fun copyWithRemappedIDs(remappingFunction: LongUnaryOperator): ClassDefinition { fun map(id: Long): Long = remappingFunction.applyAsLong(id) val newConstantFields = LongArray(constantFields.size) { map(constantFields[it]) } val newStaticObjectFields = Array(objectStaticFields.size) { val oldStaticField = objectStaticFields[it] StaticField(oldStaticField.name, map(oldStaticField.value)) } return ClassDefinition( name, map(id), map(superClassId), map(classLoaderId), instanceSize, superClassOffset, refInstanceFields, primitiveInstanceFields, newConstantFields, newStaticObjectFields, primitiveStaticFields ) } fun allRefFieldNames(classStore: ClassStore): List<String> { val result = mutableListOf<String>() var currentClass = this do { result.addAll(currentClass.refInstanceFields.map { it.name }) currentClass = currentClass.getSuperClass(classStore) ?: break } while (true) return result } fun getRefField(classStore: ClassStore, index: Int): InstanceField { var currentIndex = index var currentClass = this do { val size = currentClass.refInstanceFields.size if (currentIndex < size) { return currentClass.refInstanceFields[currentIndex] } currentIndex -= size currentClass = currentClass.getSuperClass(classStore) ?: break } while (true) if (currentIndex == 0) { return CLASS_FIELD } throw IndexOutOfBoundsException("$index on class $name") } fun getClassFieldName(index: Int): String { if (index in constantFields.indices) { return "<constant>" } if (index in constantFields.size until constantFields.size + objectStaticFields.size) { return objectStaticFields[index - constantFields.size].name } if (index == constantFields.size + objectStaticFields.size) { return "<loader>" } throw IndexOutOfBoundsException("$index on class $name") } fun getPrimitiveStaticFieldValue(name: String): Long? { return primitiveStaticFields.find { it.name == name }?.value } /** * Computes offset of a given field in the class (including superclasses) * @return Offset of the field, or -1 if the field doesn't exist. */ fun computeOffsetOfField(fieldName: String, classStore: ClassStore): Int { var classOffset = 0 var currentClass = this do { var field = currentClass.refInstanceFields.find { it.name == fieldName } if (field == null) { field = currentClass.primitiveInstanceFields.find { it.name == fieldName } } if (field != null) { return classOffset + field.offset } classOffset += currentClass.superClassOffset currentClass = currentClass.getSuperClass(classStore) ?: return -1 } while (true) } fun copyWithName(newName: String): ClassDefinition { return ClassDefinition(newName, id, superClassId, classLoaderId, instanceSize, superClassOffset, refInstanceFields, primitiveInstanceFields, constantFields, objectStaticFields, primitiveStaticFields) } }
apache-2.0
Raizlabs/DBFlow
tests/src/androidTest/java/com/dbflow5/livedata/LiveDataModels.kt
1
334
package com.dbflow5.livedata import com.dbflow5.TestDatabase import com.dbflow5.annotation.PrimaryKey import com.dbflow5.annotation.Table /** * Description: Basic live data object model. */ @Table(database = TestDatabase::class) data class LiveDataModel(@PrimaryKey var id: String = "", var name: Int = 0)
mit
leafclick/intellij-community
jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ArtifactRebuildTest.kt
1
4423
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.builders.rebuild import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.ZipUtil import com.intellij.util.io.directoryContent import java.io.File import java.io.FileInputStream import java.util.jar.Attributes import java.util.jar.Manifest class ArtifactRebuildTest: JpsRebuildTestCase() { fun testArtifactIncludesArchiveArtifact() { val name = "artifactIncludesArchiveArtifact" try { doTest("$name/${name}.ipr", directoryContent { dir("artifacts") { dir("data") { zip("a.jar") { file("a.txt") } } } }) } finally { FileUtil.delete(File(FileUtil.toSystemDependentName(testDataRootPath + "/$name/data/a.jar"))) } } fun testArtifactWithoutOutput() { val outDir = FileUtil.createTempDirectory("output", "").absolutePath loadProject("artifactWithoutOutput/artifactWithoutOutput.ipr", mapOf("OUTPUT_DIR" to outDir)) rebuild() assertOutput(outDir, directoryContent { dir("artifacts") { dir("main") { file("data.txt") file("data2.txt") } } }) } fun testExtractDir() { doTest("extractDirTest/extractDirTest.ipr", directoryContent { dir("artifacts") { dir("extractDir") { file("b.txt", "b") } dir("extractRoot") { dir("extracted") { dir("dir") { file("b.txt", "b") } file("a.txt", "a") } } dir("packedDir") { zip("packedDir.jar") { file("b.txt", "b") } } dir("packedRoot") { zip("packedRoot.jar") { dir("dir") { file("b.txt", "b") } file("a.txt", "a") } } } }) } fun testManifestInArtifact() { loadAndRebuild("manifestInArtifact/manifest.ipr", mapOf()) val jarFile = File(myOutputDirectory, "artifacts/simple/simple.jar") assertTrue(jarFile.exists()) val extracted = FileUtil.createTempDirectory("build-manifest", "") ZipUtil.extract(jarFile, extracted, null) val manifestFile = File(extracted, "META-INF/MANIFEST.MF") assertTrue(manifestFile.exists()) val manifest = Manifest(FileInputStream(manifestFile)) assertEquals("MyClass", manifest.mainAttributes!!.getValue(Attributes.Name.MAIN_CLASS)) } fun testOverwriteArtifacts() { doTest("overwriteTest/overwriteTest.ipr", directoryContent { dir("artifacts") { dir("classes") { file("a.xml", "<root2/>") } dir("dirs") { file("x.txt", "d2") } dir("fileCopy") { dir("xxx") { dir("a") { file("f.txt", "b") } } } } dir("production") { dir("dep") { file("a.xml", "<root2/>") } dir("overwriteTest") { file("a.xml", "<root1/>") } } }) } fun testPathVariablesInArtifact() { val externalDir = "${testDataRootPath}/pathVariables/external" doTest("pathVariables/pathVariables.ipr", mapOf("EXTERNAL_DIR" to externalDir), directoryContent { dir("artifacts") { dir("fileCopy") { dir("dir") { file("file.txt", "xxx") } } } }) } fun testModuleTestOutputElement() { doTest("moduleTestOutput/moduleTestOutput.ipr", directoryContent { dir("artifacts") { dir("tests") { file("MyTest.class") } } dir("production") { dir("moduleTestOutput") { file("MyClass.class") } } dir("test") { dir("moduleTestOutput") { file("MyTest.class") } } }) } }
apache-2.0
Raizlabs/DBFlow
core/src/main/kotlin/com/dbflow5/annotation/UniqueGroup.kt
1
444
package com.dbflow5.annotation /** * Description: */ @Target(AnnotationTarget.ANNOTATION_CLASS) @Retention(AnnotationRetention.SOURCE) annotation class UniqueGroup( /** * @return The number that columns point to to use this group */ val groupNumber: Int, /** * @return The conflict action that this group takes. */ val uniqueConflict: ConflictAction = ConflictAction.FAIL)
mit
leafclick/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/lang/formatter/MarkdownLanguageCodeStyleSettingsProvider.kt
1
2594
// 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.intellij.plugins.markdown.lang.formatter import com.intellij.lang.Language import com.intellij.psi.codeStyle.CodeStyleConfigurable import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider import org.intellij.plugins.markdown.lang.MarkdownLanguage class MarkdownLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() { override fun getLanguage(): Language = MarkdownLanguage.INSTANCE private val STANDARD_WRAPPING_OPTIONS = arrayOf("RIGHT_MARGIN", "WRAP_ON_TYPING") override fun createConfigurable(baseSettings: CodeStyleSettings, modelSettings: CodeStyleSettings): CodeStyleConfigurable = MarkdownCodeStyleConfigurable(baseSettings, modelSettings) override fun getConfigurableDisplayName() = "Markdown" override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) { if (settingsType == LanguageCodeStyleSettingsProvider.SettingsType.WRAPPING_AND_BRACES_SETTINGS) { consumer.showStandardOptions(*STANDARD_WRAPPING_OPTIONS) } } override fun getCodeSample(settingsType: SettingsType): String = """**Markdown parser and generator written in Kotlin** Introduction ------------- [intellij-markdown][self] is a fast and extensible markdown processor. It is aimed to suit the following needs: - Use one code base for both client and server-side processing; - Support different flavours; - Be easily extensible. Since the parser is written in [Kotlin], it can be compiled to both JS and Java bytecode thus can be used everywhere. Usage ----- One of the goals of this project is to provide flexibility in terms of the tasks being solved. [Markdown plugin] for JetBrains IDEs is an example of usage when markdown processing is done in several stages: * Parse block structure without parsing inlines to provide lazy parsable blocks for IDE; * Quickly parse inlines of a given block to provide faster syntax highlighting update; * Generate HTML for preview. These tasks may be completed independently according to the current needs. #### Simple html generation (Kotlin) ```kotlin val src = "Some *Markdown*" val flavour = CommonMarkFlavourDescriptor() val parsedTree = MarkdownParser(flavour).buildMarkdownTreeFromString(src) val html = HtmlGenerator(src, parsedTree, flavour).generateHtml() ``` """.trimMargin() }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/runtime/collections/listof0.kt
1
400
package runtime.collections.listof0 import kotlin.test.* @Test fun runTest() { main(arrayOf("a")) } fun main(args : Array<String>) { val nonConstStr = args[0] val list = arrayListOf(nonConstStr, "b", "c") for (element in list) print(element) println() list.add("d") println(list.toString()) val list2 = listOf("n", "s", nonConstStr) println(list2.toString()) }
apache-2.0