repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/LoginFunnel.kt
1
1358
package org.wikipedia.analytics import org.wikipedia.WikipediaApp class LoginFunnel(app: WikipediaApp) : Funnel(app, SCHEMA_NAME, REVISION) { @JvmOverloads fun logStart(source: String?, editSessionToken: String? = null) { log("action", "start", "source", source, "edit_session_token", editSessionToken) } fun logCreateAccountAttempt() { log("action", "createAccountAttempt") } fun logCreateAccountFailure() { log("action", "createAccountFailure") } fun logCreateAccountSuccess() { log("action", "createAccountSuccess") } fun logError(code: String?) { log("action", "error", "error_text", code) } fun logSuccess() { log("action", "success") } companion object { private const val SCHEMA_NAME = "MobileWikiAppLogin" private const val REVISION = 20710032 const val SOURCE_NAV = "navigation" const val SOURCE_EDIT = "edit" const val SOURCE_BLOCKED = "blocked" const val SOURCE_SYSTEM = "system" const val SOURCE_ONBOARDING = "onboarding" const val SOURCE_SETTINGS = "settings" const val SOURCE_READING_MANUAL_SYNC = "reading_lists_manual_sync" const val SOURCE_LOGOUT_BACKGROUND = "logout_background" const val SOURCE_SUGGESTED_EDITS = "suggestededits" } }
apache-2.0
2fcfc458fb58c3b5b01d64df204938ac
29.177778
88
0.643594
4.23053
false
false
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/tasks/ImportDataTask.kt
1
2188
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.tasks import android.util.Log import org.isoron.uhabits.core.io.GenericImporter import org.isoron.uhabits.core.models.ModelFactory import org.isoron.uhabits.core.models.sqlite.SQLModelFactory import org.isoron.uhabits.core.tasks.Task import java.io.File class ImportDataTask( private val importer: GenericImporter, modelFactory: ModelFactory, private val file: File, private val listener: Listener ) : Task { private var result = 0 private val modelFactory: SQLModelFactory = modelFactory as SQLModelFactory override fun doInBackground() { modelFactory.database.beginTransaction() try { if (importer.canHandle(file)) { importer.importHabitsFromFile(file) result = SUCCESS modelFactory.database.setTransactionSuccessful() } else { result = NOT_RECOGNIZED } } catch (e: Exception) { result = FAILED Log.e("ImportDataTask", "Import failed", e) } modelFactory.database.endTransaction() } override fun onPostExecute() { listener.onImportDataFinished(result) } fun interface Listener { fun onImportDataFinished(result: Int) } companion object { const val FAILED = 3 const val NOT_RECOGNIZED = 2 const val SUCCESS = 1 } }
gpl-3.0
8f92503e3b02098941958b21eb16065c
32.136364
79
0.68267
4.463265
false
false
false
false
Frederikam/FredBoat
FredBoat/src/main/java/fredboat/command/admin/AnnounceCommand.kt
1
5585
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fredboat.command.admin import com.fredboat.sentinel.entities.SendMessageResponse import fredboat.command.info.HelpCommand import fredboat.commandmeta.abs.Command import fredboat.commandmeta.abs.CommandContext import fredboat.commandmeta.abs.ICommandRestricted import fredboat.definitions.PermissionLevel import fredboat.main.Launcher import fredboat.messaging.internal.Context import fredboat.util.TextUtils import fredboat.util.extension.edit import org.slf4j.LoggerFactory import java.text.MessageFormat import java.util.concurrent.Phaser import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException /** * @author frederik */ class AnnounceCommand(name: String, vararg aliases: String) : Command(name, *aliases), ICommandRestricted { companion object { private val log = LoggerFactory.getLogger(AnnounceCommand::class.java) private const val HEAD = "__**[BROADCASTED MESSAGE]**__\n" } override val minimumPerms: PermissionLevel get() = PermissionLevel.BOT_ADMIN override suspend fun invoke(context: CommandContext) { val players = Launcher.botController.playerRegistry.playingPlayers if (players.isEmpty()) { context.reply("No currently playing players.") return } if (!context.hasArguments()) { HelpCommand.sendFormattedCommandHelp(context) return } val msg = HEAD + context.rawArgs var mono = context.replyMono("[0/${players.size}]") mono = mono.doOnSuccess { status -> Thread { val phaser = Phaser(players.size) for (player in players) { val activeTextChannel = player.activeTextChannel if (activeTextChannel != null) { activeTextChannel.send(msg) .doOnError { phaser.arriveAndDeregister() } .subscribe { phaser.arrive() } } else { phaser.arriveAndDeregister() } } Thread { try { do { try { phaser.awaitAdvanceInterruptibly(0, 5, TimeUnit.SECONDS) // Now all the parties have arrived, we can break out of the loop break } catch (ex: TimeoutException) { // This is fine, this means that the required parties haven't arrived } printProgress(context, status, phaser.arrivedParties, players.size, players.size - phaser.registeredParties) } while (true) printDone(context, status, phaser.registeredParties, //phaser wraps back to 0 on phase increment players.size - phaser.registeredParties) } catch (ex: InterruptedException) { Thread.currentThread().interrupt() // restore interrupt flag log.error("interrupted", ex) throw RuntimeException(ex) } }.start() }.start() } mono.doOnError { throwable -> TextUtils.handleException("Announcement failed!", throwable, context) throw RuntimeException(throwable) }.subscribe() } private fun printProgress(context: CommandContext, message: SendMessageResponse, done: Int, total: Int, error: Int) { message.edit(context.textChannel, MessageFormat.format( "[{0}/{1}]{2,choice,0#|0< {2} failed}", done, total, error) ).subscribe() } private fun printDone(context: CommandContext, message: SendMessageResponse, completed: Int, failed: Int) { message.edit(context.textChannel, "Done with $completed completed and $failed failed").subscribe() } override fun help(context: Context) = "{0}{1} <announcement>\n#Broadcast an announcement to active textchannels of playing GuildPlayers." }
mit
8f8bdd9f92baa12495c78e0c8baf419e
40.37037
121
0.599821
5.147465
false
false
false
false
mikepenz/FastAdapter
fastadapter-extensions-scroll/src/main/java/com/mikepenz/fastadapter/scroll/EndlessRecyclerOnScrollListener.kt
1
5945
package com.mikepenz.fastadapter.scroll import android.view.View import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.adapters.ItemAdapter abstract class EndlessRecyclerOnScrollListener : RecyclerView.OnScrollListener { private var enabled = true private var previousTotal = 0 private var isLoading = true private var visibleThreshold = RecyclerView.NO_POSITION var firstVisibleItem: Int = 0 private set var visibleItemCount: Int = 0 private set var totalItemCount: Int = 0 private set private var isOrientationHelperVertical: Boolean = false private var orientationHelper: OrientationHelper? = null var currentPage = 0 private set private var footerAdapter: ItemAdapter<*>? = null lateinit var layoutManager: RecyclerView.LayoutManager private set constructor() /** * @param adapter the ItemAdapter used to host footer items */ constructor(adapter: ItemAdapter<*>) { this.footerAdapter = adapter } constructor(layoutManager: RecyclerView.LayoutManager) { this.layoutManager = layoutManager } constructor(visibleThreshold: Int) { this.visibleThreshold = visibleThreshold } constructor(layoutManager: RecyclerView.LayoutManager, visibleThreshold: Int) { this.layoutManager = layoutManager this.visibleThreshold = visibleThreshold } /** * @param layoutManager * @param visibleThreshold * @param footerAdapter the ItemAdapter used to host footer items */ constructor(layoutManager: RecyclerView.LayoutManager, visibleThreshold: Int, footerAdapter: ItemAdapter<*>) { this.layoutManager = layoutManager this.visibleThreshold = visibleThreshold this.footerAdapter = footerAdapter } private fun findFirstVisibleItemPosition(recyclerView: RecyclerView): Int { val child = findOneVisibleChild(0, layoutManager.childCount, false, true) return if (child == null) RecyclerView.NO_POSITION else recyclerView.getChildAdapterPosition(child) } private fun findLastVisibleItemPosition(recyclerView: RecyclerView): Int { val child = findOneVisibleChild(recyclerView.childCount - 1, -1, false, true) return if (child == null) RecyclerView.NO_POSITION else recyclerView.getChildAdapterPosition(child) } private fun findOneVisibleChild(fromIndex: Int, toIndex: Int, completelyVisible: Boolean, acceptPartiallyVisible: Boolean): View? { if (layoutManager.canScrollVertically() != isOrientationHelperVertical || orientationHelper == null) { isOrientationHelperVertical = layoutManager.canScrollVertically() orientationHelper = if (isOrientationHelperVertical) OrientationHelper.createVerticalHelper(layoutManager) else OrientationHelper.createHorizontalHelper(layoutManager) } val mOrientationHelper = this.orientationHelper ?: return null val start = mOrientationHelper.startAfterPadding val end = mOrientationHelper.endAfterPadding val next = if (toIndex > fromIndex) 1 else -1 var partiallyVisible: View? = null var i = fromIndex while (i != toIndex) { val child = layoutManager.getChildAt(i) if (child != null) { val childStart = mOrientationHelper.getDecoratedStart(child) val childEnd = mOrientationHelper.getDecoratedEnd(child) if (childStart < end && childEnd > start) { if (completelyVisible) { if (childStart >= start && childEnd <= end) { return child } else if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child } } else { return child } } } i += next } return partiallyVisible } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (enabled) { if (!::layoutManager.isInitialized) { layoutManager = recyclerView.layoutManager ?: throw RuntimeException("A LayoutManager is required") } val footerItemCount = footerAdapter?.adapterItemCount ?: 0 if (visibleThreshold == RecyclerView.NO_POSITION) { visibleThreshold = findLastVisibleItemPosition(recyclerView) - findFirstVisibleItemPosition(recyclerView) - footerItemCount } visibleItemCount = recyclerView.childCount - footerItemCount totalItemCount = layoutManager.itemCount - footerItemCount firstVisibleItem = findFirstVisibleItemPosition(recyclerView) if (isLoading) { if (totalItemCount > previousTotal) { isLoading = false previousTotal = totalItemCount } } if (!isLoading && totalItemCount - visibleItemCount <= firstVisibleItem + visibleThreshold) { currentPage++ onLoadMore(currentPage) isLoading = true } } } fun enable(): EndlessRecyclerOnScrollListener { enabled = true return this } fun disable(): EndlessRecyclerOnScrollListener { enabled = false return this } @JvmOverloads fun resetPageCount(page: Int = 0) { previousTotal = 0 isLoading = true currentPage = page onLoadMore(currentPage) } abstract fun onLoadMore(currentPage: Int) }
apache-2.0
1ef9a56cc4d782cb037f348eb469ed9f
34.183432
139
0.63381
5.927218
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BasePartiallyExcludedChangesTest.kt
12
3814
// 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.openapi.vcs import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.changes.ui.PartiallyExcludedFilesStateHolder import com.intellij.openapi.vcs.ex.ExclusionState import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker import com.intellij.openapi.vcs.impl.PartialChangesUtil abstract class BasePartiallyExcludedChangesTest : BaseLineStatusTrackerManagerTest() { private lateinit var stateHolder: MyStateHolder override fun setUp() { super.setUp() stateHolder = MyStateHolder() stateHolder.updateExclusionStates() } protected inner class MyStateHolder : PartiallyExcludedFilesStateHolder<FilePath>(getProject()) { val paths = HashSet<FilePath>() init { Disposer.register(testRootDisposable, this) } override val trackableElements: Sequence<FilePath> get() = paths.asSequence() override fun getChangeListId(element: FilePath): String = DEFAULT.asListNameToId() override fun findElementFor(tracker: PartialLocalLineStatusTracker, changeListId: String): FilePath? { return paths.find { it.virtualFile == tracker.virtualFile } } override fun findTrackerFor(element: FilePath): PartialLocalLineStatusTracker? { val file = element.virtualFile ?: return null return PartialChangesUtil.getPartialTracker(getProject(), file) } fun toggleElements(elements: Collection<FilePath>) { val hasExcluded = elements.any { getExclusionState(it) != ExclusionState.ALL_INCLUDED } if (hasExcluded) includeElements(elements) else excludeElements(elements) } fun waitExclusionStateUpdate() { myUpdateQueue.flush() } } protected fun setHolderPaths(vararg paths: String) { stateHolder.paths.clear() stateHolder.paths.addAll(paths.toFilePaths()) } protected fun waitExclusionStateUpdate() { stateHolder.waitExclusionStateUpdate() } protected fun toggle(vararg paths: String) { assertContainsElements(stateHolder.paths, paths.toFilePaths()) stateHolder.toggleElements(paths.toFilePaths()) } protected fun include(vararg paths: String) { assertContainsElements(stateHolder.paths, paths.toFilePaths()) stateHolder.includeElements(paths.toFilePaths()) } protected fun exclude(vararg paths: String) { assertContainsElements(stateHolder.paths, paths.toFilePaths()) stateHolder.excludeElements(paths.toFilePaths()) } protected fun assertIncluded(vararg paths: String) { val expected = paths.toFilePaths().toSet() val actual = stateHolder.getIncludedSet() assertSameElements(actual.map { it.name }, expected.map { it.name }) assertSameElements(actual, expected) } protected fun PartialLocalLineStatusTracker.assertExcluded(index: Int, expected: Boolean) { val range = this.getRanges()!![index] assertEquals(expected, range.isExcludedFromCommit) } protected fun String.assertExcludedState(holderState: ExclusionState, trackerState: ExclusionState = holderState) { val actual = stateHolder.getExclusionState(this.toFilePath) assertEquals(holderState, actual) (toFilePath.virtualFile?.tracker as? PartialLocalLineStatusTracker)?.assertExcludedState(trackerState, DEFAULT) } protected fun PartialLocalLineStatusTracker.exclude(index: Int, isExcluded: Boolean) { val ranges = getRanges()!! this.setExcludedFromCommit(ranges[index], isExcluded) waitExclusionStateUpdate() } protected fun PartialLocalLineStatusTracker.moveTo(index: Int, changelistName: String) { val ranges = getRanges()!! this.moveToChangelist(ranges[index], changelistName.asListNameToList()) waitExclusionStateUpdate() } }
apache-2.0
29b3e02ea6374e9248ff41289c3fce24
35.682692
140
0.761405
4.697044
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/helpers/utils.kt
2
2101
// 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.completion.contributors.helpers import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.scopes.KtScope import org.jetbrains.kotlin.analysis.api.scopes.KtScopeNameFilter import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.idea.completion.checkers.CompletionVisibilityChecker import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.isPrivate internal fun createStarTypeArgumentsList(typeArgumentsCount: Int): String = if (typeArgumentsCount > 0) { List(typeArgumentsCount) { "*" }.joinToString(prefix = "<", postfix = ">") } else { "" } internal fun KtAnalysisSession.collectNonExtensions( scope: KtScope, visibilityChecker: CompletionVisibilityChecker, scopeNameFilter: KtScopeNameFilter, symbolFilter: (KtCallableSymbol) -> Boolean = { true } ): Sequence<KtCallableSymbol> = scope.getCallableSymbols { name -> listOfNotNull(name, name.toJavaGetterName(), name.toJavaSetterName()).any(scopeNameFilter) } .filterNot { it.isExtension } .filter { symbolFilter(it) } .filter { with(visibilityChecker) { isVisible(it) } } private fun Name.toJavaGetterName(): Name? = identifierOrNullIfSpecial?.let { Name.identifier(JvmAbi.getterName(it)) } private fun Name.toJavaSetterName(): Name? = identifierOrNullIfSpecial?.let { Name.identifier(JvmAbi.setterName(it)) } internal fun KtDeclaration.canDefinitelyNotBeSeenFromOtherFile(): Boolean { return when { isPrivate() -> true hasModifier(KtTokens.INTERNAL_KEYWORD) && containingKtFile.isCompiled -> { // internal declarations from library are invisible from source modules true } else -> false } }
apache-2.0
2b5b6113b4a13f13a9343589245ac8f6
42.791667
158
0.755831
4.377083
false
false
false
false
nadraliev/DsrWeatherApp
app/src/main/java/soutvoid/com/DsrWeatherApp/app/log/LogConstants.kt
1
478
package soutvoid.com.DsrWeatherApp.app.log object LogConstants { val LOG_SCREEN_RESUME_FORMAT = "Screen %s onResume" val LOG_SCREEN_PAUSE_FORMAT = "Screen %s onPause" val LOG_DIALOG_RESUME_FORMAT = "Dialog %s onResume" val LOG_DIALOG_PAUSE_FORMAT = "Dialog %s onPause" val LOG_SERVICE_CREATE_FORMAT = "Service %s onCreate" val LOG_SERVICE_START_COMMAND_FORMAT = "Service %s start command" val LOG_SERVICE_DESTROY_FORMAT = "Service %s onDestroy" }
apache-2.0
88d7ce1ead8c0d3f9ab1e33deb389ac2
35.769231
69
0.715481
3.540741
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/emr/src/main/kotlin/com/kotlin/emr/TerminateJobFlow.kt
1
1578
// snippet-sourcedescription:[TerminateJobFlow.kt demonstrates how to terminate a given job flow.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon EMR] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.emr // snippet-start:[erm.kotlin.terminate_job.import] import aws.sdk.kotlin.services.emr.EmrClient import aws.sdk.kotlin.services.emr.model.TerminateJobFlowsRequest import kotlin.system.exitProcess // snippet-end:[erm.kotlin.terminate_job.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <id> Where: id - An id of a job flow to shut down. """ if (args.size != 1) { System.out.println(usage) exitProcess(1) } val id = args[0] terminateFlow(id) } // snippet-start:[erm.kotlin.terminate_job.main] suspend fun terminateFlow(id: String) { val request = TerminateJobFlowsRequest { jobFlowIds = listOf(id) } EmrClient { region = "us-west-2" }.use { emrClient -> emrClient.terminateJobFlows(request) println("You have successfully terminated $id") } } // snippet-end:[erm.kotlin.terminate_job.main]
apache-2.0
549ffb8bb3742512181c0171cf30ab2c
25.684211
98
0.659696
3.69555
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/pinpoint/src/main/kotlin/com/kotlin/pinpoint/ListEndpointIds.kt
1
1971
// snippet-sourcedescription:[ListEndpointIds.kt demonstrates how to retrieve information about all the endpoints that are associated with a specific user ID.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon Pinpoint] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.pinpoint // snippet-start:[pinpoint.kotlin.list_endpoints.import] import aws.sdk.kotlin.services.pinpoint.PinpointClient import aws.sdk.kotlin.services.pinpoint.model.GetUserEndpointsRequest import kotlin.system.exitProcess // snippet-end:[pinpoint.kotlin.list_endpoints.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <applicationId> <userId> Where: applicationId - The Id value of the Amazon Pinpoint application that has the endpoint. userId - The user id applicable to the endpoints. """ if (args.size != 2) { println(usage) exitProcess(0) } val applicationId = args[0] val userId = args[1] listAllEndpoints(applicationId, userId) } suspend fun listAllEndpoints(applicationIdVal: String?, userIdVal: String?) { PinpointClient { region = "us-east-1" }.use { pinpoint -> val response = pinpoint.getUserEndpoints( GetUserEndpointsRequest { userId = userIdVal applicationId = applicationIdVal } ) response.endpointsResponse?.item?.forEach { endpoint -> println("The channel type is ${endpoint.channelType}") println("The address is ${endpoint.address}") } } }
apache-2.0
18140f3331abef569b4a3ebc06b7547b
30.311475
159
0.674277
4.399554
false
false
false
false
auricgoldfinger/Memento-Namedays
memento/src/main/java/com/alexstyl/specialdates/contact/DisplayName.kt
3
2122
package com.alexstyl.specialdates.contact data class DisplayName(val displayName: String, val allNames: Names, val firstNames: Names, val lastName: String) { fun hasMultipleFirstNames(): Boolean { return firstNames.count > 1 } override fun toString(): String { return displayName } companion object { val NO_NAME = DisplayName("", Names.parse(""), Names.parse(""), "") private const val SEPARATOR = " " fun from(displayName: String?): DisplayName { if (displayName == null || displayName.isEmpty()) { return NO_NAME } val separatorIndex = indexOfLastSeparator(displayName) val firstNameString = subStringUpTo(displayName, separatorIndex).trim { it <= ' ' } val allNames = Names.parse(displayName) val firstNames = Names.parse(firstNameString) val lastNameString = subStringAfter(displayName, separatorIndex).trim { it <= ' ' } return DisplayName(displayName, allNames, firstNames, lastNameString) } private fun indexOfLastSeparator(displayName: String): Int { var lastSeparatorIndex = -1 var currentIndex: Int do { currentIndex = displayName.indexOf(SEPARATOR, lastSeparatorIndex + 1) if (currentIndex != -1) { lastSeparatorIndex = currentIndex } } while (currentIndex != -1) return lastSeparatorIndex } private fun subStringUpTo(displayName: String, stringLength: Int): String { if (displayName.length < stringLength) { return displayName } return if (stringLength == -1) { displayName } else displayName.substring(0, stringLength) } private fun subStringAfter(displayName: String, spaceIndex: Int): String { return if (spaceIndex == -1) { "" } else displayName.substring(spaceIndex, displayName.length).trim { it <= ' ' } } } }
mit
5184e8bdb1336681914933cab473474e
34.366667
115
0.582941
5.138015
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
data/src/main/java/de/ph1b/audiobook/data/BookSettings.kt
1
1129
package de.ph1b.audiobook.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.File import java.util.UUID @Entity(tableName = "bookSettings") data class BookSettings( @ColumnInfo(name = "id") @PrimaryKey val id: UUID, @ColumnInfo(name = "currentFile") val currentFile: File, @ColumnInfo(name = "positionInChapter") val positionInChapter: Int, @ColumnInfo(name = "playbackSpeed") val playbackSpeed: Float = 1F, @ColumnInfo(name = "loudnessGain") val loudnessGain: Int = 0, @ColumnInfo(name = "skipSilence") val skipSilence: Boolean = false, @ColumnInfo(name = "active") val active: Boolean, @ColumnInfo(name = "lastPlayedAtMillis") val lastPlayedAtMillis: Long ) { init { require(playbackSpeed >= Book.SPEED_MIN) { "speed $playbackSpeed must be >= ${Book.SPEED_MIN}" } require(playbackSpeed <= Book.SPEED_MAX) { "speed $playbackSpeed must be <= ${Book.SPEED_MAX}" } require(positionInChapter >= 0) { "positionInChapter must not be negative" } require(loudnessGain >= 0) { "loudnessGain must not be negative" } } }
lgpl-3.0
c9c6845948ca85e519510976b5c082f4
30.361111
100
0.714792
3.763333
false
false
false
false
google/intellij-community
python/src/com/jetbrains/python/run/EnvironmentController.kt
2
5241
// 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.jetbrains.python.run import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.value.TargetEnvironmentFunction import com.intellij.execution.target.value.constant import com.intellij.execution.target.value.getTargetEnvironmentValueForLocalPath import com.intellij.execution.target.value.joinToStringFunction import org.jetbrains.annotations.ApiStatus import java.io.File import java.nio.file.Path /** * This is a temporary interface for smoother transition to Targets API. Its * lifetime is expected to be limited by the lifetime of the legacy * implementation based on `GeneralCommandLine`. */ @ApiStatus.Internal interface EnvironmentController { /** * Puts the constant [value] to the environment variable with the provided * [name]. */ fun putFixedValue(name: String, value: String) /** * Puts the path on the target for the provided [localPath] to the * environment variable with the provided [name]. */ fun putTargetPathValue(name: String, localPath: String) /** * Composes the value based on the paths on the target for the provided * [localPaths] by joining them using the path separator on the target OS and * puts the value to the environment variable with provided [name]. */ fun putTargetPathsValue(name: String, localPaths: Collection<String>) fun putTargetPathsValue(name: String, localPaths: Collection<String>, separator: CharSequence) /** * Composes the value based on [targetPaths] by joining them using the path * separator on the target OS and puts the value to the environment variable * with the provided [name]. */ fun putResolvedTargetPathsValue(name: String, targetPaths: Collection<String>) /** * Appends the path on the target for the provided [localPath] to the value * of the environment variable with the provided [name]. */ fun appendTargetPathToPathsValue(name: String, localPath: String) /** * Returns whether the value of the environment variable with the provided * [name] is set or not. */ fun isEnvSet(name: String): Boolean } @ApiStatus.Internal class PlainEnvironmentController(private val envs: MutableMap<String, String>) : EnvironmentController { override fun putFixedValue(name: String, value: String) { envs[name] = value } override fun putTargetPathValue(name: String, localPath: String) { envs[name] = localPath } override fun putTargetPathsValue(name: String, localPaths: Collection<String>) { putTargetPathsValue(name, localPaths, File.pathSeparator) } override fun putTargetPathsValue(name: String, localPaths: Collection<String>, separator: CharSequence) { envs[name] = localPaths.joinToString(separator = separator) } override fun putResolvedTargetPathsValue(name: String, targetPaths: Collection<String>) { envs[name] = targetPaths.joinToString(separator = File.pathSeparator) } override fun appendTargetPathToPathsValue(name: String, localPath: String) { envs.merge(name, localPath) { originalValue, additionalPath -> listOf(originalValue, additionalPath).joinToString(separator = File.pathSeparator) } } override fun isEnvSet(name: String): Boolean { return envs.containsKey(name) } } @ApiStatus.Internal class TargetEnvironmentController(private val envs: MutableMap<String, TargetEnvironmentFunction<String>>, private val targetEnvironmentRequest: TargetEnvironmentRequest) : EnvironmentController { override fun putFixedValue(name: String, value: String) { envs[name] = constant(value) } override fun putTargetPathValue(name: String, localPath: String) { val targetValue = targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(Path.of(localPath)) envs[name] = targetValue } override fun putTargetPathsValue(name: String, localPaths: Collection<String>) { val pathSeparator = targetEnvironmentRequest.targetPlatform.platform.pathSeparator.toString() putTargetPathsValue(name, localPaths, pathSeparator) } override fun putTargetPathsValue(name: String, localPaths: Collection<String>, separator: CharSequence) { envs[name] = localPaths .map { localPath -> targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(Path.of(localPath)) } .joinToStringFunction(separator) } override fun putResolvedTargetPathsValue(name: String, targetPaths: Collection<String>) { val pathSeparatorOnTarget = targetEnvironmentRequest.targetPlatform.platform.pathSeparator envs[name] = constant(targetPaths.joinToString(separator = pathSeparatorOnTarget.toString())) } override fun appendTargetPathToPathsValue(name: String, localPath: String) { val targetValue = targetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(Path.of(localPath)) envs.merge(name, targetValue) { originalValue, additionalValue -> listOf(originalValue, additionalValue).joinToPathValue(targetEnvironmentRequest.targetPlatform) } } override fun isEnvSet(name: String): Boolean { return envs.containsKey(name) } }
apache-2.0
e1ef6afe70c775b0a1a80d3b6deb5d41
38.712121
140
0.76245
4.537662
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/TransparentComponentAnimator.kt
3
4815
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.toolbar.floating import com.intellij.openapi.Disposable import com.intellij.openapi.observable.util.whenDisposed import com.intellij.openapi.ui.isComponentUnderMouse import com.intellij.util.ui.TimerUtil import com.intellij.util.ui.UIUtil.invokeLaterIfNeeded import org.jetbrains.annotations.ApiStatus import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import java.util.function.UnaryOperator @Suppress("SameParameterValue") @ApiStatus.Internal class TransparentComponentAnimator( private val component: TransparentComponent, parentDisposable: Disposable ) { private val isDisposed = AtomicBoolean() private val executor = ExecutorWithThrottling(THROTTLING_DELAY) private val clk = TimerUtil.createNamedTimer("CLK", CLK_DELAY) private val state = AtomicReference<State>(State.Invisible) private fun startTimerIfNeeded() { if (!isDisposed.get() && !clk.isRunning) { clk.start() } } private fun stopTimerIfNeeded() { if (clk.isRunning) { clk.stop() } } fun scheduleShow() = executor.executeOrSkip { state.updateAndGet(::nextShowingState) startTimerIfNeeded() } fun scheduleHide() { state.updateAndGet(::nextHidingState) startTimerIfNeeded() } internal fun hideImmediately() { updateState { State.Invisible } } private fun updateState() { updateState(::nextState) } private fun updateState(nextState: UnaryOperator<State>) { val state = state.updateAndGet(nextState) if (state is State.Invisible || state is State.Visible && !component.autoHideable) { stopTimerIfNeeded() } updateComponent(state) } private fun updateComponent(state: State) { invokeLaterIfNeeded { component.opacity = getOpacity(state) when (isVisible(state)) { true -> component.showComponent() else -> component.hideComponent() } component.component.repaint() } } private fun nextShowingState(state: State): State { return when (state) { is State.Invisible -> State.Showing(0) is State.Visible -> State.Visible(0) is State.Hiding -> State.Showing(SHOWING_COUNT - SHOWING_COUNT * state.count / HIDING_COUNT) is State.Showing -> state } } private fun nextHidingState(state: State): State { return when (state) { is State.Invisible -> State.Invisible is State.Visible -> State.Hiding(0) is State.Hiding -> state is State.Showing -> State.Hiding(HIDING_COUNT - HIDING_COUNT * state.count / SHOWING_COUNT) } } private fun nextState(state: State): State { return when (state) { is State.Invisible -> State.Invisible is State.Visible -> when { !component.autoHideable -> State.Visible(0) component.isComponentUnderMouse() -> State.Visible(0) state.count >= RETENTION_COUNT -> State.Hiding(0) else -> State.Visible(state.count + 1) } is State.Hiding -> when { state.count >= HIDING_COUNT -> State.Invisible else -> State.Hiding(state.count + 1) } is State.Showing -> when { state.count >= SHOWING_COUNT -> State.Visible(0) else -> State.Showing(state.count + 1) } } } private fun TransparentComponent.isComponentUnderMouse(): Boolean { return component.parent?.isComponentUnderMouse() == true } private fun getOpacity(state: State): Float { return when (state) { is State.Invisible -> 0.0f is State.Visible -> 1.0f is State.Hiding -> 1.0f - getOpacity(state.count, HIDING_COUNT) is State.Showing -> getOpacity(state.count, SHOWING_COUNT) } } private fun getOpacity(count: Int, maxCount: Int): Float { return maxOf(0.0f, minOf(1.0f, count / maxCount.toFloat())) } private fun isVisible(state: State): Boolean { return state !is State.Invisible } init { clk.isRepeats = true clk.addActionListener { updateState() } parentDisposable.whenDisposed { isDisposed.set(true) } parentDisposable.whenDisposed { stopTimerIfNeeded() } } private sealed interface State { object Invisible : State data class Visible(val count: Int) : State data class Hiding(val count: Int) : State data class Showing(val count: Int) : State } companion object { private const val CLK_FREQUENCY = 60 private const val CLK_DELAY = 1000 / CLK_FREQUENCY private const val RETENTION_COUNT = 1500 / CLK_DELAY private const val SHOWING_COUNT = 500 / CLK_DELAY private const val HIDING_COUNT = 1000 / CLK_DELAY private const val THROTTLING_DELAY = 1000 } }
apache-2.0
613d4e763b35b221bbf7a0246627f5c6
29.481013
140
0.688058
4.073604
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt
1
19762
// 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.refactoring.move.moveDeclarations import com.intellij.ide.IdeDeprecatedMessagesBundle import com.intellij.ide.highlighter.JavaFileType import com.intellij.ide.util.EditorHelper import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler import com.intellij.refactoring.rename.RenameUtil import com.intellij.refactoring.util.NonCodeUsageInfo import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.refactoring.util.TextOccurrencesUtil import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewDescriptor import com.intellij.usageView.UsageViewUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.HashingStrategy import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.idea.base.util.restrictByFileType import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.deleteSingle import org.jetbrains.kotlin.idea.base.searching.usages.KotlinFindUsagesHandlerFactory import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.utils.ifEmpty import org.jetbrains.kotlin.utils.keysToMap import kotlin.math.max import kotlin.math.min interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration { object Default : Mover { override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration { return when (targetContainer) { is KtFile -> { val declarationContainer: KtElement = if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer declarationContainer.add(originalElement) as KtNamedDeclaration } is KtClassOrObject -> targetContainer.addDeclaration(originalElement) else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}") }.apply { val container = originalElement.containingClassOrObject if (container is KtObjectDeclaration && container.isCompanion() && container.declarations.singleOrNull() == originalElement && KotlinFindUsagesHandlerFactory(container.project).createFindUsagesHandler(container, false) .findReferencesToHighlight(container, LocalSearchScope(container.containingFile)).isEmpty() ) { container.deleteSingle() } else { originalElement.deleteSingle() } } } } } sealed class MoveSource { abstract val elementsToMove: Collection<KtNamedDeclaration> class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource() class File(val file: KtFile) : MoveSource() { override val elementsToMove: Collection<KtNamedDeclaration> get() = file.declarations.filterIsInstance<KtNamedDeclaration>() } } fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration)) fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations) fun MoveSource(file: KtFile) = MoveSource.File(file) class MoveDeclarationsDescriptor @JvmOverloads constructor( val project: Project, val moveSource: MoveSource, val moveTarget: KotlinMoveTarget, val delegate: MoveDeclarationsDelegate, val searchInCommentsAndStrings: Boolean = true, val searchInNonCode: Boolean = true, val deleteSourceFiles: Boolean = false, val moveCallback: MoveCallback? = null, val openInEditor: Boolean = false, val allElementsToMove: List<PsiElement>? = null, val analyzeConflicts: Boolean = true, val searchReferences: Boolean = true ) class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element) private object ElementHashingStrategy : HashingStrategy<PsiElement> { override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean { if (e1 === e2) return true // Name should be enough to distinguish different light elements based on the same original declaration if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) { return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name } return false } override fun hashCode(e: PsiElement?): Int { return when (e) { null -> 0 is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0) else -> e.hashCode() } } } class MoveKotlinDeclarationsProcessor( val descriptor: MoveDeclarationsDescriptor, val mover: Mover = Mover.Default, private val throwOnConflicts: Boolean = false ) : BaseRefactoringProcessor(descriptor.project) { companion object { const val REFACTORING_ID = "move.kotlin.declarations" } val project get() = descriptor.project private var nonCodeUsages: Array<NonCodeUsageInfo>? = null private val moveEntireFile = descriptor.moveSource is MoveSource.File private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e -> e.parent != descriptor.moveTarget.getTargetPsiIfExists(e) } private val kotlinToLightElementsBySourceFile = elementsToMove .groupBy { it.containingKtFile } .mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } } private val conflicts = MultiMap<PsiElement, String>() override fun getRefactoringId() = REFACTORING_ID override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor { val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let { if (it.isRoot) IdeDeprecatedMessagesBundle.message("default.package.presentable.name") else it.asString() } ?: IdeDeprecatedMessagesBundle.message("default.package.presentable.name") return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName) } fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) } public override fun findUsages(): Array<UsageInfo> { if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: "" fun getSearchScope(element: PsiElement): GlobalSearchScope? { val projectScope = project.projectScope() val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope val moveTarget = descriptor.moveTarget val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget) val targetModule = moveTarget.getTargetModule(project) ?: return projectScope if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope // Check if facade class may change if (newContainer is ContainerInfo.Package) { val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE) val currentFile = ktDeclaration.containingKtFile val newFile = when (moveTarget) { is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null is KotlinMoveTargetForDeferredFile -> return javaScope else -> return null } val currentFacade = currentFile.findFacadeClass() val newFacade = newFile.findFacadeClass() return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null } return null } fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean { if (element?.containingFile != usage.element?.containingFile) return false val firstSegment = segment ?: return false val secondSegment = usage.segment ?: return false return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset) } fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) { kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement -> val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList() val elementName = lightElement.name ?: return@flatMapTo emptyList() val newFqName = StringUtil.getQualifiedName(newContainerName, elementName) val foundReferences = HashSet<PsiReference>() val results = ReferencesSearch .search(lightElement, searchScope) .mapNotNullTo(ArrayList()) { ref -> if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) { createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false) } else null } val name = lightElement.kotlinFqName?.quoteIfNeeded()?.asString() if (name != null) { fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) { TextOccurrencesUtil.findNonCodeUsages( lightElement, searchScope, name, descriptor.searchInCommentsAndStrings, descriptor.searchInNonCode, FqName(newFqName).quoteIfNeeded().asString(), results ) } val facadeContainer = lightElement.parent as? KtLightClassForFacade if (facadeContainer != null) { val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName) val newFqNameWithFacade = StringUtil.getQualifiedName( StringUtil.getQualifiedName(newContainerName, facadeContainer.name), elementName ) TextOccurrencesUtil.findNonCodeUsages( lightElement, searchScope, oldFqNameWithFacade, descriptor.searchInCommentsAndStrings, descriptor.searchInNonCode, FqName(newFqNameWithFacade).quoteIfNeeded().asString(), results ) ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage -> if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) { results.add(kotlinNonCodeUsage) } } } else { searchForKotlinNameUsages(results) } } MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler -> handler.preprocessUsages(results) } results } } val usages = ArrayList<UsageInfo>() val conflictChecker = MoveConflictChecker( project, elementsToMove, descriptor.moveTarget, elementsToMove.first(), allElementsToMove = descriptor.allElementsToMove ) for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { val internalUsages = LinkedHashSet<UsageInfo>() val externalUsages = LinkedHashSet<UsageInfo>() if (moveEntireFile) { val changeInfo = ContainerChangeInfo( ContainerInfo.Package(sourceFile.packageFqName), descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage ) internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) } else { kotlinToLightElements.keys.forEach { val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget) internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo) } } internalUsages += descriptor.delegate.findInternalUsages(descriptor) collectUsages(kotlinToLightElements, externalUsages) if (descriptor.analyzeConflicts) { conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts) descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts) } usages += internalUsages usages += externalUsages } return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray()) } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { return showConflicts(conflicts, refUsages.get()) } override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean { if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException() return super.showConflicts(conflicts, usages) } override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList()) internal fun doPerformRefactoring(usages: List<UsageInfo>) { fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration { val targetContainer = moveTarget.getOrCreateTargetPsi(declaration) descriptor.delegate.preprocessDeclaration(descriptor, declaration) if (moveEntireFile) return declaration return mover(declaration, targetContainer).apply { addToBeShortenedDescendantsToWaitingSet() } } val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal } val newInternalUsages = ArrayList<UsageInfo>() markInternalUsages(oldInternalUsages) val usagesToProcess = ArrayList(externalUsages) try { descriptor.delegate.preprocessUsages(descriptor, usages) val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy) val newDeclarations = ArrayList<KtNamedDeclaration>() for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { for ((oldDeclaration, oldLightElements) in kotlinToLightElements) { val elementListener = transaction?.getElementListener(oldDeclaration) val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget) newDeclarations += newDeclaration oldToNewElementsMapping[oldDeclaration] = newDeclaration oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile elementListener?.elementMoved(newDeclaration) for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) { oldToNewElementsMapping[oldElement] = newElement } if (descriptor.openInEditor) { EditorHelper.openInEditor(newDeclaration) } } if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) { sourceFile.delete() } } val internalUsageScopes: List<KtElement> = if (moveEntireFile) { newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList() } else { newDeclarations } internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) } usagesToProcess += newInternalUsages nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray() performDelayedRefactoringRequests(project) } catch (e: IncorrectOperationException) { nonCodeUsages = null RefactoringUIUtil.processIncorrectOperation(myProject, e) } finally { cleanUpInternalUsages(newInternalUsages + oldInternalUsages) } } override fun performPsiSpoilingRefactoring() { nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) } descriptor.moveCallback?.refactoringCompleted() } fun execute(usages: List<UsageInfo>) { execute(usages.toTypedArray()) } override fun doRun() { try { super.doRun() } finally { broadcastRefactoringExit(myProject, refactoringId) } } override fun getCommandName(): String = KotlinBundle.message("command.move.declarations") }
apache-2.0
5a08a45b41d2c77ea7d27929dd3e6a3c
47.317848
138
0.67311
5.853673
false
false
false
false
google/iosched
mobile/src/main/java/com/google/samples/apps/iosched/ui/MainActivity.kt
1
12596
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui import android.app.Activity import android.content.Intent import android.net.ConnectivityManager import android.os.Bundle import android.view.Menu import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.graphics.Insets import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.firebase.ui.auth.IdpResponse import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.ar.ArActivity import com.google.samples.apps.iosched.databinding.ActivityMainBinding import com.google.samples.apps.iosched.shared.analytics.AnalyticsActions import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper import com.google.samples.apps.iosched.shared.di.CodelabsEnabledFlag import com.google.samples.apps.iosched.shared.di.ExploreArEnabledFlag import com.google.samples.apps.iosched.shared.di.MapFeatureEnabledFlag import com.google.samples.apps.iosched.shared.domain.ar.ArConstants import com.google.samples.apps.iosched.ui.messages.SnackbarMessage import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager import com.google.samples.apps.iosched.ui.signin.SignInDialogFragment import com.google.samples.apps.iosched.ui.signin.SignOutDialogFragment import com.google.samples.apps.iosched.util.HeightTopWindowInsetsListener import com.google.samples.apps.iosched.util.signin.FirebaseAuthErrorCodeConverter import com.google.samples.apps.iosched.util.updateForTheme import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import timber.log.Timber import java.util.UUID import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity(), NavigationHost { companion object { /** Key for an int extra defining the initial navigation target. */ const val EXTRA_NAVIGATION_ID = "extra.NAVIGATION_ID" private const val NAV_ID_NONE = -1 private const val DIALOG_SIGN_IN = "dialog_sign_in" private const val DIALOG_SIGN_OUT = "dialog_sign_out" private val TOP_LEVEL_DESTINATIONS = setOf( R.id.navigation_feed, R.id.navigation_schedule, R.id.navigation_map, R.id.navigation_info, R.id.navigation_agenda, R.id.navigation_codelabs, R.id.navigation_settings ) } @Inject lateinit var snackbarMessageManager: SnackbarMessageManager @Inject lateinit var connectivityManager: ConnectivityManager @Inject lateinit var analyticsHelper: AnalyticsHelper @Inject @JvmField @MapFeatureEnabledFlag var mapFeatureEnabled: Boolean = false @Inject @JvmField @CodelabsEnabledFlag var codelabsFeatureEnabled: Boolean = false @Inject @JvmField @ExploreArEnabledFlag var exploreArFeatureEnabled: Boolean = false private val viewModel: MainActivityViewModel by viewModels() private lateinit var binding: ActivityMainBinding private lateinit var navController: NavController private lateinit var navHostFragment: NavHostFragment private var currentNavId = NAV_ID_NONE override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Update for Dark Mode straight away updateForTheme(viewModel.currentTheme) WindowCompat.setDecorFitsSystemWindows(window, false) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.statusBarScrim.setOnApplyWindowInsetsListener(HeightTopWindowInsetsListener) navHostFragment = supportFragmentManager .findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController navController.addOnDestinationChangedListener { _, destination, _ -> currentNavId = destination.id // TODO: hide nav if not a top-level destination? } // Either of two different navigation views might exist depending on the configuration. binding.bottomNavigation?.apply { configureNavMenu(menu) setupWithNavController(navController) setOnItemReselectedListener { } // prevent navigating to the same item } binding.navigationRail?.apply { configureNavMenu(menu) setupWithNavController(navController) setOnItemReselectedListener { } // prevent navigating to the same item } if (savedInstanceState == null) { currentNavId = navController.graph.startDestinationId val requestedNavId = intent.getIntExtra(EXTRA_NAVIGATION_ID, currentNavId) navigateTo(requestedNavId) } lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.navigationActions.collect { action -> when (action) { MainNavigationAction.OpenSignIn -> openSignInDialog() MainNavigationAction.OpenSignOut -> openSignOutDialog() } } } launch { viewModel.theme.collect { theme -> updateForTheme(theme) } } // AR-related Flows launch { viewModel.arCoreAvailability.collect { result -> // Do nothing - activate flow Timber.d("ArCoreAvailability = $result") } } launch { viewModel.pinnedSessionsJson.collect { /* Do nothing - activate flow */ } } launch { viewModel.canSignedInUserDemoAr.collect { /* Do nothing - activate flow */ } } } } binding.navigationRail?.let { ViewCompat.setOnApplyWindowInsetsListener(it) { view, insets -> // Pad the Navigation Rail so its content is not behind system bars. val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) view.updatePadding(top = systemBars.top, bottom = systemBars.bottom) insets } } ViewCompat.setOnApplyWindowInsetsListener(binding.rootContainer) { view, insets -> // Hide the bottom navigation view whenever the keyboard is visible. val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime()) binding.bottomNavigation?.isVisible = !imeVisible // If we're showing the bottom navigation, add bottom padding. Also, add left and right // padding since there's no better we can do with horizontal insets. val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) val bottomPadding = if (binding.bottomNavigation?.isVisible == true) { systemBars.bottom } else 0 view.updatePadding( left = systemBars.left, right = systemBars.right, bottom = bottomPadding ) // Consume the insets we've used. WindowInsetsCompat.Builder(insets).setInsets( WindowInsetsCompat.Type.systemBars(), Insets.of(0, systemBars.top, 0, systemBars.bottom - bottomPadding) ).build() } } private fun configureNavMenu(menu: Menu) { menu.findItem(R.id.navigation_map)?.isVisible = mapFeatureEnabled menu.findItem(R.id.navigation_codelabs)?.isVisible = codelabsFeatureEnabled menu.findItem(R.id.navigation_explore_ar)?.apply { // Handle launching new activities, otherwise assume the destination is handled // by the nav graph. We want to launch a new Activity for only the AR menu item. isVisible = exploreArFeatureEnabled setOnMenuItemClickListener { if (connectivityManager.activeNetworkInfo?.isConnected == true) { if (viewModel.arCoreAvailability.value?.isSupported == true) { analyticsHelper.logUiEvent( "Navigate to Explore I/O ARCore supported", AnalyticsActions.CLICK ) openExploreAr() } else { analyticsHelper.logUiEvent( "Navigate to Explore I/O ARCore NOT supported", AnalyticsActions.CLICK ) openArCoreNotSupported() } } else { openNoConnection() } true } } } override fun registerToolbarWithNavigation(toolbar: Toolbar) { val appBarConfiguration = AppBarConfiguration(TOP_LEVEL_DESTINATIONS) toolbar.setupWithNavController(navController, appBarConfiguration) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) currentNavId = navController.currentDestination?.id ?: NAV_ID_NONE } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_CANCELED) { Timber.d("An activity returned RESULT_CANCELED") val response = IdpResponse.fromResultIntent(data) response?.error?.let { snackbarMessageManager.addMessage( SnackbarMessage( messageId = FirebaseAuthErrorCodeConverter.convert(it.errorCode), requestChangeId = UUID.randomUUID().toString() ) ) } } } override fun onUserInteraction() { super.onUserInteraction() getCurrentFragment()?.onUserInteraction() } private fun getCurrentFragment(): MainNavigationFragment? { return navHostFragment .childFragmentManager .primaryNavigationFragment as? MainNavigationFragment } private fun navigateTo(navId: Int) { if (navId == currentNavId) { return // user tapped the current item } navController.navigate(navId) } private fun openSignInDialog() { SignInDialogFragment().show(supportFragmentManager, DIALOG_SIGN_IN) } private fun openSignOutDialog() { SignOutDialogFragment().show(supportFragmentManager, DIALOG_SIGN_OUT) } private fun openExploreAr() { val intent = Intent( this, ArActivity::class.java ).apply { addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) putExtra(ArConstants.CAN_SIGNED_IN_USER_DEMO_AR, viewModel.canSignedInUserDemoAr.value) putExtra(ArConstants.PINNED_SESSIONS_JSON_KEY, viewModel.pinnedSessionsJson.value) } startActivity(intent) } private fun openNoConnection() { navigateTo(R.id.navigation_no_network_ar) } private fun openArCoreNotSupported() { navigateTo(R.id.navigation_phone_does_not_support_arcore) } }
apache-2.0
466fb12d1dc640f82494e3c21973ade2
38.118012
99
0.655208
5.254902
false
false
false
false
ronocod/BeerSignal
android/app/src/main/kotlin/com/starstorm/beer/activity/MainActivity.kt
1
4437
package com.starstorm.beer.activity import android.app.Fragment import android.app.FragmentManager import android.content.Intent import android.os.Bundle import android.support.v13.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.support.v7.app.ActionBarActivity import android.view.Window import com.parse.ParseAnalytics import com.parse.ParseFacebookUtils import com.parse.ParseUser import com.starstorm.beer.R import com.starstorm.beer.fragment.BigRedFragment import com.starstorm.beer.fragment.FacebookFriendsFragment import com.starstorm.beer.fragment.FriendsFragment import com.starstorm.beer.fragment.YouFragment import com.starstorm.beer.ui.slidingtabs.SlidingTabLayout import java.util.Locale public class MainActivity : ActionBarActivity() { private var youFragment: YouFragment? = null private var bigRedFragment: BigRedFragment? = null private var friendListFragment: FriendsFragment? = null private var facebookFriendListFragment: FacebookFriendsFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (ParseUser.getCurrentUser() == null) { // no logged-in user, go to login screen val intent = Intent(this, javaClass<LoginActivity>()) startActivity(intent) // empty animation for an instant transition overridePendingTransition(0, 0) return } supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS) setContentView(R.layout.activity_main) ParseAnalytics.trackAppOpenedInBackground(getIntent()) val sectionsPagerAdapter = SectionsPagerAdapter(getFragmentManager()) val viewPager = findViewById(R.id.pager) as ViewPager viewPager.setAdapter(sectionsPagerAdapter) val slidingTabLayout = findViewById(R.id.sliding_tabs) as SlidingTabLayout slidingTabLayout.setViewPager(viewPager) viewPager.setCurrentItem(1, false) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data) } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment { // getItem is called to instantiate the fragment for the given page. when (position) { 0 -> { if (youFragment == null) { youFragment = YouFragment.newInstance() } return youFragment!! } 1 -> { if (bigRedFragment == null) { bigRedFragment = BigRedFragment.newInstance() } return bigRedFragment!! } 2 -> { if (friendListFragment == null) { friendListFragment = FriendsFragment.newInstance() } return friendListFragment!! } 3 -> { if (facebookFriendListFragment == null) { facebookFriendListFragment = FacebookFriendsFragment.newInstance() } return facebookFriendListFragment!! } } return Fragment() } override fun getCount(): Int { return 4 } override fun getPageTitle(position: Int): CharSequence? { val l = Locale.getDefault() val title = when (position) { 0 -> { val currentUser = ParseUser.getCurrentUser() when { currentUser != null -> currentUser.getUsername() else -> getString(R.string.title_section0) } } 1 -> getString(R.string.title_section1) 2 -> getString(R.string.title_section2) 3 -> "Facebook Friends test" else -> "" } return title.toUpperCase(l) } } }
gpl-2.0
0464c5b3409ca732fb9d49a34a6f51d1
34.782258
93
0.606942
5.410976
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/advopt/SelectionToJSONButton.kt
2
4784
package io.github.chrislo27.rhre3.editor.stage.advopt import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.fasterxml.jackson.annotation.JsonInclude import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.entity.model.IRepitchable import io.github.chrislo27.rhre3.entity.model.ModelEntity import io.github.chrislo27.rhre3.screen.EditorScreen import io.github.chrislo27.rhre3.util.JsonHandler import io.github.chrislo27.toolboks.Toolboks import io.github.chrislo27.toolboks.ui.* import kotlin.math.roundToInt class SelectionToJSONButton(val editor: Editor, palette: UIPalette, parent: UIElement<EditorScreen>, stage: Stage<EditorScreen>) : Button<EditorScreen>(palette, parent, stage) { companion object { val strings: List<String> = listOf("Copy selection as\nSFXDB pattern JSON", "[CYAN]Copied successfully![]", "No selection...", "An [RED]error[] occurred\nPlease see console") } init { this.visible = false } private var resetTextIn: Float = 0f private val label: TextLabel<EditorScreen> = TextLabel(palette, this, stage).apply { [email protected](this) this.fontScaleMultiplier = 0.4f this.text = strings[0] this.textWrapping = false this.isLocalizationKey = false } override var tooltipText: String? set(_) {} get() { return when (label.text) { strings[1] -> "Copied successfully to clipboard!" strings[2] -> "Make a selection first" strings[3] -> strings[3] else -> "Click to convert entity selection\nas SFX database pattern JSON and copy to clipboard" } } override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { super.render(screen, batch, shapeRenderer) if (resetTextIn > 0) { resetTextIn -= Gdx.graphics.deltaTime if (resetTextIn <= 0) { label.text = strings[0] } } } override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) val selection = editor.selection.toList().filterIsInstance<ModelEntity<*>>() if (selection.isEmpty()) { label.text = strings[2] } else { try { val bottommost = selection.minByOrNull { it.bounds.y }!! val leftmost = selection.minByOrNull { it.bounds.x }!! val firstGame = selection.first().datamodel.game val allSameParentId = selection.all { it.datamodel.game == firstGame } val json = JsonHandler.toJson(SmallPatternObject().also { it.id = "*_" it.deprecatedIDs = listOf() it.name = "" it.cues = selection.map { entity -> SmallCuePointer().also { pointer -> pointer.id = if (allSameParentId) entity.datamodel.id.replaceFirst(firstGame.id, "*") else entity.datamodel.id pointer.duration = entity.bounds.width pointer.beat = entity.bounds.x - leftmost.bounds.x pointer.track = (entity.bounds.y - bottommost.bounds.y).roundToInt() pointer.semitone = (entity as? IRepitchable)?.semitone ?: 0 } } }) Gdx.app.clipboard.contents = json Toolboks.LOGGER.info("\n$json\n") label.text = strings[1] } catch (e: Exception) { e.printStackTrace() label.text = strings[3] } } resetTextIn = 3f } class SmallCuePointer { lateinit var id: String var beat: Float = -1f @JsonInclude(JsonInclude.Include.NON_DEFAULT) var duration: Float = 0f @JsonInclude(JsonInclude.Include.NON_DEFAULT) var semitone: Int = 0 // @JsonInclude(JsonInclude.Include.NON_DEFAULT) // var volume: Int = IVolumetric.DEFAULT_VOLUME @JsonInclude(JsonInclude.Include.NON_DEFAULT) var track: Int = 0 // @JsonInclude(JsonInclude.Include.NON_DEFAULT) // var metadata: Map<String, Any?>? = null } class SmallPatternObject { var type: String = "pattern" lateinit var id: String lateinit var deprecatedIDs: List<String> lateinit var name: String var stretchable: Boolean = false lateinit var cues: List<SmallCuePointer> } }
gpl-3.0
b0ea5158e26547dfc02420d068622825
36.382813
182
0.596363
4.471028
false
false
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-reactive/src/ReactiveFlow.kt
1
10608
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.reactive import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.flow.internal.* import kotlinx.coroutines.intrinsics.* import org.reactivestreams.* import java.util.* import kotlin.coroutines.* import kotlinx.coroutines.internal.* /** * Transforms the given reactive [Publisher] into [Flow]. * Use the [buffer] operator on the resulting flow to specify the size of the back-pressure. * In effect, it specifies the value of the subscription's [request][Subscription.request]. * The [default buffer capacity][Channel.BUFFERED] for a suspending channel is used by default. * * If any of the resulting flow transformations fails, the subscription is immediately cancelled and all the in-flight * elements are discarded. * * This function is integrated with `ReactorContext` from `kotlinx-coroutines-reactor` module, * see its documentation for additional details. */ public fun <T : Any> Publisher<T>.asFlow(): Flow<T> = PublisherAsFlow(this) /** * Transforms the given flow into a reactive specification compliant [Publisher]. * * This function is integrated with `ReactorContext` from `kotlinx-coroutines-reactor` module, * see its documentation for additional details. * * An optional [context] can be specified to control the execution context of calls to the [Subscriber] methods. * A [CoroutineDispatcher] can be set to confine them to a specific thread; various [ThreadContextElement] can be set to * inject additional context into the caller thread. By default, the [Unconfined][Dispatchers.Unconfined] dispatcher * is used, so calls are performed from an arbitrary thread. */ @JvmOverloads // binary compatibility public fun <T : Any> Flow<T>.asPublisher(context: CoroutineContext = EmptyCoroutineContext): Publisher<T> = FlowAsPublisher(this, Dispatchers.Unconfined + context) private class PublisherAsFlow<T : Any>( private val publisher: Publisher<T>, context: CoroutineContext = EmptyCoroutineContext, capacity: Int = Channel.BUFFERED, onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND ) : ChannelFlow<T>(context, capacity, onBufferOverflow) { override fun create(context: CoroutineContext, capacity: Int, onBufferOverflow: BufferOverflow): ChannelFlow<T> = PublisherAsFlow(publisher, context, capacity, onBufferOverflow) /* * The @Suppress is for Channel.CHANNEL_DEFAULT_CAPACITY. * It's too counter-intuitive to be public, and moving it to Flow companion * will also create undesired effect. */ @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") private val requestSize: Long get() = if (onBufferOverflow != BufferOverflow.SUSPEND) { Long.MAX_VALUE // request all, since buffering strategy is to never suspend } else when (capacity) { Channel.RENDEZVOUS -> 1L // need to request at least one anyway Channel.UNLIMITED -> Long.MAX_VALUE // reactive streams way to say "give all", must be Long.MAX_VALUE Channel.BUFFERED -> Channel.CHANNEL_DEFAULT_CAPACITY.toLong() else -> capacity.toLong().also { check(it >= 1) } } override suspend fun collect(collector: FlowCollector<T>) { val collectContext = coroutineContext val newDispatcher = context[ContinuationInterceptor] if (newDispatcher == null || newDispatcher == collectContext[ContinuationInterceptor]) { // fast path -- subscribe directly in this dispatcher return collectImpl(collectContext + context, collector) } // slow path -- produce in a separate dispatcher collectSlowPath(collector) } private suspend fun collectSlowPath(collector: FlowCollector<T>) { coroutineScope { collector.emitAll(produceImpl(this + context)) } } private suspend fun collectImpl(injectContext: CoroutineContext, collector: FlowCollector<T>) { val subscriber = ReactiveSubscriber<T>(capacity, onBufferOverflow, requestSize) // inject subscribe context into publisher publisher.injectCoroutineContext(injectContext).subscribe(subscriber) try { var consumed = 0L while (true) { val value = subscriber.takeNextOrNull() ?: break coroutineContext.ensureActive() collector.emit(value) if (++consumed == requestSize) { consumed = 0L subscriber.makeRequest() } } } finally { subscriber.cancel() } } // The second channel here is used for produceIn/broadcastIn and slow-path (dispatcher change) override suspend fun collectTo(scope: ProducerScope<T>) = collectImpl(scope.coroutineContext, SendingCollector(scope.channel)) } @Suppress("ReactiveStreamsSubscriberImplementation") private class ReactiveSubscriber<T : Any>( capacity: Int, onBufferOverflow: BufferOverflow, private val requestSize: Long ) : Subscriber<T> { private lateinit var subscription: Subscription // This implementation of ReactiveSubscriber always uses "offer" in its onNext implementation and it cannot // be reliable with rendezvous channel, so a rendezvous channel is replaced with buffer=1 channel private val channel = Channel<T>(if (capacity == Channel.RENDEZVOUS) 1 else capacity, onBufferOverflow) suspend fun takeNextOrNull(): T? { val result = channel.receiveCatching() result.exceptionOrNull()?.let { throw it } return result.getOrElse { null } // Closed channel } override fun onNext(value: T) { // Controlled by requestSize require(channel.trySend(value).isSuccess) { "Element $value was not added to channel because it was full, $channel" } } override fun onComplete() { channel.close() } override fun onError(t: Throwable?) { channel.close(t) } override fun onSubscribe(s: Subscription) { subscription = s makeRequest() } fun makeRequest() { subscription.request(requestSize) } fun cancel() { subscription.cancel() } } // ContextInjector service is implemented in `kotlinx-coroutines-reactor` module only. // If `kotlinx-coroutines-reactor` module is not included, the list is empty. private val contextInjectors: Array<ContextInjector> = ServiceLoader.load(ContextInjector::class.java, ContextInjector::class.java.classLoader) .iterator().asSequence() .toList().toTypedArray() // R8 opto internal fun <T> Publisher<T>.injectCoroutineContext(coroutineContext: CoroutineContext) = contextInjectors.fold(this) { pub, contextInjector -> contextInjector.injectCoroutineContext(pub, coroutineContext) } /** * Adapter that transforms [Flow] into TCK-complaint [Publisher]. * [cancel] invocation cancels the original flow. */ @Suppress("ReactiveStreamsPublisherImplementation") private class FlowAsPublisher<T : Any>( private val flow: Flow<T>, private val context: CoroutineContext ) : Publisher<T> { override fun subscribe(subscriber: Subscriber<in T>?) { if (subscriber == null) throw NullPointerException() subscriber.onSubscribe(FlowSubscription(flow, subscriber, context)) } } /** @suppress */ @InternalCoroutinesApi public class FlowSubscription<T>( @JvmField public val flow: Flow<T>, @JvmField public val subscriber: Subscriber<in T>, context: CoroutineContext ) : Subscription, AbstractCoroutine<Unit>(context, initParentJob = false, true) { /* * We deliberately set initParentJob to false and do not establish parent-child * relationship because FlowSubscription doesn't support it */ private val requested = atomic(0L) private val producer = atomic<Continuation<Unit>?>(createInitialContinuation()) @Volatile private var cancellationRequested = false // This code wraps startCoroutineCancellable into continuation private fun createInitialContinuation(): Continuation<Unit> = Continuation(coroutineContext) { ::flowProcessing.startCoroutineCancellable(this) } private suspend fun flowProcessing() { try { consumeFlow() } catch (cause: Throwable) { @Suppress("INVISIBLE_MEMBER") val unwrappedCause = unwrap(cause) if (!cancellationRequested || isActive || unwrappedCause !== getCancellationException()) { try { subscriber.onError(cause) } catch (e: Throwable) { // Last ditch report cause.addSuppressed(e) handleCoroutineException(coroutineContext, cause) } } return } // We only call this if `consumeFlow()` finished successfully try { subscriber.onComplete() } catch (e: Throwable) { handleCoroutineException(coroutineContext, e) } } /* * This method has at most one caller at any time (triggered from the `request` method) */ private suspend fun consumeFlow() { flow.collect { value -> // Emit the value subscriber.onNext(value) // Suspend if needed before requesting the next value if (requested.decrementAndGet() <= 0) { suspendCancellableCoroutine<Unit> { producer.value = it } } else { // check for cancellation if we don't suspend coroutineContext.ensureActive() } } } override fun cancel() { cancellationRequested = true cancel(null) } override fun request(n: Long) { if (n <= 0) return val old = requested.getAndUpdate { value -> val newValue = value + n if (newValue <= 0L) Long.MAX_VALUE else newValue } if (old <= 0L) { assert(old == 0L) // Emitter is not started yet or has suspended -- spin on race with suspendCancellableCoroutine while (true) { val producer = producer.getAndSet(null) ?: continue // spin if not set yet producer.resume(Unit) break } } } }
apache-2.0
a46f47fbfb47e94b7908fc499dd56c18
38
125
0.663084
4.9043
false
false
false
false
ylemoigne/ReactKT
sampleprojects/demo-core/src/main/kotlin/fr/javatic/reactktSample/core/TodoItem.kt
1
4482
/* * Copyright 2015 Yann Le Moigne * * 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 fr.javatic.reactktSample.core import fr.javatic.reactkt.core.Component import fr.javatic.reactkt.core.ReactDOM import fr.javatic.reactkt.core.ReactElement import fr.javatic.reactkt.core.events.FormEvent import fr.javatic.reactkt.core.events.KeyboardEvent import fr.javatic.reactkt.core.ktx import fr.javatic.reactkt.core.utils.Classes import fr.javatic.reactkt.core.utils.KeyCode import fr.javatic.reactktSample.core.interfaces.TodoItemProps import fr.javatic.reactktSample.core.interfaces.TodoItemState import org.w3c.dom.HTMLInputElement class TodoItem(override var props: TodoItemProps) : Component<TodoItemProps, TodoItemState>() { init { state = TodoItemState(this.props.todo.title) } fun handleSubmit() { val value = this.state.editText.trim() if (value.isNotBlank()) { this.props.onSave(value) this.setState(TodoItemState(value)) } else { this.props.onDestroy() } } fun handleEdit() { this.props.onEdit() this.setState(TodoItemState(this.props.todo.title)) } fun handleKeyDown(event: KeyboardEvent) { if (event.keyCode == KeyCode.ESCAPE) { this.setState(TodoItemState(this.props.todo.title)) this.props.onCancel(event) } else if (event.keyCode == KeyCode.ENTER) { this.handleSubmit() } } fun handleChange(event: FormEvent) { var input: dynamic = event.target this.setState(TodoItemState(input.value)) } /** * This is a completely optional performance enhancement that you can * implement on any React component. If you were to delete this method * the app would still work correctly (and still be very performant!), we * just use it as an example of how little code it takes to get an order * of magnitude performance improvement. */ override fun shouldComponentUpdate(nextProps: TodoItemProps, nextState: TodoItemState): Boolean { return (nextProps.todo != this.props.todo) || (nextProps.editing != this.props.editing) || (nextState.editText != this.state.editText) } /** * Safely manipulate the DOM after updating the state when invoking * `this.props.onEdit()` in the `handleEdit` method above. * For more info refer to notes at https://facebook.github.io/react/docs/component-api.html#setstate * and https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate */ override fun componentDidUpdate(prevProps: TodoItemProps):Unit { if (!(prevProps.editing ?: false) && this.props.editing ?: false) { val node = ReactDOM.findDOMNode<HTMLInputElement>(this.refs.get("editField")) if (node == null) { return; } node.focus() node.setSelectionRange(node.value.length, node.value.length) } } override fun render(): ReactElement { val classes = Classes() classes.add(this.props.todo.completed, "completed") classes.add(this.props.editing, "editing") return ktx { li("className" to classes.build()) { div("className" to "view") { input("className" to "toggle", "type" to "checkbox", "checked" to props.todo.completed, "onChange" to props.onToggle) label("onDoubleClick" to { e: KeyboardEvent -> handleEdit() }) { +props.todo.title } button("className" to "destroy", "onClick" to props.onDestroy) } input("ref" to "editField", "className" to "edit", "value" to state.editText, "onBlur" to { e: FormEvent -> handleSubmit() }, "onChange" to { e: FormEvent -> handleChange(e) }, "onKeyDown" to { e: KeyboardEvent -> handleKeyDown(e) }) } } } }
apache-2.0
607745ec8def806c3fedc259d2bc0c58
39.026786
249
0.655734
4.052441
false
false
false
false
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/psi/imports/ImportedClassReference.kt
1
672
package org.purescript.psi.imports import com.intellij.psi.PsiReferenceBase import org.purescript.psi.classes.PSClassDeclaration class ImportedClassReference(importedClass: PSImportedClass) : PsiReferenceBase<PSImportedClass>( importedClass, importedClass.properName.textRangeInParent, false ) { override fun getVariants(): Array<Any> = candidates.toTypedArray() override fun resolve(): PSClassDeclaration? = candidates.firstOrNull { it.name == myElement.name } private val candidates: List<PSClassDeclaration> get() = myElement.importDeclaration?.importedModule?.exportedClassDeclarations ?: emptyList() }
bsd-3-clause
3c7f4673761d93eb837ba59cd1a456be
31
97
0.75
4.941176
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/refactoring/suggested/SuggestedRefactoringIntentionContributor.kt
1
4324
// 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.refactoring.suggested import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.IntentionMenuContributor import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.PriorityAction import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.refactoring.RefactoringBundle class SuggestedRefactoringIntentionContributor : IntentionMenuContributor { private val icon = AllIcons.Actions.SuggestedRefactoringBulb override fun collectActions( hostEditor: Editor, hostFile: PsiFile, intentions: ShowIntentionsPass.IntentionsInfo, passIdToShowIntentionsFor: Int, offset: Int ) { val project = hostFile.project val refactoringProvider = SuggestedRefactoringProviderImpl.getInstance(project) var state = refactoringProvider.state ?: return val declaration = state.declaration if (!declaration.isValid) return if (hostFile != declaration.containingFile) return if (state.syntaxError) return val refactoringSupport = state.refactoringSupport state = refactoringSupport.availability.refineSignaturesWithResolve(state) if (state.oldSignature == state.newSignature) { val document = PsiDocumentManager.getInstance(project).getDocument(hostFile)!! val modificationStamp = document.modificationStamp ApplicationManager.getApplication().invokeLater { if (document.modificationStamp == modificationStamp) { refactoringProvider.availabilityIndicator.clear() } } return } val refactoringData = refactoringSupport.availability.detectAvailableRefactoring(state) // update availability indicator with more precise state that takes into account resolve refactoringProvider.availabilityIndicator.update(declaration, refactoringData, refactoringSupport) val range = when (refactoringData) { is SuggestedRenameData -> refactoringSupport.nameRange(refactoringData.declaration)!! is SuggestedChangeSignatureData -> refactoringSupport.changeSignatureAvailabilityRange(declaration)!! else -> return } if (!range.containsOffset(offset)) return SuggestedRefactoringFeatureUsage.refactoringSuggested(refactoringData, state) val text = when (refactoringData) { is SuggestedRenameData -> RefactoringBundle.message( "suggested.refactoring.rename.intention.text", refactoringData.oldName, refactoringData.declaration.name ) is SuggestedChangeSignatureData -> RefactoringBundle.message( "suggested.refactoring.change.signature.intention.text", refactoringData.nameOfStuffToUpdate ) } val intention = MyIntention(text, showReviewBalloon = refactoringData is SuggestedChangeSignatureData) // we add it into 'errorFixesToShow' if it's not empty to always be at the top of the list // we don't add into it if it's empty to keep the color of the bulb val collectionToAdd = intentions.errorFixesToShow.takeIf { it.isNotEmpty() } ?: intentions.inspectionFixesToShow collectionToAdd.add(0, HighlightInfo.IntentionActionDescriptor(intention, icon)) } private class MyIntention( private val text: String, private val showReviewBalloon: Boolean ) : IntentionAction, PriorityAction { override fun getPriority() = PriorityAction.Priority.TOP override fun getFamilyName() = "Suggested Refactoring" override fun getText() = text override fun isAvailable(project: Project, editor: Editor, file: PsiFile?) = true override fun startInWriteAction() = false override fun invoke(project: Project, editor: Editor, file: PsiFile?) { performSuggestedRefactoring(project, editor, null, null, showReviewBalloon, ActionPlaces.INTENTION_MENU) } } }
apache-2.0
d34494b669d7e4ae9b73fe250aee0e18
39.801887
140
0.767114
5.153754
false
false
false
false
humorousz/Exercises
MyApplication/lint_tools/src/main/java/com/humrousz/lint/DimenDetector.kt
1
1855
package com.humrousz.lint import com.android.SdkConstants import com.android.resources.ResourceFolderType import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.LayoutDetector import com.android.tools.lint.detector.api.ResourceXmlDetector import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.android.tools.lint.detector.api.XmlContext import org.jetbrains.uast.UElement import org.w3c.dom.Attr import org.w3c.dom.Element /** * Description: * * author:zhangzhiquan * Date: 2022/4/17 */ class DimenDetector : ResourceXmlDetector(), SourceCodeScanner { override fun appliesTo(folderType: ResourceFolderType): Boolean { return folderType == ResourceFolderType.LAYOUT } override fun getApplicableAttributes(): Collection<String> { return listOf( SdkConstants.ATTR_LAYOUT_WIDTH, SdkConstants.ATTR_LAYOUT_HEIGHT ) } override fun visitAttribute(context: XmlContext, attribute: Attr) { val value = attribute.value val pass = value.startsWith(SdkConstants.DIMEN_PREFIX) || value.startsWith(SdkConstants.VALUE_MATCH_PARENT) if (!pass) { context.report( ISSUE, attribute, context.getLocation(attribute), "dimen value 需要定义到values中" ) } } companion object { val ISSUE = Issue.create( "ZQDimenCheck", "dimen不能直接写魔法值,需要定义变量", "需要定义dimen在values", Category.MESSAGES, 7, Severity.ERROR, Implementation( DimenDetector::class.java, Scope.RESOURCE_FILE_SCOPE ) ) } }
apache-2.0
74f8b10d94d4ae181d70e416cca8fe81
26.30303
102
0.727374
3.775681
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/intrinsics/charToInt.kt
5
147
fun box(): String { val x: Any = 'A' var y = 0 if (x is Char) { y = x.toInt() } return if (y == 65) "OK" else "fail" }
apache-2.0
b0c1be294812efc3ee52af3c69f5c50a
17.375
40
0.421769
2.722222
false
false
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/sdk/PySdkSettings.kt
9
4066
// 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.jetbrains.python.sdk import com.intellij.application.options.ReplacePathToMacroMap import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.xmlb.XmlSerializerUtil import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import org.jetbrains.annotations.SystemIndependent import org.jetbrains.jps.model.serialization.PathMacroUtil /** * @author vlan */ @State(name = "PySdkSettings", storages = [Storage(value = "pySdk.xml", roamingType = RoamingType.DISABLED)]) class PySdkSettings : PersistentStateComponent<PySdkSettings.State> { companion object { @JvmStatic val instance: PySdkSettings get() = ApplicationManager.getApplication().getService(PySdkSettings::class.java) private const val VIRTUALENV_ROOT_DIR_MACRO_NAME = "VIRTUALENV_ROOT_DIR" } private val state: State = State() var useNewEnvironmentForNewProject: Boolean get() = state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT set(value) { state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT = value } var preferredEnvironmentType: String? get() = state.PREFERRED_ENVIRONMENT_TYPE set(value) { state.PREFERRED_ENVIRONMENT_TYPE = value } var preferredVirtualEnvBaseSdk: String? get() = state.PREFERRED_VIRTUALENV_BASE_SDK set(value) { state.PREFERRED_VIRTUALENV_BASE_SDK = value } fun onVirtualEnvCreated(baseSdk: Sdk, location: @SystemIndependent String, projectPath: @SystemIndependent String?) { setPreferredVirtualEnvBasePath(location, projectPath) preferredVirtualEnvBaseSdk = baseSdk.homePath } fun setPreferredVirtualEnvBasePath(value: @SystemIndependent String, projectPath: @SystemIndependent String?) { val pathMap = ReplacePathToMacroMap().apply { projectPath?.let { addMacroReplacement(it, PathMacroUtil.PROJECT_DIR_MACRO_NAME) } defaultVirtualEnvRoot?.let { addMacroReplacement(it, VIRTUALENV_ROOT_DIR_MACRO_NAME) } } val pathToSave = when { projectPath != null && FileUtil.isAncestor(projectPath, value, true) -> value.trimEnd { !it.isLetter() } else -> PathUtil.getParentPath(value) } state.PREFERRED_VIRTUALENV_BASE_PATH = pathMap.substitute(pathToSave, true) } fun getPreferredVirtualEnvBasePath(projectPath: @SystemIndependent String?): @SystemIndependent String { val defaultPath = defaultVirtualEnvRoot ?: projectPath?.let { "$it/venv" } ?: userHome val pathMap = ExpandMacroToPathMap().apply { addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectPath ?: userHome) addMacroExpand(VIRTUALENV_ROOT_DIR_MACRO_NAME, defaultPath) } val rawSavedPath = state.PREFERRED_VIRTUALENV_BASE_PATH ?: defaultPath val savedPath = pathMap.substitute(rawSavedPath, true) return when { projectPath != null && FileUtil.isAncestor(projectPath, savedPath, true) -> savedPath projectPath != null -> "$savedPath/${PathUtil.getFileName(projectPath)}" else -> savedPath } } override fun getState(): State = state override fun loadState(state: State) { XmlSerializerUtil.copyBean(state, this.state) } @Suppress("PropertyName") class State { @JvmField var USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT: Boolean = true @JvmField var PREFERRED_ENVIRONMENT_TYPE: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_PATH: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_SDK: String? = null } private val defaultVirtualEnvRoot: @SystemIndependent String? get() = VirtualEnvSdkFlavor.getDefaultLocation()?.path private val userHome: @SystemIndependent String get() = FileUtil.toSystemIndependentName(SystemProperties.getUserHome()) }
apache-2.0
ce7386a66fcdc5aac2a7cffcd6cd9346
36.657407
140
0.742745
4.537946
false
false
false
false
smmribeiro/intellij-community
plugins/devkit/devkit-core/src/inspections/IncorrectParentDisposableInspection.kt
9
3564
// 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 org.jetbrains.idea.devkit.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.InheritanceUtil import com.intellij.uast.UastHintedVisitorAdapter.Companion.create import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UExpression import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class IncorrectParentDisposableInspection : DevKitUastInspectionBase(UCallExpression::class.java) { override fun isAllowed(holder: ProblemsHolder): Boolean = DevKitInspectionBase.isAllowedInPluginsOnly(holder.file) override fun buildInternalVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = create(holder.file.language, object : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { checkCallExpression(node, holder) return true } }, arrayOf(UCallExpression::class.java)) private val sdkLink = "https://plugins.jetbrains.com/docs/intellij/disposers.html?from=IncorrectParentDisposable#choosing-a-disposable-parent" private fun checkCallExpression(node: UCallExpression, holder: ProblemsHolder) { val psiMethod = node.resolve() ?: return if (psiMethod.name == "isDisposed") return psiMethod.parameters.forEachIndexed { index, parameter -> val parameterType = (parameter.type as? PsiClassType)?.resolve() ?: return@forEachIndexed if (parameterType.qualifiedName != Disposable::class.java.name) return@forEachIndexed val argument: UExpression = node.getArgumentForParameter(index) ?: return@forEachIndexed val argumentSourcePsi: PsiElement = argument.sourcePsi ?: return@forEachIndexed val argumentType: PsiClass = (argument.getExpressionType() as? PsiClassType)?.resolve() ?: return@forEachIndexed val project = argumentType.project val facade = JavaPsiFacade.getInstance(project) @NlsSafe val typeName: String? = when { InheritanceUtil.isInheritorOrSelf(argumentType, facade.findClass(Project::class.java.name, GlobalSearchScope.projectScope(project)), true) -> "Project" InheritanceUtil.isInheritorOrSelf(argumentType, facade.findClass(Application::class.java.name, GlobalSearchScope.projectScope(project)), true) -> "Application" InheritanceUtil.isInheritorOrSelf(argumentType, facade.findClass(Module::class.java.name, GlobalSearchScope.projectScope(project)), true) -> "Module" else -> null } if (typeName != null) { holder.registerProblem(argumentSourcePsi, HtmlBuilder() .append(DevKitBundle.message("inspections.IncorrectParentDisposableInspection.do.not.use.as.disposable", typeName)) .nbsp() .append("(") .appendLink(sdkLink, DevKitBundle.message("inspections.IncorrectParentDisposableInspection.documentation.link.title")) .append(")") .wrapWith(HtmlChunk.html()) .toString()) } } } }
apache-2.0
9b484f2d26af8a2c273269570637af4e
51.411765
169
0.764029
4.855586
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/util/Subdivide.kt
1
1695
package de.fabmax.kool.util import de.fabmax.kool.math.MutableVec3f import de.fabmax.kool.math.Vec3f import kotlin.math.max import kotlin.math.min object Subdivide { /** * Subdivides the given list of triangles in-place. */ fun subdivideTris(verts: MutableList<Vec3f>, triIndices: MutableList<Int>, computeMid: (Vec3f, Vec3f) -> Vec3f = { a, b -> MutableVec3f(a).add(b).scale(0.5f) }) { val newTris = IntArray(triIndices.size * 4) val midVerts = mutableMapOf<Double, Int>() fun getMidVertex(fromIdx: Int, toIdx: Int): Int { // using a Double as key is much faster in javascript, where Long is not a native type... val key = min(fromIdx, toIdx).toDouble() * 1048576 + max(fromIdx, toIdx) return midVerts.getOrPut(key) { val insertIdx = verts.size verts += computeMid(verts[fromIdx], verts[toIdx]) insertIdx } } var i = 0 for (j in triIndices.indices step 3) { val v1 = triIndices[j] val v2 = triIndices[j + 1] val v3 = triIndices[j + 2] // subdivide edges val a = getMidVertex(v1, v2) val b = getMidVertex(v2, v3) val c = getMidVertex(v3, v1) newTris[i++] = v1; newTris[i++] = a; newTris[i++] = c newTris[i++] = v2; newTris[i++] = b; newTris[i++] = a newTris[i++] = v3; newTris[i++] = c; newTris[i++] = b newTris[i++] = a; newTris[i++] = b; newTris[i++] = c } triIndices.clear() newTris.forEach { triIndices.add(it) } } }
apache-2.0
a3677846f058be7ae016a09fc5bf6bf8
33.612245
109
0.538053
3.330059
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_Off.kt
1
878
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRS_Packet_Basal_Set_Suspend_Off( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF aapsLogger.debug(LTag.PUMPCOMM, "Turning off suspend") } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override fun getFriendlyName(): String { return "BASAL__SET_SUSPEND_OFF" } }
agpl-3.0
077ad61eff33e1ce7eebcd87aba62d35
28.3
74
0.661731
4.368159
false
false
false
false
Flank/flank
flank-scripts/src/test/kotlin/flank/scripts/ops/dependencies/DependencyExtensionsTest.kt
1
3718
package flank.scripts.ops.dependencies import flank.scripts.ops.dependencies.common.GradleDependency import flank.scripts.utils.toAvailableVersion import flank.scripts.utils.toDependency import flank.scripts.utils.toGradleReleaseChannel import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class DependencyExtensionsTest { @Test fun `should return group with name`() { // given val dependency = toDependency( "group", "1.0", "name" ) // when val actual = dependency.groupWithName // then assertEquals("${dependency.group}:${dependency.name}:", actual) } @Test fun `should get version to update if release available`() { val dependency = toDependency( "group", "1.0", "name", toAvailableVersion( "1.1", null, null ) ) // when val actual = dependency.versionToUpdate // then assertEquals(dependency.availableVersion?.release, actual) } @Test fun `should get version to update if milestone available`() { val dependency = toDependency( "group", "1.0", "name", toAvailableVersion(null, "1.1", null) ) // when val actual = dependency.versionToUpdate // then assertEquals(dependency.availableVersion?.milestone, actual) } @Test fun `should get version to update if integration available`() { val dependency = toDependency( "group", "1.0", "name", toAvailableVersion(null, null, "1.1") ) // when val actual = dependency.versionToUpdate // then assertEquals(dependency.availableVersion?.integration, actual) } @Test fun `should get current version to update if no update`() { val dependency = toDependency( "group", "1.0", "name", null ) // when val actual = dependency.versionToUpdate // then assertEquals(dependency.version, actual) } @Test fun `should properly check if gradle needs update`() { // given val gradleWhichNeedsUpdate = GradleDependency( current = toGradleReleaseChannel("1.1", "test", false, false), nightly = toGradleReleaseChannel("1.3", "test", false, false), releaseCandidate = toGradleReleaseChannel("1.2rc", "test", false, false), running = toGradleReleaseChannel("1", "test", false, false), ) val gradleWhichNeedsUpdateRc = GradleDependency( current = toGradleReleaseChannel("1.1", "test", false, false), nightly = toGradleReleaseChannel("1.3", "test", false, false), releaseCandidate = toGradleReleaseChannel("1.2rc", "test", false, false), running = toGradleReleaseChannel("1.1", "test", false, false), ) val gradleWhichDoesNotNeedUpdate = GradleDependency( current = toGradleReleaseChannel("1.1", "test", false, false), nightly = toGradleReleaseChannel("1.3", "test", false, false), releaseCandidate = toGradleReleaseChannel("1.1", "test", false, false), running = toGradleReleaseChannel("1.1", "test", false, false), ) // when - then assertTrue(gradleWhichNeedsUpdate.needsUpdate()) assertTrue(gradleWhichNeedsUpdateRc.needsUpdate()) assertFalse(gradleWhichDoesNotNeedUpdate.needsUpdate()) } }
apache-2.0
5d1b8954428c3df4477287abc29a2645
29.227642
85
0.592254
4.706329
false
true
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.kt
1
1422
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject class DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { var dataIndex = DATA_START var dataSize = 1 val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 val carbs = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.currentCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)) if (error != 0) failed = true aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") aapsLogger.debug(LTag.PUMPCOMM, "Carbs: $carbs") aapsLogger.debug(LTag.PUMPCOMM, "Current CIR: " + danaPump.currentCIR) } override fun getFriendlyName(): String { return "BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION" } }
agpl-3.0
2327a65364617d63d94e43460803c5f9
35.487179
99
0.712377
4.416149
false
false
false
false
siosio/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/auth/services/OAuthServiceBase.kt
1
2747
// 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.collaboration.auth.services import com.intellij.collaboration.auth.credentials.Credentials import com.intellij.ide.BrowserUtil import com.intellij.util.Url import java.io.IOException import java.net.URI import java.net.http.HttpClient import java.net.http.HttpHeaders import java.net.http.HttpRequest import java.net.http.HttpResponse import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicReference /** * The basic service that implements general authorization flow methods * * @param T Service credentials, must implement the Credentials interface */ abstract class OAuthServiceBase<T : Credentials> : OAuthService<T> { protected val currentRequest = AtomicReference<CompletableFuture<T>?>() override fun authorize(): CompletableFuture<T> { if (!currentRequest.compareAndSet(null, CompletableFuture<T>())) { return currentRequest.get()!! } val request = currentRequest.get()!! request.whenComplete { _, _ -> currentRequest.set(null) } startAuthorization() return request } override fun acceptCode(code: String): Boolean { val request = currentRequest.get() ?: return false request.processCode(code) return request.isDone && !request.isCancelled && !request.isCompletedExceptionally } private fun startAuthorization() { val authUrl = getAuthUrlWithParameters().toExternalForm() BrowserUtil.browse(authUrl) } private fun CompletableFuture<T>.processCode(code: String) { try { val tokenUrl = getTokenUrlWithParameters(code).toExternalForm() val response = postHttpResponse(tokenUrl) if (response.statusCode() == 200) { val result = getCredentials(response.body(), response.headers()) complete(result) } else { completeExceptionally(RuntimeException(response.body().ifEmpty { "No token provided" })) } } catch (e: IOException) { completeExceptionally(e) } } protected fun postHttpResponse(url: String): HttpResponse<String> { val client = HttpClient.newHttpClient() val request: HttpRequest = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.noBody()) .build() return client.send(request, HttpResponse.BodyHandlers.ofString()) } protected abstract fun getAuthUrlWithParameters(): Url protected abstract fun getTokenUrlWithParameters(code: String): Url protected abstract fun getCredentials(responseBody: String, responseHeaders: HttpHeaders): T }
apache-2.0
8697b8ae4007e5c6f798ae621f05a818
32.512195
158
0.735348
4.593645
false
false
false
false
siosio/intellij-community
platform/platform-api/src/com/intellij/openapi/ui/MessageDialogBuilder.kt
1
10665
// 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.openapi.ui import com.intellij.CommonBundle import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper.DoNotAskOption import com.intellij.openapi.ui.Messages.* import com.intellij.openapi.ui.messages.AlertMessagesManager import com.intellij.openapi.ui.messages.MessagesService import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.wm.WindowManager import com.intellij.ui.ComponentUtil import com.intellij.ui.mac.MacMessages import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.awt.Component import java.awt.Window import javax.swing.Icon sealed class MessageDialogBuilder<T : MessageDialogBuilder<T>>(protected val title: @NlsContexts.DialogTitle String, protected val message: @DialogMessage String) { protected var yesText: String? = null protected var noText: String? = null protected var project: Project? = null protected var parentComponent: Component? = null protected var icon: Icon? = null protected var doNotAskOption: DoNotAskOption? = null @NonNls protected var helpId: String? = null protected abstract fun getThis(): T companion object { @JvmStatic fun yesNo(title: @NlsContexts.DialogTitle String, message: @DialogMessage String): YesNo { return YesNo(title, message).icon(UIUtil.getQuestionIcon()) } @JvmStatic fun okCancel(title: @NlsContexts.DialogTitle String, message: @DialogMessage String): OkCancelDialogBuilder { return OkCancelDialogBuilder(title, message).icon(UIUtil.getQuestionIcon()) } @JvmStatic fun yesNoCancel(title: @NlsContexts.DialogTitle String, message: @DialogMessage String): YesNoCancel { return YesNoCancel(title, message).icon(UIUtil.getQuestionIcon()) } } @Deprecated(message = "Pass project to show", level = DeprecationLevel.ERROR) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") fun project(project: Project?): T { this.project = project return getThis() } /** * @see asWarning * @see UIUtil.getInformationIcon * @see UIUtil.getWarningIcon * @see UIUtil.getErrorIcon * @see UIUtil.getQuestionIcon */ fun icon(icon: Icon?): T { this.icon = icon return getThis() } fun asWarning(): T { icon = UIUtil.getWarningIcon() return getThis() } fun doNotAsk(doNotAskOption: DoNotAskOption?): T { this.doNotAskOption = doNotAskOption return getThis() } fun yesText(yesText: @NlsContexts.Button String): T { this.yesText = yesText return getThis() } fun noText(noText: @NlsContexts.Button String): T { this.noText = noText return getThis() } fun help(@NonNls helpId: String): T { this.helpId = helpId return getThis() } class YesNo internal constructor(title: String, message: String) : MessageDialogBuilder<YesNo>(title, message) { override fun getThis() = this fun ask(project: Project?) = show(project = project, parentComponent = null) fun ask(parentComponent: Component?) = show(project = null, parentComponent = parentComponent) /** * Use this method only if you know neither project nor component. */ fun guessWindowAndAsk() = show(project = null, parentComponent = null) @Deprecated(message = "Use ask(project)", level = DeprecationLevel.ERROR) fun isYes(): Boolean = show(project = null, parentComponent = null) @Deprecated(message = "Use ask(project)", level = DeprecationLevel.ERROR) fun show(): Int = if (show(project = project, parentComponent = parentComponent)) YES else NO @YesNoResult private fun show(project: Project?, parentComponent: Component?): Boolean { val yesText = yesText ?: CommonBundle.getYesButtonText() val noText = noText ?: CommonBundle.getNoButtonText() return showMessage( project, parentComponent, mac = { MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, it, doNotAskOption, icon, helpId) }, other = { MessagesService.getInstance().showMessageDialog( project = project, parentComponent = parentComponent, message = message, title = title, icon = icon, options = arrayOf(yesText, noText), doNotAskOption = doNotAskOption, helpId = helpId, alwaysUseIdeaUI = true ) == YES } ) } } class YesNoCancel internal constructor(title: String, message: String) : MessageDialogBuilder<YesNoCancel>(title, message) { @NlsContexts.Button private var cancelText: String? = null fun cancelText(cancelText: @NlsContexts.Button String): YesNoCancel { this.cancelText = cancelText return getThis() } override fun getThis() = this @YesNoCancelResult fun show(project: Project?) = show(project = project, parentComponent = null) @YesNoCancelResult fun show(parentComponent: Component?) = show(project = null, parentComponent = parentComponent) @YesNoCancelResult fun guessWindowAndAsk() = show(project = null, parentComponent = null) @Deprecated(message = "Use show(project)", level = DeprecationLevel.ERROR) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") fun show() = show(project = project, parentComponent = parentComponent) @YesNoCancelResult private fun show(project: Project?, parentComponent: Component?): Int { val yesText = yesText ?: CommonBundle.getYesButtonText() val noText = noText ?: CommonBundle.getNoButtonText() val cancelText = cancelText ?: CommonBundle.getCancelButtonText() return showMessage(project, parentComponent, mac = { window -> MacMessages.getInstance().showYesNoCancelDialog(title, message, yesText, noText, cancelText, window, doNotAskOption, icon, helpId) }, other = { val options = arrayOf(yesText, noText, cancelText) when (MessagesService.getInstance().showMessageDialog(project = project, parentComponent = parentComponent, message = message, title = title, options = options, icon = icon, doNotAskOption = doNotAskOption, helpId = helpId, alwaysUseIdeaUI = true)) { 0 -> YES 1 -> NO else -> CANCEL } }) } } @ApiStatus.Experimental class Message(title: String, message: String) : MessageDialogBuilder<Message>(title, message) { private lateinit var buttons: List<String> private var defaultButton: String? = null private var focusedButton: String? = null override fun getThis() = this fun buttons(vararg buttonNames: String): Message { buttons = buttonNames.toList() return this } fun defaultButton(defaultButtonName: String): Message { defaultButton = defaultButtonName return this } fun focusedButton(focusedButtonName: String): Message { focusedButton = focusedButtonName return this } fun show(project: Project? = null, parentComponent: Component? = null): String? { val options = buttons.toTypedArray() val defaultOptionIndex = buttons.indexOf(defaultButton) val focusedOptionIndex = buttons.indexOf(focusedButton) val result = showMessage(project, parentComponent, mac = { window -> MacMessages.getInstance().showMessageDialog(title, message, options, window, defaultOptionIndex, focusedOptionIndex, doNotAskOption, icon, helpId) }, other = { MessagesService.getInstance().showMessageDialog(project = project, parentComponent = parentComponent, message = message, title = title, options = options, defaultOptionIndex = defaultOptionIndex, focusedOptionIndex = focusedOptionIndex, icon = icon, doNotAskOption = doNotAskOption, helpId = helpId, alwaysUseIdeaUI = true) }) return if (result < 0) null else buttons[result] } } } class OkCancelDialogBuilder internal constructor(title: String, message: String) : MessageDialogBuilder<OkCancelDialogBuilder>(title, message) { override fun getThis() = this fun ask(project: Project?) = show(project = project, parentComponent = null) fun ask(parentComponent: Component?) = show(project = null, parentComponent = parentComponent) /** * Use this method only if you know neither project nor component. */ fun guessWindowAndAsk() = show(project = null, parentComponent = null) private fun show(project: Project?, parentComponent: Component?): Boolean { val yesText = yesText ?: CommonBundle.getOkButtonText() val noText = noText ?: CommonBundle.getCancelButtonText() return showMessage(project, parentComponent, mac = { window -> MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, window, doNotAskOption, icon, helpId) }, other = { MessagesService.getInstance().showMessageDialog(project = project, parentComponent = parentComponent, message = message, title = title, options = arrayOf(yesText, noText), icon = icon, doNotAskOption = doNotAskOption, alwaysUseIdeaUI = true) == 0 }) } } private inline fun <T> showMessage(project: Project?, parentComponent: Component?, mac: (Window?) -> T, other: () -> T): T { if (canShowMacSheetPanel() || (SystemInfoRt.isMac && AlertMessagesManager.isEnabled())) { try { val window = if (parentComponent == null) { WindowManager.getInstance().suggestParentWindow(project) } else { ComponentUtil.getWindow(parentComponent) } return mac(window) } catch (e: Exception) { if (e.message != "Cannot find any window") { logger<MessagesService>().error(e) } } } return other() }
apache-2.0
ea4e4ee3f8d6b59f8de05a7ad3dc7a70
39.093985
158
0.662447
5.059298
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/base/BaseLinksFragment.kt
1
4115
package io.github.feelfreelinux.wykopmobilny.base import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.api.links.LinksApi import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.ui.adapters.LinksAdapter import io.github.feelfreelinux.wykopmobilny.ui.fragments.links.LinksFragmentView import io.github.feelfreelinux.wykopmobilny.utils.isVisible import io.github.feelfreelinux.wykopmobilny.utils.prepare import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.entries_fragment.* import kotlinx.android.synthetic.main.search_empty_view.* import javax.inject.Inject open class BaseLinksFragment : BaseFragment(), LinksFragmentView, androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener { @Inject lateinit var linksApi: LinksApi @Inject lateinit var linksAdapter: LinksAdapter var showSearchEmptyView: Boolean get() = searchEmptyView.isVisible set(value) { searchEmptyView.isVisible = value } open var loadDataListener: (Boolean) -> Unit = {} private val subjectDisposable by lazy { CompositeDisposable() } // Inflate view override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.entries_fragment, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) linksAdapter.loadNewDataListener = { loadDataListener(false) } // Setup views swipeRefresh.setOnRefreshListener(this) recyclerView.run { prepare() adapter = linksAdapter } loadingView.isVisible = true val schedulers = WykopSchedulers() subjectDisposable.addAll( linksApi.digSubject .subscribeOn(schedulers.backgroundThread()) .observeOn(schedulers.mainThread()) .subscribe { updateLinkVoteState(it.linkId, it.voteResponse.buries, it.voteResponse.diggs, "dig") }, linksApi.burySubject .subscribeOn(schedulers.backgroundThread()) .observeOn(schedulers.mainThread()) .subscribe { updateLinkVoteState(it.linkId, it.voteResponse.buries, it.voteResponse.diggs, "bury") }, linksApi.voteRemoveSubject .subscribeOn(schedulers.backgroundThread()) .observeOn(schedulers.mainThread()) .subscribe { updateLinkVoteState(it.linkId, it.voteResponse.buries, it.voteResponse.diggs, null) } ) } private fun updateLinkVoteState(linkId: Int, buryCount: Int, voteCount: Int, userVote: String?) { linksAdapter.data.firstOrNull { it.id == linkId }?.apply { this.buryCount = buryCount this.voteCount = voteCount this.userVote = userVote linksAdapter.updateLink(this) } } /** * Removes progressbar from adapter */ override fun disableLoading() = linksAdapter.disableLoading() /** * Use this function to add items to EntriesFragment * @param items List of entries to add * @param shouldRefresh If true adapter will refresh its data with provided items. False by default */ override fun addItems(items: List<Link>, shouldRefresh: Boolean) { linksAdapter.addData(items, shouldRefresh) swipeRefresh?.isRefreshing = false loadingView?.isVisible = false // Scroll to top if refreshing list if (shouldRefresh) { (recyclerView?.layoutManager as? androidx.recyclerview.widget.LinearLayoutManager)?.scrollToPositionWithOffset(0, 0) } } override fun updateLink(link: Link) = linksAdapter.updateLink(link) override fun onRefresh() = loadDataListener(true) override fun onDestroy() { subjectDisposable.dispose() super.onDestroy() } }
mit
77cbaf68890b38a3a20869fe5404d0fd
38.2
139
0.699878
5.006083
false
false
false
false
siosio/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/statistics/VcsLogIndexStatisticsCollectors.kt
2
3858
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.statistics import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newCounterMetric import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.vcs.log.data.index.VcsLogBigRepositoriesList import com.intellij.vcs.log.impl.VcsLogSharedSettings import org.jetbrains.annotations.NonNls import java.util.concurrent.TimeUnit @NonNls internal class VcsLogIndexApplicationStatisticsCollector : ApplicationUsagesCollector() { override fun getMetrics(): MutableSet<MetricEvent> { val metricEvents = mutableSetOf<MetricEvent>() if (!Registry.`is`("vcs.log.index.git")) { metricEvents.add(newMetric("index.disabled.in.registry", true)) } if (Registry.`is`("vcs.log.index.force")) { metricEvents.add(newMetric("index.forced.in.registry", true)) } getBigRepositoriesList()?.let { bigRepositoriesList -> if (bigRepositoriesList.repositoriesCount > 0) { metricEvents.add(newCounterMetric("big.repositories", bigRepositoriesList.repositoriesCount)) } } return metricEvents } private fun getBigRepositoriesList() = serviceIfCreated<VcsLogBigRepositoriesList>() override fun getGroupId(): String = "vcs.log.index.application" override fun getVersion(): Int = 2 } class VcsLogIndexProjectStatisticsCollector : ProjectUsagesCollector() { override fun getMetrics(project: Project): MutableSet<MetricEvent> { val usages = mutableSetOf<MetricEvent>() getIndexCollector(project)?.state?.let { indexCollectorState -> val indexingTime = TimeUnit.MILLISECONDS.toMinutes(indexCollectorState.indexTime).toInt() usages.add(newCounterMetric("indexing.time.minutes", indexingTime)) } getSharedSettings(project)?.let { sharedSettings -> if (!sharedSettings.isIndexSwitchedOn) { usages.add(newMetric("index.disabled.in.project", true)) } } return usages } private fun getSharedSettings(project: Project) = project.serviceIfCreated<VcsLogSharedSettings>() private fun getIndexCollector(project: Project) = project.serviceIfCreated<VcsLogIndexCollector>() override fun getGroupId(): String = "vcs.log.index.project" override fun getVersion(): Int = 2 } class VcsLogIndexCollectorState { var indexTime: Long = 0 fun copy(): VcsLogIndexCollectorState { val copy = VcsLogIndexCollectorState() copy.indexTime = indexTime return copy } } @State(name = "VcsLogIndexCollector", storages = [Storage(value = StoragePathMacros.CACHE_FILE)]) class VcsLogIndexCollector : PersistentStateComponent<VcsLogIndexCollectorState> { private val lock = Any() private var state: VcsLogIndexCollectorState init { synchronized(lock) { state = VcsLogIndexCollectorState() } } override fun getState(): VcsLogIndexCollectorState? { synchronized(lock) { return state.copy() } } override fun loadState(state: VcsLogIndexCollectorState) { synchronized(lock) { this.state = state } } fun reportIndexingTime(time: Long) { synchronized(lock) { state.indexTime += time } } fun reportFreshIndex() { synchronized(lock) { state.indexTime = 0 } } companion object { @JvmStatic fun getInstance(project: Project): VcsLogIndexCollector = project.getService(VcsLogIndexCollector::class.java) } }
apache-2.0
60cb7347de65f536580a0cd7b406a374
30.622951
140
0.745723
4.414188
false
false
false
false
idea4bsd/idea4bsd
platform/script-debugger/debugger-ui/src/DebuggerViewSupport.kt
4
3943
/* * 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.debugger import com.intellij.util.ThreeState import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XInlineDebuggerDataCallback import com.intellij.xdebugger.frame.XNavigatable import com.intellij.xdebugger.frame.XValueNode import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.frame.CallFrameView import org.jetbrains.debugger.values.ObjectValue import org.jetbrains.debugger.values.Value import org.jetbrains.rpc.LOG import javax.swing.Icon interface DebuggerViewSupport { val vm: Vm? get() = null fun getSourceInfo(script: Script?, frame: CallFrame): SourceInfo? = null fun getSourceInfo(functionName: String?, scriptUrl: String, line: Int, column: Int): SourceInfo? = null fun getSourceInfo(functionName: String?, script: Script, line: Int, column: Int): SourceInfo? = null fun propertyNamesToString(list: List<String>, quotedAware: Boolean): String // Please, don't hesitate to ask to share some generic implementations. Don't reinvent the wheel and keep in mind - user expects the same UI across all IDEA-based IDEs. fun computeObjectPresentation(value: ObjectValue, variable: Variable, context: VariableContext, node: XValueNode, icon: Icon) fun computeArrayPresentation(value: Value, variable: Variable, context: VariableContext, node: XValueNode, icon: Icon) fun createFrameEvaluator(frame: CallFrameView): XDebuggerEvaluator = PromiseDebuggerEvaluator(frame) /** * [org.jetbrains.debugger.values.FunctionValue] is special case and handled by SDK */ fun canNavigateToSource(variable: Variable, context: VariableContext) = false fun computeSourcePosition(name: String, value: Value?, variable: Variable, context: VariableContext, navigatable: XNavigatable) { } fun computeInlineDebuggerData(name: String, variable: Variable, context: VariableContext, callback: XInlineDebuggerDataCallback) = ThreeState.UNSURE // return null if you don't need to add additional properties fun computeAdditionalObjectProperties(value: ObjectValue, variable: Variable, context: VariableContext, node: XCompositeNode): Promise<Any?>? = null fun getMemberFilter(context: VariableContext): Promise<MemberFilter> fun transformErrorOnGetUsedReferenceValue(value: Value?, error: String?) = value fun isInLibraryContent(sourceInfo: SourceInfo, script: Script?) = false fun computeReceiverVariable(context: VariableContext, callFrame: CallFrame, node: XCompositeNode): Promise<*> } open class PromiseDebuggerEvaluator(protected val context: VariableContext) : XDebuggerEvaluator() { override final fun evaluate(expression: String, callback: XDebuggerEvaluator.XEvaluationCallback, expressionPosition: XSourcePosition?) { try { evaluate(expression, expressionPosition) .done { callback.evaluated(VariableView(VariableImpl(expression, it.value), context)) } .rejected { callback.errorOccurred(it.toString()) } } catch (e: Throwable) { LOG.error(e) callback.errorOccurred(e.toString()) return } } protected open fun evaluate(expression: String, expressionPosition: XSourcePosition?): Promise<EvaluateResult> = context.evaluateContext.evaluate(expression) }
apache-2.0
d1d43030449ef472f4af8cc9e1691137
43.818182
170
0.780117
4.622509
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/livedata/ArticleDetailActivity.kt
1
1890
package com.zhou.android.livedata import android.content.Intent import com.zhou.android.R import com.zhou.android.common.BaseActivity import com.zhou.android.common.Tools import com.zhou.android.common.text import kotlinx.android.synthetic.main.activity_article_detail.* /** * Created by mxz on 2020/5/22. */ class ArticleDetailActivity : BaseActivity() { // private lateinit var model: ArticleModel private var article: Article? = null private var pos = -1 override fun setContentView() { setContentView(R.layout.activity_article_detail) } override fun addListener() { btnClean.setOnClickListener { etImage.setText("") } btnSave.setOnClickListener { Tools.hideSoftInput(this, it.windowToken) val title = etTitle.text.toString() val content = etContent.text.toString() val image = etImage.text.toString() if (title.isEmpty() && content.isEmpty() && image.isEmpty()) { article = null } else { article?.apply { this.title = title this.content = content this.image = if (image.isEmpty()) null else image } } setResult(RESULT_OK, Intent().apply { putExtra("Article", article) putExtra("index", pos) }) finish() } } override fun init() { // model = ViewModelProviders.of(this).get(ArticleModel::class.java) article = intent.getParcelableExtra<Article>("Article") pos = intent.getIntExtra("index", -1) if (article != null) { etTitle.text = article!!.title.text() etContent.text = article!!.content.text() etImage.text = (article!!.image ?: "").text() } } }
mit
a2c4cf67bb164dd981cacce248edbbed
28.092308
75
0.573016
4.587379
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/PlFlow.kt
1
3586
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import cc.altruix.econsimtr01.ch0201.After import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.util.* /** * Created by pisarenko on 09.04.2016. */ open class PlFlow(val id:String, val src: String, val target:String, val resource:String, val amount:Double?, val timeTriggerFunction: (DateTime) -> Boolean) : IAction { val LOGGER = LoggerFactory.getLogger(PlFlow::class.java) val followingTriggers : MutableList<After> = LinkedList() lateinit var agents:List<IAgent> lateinit var flows:MutableList<ResourceFlow> val subscribers : MutableList<IActionSubscriber> = LinkedList() override fun timeToRun(time: DateTime): Boolean = timeTriggerFunction(time) override fun run(time: DateTime) { run(amount, time) } open fun run(amount: Double?, time: DateTime) { val targetAgent = findAgent(target, agents) val srcAgent = findAgent(src, agents) if (targetAgent == null) { LOGGER.error("Can't find agent $target") return } if (srcAgent == null) { LOGGER.error("Can't find agent $src") return } if ((targetAgent is IResourceStorage) && (srcAgent is IResourceStorage)) { if (amount != null) { val availableAmount = srcAgent.amount(resource) if (!srcAgent.isInfinite(resource) && (availableAmount < amount)) { LOGGER.error("Quantity of $resource at $src ($availableAmount) is less than flow amount of $amount") } else { srcAgent.remove(resource, amount) targetAgent.put(resource, amount) addFlow(srcAgent, targetAgent, time) } } else { addFlow(srcAgent, targetAgent, time) } } else { LOGGER.error("Agent '$targetAgent' isn't a resource storage") } } fun addFlow(srcAgent: IAgent, targetAgent: IAgent, time: DateTime) { flows.add(ResourceFlow(time, srcAgent, targetAgent, resource, amount)) followingTriggers.forEach { it.updateNextFiringTime(time) } } open fun addFollowUpFlow(nextTrigger: After) { followingTriggers.add(nextTrigger) } override fun notifySubscribers(time: DateTime) { this.subscribers.forEach { it.actionOccurred(this, time) } } override fun subscribe(subscriber: IActionSubscriber) { this.subscribers.add(subscriber) } }
gpl-3.0
a8479dfa4447911e8ea979e625cd70e1
31.899083
120
0.637479
4.238771
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/keywords/OverrideKeywordHandler.kt
1
7737
// 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.completion.contributors.keywords import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.ui.RowIcon import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.completion.* import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler import org.jetbrains.kotlin.idea.core.overrideImplement.* import org.jetbrains.kotlin.idea.core.overrideImplement.KtClassMember import org.jetbrains.kotlin.idea.core.overrideImplement.KtGenerateMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyse import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.idea.KtIconProvider.getIcon import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.nameOrAnonymous import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt import org.jetbrains.kotlin.idea.util.application.runWriteAction internal class OverrideKeywordHandler( private val basicContext: FirBasicCompletionContext ) : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.OVERRIDE_KEYWORD) { @OptIn(ExperimentalStdlibApi::class) override fun KtAnalysisSession.createLookups( parameters: CompletionParameters, expression: KtExpression?, lookup: LookupElement, project: Project ): Collection<LookupElement> { val result = mutableListOf(lookup) val position = parameters.position val isConstructorParameter = position.getNonStrictParentOfType<KtPrimaryConstructor>() != null val classOrObject = position.getNonStrictParentOfType<KtClassOrObject>() ?: return result val members = collectMembers(classOrObject, isConstructorParameter) for (member in members) { result += createLookupElementToGenerateSingleOverrideMember(member, classOrObject, isConstructorParameter, project) } return result } private fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject, isConstructorParameter: Boolean): List<KtClassMember> { val allMembers = KtOverrideMembersHandler().collectMembersToGenerate(classOrObject) return if (isConstructorParameter) { allMembers.mapNotNull { member -> if (member.memberInfo.isProperty) { member.copy(bodyType = BodyType.FROM_TEMPLATE, preferConstructorParameter = true) } else null } } else allMembers.toList() } private fun KtAnalysisSession.createLookupElementToGenerateSingleOverrideMember( member: KtClassMember, classOrObject: KtClassOrObject, isConstructorParameter: Boolean, project: Project ): OverridesCompletionLookupElementDecorator { val memberSymbol = member.symbol check(memberSymbol is KtNamedSymbol) val text = getSymbolTextForLookupElement(memberSymbol) val baseIcon = getIcon(memberSymbol) val isImplement = (memberSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT val additionalIcon = if (isImplement) AllIcons.Gutter.ImplementingMethod else AllIcons.Gutter.OverridingMethod val icon = RowIcon(baseIcon, additionalIcon) val baseClass = classOrObject.getClassOrObjectSymbol() val baseClassIcon = getIcon(baseClass) val isSuspendFunction = (memberSymbol as? KtFunctionSymbol)?.isSuspend == true val baseClassName = baseClass.nameOrAnonymous.asString() val memberPointer = memberSymbol.createPointer() val baseLookupElement = with(basicContext.lookupElementFactory) { createLookupElement(memberSymbol) } ?: error("Lookup element should be available for override completion") return OverridesCompletionLookupElementDecorator( baseLookupElement, declaration = null, text, isImplement, icon, baseClassName, baseClassIcon, isConstructorParameter, isSuspendFunction, generateMember = { generateMemberInNewAnalysisSession(classOrObject, memberPointer, member, project) }, shortenReferences = { element -> @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) val shortenings = hackyAllowRunningOnEdt { analyse(classOrObject) { collectPossibleReferenceShortenings(element.containingKtFile, element.textRange) } } runWriteAction { shortenings.invokeShortening() } } ) } private fun KtAnalysisSession.getSymbolTextForLookupElement(memberSymbol: KtCallableSymbol): String = buildString { append(KtTokens.OVERRIDE_KEYWORD.value) .append(" ") .append(memberSymbol.render(renderingOptionsForLookupElementRendering)) if (memberSymbol is KtFunctionSymbol) { append(" {...}") } } @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) private fun generateMemberInNewAnalysisSession( classOrObject: KtClassOrObject, memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember, project: Project ) = hackyAllowRunningOnEdt { analyse(classOrObject) { val memberInCorrectAnalysisSession = createCopyInCurrentAnalysisSession(memberPointer, member) generateMember( project, memberInCorrectAnalysisSession, classOrObject, copyDoc = false, mode = MemberGenerateMode.OVERRIDE ) } } //todo temporary hack until KtSymbolPointer is properly implemented private fun KtAnalysisSession.createCopyInCurrentAnalysisSession( memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember ) = KtClassMember( KtClassMemberInfo( memberPointer.restoreSymbol() ?: error("Cannot restore symbol from $memberPointer"), member.memberInfo.memberText, member.memberInfo.memberIcon, member.memberInfo.containingSymbolText, member.memberInfo.containingSymbolIcon, ), member.bodyType, member.preferConstructorParameter, ) companion object { private val renderingOptionsForLookupElementRendering = KtGenerateMembersHandler.renderOption.copy( renderUnitReturnType = false, renderDeclarationHeader = true ) } }
apache-2.0
4c4cc2ee2ea13b687c3aa639dcabffb7
44.251462
158
0.716428
5.518545
false
false
false
false
JetBrains/kotlin-native
performance/ring/src/main/kotlin-native/org/jetbrains/ring/Utils.kt
2
1739
/* * Copyright 2010-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 org.jetbrains.ring import kotlin.native.concurrent.FreezableAtomicReference as KAtomicRef import kotlin.native.concurrent.isFrozen import kotlin.native.concurrent.freeze public actual class AtomicRef<T> constructor(@PublishedApi internal val a: KAtomicRef<T>) { public actual inline var value: T get() = a.value set(value) { if (a.isFrozen) value.freeze() a.value = value } public actual inline fun lazySet(value: T) { if (a.isFrozen) value.freeze() a.value = value } public actual inline fun compareAndSet(expect: T, update: T): Boolean { if (a.isFrozen) update.freeze() return a.compareAndSet(expect, update) } public actual fun getAndSet(value: T): T { if (a.isFrozen) value.freeze() while (true) { val cur = a.value if (cur === value) return cur if (a.compareAndSwap(cur, value) === cur) return cur } } override fun toString(): String = value.toString() } public actual fun <T> atomic(initial: T): AtomicRef<T> = AtomicRef<T>(KAtomicRef(initial))
apache-2.0
2003b5906ae1e18ad87f1d76387ff8a6
31.830189
91
0.66935
3.988532
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/RedundantAsyncInspection.kt
5
6204
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.coroutines import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.collections.AbstractCallChainChecker import org.jetbrains.kotlin.idea.inspections.collections.SimplifyCallChainFix import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi.qualifiedExpressionVisitor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RedundantAsyncInspection : AbstractCallChainChecker() { fun generateConversion(expression: KtQualifiedExpression): Conversion? { var defaultContext: Boolean? = null var defaultStart: Boolean? = null var conversion = findQualifiedConversion(expression, conversionGroups) check@{ _, firstResolvedCall, _, _ -> for ((parameterDescriptor, valueArgument) in firstResolvedCall.valueArguments) { val default = valueArgument is DefaultValueArgument when (parameterDescriptor.name.asString()) { CONTEXT_ARGUMENT_NAME -> defaultContext = default START_ARGUMENT_NAME -> defaultStart = default } } true } ?: return null defaultContext ?: return null defaultStart ?: return null if (!defaultStart!!) return null val receiverExpression = expression.receiverExpression val scopeExpression = (receiverExpression as? KtQualifiedExpression)?.receiverExpression if (scopeExpression != null) { val context = scopeExpression.analyze(BodyResolveMode.PARTIAL) val scopeDescriptor = (scopeExpression as? KtNameReferenceExpression)?.let { context[BindingContext.REFERENCE_TARGET, it] } if (scopeDescriptor?.fqNameSafe?.toString() != GLOBAL_SCOPE) { conversion = conversion.withArgument("${scopeExpression.text}.coroutineContext") } } if (conversion.additionalArgument == null && defaultContext!! && defaultStart!!) { conversion = conversion.withArgument( if (conversion === conversions[0]) { DEFAULT_ASYNC_ARGUMENT } else { DEFAULT_ASYNC_ARGUMENT_EXPERIMENTAL } ) } return conversion } fun generateFix(conversion: Conversion): SimplifyCallChainFix { val contextArgument = conversion.additionalArgument return SimplifyCallChainFix(conversion, removeReceiverOfFirstCall = true, runOptimizeImports = true) { callExpression -> if (contextArgument != null) { val call = callExpression.resolveToCall() if (call != null) { for (argument in callExpression.valueArguments) { val mapping = call.getArgumentMapping(argument) as? ArgumentMatch ?: continue if (mapping.valueParameter.name.asString() == CONTEXT_ARGUMENT_NAME) { val name = argument.getArgumentName()?.asName val expressionText = contextArgument + " + " + argument.getArgumentExpression()!!.text argument.replace( if (name == null) { createArgument(expressionText) } else { createArgument("$name = $expressionText") } ) break } } } } } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(expression) { val conversion = generateConversion(expression) ?: return val descriptor = holder.manager.createProblemDescriptor( expression, expression.firstCalleeExpression()!!.textRange.shiftRight(-expression.startOffset), "${KotlinBundle.message("redundant.async.call.may.be.reduced.to.0", conversion.replacement)}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, generateFix(conversion) ) holder.registerProblem(descriptor) }) private val conversionGroups = conversions.group() companion object { private val conversions = listOf( Conversion( "$COROUTINE_PACKAGE.async", "$COROUTINE_PACKAGE.Deferred.await", "$COROUTINE_PACKAGE.withContext" ), Conversion( "$COROUTINE_EXPERIMENTAL_PACKAGE.async", "$COROUTINE_EXPERIMENTAL_PACKAGE.Deferred.await", "$COROUTINE_EXPERIMENTAL_PACKAGE.withContext" ) ) private const val GLOBAL_SCOPE = "kotlinx.coroutines.GlobalScope" private const val CONTEXT_ARGUMENT_NAME = "context" private const val START_ARGUMENT_NAME = "start" private const val DEFAULT_ASYNC_ARGUMENT = "$COROUTINE_PACKAGE.Dispatchers.Default" private const val DEFAULT_ASYNC_ARGUMENT_EXPERIMENTAL = "$COROUTINE_EXPERIMENTAL_PACKAGE.DefaultDispatcher" } } internal const val COROUTINE_PACKAGE = "kotlinx.coroutines" internal const val COROUTINE_EXPERIMENTAL_PACKAGE = "kotlinx.coroutines.experimental"
apache-2.0
fdab0631df35c410b47ad08def93899f
45.298507
158
0.63862
5.691743
false
false
false
false
apollographql/apollo-android
apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/transformation/add_required_fields.kt
1
4504
package com.apollographql.apollo3.ast.transformation import com.apollographql.apollo3.ast.GQLField import com.apollographql.apollo3.ast.GQLFragmentDefinition import com.apollographql.apollo3.ast.GQLFragmentSpread import com.apollographql.apollo3.ast.GQLInlineFragment import com.apollographql.apollo3.ast.GQLNode import com.apollographql.apollo3.ast.GQLOperationDefinition import com.apollographql.apollo3.ast.GQLSelectionSet import com.apollographql.apollo3.ast.NodeTransformer import com.apollographql.apollo3.ast.Schema import com.apollographql.apollo3.ast.SourceLocation import com.apollographql.apollo3.ast.TransformResult import com.apollographql.apollo3.ast.definitionFromScope import com.apollographql.apollo3.ast.leafType import com.apollographql.apollo3.ast.rootTypeDefinition import com.apollographql.apollo3.ast.transform fun addRequiredFields(operation: GQLOperationDefinition, schema: Schema): GQLOperationDefinition { val parentType = operation.rootTypeDefinition(schema)!!.name return operation.transform( AddRequiredFieldsTransformer( schema, parentType, emptySet() ) ) as GQLOperationDefinition } fun addRequiredFields(fragmentDefinition: GQLFragmentDefinition, schema: Schema): GQLFragmentDefinition { return fragmentDefinition.transform( AddRequiredFieldsTransformer( schema, fragmentDefinition.typeCondition.name, emptySet() ) ) as GQLFragmentDefinition } private class AddRequiredFieldsTransformer( val schema: Schema, val parentType: String, val parentFields: Set<String>, ) : NodeTransformer { override fun transform(node: GQLNode): TransformResult { if (node !is GQLSelectionSet) { return TransformResult.Continue } val selectionSet = node val hasFragment = selectionSet.selections.any { it is GQLFragmentSpread || it is GQLInlineFragment } val requiredFieldNames = schema.keyFields(parentType).toMutableSet() if (requiredFieldNames.isNotEmpty()) { requiredFieldNames.add("__typename") } val fieldNames = parentFields + selectionSet.selections.filterIsInstance<GQLField>().map { it.name }.toSet() var newSelections = selectionSet.selections.map { when (it) { is GQLInlineFragment -> { it.copy( selectionSet = it.selectionSet.transform( AddRequiredFieldsTransformer( schema, it.typeCondition.name, fieldNames + requiredFieldNames ) ) as GQLSelectionSet ) } is GQLFragmentSpread -> it is GQLField -> { val typeDefinition = it.definitionFromScope(schema, parentType)!! val newSelectionSet = it.selectionSet?.transform( AddRequiredFieldsTransformer( schema, typeDefinition.type.leafType().name, emptySet() ) ) as GQLSelectionSet? it.copy( selectionSet = newSelectionSet ) } } } val fieldNamesToAdd = (requiredFieldNames - fieldNames).toMutableList() if (hasFragment) { fieldNamesToAdd.add("__typename") } newSelections.filterIsInstance<GQLField>().forEach { /** * Verify that the fields we add won't overwrite an existing alias * This is not 100% correct as this validation should be made more globally */ check(!fieldNamesToAdd.contains(it.alias)) { "Field ${it.alias}: ${it.name} in $parentType conflicts with key fields" } } newSelections = newSelections + fieldNamesToAdd.map { buildField(it) } newSelections = if (hasFragment) { // remove the __typename if it exists // and add it again at the top so we're guaranteed to have it at the beginning of json parsing val typeNameField = newSelections.firstOrNull { (it as? GQLField)?.name == "__typename" } listOfNotNull(typeNameField) + newSelections.filter { (it as? GQLField)?.name != "__typename" } } else { newSelections } return TransformResult.Replace( selectionSet.copy( selections = newSelections ) ) } } private fun buildField(name: String): GQLField { return GQLField( name = name, arguments = null, selectionSet = null, sourceLocation = SourceLocation.UNKNOWN, directives = emptyList(), alias = null ) }
mit
a97e4b724e062ed8db5de7eb34313d2c
33.128788
112
0.678064
4.662526
false
false
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/BottomSheetScaffold.kt
3
17911
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.animation.core.AnimationSpec import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeightIn import androidx.compose.material.BottomSheetValue.Collapsed import androidx.compose.material.BottomSheetValue.Expanded import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.collapse import androidx.compose.ui.semantics.expand import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import kotlin.math.roundToInt /** * Possible values of [BottomSheetState]. */ @ExperimentalMaterialApi enum class BottomSheetValue { /** * The bottom sheet is visible, but only showing its peek height. */ Collapsed, /** * The bottom sheet is visible at its maximum height. */ Expanded } /** * State of the persistent bottom sheet in [BottomSheetScaffold]. * * @param initialValue The initial value of the state. * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @ExperimentalMaterialApi @Stable class BottomSheetState( initialValue: BottomSheetValue, animationSpec: AnimationSpec<Float> = SwipeableDefaults.AnimationSpec, confirmStateChange: (BottomSheetValue) -> Boolean = { true } ) : SwipeableState<BottomSheetValue>( initialValue = initialValue, animationSpec = animationSpec, confirmStateChange = confirmStateChange ) { /** * Whether the bottom sheet is expanded. */ val isExpanded: Boolean get() = currentValue == Expanded /** * Whether the bottom sheet is collapsed. */ val isCollapsed: Boolean get() = currentValue == BottomSheetValue.Collapsed /** * Expand the bottom sheet with animation and suspend until it if fully expanded or animation * has been cancelled. This method will throw [CancellationException] if the animation is * interrupted * * @return the reason the expand animation ended */ suspend fun expand() = animateTo(Expanded) /** * Collapse the bottom sheet with animation and suspend until it if fully collapsed or animation * has been cancelled. This method will throw [CancellationException] if the animation is * interrupted * * @return the reason the collapse animation ended */ suspend fun collapse() = animateTo(BottomSheetValue.Collapsed) companion object { /** * The default [Saver] implementation for [BottomSheetState]. */ fun Saver( animationSpec: AnimationSpec<Float>, confirmStateChange: (BottomSheetValue) -> Boolean ): Saver<BottomSheetState, *> = Saver( save = { it.currentValue }, restore = { BottomSheetState( initialValue = it, animationSpec = animationSpec, confirmStateChange = confirmStateChange ) } ) } internal val nestedScrollConnection = this.PreUpPostDownNestedScrollConnection } /** * Create a [BottomSheetState] and [remember] it. * * @param initialValue The initial value of the state. * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @Composable @ExperimentalMaterialApi fun rememberBottomSheetState( initialValue: BottomSheetValue, animationSpec: AnimationSpec<Float> = SwipeableDefaults.AnimationSpec, confirmStateChange: (BottomSheetValue) -> Boolean = { true } ): BottomSheetState { return rememberSaveable( animationSpec, saver = BottomSheetState.Saver( animationSpec = animationSpec, confirmStateChange = confirmStateChange ) ) { BottomSheetState( initialValue = initialValue, animationSpec = animationSpec, confirmStateChange = confirmStateChange ) } } /** * State of the [BottomSheetScaffold] composable. * * @param drawerState The state of the navigation drawer. * @param bottomSheetState The state of the persistent bottom sheet. * @param snackbarHostState The [SnackbarHostState] used to show snackbars inside the scaffold. */ @ExperimentalMaterialApi @Stable class BottomSheetScaffoldState( val drawerState: DrawerState, val bottomSheetState: BottomSheetState, val snackbarHostState: SnackbarHostState ) /** * Create and [remember] a [BottomSheetScaffoldState]. * * @param drawerState The state of the navigation drawer. * @param bottomSheetState The state of the persistent bottom sheet. * @param snackbarHostState The [SnackbarHostState] used to show snackbars inside the scaffold. */ @Composable @ExperimentalMaterialApi fun rememberBottomSheetScaffoldState( drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed), bottomSheetState: BottomSheetState = rememberBottomSheetState(BottomSheetValue.Collapsed), snackbarHostState: SnackbarHostState = remember { SnackbarHostState() } ): BottomSheetScaffoldState { return remember(drawerState, bottomSheetState, snackbarHostState) { BottomSheetScaffoldState( drawerState = drawerState, bottomSheetState = bottomSheetState, snackbarHostState = snackbarHostState ) } } /** * <a href="https://material.io/components/sheets-bottom#standard-bottom-sheet" class="external" target="_blank">Material Design standard bottom sheet</a>. * * Standard bottom sheets co-exist with the screen’s main UI region and allow for simultaneously * viewing and interacting with both regions. They are commonly used to keep a feature or * secondary content visible on screen when content in main UI region is frequently scrolled or * panned. * * ![Standard bottom sheet image](https://developer.android.com/images/reference/androidx/compose/material/standard-bottom-sheet.png) * * This component provides an API to put together several material components to construct your * screen. For a similar component which implements the basic material design layout strategy * with app bars, floating action buttons and navigation drawers, use the standard [Scaffold]. * For similar component that uses a backdrop as the centerpiece of the screen, use * [BackdropScaffold]. * * A simple example of a bottom sheet scaffold looks like this: * * @sample androidx.compose.material.samples.BottomSheetScaffoldSample * * @param sheetContent The content of the bottom sheet. * @param modifier An optional [Modifier] for the root of the scaffold. * @param scaffoldState The state of the scaffold. * @param topBar An optional top app bar. * @param snackbarHost The composable hosting the snackbars shown inside the scaffold. * @param floatingActionButton An optional floating action button. * @param floatingActionButtonPosition The position of the floating action button. * @param sheetGesturesEnabled Whether the bottom sheet can be interacted with by gestures. * @param sheetShape The shape of the bottom sheet. * @param sheetElevation The elevation of the bottom sheet. * @param sheetBackgroundColor The background color of the bottom sheet. * @param sheetContentColor The preferred content color provided by the bottom sheet to its * children. Defaults to the matching content color for [sheetBackgroundColor], or if that is * not a color from the theme, this will keep the same content color set above the bottom sheet. * @param sheetPeekHeight The height of the bottom sheet when it is collapsed. * @param drawerContent The content of the drawer sheet. * @param drawerGesturesEnabled Whether the drawer sheet can be interacted with by gestures. * @param drawerShape The shape of the drawer sheet. * @param drawerElevation The elevation of the drawer sheet. * @param drawerBackgroundColor The background color of the drawer sheet. * @param drawerContentColor The preferred content color provided by the drawer sheet to its * children. Defaults to the matching content color for [drawerBackgroundColor], or if that is * not a color from the theme, this will keep the same content color set above the drawer sheet. * @param drawerScrimColor The color of the scrim that is applied when the drawer is open. * @param content The main content of the screen. You should use the provided [PaddingValues] * to properly offset the content, so that it is not obstructed by the bottom sheet when collapsed. */ @Composable @ExperimentalMaterialApi fun BottomSheetScaffold( sheetContent: @Composable ColumnScope.() -> Unit, modifier: Modifier = Modifier, scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState(), topBar: (@Composable () -> Unit)? = null, snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) }, floatingActionButton: (@Composable () -> Unit)? = null, floatingActionButtonPosition: FabPosition = FabPosition.End, sheetGesturesEnabled: Boolean = true, sheetShape: Shape = MaterialTheme.shapes.large, sheetElevation: Dp = BottomSheetScaffoldDefaults.SheetElevation, sheetBackgroundColor: Color = MaterialTheme.colors.surface, sheetContentColor: Color = contentColorFor(sheetBackgroundColor), sheetPeekHeight: Dp = BottomSheetScaffoldDefaults.SheetPeekHeight, drawerContent: @Composable (ColumnScope.() -> Unit)? = null, drawerGesturesEnabled: Boolean = true, drawerShape: Shape = MaterialTheme.shapes.large, drawerElevation: Dp = DrawerDefaults.Elevation, drawerBackgroundColor: Color = MaterialTheme.colors.surface, drawerContentColor: Color = contentColorFor(drawerBackgroundColor), drawerScrimColor: Color = DrawerDefaults.scrimColor, backgroundColor: Color = MaterialTheme.colors.background, contentColor: Color = contentColorFor(backgroundColor), content: @Composable (PaddingValues) -> Unit ) { val scope = rememberCoroutineScope() BoxWithConstraints(modifier) { val fullHeight = constraints.maxHeight.toFloat() val peekHeightPx = with(LocalDensity.current) { sheetPeekHeight.toPx() } var bottomSheetHeight by remember { mutableStateOf(fullHeight) } val swipeable = Modifier .nestedScroll(scaffoldState.bottomSheetState.nestedScrollConnection) .swipeable( state = scaffoldState.bottomSheetState, anchors = mapOf( fullHeight - peekHeightPx to BottomSheetValue.Collapsed, fullHeight - bottomSheetHeight to Expanded ), orientation = Orientation.Vertical, enabled = sheetGesturesEnabled, resistance = null ) .semantics { if (peekHeightPx != bottomSheetHeight) { if (scaffoldState.bottomSheetState.isCollapsed) { expand { if (scaffoldState.bottomSheetState.confirmStateChange(Expanded)) { scope.launch { scaffoldState.bottomSheetState.expand() } } true } } else { collapse { if (scaffoldState.bottomSheetState.confirmStateChange(Collapsed)) { scope.launch { scaffoldState.bottomSheetState.collapse() } } true } } } } val child = @Composable { BottomSheetScaffoldStack( body = { Surface( color = backgroundColor, contentColor = contentColor ) { Column(Modifier.fillMaxSize()) { topBar?.invoke() content(PaddingValues(bottom = sheetPeekHeight)) } } }, bottomSheet = { Surface( swipeable .fillMaxWidth() .requiredHeightIn(min = sheetPeekHeight) .onGloballyPositioned { bottomSheetHeight = it.size.height.toFloat() }, shape = sheetShape, elevation = sheetElevation, color = sheetBackgroundColor, contentColor = sheetContentColor, content = { Column(content = sheetContent) } ) }, floatingActionButton = { Box { floatingActionButton?.invoke() } }, snackbarHost = { Box { snackbarHost(scaffoldState.snackbarHostState) } }, bottomSheetOffset = scaffoldState.bottomSheetState.offset, floatingActionButtonPosition = floatingActionButtonPosition ) } if (drawerContent == null) { child() } else { ModalDrawer( drawerContent = drawerContent, drawerState = scaffoldState.drawerState, gesturesEnabled = drawerGesturesEnabled, drawerShape = drawerShape, drawerElevation = drawerElevation, drawerBackgroundColor = drawerBackgroundColor, drawerContentColor = drawerContentColor, scrimColor = drawerScrimColor, content = child ) } } } @Composable private fun BottomSheetScaffoldStack( body: @Composable () -> Unit, bottomSheet: @Composable () -> Unit, floatingActionButton: @Composable () -> Unit, snackbarHost: @Composable () -> Unit, bottomSheetOffset: State<Float>, floatingActionButtonPosition: FabPosition ) { Layout( content = { body() bottomSheet() floatingActionButton() snackbarHost() } ) { measurables, constraints -> val placeable = measurables.first().measure(constraints) layout(placeable.width, placeable.height) { placeable.placeRelative(0, 0) val (sheetPlaceable, fabPlaceable, snackbarPlaceable) = measurables.drop(1).map { it.measure(constraints.copy(minWidth = 0, minHeight = 0)) } val sheetOffsetY = bottomSheetOffset.value.roundToInt() sheetPlaceable.placeRelative(0, sheetOffsetY) val fabOffsetX = when (floatingActionButtonPosition) { FabPosition.Center -> (placeable.width - fabPlaceable.width) / 2 else -> placeable.width - fabPlaceable.width - FabEndSpacing.roundToPx() } val fabOffsetY = sheetOffsetY - fabPlaceable.height / 2 fabPlaceable.placeRelative(fabOffsetX, fabOffsetY) val snackbarOffsetX = (placeable.width - snackbarPlaceable.width) / 2 val snackbarOffsetY = placeable.height - snackbarPlaceable.height snackbarPlaceable.placeRelative(snackbarOffsetX, snackbarOffsetY) } } } private val FabEndSpacing = 16.dp /** * Contains useful defaults for [BottomSheetScaffold]. */ object BottomSheetScaffoldDefaults { /** * The default elevation used by [BottomSheetScaffold]. */ val SheetElevation = 8.dp /** * The default peek height used by [BottomSheetScaffold]. */ val SheetPeekHeight = 56.dp }
apache-2.0
0f118300607eef624b4e052e8a284e59
39.244944
155
0.672846
5.353961
false
false
false
false
GunoH/intellij-community
plugins/kotlin/util/test-generator-fir/test/org/jetbrains/kotlin/fir/testGenerator/GenerateK2RefactoringsTests.kt
1
2781
// 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.fir.testGenerator import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractK2SafeDeleteTest import org.jetbrains.kotlin.testGenerator.model.* internal fun MutableTWorkspace.generateK2RefactoringsTests() { testGroup("refactorings/kotlin.refactorings.tests.k2", testDataPath = "../../idea/tests/testData") { testClass<AbstractK2SafeDeleteTest> { model("refactoring/safeDelete/deleteClass/kotlinClass", testMethodName = "doClassTest") //todo secondary constructor //model("refactoring/safeDelete/deleteClass/kotlinClassWithJava", testMethodName = "doClassTestWithJava") model("refactoring/safeDelete/deleteClass/javaClassWithKotlin", pattern = Patterns.JAVA, testMethodName = "doJavaClassTest") model("refactoring/safeDelete/deleteObject/kotlinObject", testMethodName = "doObjectTest") model("refactoring/safeDelete/deleteFunction/kotlinFunction", testMethodName = "doFunctionTest") model( "refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava", Patterns.forRegex("^(((?!secondary)(?!implement4).)+)\\.kt"),//todo secondary constructor, super method search from java override testMethodName = "doFunctionTestWithJava" ) model("refactoring/safeDelete/deleteFunction/javaFunctionWithKotlin", testMethodName = "doJavaMethodTest") model("refactoring/safeDelete/deleteProperty/kotlinProperty", testMethodName = "doPropertyTest") //model("refactoring/safeDelete/deleteProperty/kotlinPropertyWithJava", testMethodName = "doPropertyTestWithJava")//todo super method search from java override model("refactoring/safeDelete/deleteProperty/javaPropertyWithKotlin", testMethodName = "doJavaPropertyTest") model("refactoring/safeDelete/deleteTypeAlias/kotlinTypeAlias", testMethodName = "doTypeAliasTest") model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameter", testMethodName = "doTypeParameterTest") model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameterWithJava", testMethodName = "doTypeParameterTestWithJava") model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameter", testMethodName = "doValueParameterTest") model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameterWithJava", testMethodName = "doValueParameterTestWithJava") model("refactoring/safeDelete/deleteValueParameter/javaParameterWithKotlin", pattern = Patterns.JAVA, testMethodName = "doJavaParameterTest") } } }
apache-2.0
64898e4f0eaaf6abfc3ab23c21d7d756
83.30303
172
0.750449
5.496047
false
true
false
false
GunoH/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/SimpleFocusBorder.kt
7
1238
// 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.collaboration.ui import com.intellij.ide.ui.laf.darcula.DarculaUIUtil import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBInsets import com.intellij.util.ui.UIUtil import java.awt.Component import java.awt.Graphics import java.awt.Graphics2D import java.awt.Insets import javax.swing.border.Border class SimpleFocusBorder : Border { override fun paintBorder(c: Component?, g: Graphics?, x: Int, y: Int, width: Int, height: Int) { if (c?.hasFocus() == true && g is Graphics2D) { DarculaUIUtil.paintFocusBorder(g, width, height, 0f, true) } } override fun getBorderInsets(c: Component): Insets { val g2d = c.graphics as? Graphics2D ?: return JBInsets.emptyInsets() val bw = if (UIUtil.isUnderDefaultMacTheme()) JBUIScale.scale(3).toFloat() else DarculaUIUtil.BW.float val f = if (UIUtil.isRetina(g2d)) 0.5f else 1.0f val lw = if (UIUtil.isUnderDefaultMacTheme()) JBUIScale.scale(f) else DarculaUIUtil.LW.float val insets = (bw + lw).toInt() return Insets(insets, insets, insets, insets) } override fun isBorderOpaque() = false }
apache-2.0
72f3fbda24dd6c2009d0f322bfacc1cd
37.71875
120
0.736672
3.497175
false
false
false
false
GunoH/intellij-community
java/compiler/tests/com/intellij/compiler/artifacts/ElementsModificationTest.kt
3
16932
// 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.compiler.artifacts import com.intellij.openapi.application.WriteAction import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.packaging.artifacts.Artifact import com.intellij.packaging.artifacts.ArtifactManager import com.intellij.packaging.elements.PackagingElementFactory import com.intellij.packaging.impl.artifacts.PlainArtifactType import com.intellij.packaging.impl.elements.ExtractedDirectoryPackagingElement import com.intellij.packaging.impl.elements.FileCopyPackagingElement import com.intellij.packaging.impl.elements.LibraryPackagingElement import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.VfsTestUtil import com.intellij.testFramework.rules.ProjectModelRule import org.junit.Assert.assertEquals import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.File class ElementsModificationTest { @Rule @JvmField val projectModel = ProjectModelRule() @Test fun `create library artifact`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) WriteAction.runAndWait<RuntimeException> { val artifact = artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), PackagingElementFactory.getInstance().createArtifactRootElement()) val modifiableModel = artifactManager.createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) modifiableArtifact.rootElement.addOrFindChild(PackagingElementFactory.getInstance().createLibraryFiles("One", "project", null)) modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="project" name="One" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `rename library artifact`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createLibraryFiles("One", "project", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.libraryName = "AnotherName" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="project" name="AnotherName" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `change level of library artifact`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createLibraryFiles("One", "project", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.level = "Custom" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="Custom" name="One" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `change module name of library artifact`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createLibraryFiles("One", "module", "myModule")) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.moduleName = "AnotherModuleName" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="module" name="One" module-name="AnotherModuleName" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `change path in jar for extracted directory`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() val file = VfsTestUtil.createFile(projectModel.baseProjectDir.virtualFileRoot, "MyPath.jar", "") val jarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(file)!! rootElement.addOrFindChild(PackagingElementFactory.getInstance().createExtractedDirectory(jarRoot)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val element = mutableArtifact.rootElement.children[0] as ExtractedDirectoryPackagingElement element.pathInJar = "AnotherPath" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="extracted-dir" path="${'$'}PROJECT_DIR${'$'}/MyPath.jar" path-in-jar="AnotherPath" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `update file copy packaging element`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createFileCopy("myPath", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val element = mutableArtifact.rootElement.children[0] as FileCopyPackagingElement element.renamedOutputFileName = "Rename" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="file-copy" path="myPath" output-file-name="Rename" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `update file copy packaging element rename`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createFileCopy("myPath", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val element = mutableArtifact.rootElement.children[0] as FileCopyPackagingElement element.rename("Rename") modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="file-copy" path="myPath" output-file-name="Rename" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `update file copy packaging element set file path`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createFileCopy("myPath", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val element = mutableArtifact.rootElement.children[0] as FileCopyPackagingElement element.filePath = "AnotherFilePath" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="file-copy" path="AnotherFilePath" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `modification double modification`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createLibraryFiles("One", "project", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.libraryName = "Two" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="project" name="Two" /> | </root> | </artifact> |</component>""".trimMargin()) PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.libraryName = "Three" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="project" name="Three" /> | </root> | </artifact> |</component>""".trimMargin()) } @Test fun `modification with dispose`() { val project = projectModel.project val artifactManager = ArtifactManager.getInstance(project) val artifact = WriteAction.computeAndWait<Artifact, Throwable> { val rootElement = PackagingElementFactory.getInstance().createArtifactRootElement() rootElement.addOrFindChild(PackagingElementFactory.getInstance().createLibraryFiles("One", "project", null)) artifactManager.addArtifact("Artifact", PlainArtifactType.getInstance(), rootElement) } PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.libraryName = "Two" modifiableModel.dispose() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="project" name="One" /> | </root> | </artifact> |</component>""".trimMargin()) PlatformTestUtil.saveProject(project) WriteAction.runAndWait<RuntimeException> { val modifiableModel = artifactManager.createModifiableModel() val mutableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val libraryElement = mutableArtifact.rootElement.children[0] as LibraryPackagingElement libraryElement.libraryName = "Three" modifiableModel.commit() } PlatformTestUtil.saveProject(project) assertArtifactFileTextEquals(""" |<component name="ArtifactManager"> | <artifact name="Artifact"> | <output-path>${'$'}PROJECT_DIR${'$'}/out/artifacts/Artifact</output-path> | <root id="root"> | <element id="library" level="project" name="Three" /> | </root> | </artifact> |</component>""".trimMargin()) } private fun assertArtifactFileTextEquals(expectedText: String) { assertEquals(StringUtil.convertLineSeparators(expectedText), StringUtil.convertLineSeparators(File(projectModel.baseProjectDir.root, ".idea/artifacts/Artifact.xml").readText())) } companion object { @JvmField @ClassRule val appRule = ApplicationRule() } }
apache-2.0
995ae2ee13d0b080578be4553befa3e3
40.398533
158
0.714387
5.472527
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/textField.kt
1
4948
// 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.lockOrSkip import com.intellij.openapi.observable.util.transform import com.intellij.openapi.observable.util.whenTextChanged 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 java.util.concurrent.atomic.AtomicBoolean 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 (used instead of deprecated [GrowPolicy.SHORT_TEXT]) */ const val COLUMNS_SHORT = 18 /** * Columns for text components with medium width (used instead of deprecated [GrowPolicy.MEDIUM_TEXT]) */ 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) return applyToComponent { bind(property.transform({ it.toString() }, { component.getValidatedIntValue(it) })) } } 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.bind(property: ObservableMutableProperty<String>) { text = property.get() // See: IDEA-238573 removed cyclic update of UI components that bound with properties val mutex = AtomicBoolean() property.afterChange { mutex.lockOrSkip { text = it } } whenTextChanged { mutex.lockOrSkip { // Catch transformed GraphProperties, e.g. for intTextField catchValidationException { property.set(text) } } } } 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
db53052150298d515a314ebee98ba348
35.124088
158
0.758892
3.961569
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/PlayerFragment.kt
1
6073
package io.github.sdsstudios.ScoreKeeper.Fragment import android.app.Activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.DialogInterface import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.widget.TextInputEditText import android.support.design.widget.TextInputLayout import android.support.v7.app.AlertDialog import android.text.Editable import android.text.TextWatcher import android.view.View import com.theartofdev.edmodo.cropper.CropImage import com.theartofdev.edmodo.cropper.CropImageView import io.github.sdsstudios.ScoreKeeper.PlayerIconLayout import io.github.sdsstudios.ScoreKeeper.R import io.github.sdsstudios.ScoreKeeper.Utils.ColorUtils.getPlayerColors import io.github.sdsstudios.ScoreKeeper.Utils.FileUtils import io.github.sdsstudios.ScoreKeeper.ViewModels.PlayersViewModel import java.io.File import java.util.* /** * Created by sethsch1 on 04/11/17. */ abstract class PlayerFragment : BaseDialogFragment(), View.OnClickListener { companion object { val TAG: String get() = this::class.java.simpleName private const val REQUEST_CODE_GET_IMAGE = 1 } var selectedColor set(value) { mSelectPlayerColorsFragment.adapter.selectedColor = value } get() = mSelectPlayerColorsFragment.adapter.selectedColor val playerColors by lazy { getPlayerColors(resources) } var outputUri: Uri? = null lateinit var playersViewModel: PlayersViewModel lateinit var playerIconLayout: PlayerIconLayout lateinit var editTextName: TextInputEditText private lateinit var mTextInputLayoutName: TextInputLayout private val mSelectPlayerColorsFragment = SelectPlayerColorsFragment() override val layoutId = R.layout.fragment_player override val negText by lazy { getString(R.string.neg_cancel) } override val setOnClickListenersInOnShowDialog = true override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog { playersViewModel = ViewModelProviders.of(activity!!) .get(PlayersViewModel::class.java) return super.onCreateDialog(savedInstanceState) } override fun onDismiss(dialog: DialogInterface?) { if (deleteIconOnDismiss) deleteIconFile() super.onDismiss(dialog) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mTextInputLayoutName = view.findViewById(R.id.textInputLayoutName) mTextInputLayoutName.error = getString(R.string.error_can_not_be_empty) editTextName = view.findViewById(R.id.editTextName) editTextName.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { if (s.isNullOrEmpty()) { mTextInputLayoutName.error = getString(R.string.error_can_not_be_empty) return } if (mTextInputLayoutName.error != null) mTextInputLayoutName.error = null } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) playerIconLayout = view.findViewById(R.id.playerIconLayout) playerIconLayout.button.setOnClickListener(this) childFragmentManager.beginTransaction().replace( R.id.colorFragmentContainer, mSelectPlayerColorsFragment ).runOnCommit { playersViewModel.playerList.observe(this, Observer { setSelectedColorIndex() }) }.commit() } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { if (resultCode == Activity.RESULT_OK) { if (resultData != null) { when (requestCode) { REQUEST_CODE_GET_IMAGE -> { deleteIconFile() outputUri = Uri.fromFile(File( "${context!!.filesDir}/playerIcon${UUID.randomUUID()}.jpg")) val uri = resultData.data CropImage.activity(uri) .setOutputUri(outputUri) .setGuidelines(CropImageView.Guidelines.ON) .setCropShape(CropImageView.CropShape.RECTANGLE) .setAspectRatio(1, 1) .setFixAspectRatio(true) .start(context!!, this) } CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE -> { playerIconLayout.setIcon(getIconName()) } } } } } override fun onClick(view: View?) { when (view!!.id) { R.id.buttonEdit -> { if (playerIconLayout.buttonIsBrowse()) { startActivityForResult(browseIntent(), REQUEST_CODE_GET_IMAGE) } else if (playerIconLayout.buttonIsRemove()) { deleteIconFile() playerIconLayout.removeIcon() outputUri = null } } } } private fun getIconName() = outputUri?.pathSegments?.last() private fun browseIntent(): Intent = Intent(Intent.ACTION_GET_CONTENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "image/*" } private fun deleteIconFile() { if (outputUri != null) FileUtils.delete(outputUri!!.path) } override fun onPosClick() { if (mTextInputLayoutName.error == null) { onPositiveButtonClick(getIconName()) super.onPosClick() } } abstract fun setSelectedColorIndex() abstract fun onPositiveButtonClick(iconName: String?) abstract var deleteIconOnDismiss: Boolean }
gpl-3.0
25d7caa9688afdeea72ab8b713e442a6
34.313953
92
0.636259
4.986043
false
false
false
false
siosio/intellij-community
plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenImportingConnectorsTest.kt
1
11249
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.importing import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.idea.maven.MavenMultiVersionImportingTestCase import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.wizards.MavenOpenProjectProvider import org.junit.Test import java.io.File class MavenImportingConnectorsTest : MavenMultiVersionImportingTestCase() { protected lateinit var myAnotherProjectRoot: VirtualFile @Throws(Exception::class) override fun setUpInWriteAction() { super.setUpInWriteAction() val projectDir = File(myDir, "anotherProject") projectDir.mkdirs() myAnotherProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir)!! } @Test fun testShouldNotCreateNewConnectorForNewProject() { createProjectPom("<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>m1</module>" + " </modules>") createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>") importProject() assertModules("project1", "m1") val p2Root = createPomFile(myAnotherProjectRoot, "<groupId>test</groupId>" + "<artifactId>project2</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>m2</module>" + " </modules>") createModulePom("../anotherProject/m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>2</version>") MavenOpenProjectProvider().linkToExistingProject(p2Root, myProject) assertModules("project1", "m1", "project2", "m2") assertEquals(1, MavenServerManager.getInstance().allConnectors.size); assertUnorderedElementsAreEqual( MavenServerManager.getInstance().allConnectors.first().multimoduleDirectories.map { FileUtil.getRelativePath(myDir, File(it)) }, listOf("project", "anotherProject") ) } @Test fun testShouldCreateNewConnectorForNewProjectIfJvmConfigPresents() { createProjectPom("<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>m1</module>" + " </modules>") createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>") importProject() assertModules("project1", "m1") val p2Root = createPomFile(myAnotherProjectRoot, "<groupId>test</groupId>" + "<artifactId>project2</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>m2</module>" + " </modules>") createModulePom("../anotherProject/m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>2</version>") createProjectSubFile("../anotherProject/.mvn/jvm.config", "-Dsomething=blablabla") MavenOpenProjectProvider().linkToExistingProject(p2Root, myProject) assertModules("project1", "m1", "project2", "m2") assertEquals(2, MavenServerManager.getInstance().allConnectors.size); assertUnorderedElementsAreEqual( MavenServerManager.getInstance().allConnectors.map { FileUtil.getRelativePath(myDir, File(it.multimoduleDirectories.first())) }, listOf("project", "anotherProject") ) } @Test fun testShouldNotCreateNewConnectorForNewProjectIfJvmConfigPresentsAndRegistrySet() { createProjectPom("<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>m1</module>" + " </modules>") createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>") importProject() assertModules("project1", "m1") val p2Root = createPomFile(myAnotherProjectRoot, "<groupId>test</groupId>" + "<artifactId>project2</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>m2</module>" + " </modules>") createModulePom("../anotherProject/m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>2</version>") createProjectSubFile("../anotherProject/.mvn/jvm.config", "-Dsomething=blablabla") val value = Registry.`is`("maven.server.per.idea.project") try { Registry.get("maven.server.per.idea.project").setValue(true); MavenOpenProjectProvider().linkToExistingProject(p2Root, myProject) assertModules("project1", "m1", "project2", "m2") assertEquals(1, MavenServerManager.getInstance().allConnectors.size); assertUnorderedElementsAreEqual( MavenServerManager.getInstance().allConnectors.first().multimoduleDirectories.map { FileUtil.getRelativePath(myDir, File(it)) }, listOf("project", "anotherProject") ) } finally { Registry.get("maven.server.per.idea.project").setValue(value) } } @Test fun testShouldNotCreateNewConnectorsIfProjectRootIsInSiblingDir() { myProjectPom = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + "<module>../m1</module>" + " </modules>") createModulePom("m1", "<parent>\n" + " <groupId>test</groupId>\n" + " <artifactId>project1</artifactId>\n" + " <version>1</version>\n" + " <relativePath>../parent/pom.xml</relativePath>\n" + " </parent>") importProject() assertModules("project1", "m1") assertEquals(1, MavenServerManager.getInstance().allConnectors.size); assertUnorderedElementsAreEqual( MavenServerManager.getInstance().allConnectors.first().multimoduleDirectories.map { FileUtil.getRelativePath(myDir, File(it)) }.map { it?.replace("\\", "/") }, listOf("project/parent", "project/m1") ) } @Test fun testCreateNewConnectorsVmOptionsMvnAndSettings() { myProjectPom = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" ) val settingsComponent = MavenWorkspaceSettingsComponent.getInstance(myProject) settingsComponent.getSettings().getImportingSettings().setVmOptionsForImporter("-Dsomething=settings"); createProjectSubFile(".mvn/jvm.config", "-Dsomething=jvm") importProject() val allConnectors = MavenServerManager.getInstance().allConnectors assertEquals(1, allConnectors.size); val mavenServerConnector = allConnectors.elementAt(0) assertEquals("-Dsomething=settings", mavenServerConnector.vmOptions) } @Test fun testCreateNewConnectorsVmOptionsMvn() { myProjectPom = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" ) createProjectSubFile(".mvn/jvm.config", "-Dsomething=something") importProject() val allConnectors = MavenServerManager.getInstance().allConnectors assertEquals(1, allConnectors.size); val mavenServerConnector = allConnectors.elementAt(0) assertEquals("-Dsomething=something", mavenServerConnector.vmOptions) } @Test fun testCreateNewConnectorsVmOptionsSettings() { myProjectPom = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" ) val settingsComponent = MavenWorkspaceSettingsComponent.getInstance(myProject) settingsComponent.getSettings().getImportingSettings().setVmOptionsForImporter("-Dsomething=settings"); importProject() val allConnectors = MavenServerManager.getInstance().allConnectors assertEquals(1, allConnectors.size); val mavenServerConnector = allConnectors.elementAt(0) assertEquals("-Dsomething=settings", mavenServerConnector.vmOptions) } @Test fun testCreateNewConnectorsVmOptionsJvmXms() { myProjectPom = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" ) createProjectSubFile(".mvn/jvm.config", "-Xms800m") importProject() assertEquals(1, MavenServerManager.getInstance().allConnectors.size); } }
apache-2.0
334f6a0142664b60f992c2eb5aa8b026
46.268908
140
0.546804
5.442187
false
true
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/database/queries/HistoryQueries.kt
2
2291
package eu.kanade.tachiyomi.data.database.queries import com.pushtorefresh.storio.sqlite.queries.RawQuery import eu.kanade.tachiyomi.data.database.DbProvider import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory import eu.kanade.tachiyomi.data.database.resolvers.HistoryLastReadPutResolver import eu.kanade.tachiyomi.data.database.resolvers.MangaChapterHistoryGetResolver import eu.kanade.tachiyomi.data.database.tables.HistoryTable import java.util.* interface HistoryQueries : DbProvider { /** * Insert history into database * @param history object containing history information */ fun insertHistory(history: History) = db.put().`object`(history).prepare() /** * Returns history of recent manga containing last read chapter * @param date recent date range */ fun getRecentManga(date: Date) = db.get() .listOfObjects(MangaChapterHistory::class.java) .withQuery(RawQuery.builder() .query(getRecentMangasQuery()) .args(date.time) .observesTables(HistoryTable.TABLE) .build()) .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) .prepare() fun getHistoryByMangaId(mangaId: Long) = db.get() .listOfObjects(History::class.java) .withQuery(RawQuery.builder() .query(getHistoryByMangaId()) .args(mangaId) .observesTables(HistoryTable.TABLE) .build()) .prepare() /** * Updates the history last read. * Inserts history object if not yet in database * @param history history object */ fun updateHistoryLastRead(history: History) = db.put() .`object`(history) .withPutResolver(HistoryLastReadPutResolver()) .prepare() /** * Updates the history last read. * Inserts history object if not yet in database * @param historyList history object list */ fun updateHistoryLastRead(historyList: List<History>) = db.put() .objects(historyList) .withPutResolver(HistoryLastReadPutResolver()) .prepare() }
gpl-3.0
7273f9ce75bc84a459194683f8b10892
35.365079
81
0.65168
4.743271
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinNestedClassAllUsages.1.kt
4
622
package b import a.Outer public class X(bar: String? = Outer.A.bar): Outer.A() { var next: Outer.A? = Outer.A() val myBar: String? = Outer.A.bar init { Outer.A.bar = "" Outer.A.foo() } fun foo(a: Outer.A) { val aa: Outer.A = a aa.bar = "" } fun getNext(): Outer.A? { return next } public override fun foo() { super<Outer.A>.foo() } companion object: Outer.A() { } } object O: Outer.A() { } fun X.bar(a: Outer.A = Outer.A()) { } fun Any.toA(): Outer.A? { return if (this is Outer.A) this as Outer.A else null }
apache-2.0
2a0620e3ec188c648c7bd7630ba123b5
13.833333
57
0.512862
2.893023
false
false
false
false
sirekanyan/exif-sample-android
app/src/main/java/me/vadik/exif/MainActivity.kt
1
2735
package me.vadik.exif import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.content.Intent import android.content.Intent.ACTION_VIEW import android.content.pm.PackageManager.PERMISSION_GRANTED import android.support.media.ExifInterface import android.support.media.ExifInterface.* import android.net.Uri import android.os.Bundle import android.os.Environment import android.os.Environment.DIRECTORY_PICTURES import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.widget.Button import java.io.File import java.io.FileOutputStream class MainActivity : AppCompatActivity() { private companion object { private val DIRECTORY = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initButton(R.id.button0, ORIENTATION_UNDEFINED) initButton(R.id.button1, ORIENTATION_NORMAL) initButton(R.id.button2, ORIENTATION_FLIP_HORIZONTAL) initButton(R.id.button3, ORIENTATION_ROTATE_180) initButton(R.id.button4, ORIENTATION_FLIP_VERTICAL) initButton(R.id.button5, ORIENTATION_TRANSPOSE) initButton(R.id.button6, ORIENTATION_ROTATE_90) initButton(R.id.button7, ORIENTATION_TRANSVERSE) initButton(R.id.button8, ORIENTATION_ROTATE_270) } override fun onStart() { super.onStart() if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) { startActivity(Intent( ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null) )) } } private fun initButton(buttonResId: Int, orientation: Int) { val button = findViewById(buttonResId) as Button button.text = getString(R.string.button_text, orientation) button.setOnClickListener { val outputFile = File(DIRECTORY, "$orientation.jpg") assets.open(getString(R.string.input_filename)).use { input -> FileOutputStream(outputFile).use { output -> input.copyTo(output) } } outputFile.setOrientation(orientation) startActivity(Intent(ACTION_VIEW).setDataAndType(Uri.fromFile(outputFile), "image/*")) } } private fun File.setOrientation(orientation: Int) { ExifInterface(path).apply { setAttribute(TAG_ORIENTATION, orientation.toString()) saveAttributes() } } }
mit
9a6cd1a9da4688dbb3219505df86d6c2
37.521127
100
0.696892
4.612142
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/VectorBaseBottomSheetDialogFragment.kt
2
3131
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.fragments import android.content.Context import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import butterknife.ButterKnife import com.airbnb.mvrx.MvRx import com.airbnb.mvrx.MvRxView import com.airbnb.mvrx.MvRxViewModelStore import com.google.android.material.bottomsheet.BottomSheetDialogFragment import im.vector.R import im.vector.activity.VectorAppCompatActivity import java.util.* /** * Add MvRx capabilities to bottomsheetdialog (like BaseMvRxFragment) */ abstract class VectorBaseBottomSheetDialogFragment : BottomSheetDialogFragment(), MvRxView { override val mvrxViewModelStore by lazy { MvRxViewModelStore(viewModelStore) } private lateinit var mvrxPersistedViewId: String final override val mvrxViewId: String by lazy { mvrxPersistedViewId } @LayoutRes abstract fun getLayoutResId(): Int protected var vectorActivity: VectorAppCompatActivity? = null override fun onAttach(context: Context?) { super.onAttach(context) vectorActivity = context as VectorAppCompatActivity } override fun onDetach() { super.onDetach() vectorActivity = null } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(getLayoutResId(), container, false) ButterKnife.bind(this, view) return view } override fun onCreate(savedInstanceState: Bundle?) { mvrxViewModelStore.restoreViewModels(this, savedInstanceState) mvrxPersistedViewId = savedInstanceState?.getString(PERSISTED_VIEW_ID_KEY) ?: this::class.java.simpleName + "_" + UUID.randomUUID().toString() super.onCreate(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) mvrxViewModelStore.saveViewModels(outState) outState.putString(PERSISTED_VIEW_ID_KEY, mvrxViewId) } override fun onStart() { super.onStart() // This ensures that invalidate() is called for static screens that don't // subscribe to a ViewModel. postInvalidate() } protected fun setArguments(args: Parcelable? = null) { arguments = args?.let { Bundle().apply { putParcelable(MvRx.KEY_ARG, it) } } } } private const val PERSISTED_VIEW_ID_KEY = "mvrx:bottomsheet_persisted_view_id"
apache-2.0
e1bd0082fbed12c0e9791b5193633bb0
33.043478
116
0.735548
4.652303
false
false
false
false
AVnetWS/Hentoid
app/src/main/java/me/devsaki/hentoid/database/DuplicatesDAO.kt
1
2429
package me.devsaki.hentoid.database import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import io.objectbox.android.ObjectBoxLiveData import me.devsaki.hentoid.database.domains.Content import me.devsaki.hentoid.database.domains.DuplicateEntry class DuplicatesDAO(ctx: Context) { private val duplicatesDb: DuplicatesDB = DuplicatesDB.getInstance(ctx) private val db: ObjectBoxDB = ObjectBoxDB.getInstance(ctx) fun cleanup() { db.closeThreadResources() duplicatesDb.closeThreadResources() } fun getDbSizeBytes(): Long { return duplicatesDb.dbSizeBytes } fun getEntries(): List<DuplicateEntry> { val entries = duplicatesDb.selectEntriesQ().find() // Get all contents in one go val contentIds = entries.map { it.referenceId } val contents = db.selectContentById(contentIds) if (contents != null) { val contentsMap = contents.groupBy { it.id } // Map them back to the corresponding entry for (entry in entries) { entry.referenceContent = contentsMap[entry.referenceId]?.get(0) entry.duplicateContent = contentsMap[entry.duplicateId]?.get(0) } } return entries } fun getEntriesLive(): LiveData<List<DuplicateEntry>> { val livedata = ObjectBoxLiveData(duplicatesDb.selectEntriesQ()) // Get all contents in one go val livedata2 = MediatorLiveData<List<DuplicateEntry>>() livedata2.addSource(livedata) { it -> val enrichedItems = it.map { enrichWithContent(it) } livedata2.value = enrichedItems } return livedata2 } private fun enrichWithContent(e: DuplicateEntry): DuplicateEntry { val items: List<Content>? = db.selectContentById(mutableListOf(e.referenceId, e.duplicateId)) if (items != null && items.size > 1) { e.referenceContent = items[0] e.duplicateContent = items[1] } return e } fun clearEntries() { duplicatesDb.clearEntries() } fun insertEntry(entry: DuplicateEntry) { duplicatesDb.insertEntry(entry) } fun insertEntries(entry: List<DuplicateEntry>) { duplicatesDb.insertEntries(entry) } fun delete(entry: DuplicateEntry) { duplicatesDb.delete(entry) } }
apache-2.0
f987d29ce229f259fc21190ccd046fb0
30.153846
101
0.657061
4.3375
false
false
false
false
seventhroot/elysium
bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/warn/WarningCreateCommand.kt
1
4203
/* * Copyright 2020 Ren Binden * * 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.rpkit.moderation.bukkit.command.warn import com.rpkit.moderation.bukkit.RPKModerationBukkit import com.rpkit.moderation.bukkit.warning.RPKWarningImpl import com.rpkit.moderation.bukkit.warning.RPKWarningProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.players.bukkit.profile.RPKProfile import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.time.format.DateTimeFormatter class WarningCreateCommand(private val plugin: RPKModerationBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.moderation.command.warning.create")) { sender.sendMessage(plugin.messages["no-permission-warning-create"]) return true } if (args.size < 2) { sender.sendMessage(plugin.messages["warning-create-usage"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val targetPlayer = plugin.server.getPlayer(args[0]) if (targetPlayer == null) { sender.sendMessage(plugin.messages["warning-create-invalid-target"]) return true } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val targetMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(targetPlayer) if (targetMinecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val issuerMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (issuerMinecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val targetProfile = targetMinecraftProfile.profile if (targetProfile !is RPKProfile) { sender.sendMessage(plugin.messages["no-profile"]) return true } val issuerProfile = issuerMinecraftProfile.profile if (issuerProfile !is RPKProfile) { sender.sendMessage(plugin.messages["no-profile"]) return true } val warningReason = args.drop(1).joinToString(" ") val warningProvider = plugin.core.serviceManager.getServiceProvider(RPKWarningProvider::class) val warning = RPKWarningImpl(warningReason, targetProfile, issuerProfile) warningProvider.addWarning(warning) sender.sendMessage(plugin.messages["warning-create-valid", mapOf( Pair("reason", warningReason), Pair("issuer", issuerProfile.name), Pair("profile", targetProfile.name), Pair("time", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(warning.time)), Pair("index", warningProvider.getWarnings(targetProfile).size.toString()) )]) targetPlayer.sendMessage(plugin.messages["warning-received", mapOf( Pair("reason", warningReason), Pair("issuer", issuerProfile.name), Pair("profile", targetProfile.name), Pair("time", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(warning.time)), Pair("index", warningProvider.getWarnings(targetProfile).size.toString()) )]) return true } }
apache-2.0
0014b5dda213697fcfd22446aa01e291
43.723404
120
0.683559
4.831034
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/data/bodies/HunterPostBody.kt
2
2106
package nl.rsdt.japp.jotial.data.bodies import com.google.android.gms.maps.model.LatLng import com.google.gson.annotations.SerializedName import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 14-8-2016 * Description... */ class HunterPostBody { @SerializedName("SLEUTEL") private var sleutel: String? = null @SerializedName("hunter") private var hunter: String? = null @SerializedName("latitude") private var latitude: String? = null @SerializedName("longitude") private var longitude: String? = null @SerializedName("icon") private var icon: String? = null fun setKey(key: String?): HunterPostBody { this.sleutel = key return this } fun setName(name: String?): HunterPostBody { this.hunter = name return this } fun setLatLng(latLng: LatLng): HunterPostBody { this.latitude = latLng.latitude.toString() this.longitude = latLng.longitude.toString() return this } fun setIcon(icon: Int): HunterPostBody { this.icon = icon.toString() return this } fun prependDeelgebiedToName(dg: Deelgebied): HunterPostBody{ hunter = hunter?.replace('.', ' ') if (JappPreferences.prependDeelgebied){ hunter = "${dg.name}.$hunter" } else if(icon == "0"){ icon = "1" } return this } companion object { val default: HunterPostBody get() { val builder = HunterPostBody() var icon = JappPreferences.accountIcon val dg = JappPreferences.taak var huntname = JappPreferences.huntname if (huntname.isEmpty()){ huntname = JappPreferences.accountUsername } builder.setKey(JappPreferences.accountKey) builder.setIcon(icon) builder.setName(huntname) return builder } } }
apache-2.0
8b2ef65b0448851cbe3dce6c9ef5f8ca
24.682927
64
0.60019
4.461864
false
false
false
false
square/sqldelight
extensions/rxjava2-extensions/src/main/kotlin/com/squareup/sqldelight/runtime/rx/RxJavaExtensions.kt
1
2493
@file:JvmName("RxQuery") package com.squareup.sqldelight.runtime.rx import com.squareup.sqldelight.Query import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.ObservableOnSubscribe import io.reactivex.Scheduler import io.reactivex.annotations.CheckReturnValue import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.Optional import java.util.concurrent.atomic.AtomicBoolean /** * Turns this [Query] into an [Observable] which emits whenever the underlying result set changes. * * @param scheduler By default, emissions occur on the [Schedulers.io] scheduler but can be * optionally overridden. */ @CheckReturnValue @JvmOverloads @JvmName("toObservable") fun <T : Any> Query<T>.asObservable(scheduler: Scheduler = Schedulers.io()): Observable<Query<T>> { return Observable.create(QueryOnSubscribe(this)).observeOn(scheduler) } private class QueryOnSubscribe<T : Any>( private val query: Query<T> ) : ObservableOnSubscribe<Query<T>> { override fun subscribe(emitter: ObservableEmitter<Query<T>>) { val listenerAndDisposable = QueryListenerAndDisposable(emitter, query) query.addListener(listenerAndDisposable) emitter.setDisposable(listenerAndDisposable) emitter.onNext(query) } } private class QueryListenerAndDisposable<T : Any>( private val emitter: ObservableEmitter<Query<T>>, private val query: Query<T> ) : AtomicBoolean(), Query.Listener, Disposable { override fun queryResultsChanged() { emitter.onNext(query) } override fun isDisposed() = get() override fun dispose() { if (compareAndSet(false, true)) { query.removeListener(this) } } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOne(): Observable<T> { return map { it.executeAsOne() } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOneOrDefault(defaultValue: T): Observable<T> { return map { it.executeAsOneOrNull() ?: defaultValue } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOptional(): Observable<Optional<T>> { return map { Optional.ofNullable(it.executeAsOneOrNull()) } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToList(): Observable<List<T>> { return map { it.executeAsList() } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOneNonNull(): Observable<T> { return flatMap { val result = it.executeAsOneOrNull() if (result == null) Observable.empty() else Observable.just(result) } }
apache-2.0
24a8619460c9163a807c46c830657f32
29.036145
99
0.750501
4.093596
false
false
false
false
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/problem/rest/SameObjectNameTest.kt
1
2553
package org.evomaster.core.problem.rest import io.swagger.parser.OpenAPIParser import org.evomaster.core.problem.rest.param.BodyParam import org.evomaster.core.search.Action import org.evomaster.core.search.gene.ObjectGene import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class SameObjectNameTest { @Test fun test(){ val xyz1 = OpenAPIParser().readLocation("swagger/artificial/xyz1.json", null, null).openAPI val xyz1Cluster: MutableMap<String, Action> = mutableMapOf() RestActionBuilderV3.addActionsFromSwagger(xyz1, xyz1Cluster) assertEquals(1, xyz1Cluster.size) val xyz1post = xyz1Cluster["POST:/v1/xyz1"] assertTrue(xyz1post is RestCallAction) (xyz1post!! as RestCallAction).apply { assertEquals(1, parameters.size) assertTrue(parameters.first() is BodyParam) assertTrue((parameters.first().gene) is ObjectGene) (parameters.first().gene as ObjectGene).apply { assertEquals(4, fields.size) assertEquals("xyzf1", fields[0].name) assertEquals("xyzf2", fields[1].name) assertEquals("xyzf3", fields[2].name) assertEquals("xyzf4", fields[3].name) } } val xyz2 = OpenAPIParser().readLocation("swagger/artificial/xyz2.json", null, null).openAPI val xyz2Cluster: MutableMap<String, Action> = mutableMapOf() RestActionBuilderV3.addActionsFromSwagger(xyz2, xyz2Cluster) assertEquals(1, xyz2Cluster.size) val xyz2post = xyz2Cluster["POST:/v2/xyz2"] assertTrue(xyz2post is RestCallAction) (xyz2post!! as RestCallAction).apply { assertEquals(1, parameters.size) assertTrue(parameters.first() is BodyParam) assertTrue((parameters.first().gene) is ObjectGene) (parameters.first().gene as ObjectGene).apply { // assertEquals(4, fields.size) // assertEquals("xyzf1", fields[0].name) // assertEquals("xyzf2", fields[1].name) // assertEquals("xyzf3", fields[2].name) // assertEquals("xyzf4", fields[3].name) // but this should be 3 assertEquals(3, fields.size) assertEquals("f1", fields[0].name) assertEquals("f2", fields[1].name) assertEquals("f3", fields[2].name) } } } }
lgpl-3.0
6d9a7163ad8052fd128337fd4884ff6f
37.69697
99
0.627889
4.199013
false
true
false
false
ilya-g/kotlinx.collections.immutable
benchmarks/commonMain/src/benchmarks/immutableList/builder/Add.kt
1
2155
/* * Copyright 2016-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.txt file. */ package benchmarks.immutableList.builder import benchmarks.* import kotlinx.collections.immutable.PersistentList import kotlinx.benchmark.* @State(Scope.Benchmark) open class Add { @Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000, BM_10000000) var size: Int = 0 @Param(IP_100, IP_99_09, IP_95, IP_70, IP_50, IP_30, IP_0) var immutablePercentage: Double = 0.0 @Benchmark fun addLast(): PersistentList.Builder<String> { return persistentListBuilderAdd(size, immutablePercentage) } @Benchmark fun addLastAndIterate(bh: Blackhole) { val builder = persistentListBuilderAdd(size, immutablePercentage) for (e in builder) { bh.consume(e) } } @Benchmark fun addLastAndGet(bh: Blackhole) { val builder = persistentListBuilderAdd(size, immutablePercentage) for (i in 0 until builder.size) { bh.consume(builder[i]) } } /** * Adds [size] - 1 elements to an empty persistent list builder * and then inserts one element at the beginning. * * Measures mean time and memory spent per `add` operation. * * Expected time: nearly constant. * Expected memory: nearly constant. */ @Benchmark fun addFirst(): PersistentList.Builder<String> { val builder = persistentListBuilderAdd(size - 1, immutablePercentage) builder.add(0, "another element") return builder } /** * Adds [size] - 1 elements to an empty persistent list builder * and then inserts one element at the middle. * * Measures mean time and memory spent per `add` operation. * * Expected time: nearly constant. * Expected memory: nearly constant. */ @Benchmark fun addMiddle(): PersistentList.Builder<String> { val builder = persistentListBuilderAdd(size - 1, immutablePercentage) builder.add(size / 2, "another element") return builder } }
apache-2.0
134d0408b3140824ec4a7b799f253c99
28.944444
107
0.651972
4.144231
false
false
false
false
ibinti/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStreamProviderFactory.kt
4
5604
/* * 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.externalSystem.configurationStore import com.intellij.ProjectTopics import com.intellij.configurationStore.FileStorageAnnotation import com.intellij.configurationStore.StreamProviderFactory import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.module.Module import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.roots.ProjectModelElement import com.intellij.util.Function import org.jdom.Element import java.util.* private val EXTERNAL_MODULE_STORAGE_ANNOTATION = FileStorageAnnotation(StoragePathMacros.MODULE_FILE, false, ExternalModuleStorage::class.java) private val LOG = logger<ExternalSystemStreamProviderFactory>() // todo handle module rename internal class ExternalSystemStreamProviderFactory(private val project: Project) : StreamProviderFactory { val moduleStorage = ModuleFileSystemExternalSystemStorage(project) val fileStorage = ProjectFileSystemExternalSystemStorage(project) private var isStorageFlushInProgress = false init { // flush on save to be sure that data is saved (it is easy to reimport if corrupted (force exit, blue screen), but we need to avoid it if possible) ApplicationManager.getApplication().messageBus .connect(project) .subscribe(ProjectEx.ProjectSaved.TOPIC, ProjectEx.ProjectSaved { if (it === project && !isStorageFlushInProgress && moduleStorage.isDirty) { isStorageFlushInProgress = true ApplicationManager.getApplication().executeOnPooledThread { try { LOG.runAndLogException { moduleStorage.forceSave() } } finally { isStorageFlushInProgress = false } } } }) project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener { override fun moduleRemoved(project: Project, module: Module) { moduleStorage.remove(module.name) } override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) { for (module in modules) { moduleStorage.rename(oldNameProvider.`fun`(module), module.name) } } }) } override fun customizeStorageSpecs(component: PersistentStateComponent<*>, componentManager: ComponentManager, storages: List<Storage>, operation: StateStorageOperation): List<Storage>? { val project = componentManager as? Project ?: (componentManager as Module).project // we store isExternalStorageEnabled option in the project workspace file, so, for such components external storage is always disabled and not applicable if ((storages.size == 1 && storages.first().value == StoragePathMacros.WORKSPACE_FILE) || !project.isExternalStorageEnabled) { return null } if (componentManager is Project) { val fileSpec = storages.firstOrNull()?.value if (fileSpec == "libraries") { val result = ArrayList<Storage>(storages.size + 1) result.add(FileStorageAnnotation("$fileSpec.xml", false, ExternalProjectStorage::class.java)) result.addAll(storages) return result } } if (component !is ProjectModelElement) { return null } // Keep in mind - this call will require storage for module because module option values are used. // We cannot just check that module name exists in the nameToData - new external system module will be not in the nameToData because not yet saved. if (operation == StateStorageOperation.WRITE && component.externalSource == null) { return null } // on read we cannot check because on import module is just created and not yet marked as external system module, // so, we just add our storage as first and default storages in the end as fallback // on write default storages also returned, because default FileBasedStorage will remove data if component has external source val result = ArrayList<Storage>(storages.size + 1) if (componentManager is Project) { result.add(FileStorageAnnotation(storages.get(0).value, false, ExternalProjectStorage::class.java)) } else { result.add(EXTERNAL_MODULE_STORAGE_ANNOTATION) } result.addAll(storages) return result } fun readModuleData(name: String): Element? { val result = moduleStorage.read(name) if (result == null) { // todo we must detect situation when module was really stored but file was somehow deleted by user / corrupted // now we use file-based storage, and, so, not easy to detect this situation on start (because all modules data stored not in the one file, but per file) } return result } }
apache-2.0
d72aa026cfe64c24ebf45e08ebc92c73
43.484127
189
0.738044
4.843561
false
false
false
false
tommyettinger/SquidSetup
src/main/kotlin/com/github/czyzby/setup/views/platforms.kt
1
2040
package com.github.czyzby.setup.views import com.badlogic.gdx.scenes.scene2d.ui.Button import com.badlogic.gdx.scenes.scene2d.utils.Disableable import com.badlogic.gdx.utils.ObjectSet import com.github.czyzby.autumn.annotation.Processor import com.github.czyzby.autumn.context.Context import com.github.czyzby.autumn.context.ContextDestroyer import com.github.czyzby.autumn.context.ContextInitializer import com.github.czyzby.autumn.processor.AbstractAnnotationProcessor import com.github.czyzby.lml.annotation.LmlActor import com.github.czyzby.setup.data.platforms.Platform /** * Handles platform-related input. * @author MJ */ @Processor class PlatformsData : AbstractAnnotationProcessor<GdxPlatform>() { val platforms = mutableMapOf<String, Platform>() @LmlActor("androidSdk") private lateinit var androidSdk: Disableable @LmlActor("androidSdkButton") private lateinit var androidSdkButton: Disableable @LmlActor("\$platforms") private lateinit var platformButtons: ObjectSet<Button> fun toggleAndroidPlatform(active: Boolean) { androidSdk.isDisabled = !active androidSdkButton.isDisabled = !active } operator fun get(platformId: String): Platform = platforms[platformId]!! fun getSelectedPlatforms(): Map<String, Platform> = platformButtons.filter { it.isChecked }.map { platforms[it.name]!! }.associateBy { it.id } // Automatic scanning of platforms: override fun getSupportedAnnotationType(): Class<GdxPlatform> = GdxPlatform::class.java override fun isSupportingTypes(): Boolean = true override fun processType(type: Class<*>, annotation: GdxPlatform, component: Any, context: Context, initializer: ContextInitializer, contextDestroyer: ContextDestroyer) { val platform = component as Platform platforms[platform.id] = platform } } /** * Should annotate all libGDX platforms. * @author MJ */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class GdxPlatform
apache-2.0
77ef3232df2aac5e83c1cc5847731cbe
37.490566
103
0.758333
4.368308
false
false
false
false
GoldRenard/JuniperBotJ
modules/jb-module-ranking/src/main/java/ru/juniperbot/module/ranking/utils/GuildVoiceActivityTracker.kt
1
2887
/* * This file is part of JuniperBot. * * JuniperBot 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. * JuniperBot 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 JuniperBot. If not, see <http://www.gnu.org/licenses/>. */ package ru.juniperbot.module.ranking.utils import com.google.common.cache.CacheBuilder import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.VoiceChannel import ru.juniperbot.common.service.RankingConfigService import ru.juniperbot.module.ranking.model.MemberVoiceState import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit class GuildVoiceActivityTracker(private val configService: RankingConfigService, private val guildId: Long) { private val trackers = CacheBuilder.newBuilder() .concurrencyLevel(4) .expireAfterAccess(10, TimeUnit.DAYS) .build<Long, VoiceActivityTracker>()/* Channel Id */ val isEmpty: Boolean @Synchronized get() = trackers.size() == 0L /** * Starts voice activity recording for member * * @param channel Target voice channel * @param member Member to start record * @param frozen Whether is he frozen */ @Synchronized fun add(channel: VoiceChannel, member: Member, frozen: Boolean) { try { val tracker = trackers.get(channel.idLong) { VoiceActivityTracker(configService, guildId) } tracker.add(member, frozen) } catch (e: ExecutionException) { // ignore } } /** * Stops voice activity recording for member * * @param channel Target voice channel * @param member Member to start record * @return Pair of activity time and points */ @Synchronized fun remove(channel: VoiceChannel, member: Member): MemberVoiceState? { val tracker = trackers.getIfPresent(channel.idLong) ?: return null val state = tracker.remove(member) if (tracker.isEmpty) { trackers.invalidate(channel.idLong) } return state } /** * (Un-)Freezes member. Frozen members will not gain activity points. * * @param member Target member * @param frozen Whether is he frozen */ @Synchronized fun freeze(member: Member, frozen: Boolean) { trackers.asMap().forEach { (_, tracker) -> tracker.freeze(member, frozen) } } }
gpl-3.0
e24f42bb07fe8eebda0f0620fbb03655
33.783133
103
0.678213
4.517997
false
false
false
false
xwiki-contrib/android-authenticator
app/src/main/java/org/xwiki/android/sync/contactdb/BatchOperation.kt
1
3004
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.android.sync.contactdb import android.content.ContentProviderOperation import android.content.ContentResolver import android.content.OperationApplicationException import android.net.Uri import android.os.RemoteException import android.provider.ContactsContract import android.util.Log import java.util.* /** * Tag for logging. */ private val TAG = "BatchOperation" /** * This class handles execution of batch mOperations on Contacts provider. * * @version $Id: ee2b72a85bf367d574d8910e4cc22db931c20841 $ */ /** * Standard constructor. * * @param resolver Will be set to [.mResolver] */ class BatchOperation(private val mResolver: ContentResolver) { /** * Currently actual operations list. */ private val mOperations: ArrayList<ContentProviderOperation> init { mOperations = ArrayList() } /** * @return Currently not executed operations */ @Synchronized fun size(): Int { return mOperations.size } /** * Add operation to the list for future executing. * * @param cpo Operation for adding */ @Synchronized fun add(cpo: ContentProviderOperation) { mOperations.add(cpo) } /** * Execute operations which are stored in [.mOperations]. * * @return Result of executing [Uri]'s list */ @Synchronized fun execute(): List<Uri> { val resultUris = ArrayList<Uri>() if (mOperations.size == 0) { return resultUris } try { val results = mResolver.applyBatch( ContactsContract.AUTHORITY, mOperations ) if (results.size > 0) { for (result in results) { resultUris.add(result.uri) } } } catch (e1: OperationApplicationException) { Log.e(TAG, "storing contact data failed", e1) } catch (e2: RemoteException) { Log.e(TAG, "storing contact data failed", e2) } mOperations.clear() return resultUris } }
lgpl-2.1
da2c9b05c0a4f26a68f296ed8d02609e
26.309091
74
0.653462
4.379009
false
false
false
false
alt236/Under-the-Hood---Android
app/src/main/java/aws/apps/underthehood/ui/views/FontSizeChanger.kt
1
1027
package aws.apps.underthehood.ui.views import android.util.Log import android.util.TypedValue import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView class FontSizeChanger { val TAG = this.javaClass.name fun changeFontSize(t: TableLayout, fontSize: Float) { for (i in 0 until t.childCount) { val row = t.getChildAt(i) as TableRow for (j in 0 until row.childCount) { val v = row.getChildAt(j) try { if (v.javaClass == TextView::class.java) { val textView = v as TextView if (i % 2 == 0) { // DO NOTHING } else { textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize) } } } catch (e: Exception) { Log.e(TAG, "^ changeFontSize: ") } } } } }
apache-2.0
e379968301c33a2aeace351317084486
28.371429
86
0.487829
4.821596
false
false
false
false
t-yoshi/peca-android
core/src/main/java/org/peercast/core/PeerCastService.kt
1
9755
package org.peercast.core /** * (c) 2014, T Yoshizawa * Dual licensed under the MIT or GPL licenses. */ import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.net.Network import android.os.* import android.widget.Toast import androidx.annotation.BinderThread import androidx.annotation.MainThread import androidx.lifecycle.LifecycleService import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.peercast.core.common.AppPreferences import org.peercast.core.lib.PeerCastRpcClient import org.peercast.core.lib.internal.NotificationUtils import org.peercast.core.lib.internal.ServiceIntents import org.peercast.core.lib.notify.NotifyChannelType import org.peercast.core.lib.rpc.io.JsonRpcConnection import org.peercast.core.upnp.MiniUpnpManager import org.peercast.core.upnp.UpnpWorker import org.peercast.core.util.NotificationHelper import org.peercast.core.util.unzipFile import timber.log.Timber import java.io.File import java.io.IOException class PeerCastService : LifecycleService() { private lateinit var notificationHelper: NotificationHelper private val appPrefs by inject<AppPreferences>() private lateinit var connMan: ConnectivityManager private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { val cap = connMan.getNetworkCapabilities(network) Timber.d("onAvailable: $network, $cap") if (appPrefs.isUPnPEnabled) UpnpWorker.openPort(this@PeerCastService, nativeGetPort()) } } override fun onCreate() { super.onCreate() unzipHtmlDir() nativeStart(filesDir.absolutePath) notificationHelper = NotificationHelper(this) registerReceiver(commandReceiver, IntentFilter().also { it.addAction(ACTION_BUMP_CHANNEL) it.addAction(ACTION_STOP_CHANNEL) it.addAction(ACTION_CLEAR_CACHE) }) connMan = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connMan.registerNetworkCallback(MiniUpnpManager.REQ_TYPE_WIFI_ETHERNET, networkCallback) } private fun unzipHtmlDir() { //解凍済みを示す空フォルダ ex: 3.0.0-YT28 val d = File(filesDir, "${BuildConfig.VERSION_NAME}-${BuildConfig.YT_VERSION}") if (d.exists()) return try { assets.unzipFile("peca-yt.zip", filesDir) d.mkdir() } catch (e: IOException) { Timber.e(e, "html-dir install failed.") } } /** * 通知バーのボタンのイベントを処理する。 */ private val commandReceiver = object : BroadcastReceiver() { override fun onReceive(c: Context, intent: Intent) { fun runRpc(f: suspend PeerCastRpcClient.(String) -> Unit) = lifecycleScope.launch { val conn = JsonRpcConnection(port = nativeGetPort()) val client = PeerCastRpcClient(conn) runCatching { intent.getStringExtra(EX_CHANNEL_ID)?.let { client.f(it) } }.onFailure(Timber::e) } when (intent.action) { ACTION_BUMP_CHANNEL -> runRpc { bumpChannel(it) } ACTION_STOP_CHANNEL -> runRpc { stopChannel(it) } ACTION_CLEAR_CACHE -> nativeClearCache() else -> throw IllegalArgumentException("invalid action: $intent") } } } private val aidlBinder = object : IPeerCastService.Stub() { override fun getVersion() = BuildConfig.VERSION_CODE var callbacks = ArrayList<INotificationCallback>() @BinderThread override fun registerNotificationCallback(callback: INotificationCallback) { lifecycleScope.launch { callbacks.add(callback) } } @BinderThread override fun unregisterNotificationCallback(callback: INotificationCallback) { lifecycleScope.launch { callbacks.remove(callback) } } @MainThread fun fireNotifyChannel(notifyType: Int, chId: String, jsonChannelInfo: String) { fireEvent { it.onNotifyChannel(notifyType, chId, jsonChannelInfo) } } @MainThread fun fireNotifyMessage(notifyType: Int, message: String) { fireEvent { it.onNotifyMessage(notifyType, message) } } private fun fireEvent(f: (INotificationCallback) -> Unit) { val it = callbacks.listIterator() while (it.hasNext()) { kotlin.runCatching { f(it.next()) }.onFailure { e -> when (e) { is RemoteException, is SecurityException, -> { it.remove() Timber.w(e, "remove callback") } else -> throw e } } } } override fun getPort() = [email protected]() override fun setPort(port: Int) = [email protected](port) } override fun onBind(intent: Intent): IBinder? { super.onBind(intent) Timber.d("$intent") //NOTE: 同じインテントだとBinderはキャッシュされる //https://commonsware.com/blog/2011/07/02/about-binder-caching.html return when (intent.action) { ServiceIntents.ACT_PEERCAST_SERVICE -> { Toast.makeText(applicationContext, "Please update PeerCast app.", Toast.LENGTH_LONG) .show() null } ServiceIntents.ACT_PEERCAST_SERVICE4 -> aidlBinder else -> null } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { //フォアグラウンド状態のアプリからstartService() if (intent?.action == ServiceIntents.ACT_PEERCAST_SERVICE4) notificationHelper.isAllowedForeground = true return super.onStartCommand(intent, flags, startId) } override fun onUnbind(intent: Intent): Boolean { return false } override fun onDestroy() { super.onDestroy() unregisterReceiver(commandReceiver) notificationHelper.stopForeground() connMan.unregisterNetworkCallback(networkCallback) if (appPrefs.isUPnPEnabled) UpnpWorker.closePort(this@PeerCastService, nativeGetPort()) nativeQuit() } /** * ネイティブ側から呼ばれる。 * @see org.peercast.core.lib.notify.NotifyMessageType */ @Suppress("unused") private fun notifyMessage(notifyType: Int, message: String) { Timber.d("notifyMessage: $notifyType, $message") lifecycleScope.launch { aidlBinder.fireNotifyMessage(notifyType, message) } } /** * ネイティブ側から呼ばれる。 * @see org.peercast.core.lib.notify.NotifyChannelType */ @Suppress("unused") private fun notifyChannel(notifyType: Int, chId: String, jsonChannelInfo: String) { Timber.d("notifyChannel: $notifyType $chId $jsonChannelInfo") val chInfo = NotificationUtils.jsonToChannelInfo(jsonChannelInfo) ?: return // nativeStart時のnotificationHelperが未初期化なときに // 到達する場合があるのでimmediateにしない lifecycleScope.launch(Dispatchers.Main) { when (notifyType) { NotifyChannelType.Start.nativeValue -> notificationHelper.startChannel(chId, chInfo) NotifyChannelType.Update.nativeValue -> notificationHelper.updateChannel(chId, chInfo) NotifyChannelType.Stop.nativeValue -> notificationHelper.removeChannel(chId) else -> throw IllegalArgumentException() } aidlBinder.fireNotifyChannel(notifyType, chId, jsonChannelInfo) } } /** * PeerCastを開始します。 * * @param filesDirPath Context.getFilesDir() */ private external fun nativeStart(filesDirPath: String) /** * @param port 動作ポート (1025..65532) */ private external fun nativeSetPort(port: Int) external fun nativeGetPort(): Int external fun nativeClearCache(cmd: Int = CMD_CLEAR_HOST_CACHE or CMD_CLEAR_HIT_LISTS_CACHE) /** * PeerCastを終了します。 */ private external fun nativeQuit() companion object { // 通知ボタンAction const val ACTION_BUMP_CHANNEL = "org.peercast.core.ACTION.bumpChannel" const val ACTION_STOP_CHANNEL = "org.peercast.core.ACTION.stopChannel" const val ACTION_CLEAR_CACHE = "org.peercast.core.ACTION.clearCache" const val CMD_CLEAR_HOST_CACHE = 1 const val CMD_CLEAR_HIT_LISTS_CACHE = 2 const val CMD_CLEAR_CHANNELS_CACHE = 4 /**(String)*/ const val EX_CHANNEL_ID = "channelId" /** * クラス初期化に呼ぶ。 */ @JvmStatic private external fun nativeClassInit() init { System.loadLibrary("peercast") nativeClassInit() } } }
gpl-3.0
c012ab60282695742bb88455c6a6286f
31.596552
100
0.619063
4.549086
false
false
false
false
luxons/seven-wonders
sw-server/src/test/kotlin/org/luxons/sevenwonders/server/controllers/LobbyControllerTest.kt
1
8034
package org.luxons.sevenwonders.server.controllers import org.junit.Before import org.junit.Test import org.luxons.sevenwonders.model.Settings import org.luxons.sevenwonders.model.api.State import org.luxons.sevenwonders.model.api.actions.ReorderPlayersAction import org.luxons.sevenwonders.model.api.actions.UpdateSettingsAction import org.luxons.sevenwonders.server.lobby.Lobby import org.luxons.sevenwonders.server.lobby.Player import org.luxons.sevenwonders.server.lobby.PlayerIsNotOwnerException import org.luxons.sevenwonders.server.lobby.PlayerNotInLobbyException import org.luxons.sevenwonders.server.repositories.LobbyRepository import org.luxons.sevenwonders.server.repositories.PlayerNotFoundException import org.luxons.sevenwonders.server.repositories.PlayerRepository import org.luxons.sevenwonders.server.test.mockSimpMessagingTemplate import java.util.* import kotlin.test.* class LobbyControllerTest { private lateinit var playerRepository: PlayerRepository private lateinit var lobbyRepository: LobbyRepository private lateinit var lobbyController: LobbyController @Before fun setUp() { val template = mockSimpMessagingTemplate() playerRepository = PlayerRepository() lobbyRepository = LobbyRepository() lobbyController = LobbyController(lobbyRepository, playerRepository, template, "UNUSED") } @Test fun init_succeeds() { val owner = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", owner) assertTrue(lobby.getPlayers().contains(owner)) assertSame(lobby, owner.lobby) assertEquals(owner, lobby.owner) assertTrue(owner.isInLobby) assertFalse(owner.isInGame) } @Test fun leave_failsWhenPlayerDoesNotExist() { val principal = TestPrincipal("I don't exist") assertFailsWith<PlayerNotFoundException> { lobbyController.leave(principal) } } @Test fun leave_failsWhenNotInLobby() { playerRepository.createOrUpdate("testuser", "Test User") val principal = TestPrincipal("testuser") assertFailsWith<PlayerNotInLobbyException> { lobbyController.leave(principal) } } @Test fun leave_ownerAloneInLobby_succeedsAndRemovesLobby() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) val principal = TestPrincipal("testuser") lobbyController.leave(principal) assertFalse(lobbyRepository.list().contains(lobby)) assertFalse(player.isInLobby) assertFalse(player.isInGame) } @Test fun leave_ownerInLobbyWithOthers_succeedsAndTransfersOwnership() { val player1 = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player1) val player2 = addPlayer(lobby, "testuser2") val principal = TestPrincipal("testuser") lobbyController.leave(principal) assertTrue(lobbyRepository.list().contains(lobby)) assertFalse(lobby.getPlayers().contains(player1)) assertEquals(lobby.owner, player2) assertTrue(player2.isGameOwner) assertTrue(player2.isInLobby) assertFalse(player2.isInGame) assertFalse(player1.isGameOwner) assertFalse(player1.isInLobby) assertFalse(player1.isInGame) } @Test fun leave_succeedsWhenInALobby_asJoiner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) val player2 = addPlayer(lobby, "testuser2") val principal = TestPrincipal("testuser2") lobbyController.leave(principal) assertFalse(lobby.getPlayers().contains(player2)) assertFalse(player2.isInLobby) assertFalse(player2.isInGame) } @Test fun reorderPlayers_succeedsForOwner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) val player2 = addPlayer(lobby, "testuser2") val player3 = addPlayer(lobby, "testuser3") val player4 = addPlayer(lobby, "testuser4") val players = listOf(player, player2, player3, player4) assertEquals(players, lobby.getPlayers()) val reorderedPlayers = listOf(player3, player, player2, player4) val playerNames = reorderedPlayers.map { it.username } val reorderPlayersAction = ReorderPlayersAction(playerNames) val principal = TestPrincipal("testuser") lobbyController.reorderPlayers(reorderPlayersAction, principal) assertEquals(reorderedPlayers, lobby.getPlayers()) } @Test fun reorderPlayers_failsForJoiner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) val player2 = addPlayer(lobby, "testuser2") val player3 = addPlayer(lobby, "testuser3") val reorderedPlayers = listOf(player3, player, player2) val playerNames = reorderedPlayers.map { it.username } val reorderPlayersAction = ReorderPlayersAction(playerNames) val principal = TestPrincipal("testuser2") assertFailsWith<PlayerIsNotOwnerException> { lobbyController.reorderPlayers(reorderPlayersAction, principal) } } @Test fun updateSettings_succeedsForOwner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) addPlayer(lobby, "testuser2") addPlayer(lobby, "testuser3") addPlayer(lobby, "testuser4") assertEquals(Settings(), lobby.settings) val newSettings = Settings(12L, 5, false, 5, 5, 4, 10, 2, HashMap()) val updateSettingsAction = UpdateSettingsAction(newSettings) val principal = TestPrincipal("testuser") lobbyController.updateSettings(updateSettingsAction, principal) assertEquals(newSettings, lobby.settings) } @Test fun updateSettings_failsForJoiner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) addPlayer(lobby, "testuser2") addPlayer(lobby, "testuser3") val updateSettingsAction = UpdateSettingsAction(Settings()) val principal = TestPrincipal("testuser2") assertFailsWith<PlayerIsNotOwnerException> { lobbyController.updateSettings(updateSettingsAction, principal) } } @Test fun startGame_succeedsForOwner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) addPlayer(lobby, "testuser2") addPlayer(lobby, "testuser3") addPlayer(lobby, "testuser4") val principal = TestPrincipal("testuser") lobbyController.startGame(principal) assertSame(State.PLAYING, lobby.state) } @Test fun startGame_failsForJoiner() { val player = playerRepository.createOrUpdate("testuser", "Test User") val lobby = lobbyRepository.create("Test Game", player) addPlayer(lobby, "testuser2") addPlayer(lobby, "testuser3") val principal = TestPrincipal("testuser2") assertFailsWith<PlayerIsNotOwnerException> { lobbyController.startGame(principal) } } private fun addPlayer(lobby: Lobby, username: String): Player { val player = playerRepository.createOrUpdate(username, username) lobby.addPlayer(player) assertTrue(lobby.getPlayers().contains(player)) assertSame(lobby, player.lobby) assertTrue(player.isInLobby) assertFalse(player.isInGame) return player } }
mit
32213c6a9484d6f56f720ebc8351f574
33.333333
96
0.696664
4.643931
false
true
false
false
reid112/Reidit
app/src/main/java/ca/rjreid/reidit/di/module/DataModule.kt
1
2133
package ca.rjreid.reidit.di.module import android.content.Context import ca.rjreid.reidit.BuildConfig import ca.rjreid.reidit.data.DataManager import ca.rjreid.reidit.data.DataManagerImpl import ca.rjreid.reidit.data.remote.RedditService import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class DataModule { companion object { const val REDDIT_BASE_URL = "https://www.reddit.com" } @Provides @Singleton fun provideCache(context: Context) = Cache(context.cacheDir, 10 * 1024 * 1024.toLong()) @Provides @Singleton fun provideGsonConverterFactory(): GsonConverterFactory = GsonConverterFactory.create() @Provides @Singleton fun provideRxJavaCallAdapterFactory(): RxJava2CallAdapterFactory = RxJava2CallAdapterFactory.create() @Provides @Singleton fun provideOkHttpClient(cache: Cache): OkHttpClient = OkHttpClient().newBuilder() .cache(cache) .addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE }) .build() @Provides @Singleton fun provideRestAdapter(client: OkHttpClient, converterFactory: GsonConverterFactory, callAdapterFactory: RxJava2CallAdapterFactory): Retrofit { return Retrofit.Builder() .baseUrl(REDDIT_BASE_URL) .client(client) .addConverterFactory(converterFactory) .addCallAdapterFactory(callAdapterFactory) .build() } @Provides @Singleton fun providesRedditService(retrofit: Retrofit): RedditService = retrofit.create(RedditService::class.java) @Provides @Singleton fun providesDataManger(redditService: RedditService): DataManager = DataManagerImpl(redditService) }
apache-2.0
6f7f2f726ae71a4c5b1cbcd21d9a0287
35.793103
147
0.724801
5.018824
false
false
false
false
MaibornWolff/codecharta
analysis/import/SVNLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/input/metrics/CalendarWeekTest.kt
1
3171
package de.maibornwolff.codecharta.importer.svnlogparser.input.metrics import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.time.OffsetDateTime import java.time.ZoneOffset class CalendarWeekTest { private val zoneOffset = ZoneOffset.UTC @Test fun canCreateCalendarWeekFromADateTime() { // given val commitDateTime = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset) // when val kw = CalendarWeek.forDateTime(commitDateTime) // then assertThat(kw).isEqualTo(CalendarWeek(13, 2016)) } @Test fun calendarWeekProperlyCalculated_when_dayAtStartOfYear_and_weekInLastYear_and_53WeeksInLastYear() { // given val commitDateTime = OffsetDateTime.of(2016, 1, 3, 12, 0, 0, 0, zoneOffset) // when val kw = CalendarWeek.forDateTime(commitDateTime) // then assertThat(kw).isEqualTo(CalendarWeek(53, 2015)) // 2015 has 53 Weeks } @Test fun calendarWeekProperlyCalculated_when_dayAtStartOfYear_and_weekInLastYear_and_52WeeksInLastYear() { // given val commitDateTime = OffsetDateTime.of(2017, 1, 3, 12, 0, 0, 0, zoneOffset) // when val kw = CalendarWeek.forDateTime(commitDateTime) // then assertThat(kw).isEqualTo(CalendarWeek(1, 2017)) } @Test fun calendarWeekProperlyCalculated_when_dayAtEndOfYear_and_weekInNextYear() { // given val commitDateTime = OffsetDateTime.of(2018, 12, 31, 12, 0, 0, 0, zoneOffset) // when val kw = CalendarWeek.forDateTime(commitDateTime) // then assertThat(kw).isEqualTo(CalendarWeek(1, 2019)) } @Test fun weeksBetweenCommitsProperlyCalculated_when_52WeeksInYears() { // given val commitDateTime2 = OffsetDateTime.of(2018, 1, 11, 12, 0, 0, 0, zoneOffset) val commitDateTime3 = OffsetDateTime.of(2017, 12, 13, 12, 0, 0, 0, zoneOffset) val kw1 = CalendarWeek.forDateTime(commitDateTime2) val kw2 = CalendarWeek.forDateTime(commitDateTime3) // then assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw1)).isEqualTo(4) assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw2)).isEqualTo(-4) assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw1)).isEqualTo(0) assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw2)).isEqualTo(0) } @Test fun weeksBetweenCommitsProperlyCalculated_when_firstWeek_and_53WeeksInOldYear() { // given val commitDateTime2 = OffsetDateTime.of(2021, 1, 11, 12, 0, 0, 0, zoneOffset) val commitDateTime3 = OffsetDateTime.of(2020, 12, 13, 12, 0, 0, 0, zoneOffset) val kw1 = CalendarWeek.forDateTime(commitDateTime2) val kw2 = CalendarWeek.forDateTime(commitDateTime3) // then assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw1)).isEqualTo(5) assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw2)).isEqualTo(-5) assertThat(CalendarWeek.numberOfWeeksBetween(kw1, kw1)).isEqualTo(0) assertThat(CalendarWeek.numberOfWeeksBetween(kw2, kw2)).isEqualTo(0) } }
bsd-3-clause
5138e5c0f199c78f23c29b42a73a3d98
33.846154
105
0.680858
3.890798
false
true
false
false
googlecodelabs/odml-pathways
product-search/codelab2/android/starter/app/src/main/java/com/google/codelabs/productimagesearch/ObjectDetectorActivity.kt
2
9885
/** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.codelabs.productimagesearch import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.google.codelabs.productimagesearch.databinding.ActivityObjectDetectorBinding import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.objects.DetectedObject import com.google.mlkit.vision.objects.ObjectDetection import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions import com.google.mlkit.vision.objects.defaults.PredefinedCategory import java.io.File import java.io.FileOutputStream import java.io.IOException class ObjectDetectorActivity : AppCompatActivity() { companion object { private const val REQUEST_IMAGE_CAPTURE = 1000 private const val REQUEST_IMAGE_GALLERY = 1001 private const val TAKEN_BY_CAMERA_FILE_NAME = "MLKitDemo_" private const val IMAGE_PRESET_1 = "Preset1.jpg" private const val IMAGE_PRESET_2 = "Preset2.jpg" private const val IMAGE_PRESET_3 = "Preset3.jpg" private const val TAG = "MLKit-ODT" } private lateinit var viewBinding: ActivityObjectDetectorBinding private var cameraPhotoUri: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivityObjectDetectorBinding.inflate(layoutInflater) setContentView(viewBinding.root) initViews() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // After taking camera, display to Preview if (resultCode == RESULT_OK) { when (requestCode) { REQUEST_IMAGE_CAPTURE -> cameraPhotoUri?.let { this.setViewAndDetect( getBitmapFromUri(it) ) } REQUEST_IMAGE_GALLERY -> data?.data?.let { this.setViewAndDetect(getBitmapFromUri(it)) } } } } private fun initViews() { with(viewBinding) { ivPreset1.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_1)) ivPreset2.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_2)) ivPreset3.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_3)) ivCapture.setOnClickListener { dispatchTakePictureIntent() } ivGalleryApp.setOnClickListener { choosePhotoFromGalleryApp() } ivPreset1.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_1)) } ivPreset2.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2)) } ivPreset3.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_3)) } // Default display setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2)) } } /** * Update the UI with the input image and start object detection */ private fun setViewAndDetect(bitmap: Bitmap?) { bitmap?.let { // Clear the dots indicating the previous detection result viewBinding.ivPreview.drawDetectionResults(emptyList()) // Display the input image on the screen. viewBinding.ivPreview.setImageBitmap(bitmap) // Run object detection and show the detection results. runObjectDetection(bitmap) } } /** * Detect Objects in a given Bitmap */ private fun runObjectDetection(bitmap: Bitmap) { // Step 1: create ML Kit's InputImage object val image = InputImage.fromBitmap(bitmap, 0) // Step 2: acquire detector object val options = ObjectDetectorOptions.Builder() .setDetectorMode(ObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .build() val objectDetector = ObjectDetection.getClient(options) // Step 3: feed given image to detector and setup callback objectDetector.process(image) .addOnSuccessListener { results -> // Keep only the FASHION_GOOD objects val filteredResults = results.filter { result -> result.labels.indexOfFirst { it.text == PredefinedCategory.FASHION_GOOD } != -1 } // Visualize the detection result runOnUiThread { viewBinding.ivPreview.drawDetectionResults(filteredResults) } } .addOnFailureListener { // Task failed with an exception Log.e(TAG, it.message.toString()) } } /** * Show Camera App to take a picture based Intent */ private fun dispatchTakePictureIntent() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> // Ensure that there's a camera activity to handle the intent takePictureIntent.resolveActivity(packageManager)?.also { // Create the File where the photo should go val photoFile: File? = try { createImageFile(TAKEN_BY_CAMERA_FILE_NAME) } catch (ex: IOException) { // Error occurred while creating the File null } // Continue only if the File was successfully created photoFile?.also { cameraPhotoUri = FileProvider.getUriForFile( this, "com.google.codelabs.productimagesearch.fileprovider", it ) // Setting output file to take a photo takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPhotoUri) // Open camera based Intent. startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) } } ?: run { Toast.makeText(this, getString(R.string.camera_app_not_found), Toast.LENGTH_LONG) .show() } } } /** * Show gallery app to pick photo from intent. */ private fun choosePhotoFromGalleryApp() { startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { type = "image/*" addCategory(Intent.CATEGORY_OPENABLE) }, REQUEST_IMAGE_GALLERY) } /** * The output file will be stored on private storage of this app * By calling function getExternalFilesDir * This photo will be deleted when uninstall app. */ @Throws(IOException::class) private fun createImageFile(fileName: String): File { // Create an image file name val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( fileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ) } /** * Method to copy asset files sample to private app folder. * Return the Uri of an output file. */ private fun getBitmapFromAsset(fileName: String): Bitmap? { return try { BitmapFactory.decodeStream(assets.open(fileName)) } catch (ex: IOException) { null } } /** * Function to get the Bitmap From Uri. * Uri is received by using Intent called to Camera or Gallery app * SuppressWarnings => we have covered this warning. */ private fun getBitmapFromUri(imageUri: Uri): Bitmap? { val bitmap = try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, imageUri)) } else { // Add Suppress annotation to skip warning by Android Studio. // This warning resolved by ImageDecoder function. @Suppress("DEPRECATION") MediaStore.Images.Media.getBitmap(contentResolver, imageUri) } } catch (ex: IOException) { null } // Make a copy of the bitmap in a desirable format return bitmap?.copy(Bitmap.Config.ARGB_8888, false) } /** * Function to log information about object detected by ML Kit. */ private fun debugPrint(detectedObjects: List<DetectedObject>) { detectedObjects.forEachIndexed { index, detectedObject -> val box = detectedObject.boundingBox Log.d(TAG, "Detected object: $index") Log.d(TAG, " trackingId: ${detectedObject.trackingId}") Log.d(TAG, " boundingBox: (${box.left}, ${box.top}) - (${box.right},${box.bottom})") detectedObject.labels.forEach { Log.d(TAG, " categories: ${it.text}") Log.d(TAG, " confidence: ${it.confidence}") } } } }
apache-2.0
f197788fef37f2838c5e20a9c39efec4
37.166023
104
0.627213
5.097989
false
false
false
false
intellij-rust/intellij-rust
src/test/kotlin/org/rust/lang/core/resolve/RsTypeAwareResolveTest.kt
1
23281
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve import org.rust.CheckTestmarkHit import org.rust.lang.core.psi.RsTupleFieldDecl class RsTypeAwareResolveTest : RsResolveTestBase() { fun `test self method call expr`() = checkByCode(""" struct S; impl S { fn bar(self) { } //X fn foo(self) { self.bar() } //^ } """) fun `test trait impl method`() = checkByCode(""" trait T { fn foo(&self); } struct S; impl T for S { fn foo(&self) {} } //X fn foo(s: S) { s.foo() } //^ """) fun `test trait impl for various types`() { for (type in listOf("bool", "char", "&str", "u32", "f32", "f64", "()", "(i32)", "(i16,)", "(u32, u16)", "[u8; 1]", "&[u16]", "*const u8", "*const i8", "fn(u32) -> u8", "!")) { checkByCode(""" trait T { fn foo(&self) {} } impl T for $type { fn foo(&self) {} } //X fn test(s: $type) { s.foo() } //^ """) } } fun `test trait default method`() = checkByCode(""" trait T { fn foo(&self) {} } //X struct S; impl T for S { } fn foo(s: S) { s.foo() } //^ """) fun `test trait overridden default method`() = checkByCode(""" trait T { fn foo(&self) {} } struct S; impl T for S { fn foo(&self) {} } //X fn foo(s: S) { s.foo() } //^ """) fun `test method reference`() = checkByCode(""" //- main.rs mod x; use self::x::Stdin; fn main() { Stdin::read_line; //^ } //- x.rs pub struct Stdin { } impl Stdin { pub fn read_line(&self) { } //X } """) fun `test method call on trait object`() = stubOnlyResolve(""" //- main.rs mod aux; use aux::T; fn call_virtually(obj: &T) { obj.virtual_function() } //^ aux.rs //- aux.rs pub trait T { fn virtual_function(&self) {} } """) fun `test method inherent vs trait conflict`() = checkByCode(""" struct Foo; impl Foo { fn bar(&self) {} //X } trait Bar { fn bar(&self); } impl Bar for Foo { fn bar(&self) {} } fn main() { let foo = Foo; foo.bar(); //^ } """) fun `test self field expr`() = checkByCode(""" struct S { x: f32 } //X impl S { fn foo(&self) { self.x; } //^ } """) fun `test field expr`() = stubOnlyResolve(""" //- main.rs mod aux; use aux::S; fn main() { let s: S = S { x: 0. }; s.x; //^ aux.rs } //- aux.rs pub struct S { pub x: f32 } """) fun `test tuple field expr`() = checkByCode(""" struct T; impl T { fn foo(&self) {} } //X struct S(T); impl S { fn foo(&self) { let s = S(92.0); s.0.foo(); //^ } } """) fun `test tuple field expr out of bounds`() = checkByCode(""" struct S(f64); impl S { fn foo(&self) { let s: S = S(92.0); s.92; //^ unresolved } } """) fun `test tuple field expr suffix`() = checkByCode(""" struct S(f64); impl S { fn foo(&self) { let s: S = S(92.0); s.0u32; //^ unresolved } } """) fun `test nested field expr`() = checkByCode(""" struct Foo { bar: Bar } struct Bar { baz: i32 } //X fn main() { let foo = Foo { bar: Bar { baz: 92 } }; foo.bar.baz; //^ } """) fun `test let decl call expr`() = checkByCode(""" struct S { x: f32 } //X fn bar() -> S {} impl S { fn foo(&self) { let s = bar(); s.x; //^ } } """) fun `test let decl method call expr`() = checkByCode(""" struct S { x: f32 } //X impl S { fn bar(&self) -> S {} fn foo(&self) { let s = self.bar(); s.x; //^ } } """) fun `test let decl pat ident expr`() = checkByCode(""" struct S { x: f32 } //X impl S { fn foo(&self) { let s = S { x: 0. }; s.x; //^ } } """) fun `test let decl pat tup expr`() = checkByCode(""" struct S { x: f32 } //X impl S { fn foo(&self) { let (_, s) = ((), S { x: 0. }); s.x; //^ } } """) fun `test let decl pat struct expr`() = checkByCode(""" struct S { x: f32 } impl S { fn foo(&self) { let S { x: x } = S { x: 0. }; //X x; //^ } } """) fun `test let struct literal field`() = checkByCode(""" struct S { x: f32 } //X impl S { fn foo(&self) { let S { x: x } = S { x: 0. }; //^ x; } } """) fun `test let decl pat struct field`() = checkByCode(""" struct S { x: f32 } //X impl S { fn foo(&self) { let S { x: x } = S { x: 0. }; //^ x; } } """) fun `test let tuple literal field`() = checkByCodeGeneric<RsTupleFieldDecl>(""" struct S (f32); //X fn foo() { let S { 0: x } = S { 0: 0. }; //^ x; } """) fun `test let decl pat tuple field`() = checkByCodeGeneric<RsTupleFieldDecl>(""" struct S (f32); //X fn foo() { let S { 0: x } = S { 0: 0. }; //^ x; } """) fun `test let decl pat struct expr complex`() = checkByCode(""" struct S { x: f32 } //X struct X { s: S } impl S { fn foo(&self) { let X { s: f } = X { s: S { x: 0. } }; f.x; //^ } } """) fun `test associated fn from inherent impl`() = checkByCode(""" struct S; impl S { fn test() { } } //X fn main() { S::test(); } //^ """) fun `test associated function inherent vs trait conflict`() = checkByCode(""" struct Foo; impl Foo { fn bar() {} //X } trait Bar { fn bar(); } impl Bar for Foo { fn bar() {} } fn main() { Foo::bar(); //^ } """) fun `test hidden inherent impl`() = checkByCode(""" struct S; fn main() { let s: S = S; s.transmogrify(); //^ } mod hidden { use super::S; impl S { pub fn transmogrify(self) -> S { S } } //X } """) fun `test wrong inherent impl`() = checkByCode(""" struct S; fn main() { let s: S = S; s.transmogrify(); //^ unresolved } mod hidden { struct S; impl S { pub fn transmogrify(self) -> S { S } } } """) fun `test non inherent impl 1`() = checkByCode(""" struct S; mod m { trait T { fn foo(); } } mod hidden { use super::S; use super::m::T; impl T for S { fn foo() {} } //X } fn main() { use m::T; let _ = S::foo(); //^ } """) fun `test self implements trait`() = checkByCode(""" trait Foo { fn foo(&self); //X fn bar(&self) { self.foo(); } //^ } """) fun `test self implements trait from bound`() = checkByCode(""" trait Bar { fn bar(&self); //X } trait Foo : Bar { fn foo(&self) { self.bar(); } //^ } """) fun `test self implements trait from where clause bound`() = checkByCode(""" trait Bar { fn bar(&self); //X } trait Foo where Self : Bar { fn foo(&self) { self.bar(); } } //^ """) fun `test match enum tuple variant`() = checkByCode(""" enum E { V(S) } struct S; impl S { fn frobnicate(&self) {} } //X impl E { fn foo(&self) { match *self { E::V(ref s) => s.frobnicate() } //^ } } """) fun `test static`() = checkByCode(""" struct S { field: i32 } //X const FOO: S = S { field: 92 }; fn main() { FOO.field; } //^ """) fun `test string slice resolve`() = checkByCode(""" impl<T> &str { fn foo(&self) {} //X } fn main() { "test".foo(); //^ } """) fun `test slice resolve`() = checkByCode(""" impl<T> [T] { fn foo(&self) {} //X } fn main() { let x: &[i32]; x.foo(); //^ } """) fun `test slice resolve UFCS`() = checkByCode(""" impl<T> [T] { fn foo(&self) {} //X } fn main() { let x: &[i32]; <[i32]>::foo(x); //^ } """) fun `test array coercing to slice resolve`() = checkByCode(""" impl<T> [T] { fn foo(&self) {} //X } fn main() { let x: [i32; 1]; x.foo(); //^ } """) // https://github.com/intellij-rust/intellij-rust/issues/1269 fun `test tuple field`() = checkByCode(""" struct Foo; impl Foo { fn foo(&self) { unimplemented!() } //X } fn main() { let t = (1, Foo); t.1.foo(); //^ } """) fun `test array to slice`() = checkByCode(""" struct Foo; impl Foo { fn foo(&self) { unimplemented!() } //X } fn foo<T>(xs: &[T]) -> T { unimplemented!() } fn main() { let x = foo(&[Foo, Foo]); x.foo() //^ } """) fun `test tuple paren cast 1`() = checkByCode(""" struct Foo; impl Foo { fn foo(&self) {} } //X fn main() { let foo = unimplemented!() as (Foo); foo.foo(); } //^ """) fun `test tuple paren cast 2`() = checkByCode(""" struct Foo; impl Foo { fn foo(&self) {} } fn main() { let foo = unimplemented!() as (Foo,); foo.foo(); } //^ unresolved """) // https://github.com/intellij-rust/intellij-rust/issues/1549 fun `test Self type in assoc function`() = checkByCode(""" struct Foo; impl Foo { fn new() -> Self { unimplemented!() } fn bar(&self) {} //X } fn main() { let foo = Foo::new(); foo.bar(); //^ } """) fun `test incomplete dot expr`() = checkByCode(""" struct Foo; impl Foo { fn foo(&self) {} //X } fn main() { Foo.foo(). //^ } """) fun `test impl trait for mutable reference`() = checkByCode(""" struct Foo; trait T { fn foo(self); } impl<'a> T for &'a Foo { fn foo(self) {} } impl<'a> T for &'a mut Foo { fn foo(self) {} } //X fn main() { let foo = &mut Foo {}; foo.foo(); } //^ """) fun `test impl trait for mutable pointer`() = checkByCode(""" struct Foo; trait T { fn foo(self); } impl T for *const Foo { fn foo(self) {} } impl T for *mut Foo { fn foo(self) {} } //X fn main() { let foo = &mut Foo {} as *mut Foo; foo.foo(); } //^ """) fun `test impl trait for integer`() = checkByCode(""" trait T { fn foo(self); } impl T for u8 { fn foo(self) {} } //X fn main() { 0.foo(); } //^ """) fun `test impl trait for float`() = checkByCode(""" trait T { fn foo(self); } impl T for f32 { fn foo(self) {} } //X fn main() { 0.0.foo(); } //^ """) fun `test impl trait for integer reference`() = checkByCode(""" trait T { fn foo(self); } impl T for &u8 { fn foo(self) {} } //X fn main() { (&0).foo(); } //^ """) fun `test multiple impl trait for integer`() = checkByCode(""" trait T { fn foo(self); } impl T for u8 { fn foo(self) {} } impl T for i32 { fn foo(self) {} } //X fn main() { 0.foo(); } //^ """) fun `test resolve UFCS method call`() = checkByCode(""" struct S; trait T { fn foo(&self); } impl T for S { fn foo(&self) {} } //X fn main() { T::foo(&S); } //^ """) fun `test resolve trait associated function`() = checkByCode(""" struct S; trait T { fn foo() -> Self; } impl T for S { fn foo() -> Self { unimplemented!() } } //X fn main() { let a: S = T::foo(); } //^ """) fun `test resolve impl Trait method`() = checkByCode(""" trait Trait { fn bar(self); } //X fn foo() -> impl Trait { unimplemented!() } fn main() { foo().bar(); } //^ """) fun `test resolve impl Trait1+Trait2 method of Trait1`() = checkByCode(""" trait Trait1 { fn bar(self); } //X trait Trait2 { fn baz(self); } fn foo() -> impl Trait1+Trait2 { unimplemented!() } fn main() { foo().bar(); //^ } """) fun `test resolve impl Trait1+Trait2 method of Trait2`() = checkByCode(""" trait Trait1 { fn bar(self); } trait Trait2 { fn baz(self); } //X fn foo() -> impl Trait1+Trait2 { unimplemented!() } fn main() { foo().baz(); //^ } """) fun `test trait object inherent impl`() = checkByCode(""" trait Test{} impl dyn Test{ fn test(&self){} //X } fn main(){ let a:&dyn Test = unimplemented!(); a.test() //^ } """) fun `test trait object method wins over non-inherent trait impl`() = checkByCode(""" trait Foo { fn bar(&self) {} } //X trait Bar { fn bar(&self); } impl Bar for dyn Foo { fn bar(&self) {} } fn foo(a: &(dyn Foo + 'static)) { (*a).bar() } //^ """) fun `test filter methods from dangling (not attached to some crate) rust files`() = stubOnlyResolve(""" //- dangling.rs trait Tr { fn foo(self); } impl Tr for u8 { fn foo(self){} } //- main.rs fn main() { 0u8.foo(); } //^ unresolved """) fun `test dbg macro`() = checkByCode(""" struct Foo; impl Foo { fn foo(&self) {} //X } fn main() { dbg!(Foo).foo(); //^ } """) // The go-to-declaration behavior differs in this case. See `RsGotoDeclarationTest` @CheckTestmarkHit(NameResolutionTestmarks.SelfRelatedTypeSpecialCase::class) fun `test Self-qualified path in trait impl is resolved to assoc type of current impl`() = checkByCode(""" struct S; trait Trait { type Item; //X fn foo() -> Self::Item; } impl Trait for S { type Item = i32; fn foo() -> Self::Item { unreachable!() } } //^ """) @CheckTestmarkHit(NameResolutionTestmarks.SelfRelatedTypeSpecialCase::class) fun `test Self-qualified path in trait impl is not resolved to assoc type of another trait`() = checkByCode(""" struct S; trait Trait1 { type Item; } trait Trait2 { fn foo() -> i32; } impl Trait1 for S { type Item = i32; } impl Trait2 for S { fn foo() -> Self::Item { unreachable!() } } //^ unresolved """) // The go-to-declaration behavior differs in this case. See `RsGotoDeclarationTest` @CheckTestmarkHit(NameResolutionTestmarks.SelfRelatedTypeSpecialCase::class) fun `test Self-qualified path in trait impl is resolved to assoc type of super trait`() = checkByCode(""" struct S; trait Trait1 { type Item; } //X trait Trait2: Trait1 { fn foo() -> i32; } impl Trait1 for S { type Item = i32; } impl Trait2 for S { fn foo() -> Self::Item { unreachable!() } } //^ """) fun `test explicit UFCS-like type-qualified path`() = checkByCode(""" struct S; impl S { fn foo() {} } //X fn main () { <S>::foo; } //^ """) fun `test module wins over primitive type`() = checkByCode(""" mod f64 { pub const INFINITY: f64 = 0.0; } //X trait T { const INFINITY: Self; } impl T for f64 { const INFINITY: Self = 17.0; } fn main() { let a = f64::INFINITY; } //^ """) fun `test impl for alias`() = checkByCode(""" struct X; type Y = X; impl Y { fn foo(&self) {} } //X fn main() { X.foo(); } //^ """) fun `test impl for alias with multiple aliases with the same name`() = checkByCode(""" mod a { pub struct X; pub type Y = X; impl Y { pub fn foo(&self) {} } } mod b { pub struct X; pub type Y = X; impl Y { pub fn foo(&self) {} } //X } mod c { pub struct X; pub type Y = X; impl Y { pub fn foo(&self) {} } } fn main() { b::X.foo(); } //^ """) fun `test primitive vs mod`() = checkByCode(""" mod impls { #[lang = "str"] impl str { pub fn trim() {} } } mod str { pub fn trim() {} } //X fn main() { str::trim(); } //^ """) fun `test primitive vs mod 2`() = checkByCode(""" mod impls { #[lang = "str"] impl str { pub fn trim() {} } //X } mod str {} fn main() { str::trim(); } //^ """) fun `test impl for a macro type`() = checkByCode(""" struct S; macro_rules! foo { () => { S }; } impl foo!() { fn bar(self) {} } //X fn main() { S.bar(); } //^ """) fun `test method in impl for reference`() = checkByCode(""" trait Foo { fn foo(self); } struct S; impl<'a> Foo for &'a S { fn foo(self) { } } //X fn bar(s: S) { s.foo(); } //^ """) fun `test method in impl for mut reference`() = checkByCode(""" trait Foo { fn foo(self); } struct S; impl<'a> Foo for &'a mut S { fn foo(self) { } } //X fn bar(mut s: S) { s.foo(); } //^ """) fun `test method in impl for reference with mut ref receiver`() = checkByCode(""" trait Foo { fn foo(self); } struct S; impl<'a> Foo for &'a S { fn foo(self) { } } //X fn bar(s: &mut S) { s.foo(); } //^ """) fun `test method in impl for mut reference with ref receiver`() = checkByCode(""" trait Foo { fn foo(self); } struct S; impl<'a> Foo for &'a mut S { fn foo(self) { } } //X fn bar(s: &S) { s.foo(); } //^ """) fun `test resolve impl from a file included into multiple crates 1`() = stubOnlyResolve(""" //- tests/foo.rs pub struct Foo; impl Foo { pub fn foo(&self) {} } //- tests/a.rs mod foo; fn main() { foo::Foo.foo(); } //^ tests/foo.rs //- tests/b.rs mod foo; fn main() { foo::Foo.foo(); } """) fun `test resolve impl from a file included into multiple crates 2`() = stubOnlyResolve(""" //- tests/foo.rs pub struct Foo; impl Foo { pub fn foo(&self) {} } //- tests/a.rs mod foo; fn main() { foo::Foo.foo(); } //- tests/b.rs mod foo; fn main() { foo::Foo.foo(); } //^ tests/foo.rs """) }
mit
407182748a57fc7387894f204b0fb7ff
22.587639
115
0.368584
4.340231
false
true
false
false
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/api/BlueApiController.kt
1
48291
package org.openapitools.api import org.openapitools.model.BranchImpl import org.openapitools.model.FavoriteImpl import org.openapitools.model.GithubOrganization import org.openapitools.model.GithubScm import org.openapitools.model.MultibranchPipeline import org.openapitools.model.Organisation import org.openapitools.model.Pipeline import org.openapitools.model.PipelineActivity import org.openapitools.model.PipelineFolderImpl import org.openapitools.model.PipelineImpl import org.openapitools.model.PipelineRun import org.openapitools.model.PipelineRunNode import org.openapitools.model.PipelineStepImpl import org.openapitools.model.QueueItemImpl import org.openapitools.model.User import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* import io.swagger.v3.oas.annotations.media.* import io.swagger.v3.oas.annotations.responses.* import io.swagger.v3.oas.annotations.security.* import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.validation.annotation.Validated import org.springframework.web.context.request.NativeWebRequest import org.springframework.beans.factory.annotation.Autowired import javax.validation.Valid import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import kotlin.collections.List import kotlin.collections.Map @RestController @Validated @RequestMapping("\${api.base-path:}") class BlueApiController() { @Operation( summary = "", operationId = "deletePipelineQueueItem", description = "Delete queue item from an organization pipeline queue", responses = [ ApiResponse(responseCode = "200", description = "Successfully deleted queue item"), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.DELETE], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/queue/{queue}"] ) fun deletePipelineQueueItem(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the queue item", required = true) @PathVariable("queue") queue: kotlin.String): ResponseEntity<Unit> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getAuthenticatedUser", description = "Retrieve authenticated user details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved authenticated user details", content = [Content(schema = Schema(implementation = User::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/user/"], produces = ["application/json"] ) fun getAuthenticatedUser(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String): ResponseEntity<User> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getClasses", description = "Get a list of class names supported by a given class", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved class names", content = [Content(schema = Schema(implementation = kotlin.String::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/classes/{class}"], produces = ["application/json"] ) fun getClasses(@Parameter(description = "Name of the class", required = true) @PathVariable("class") propertyClass: kotlin.String): ResponseEntity<kotlin.String> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getOrganisation", description = "Retrieve organization details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipeline details", content = [Content(schema = Schema(implementation = Organisation::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password"), ApiResponse(responseCode = "404", description = "Pipeline cannot be found on Jenkins instance") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}"], produces = ["application/json"] ) fun getOrganisation(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String): ResponseEntity<Organisation> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getOrganisations", description = "Retrieve all organizations details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipelines details", content = [Content(schema = Schema(implementation = Organisation::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/"], produces = ["application/json"] ) fun getOrganisations(): ResponseEntity<List<Organisation>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipeline", description = "Retrieve pipeline details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipeline details", content = [Content(schema = Schema(implementation = Pipeline::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password"), ApiResponse(responseCode = "404", description = "Pipeline cannot be found on Jenkins instance") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}"], produces = ["application/json"] ) fun getPipeline(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String): ResponseEntity<Pipeline> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineActivities", description = "Retrieve all activities details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved all activities details", content = [Content(schema = Schema(implementation = PipelineActivity::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/activities"], produces = ["application/json"] ) fun getPipelineActivities(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String): ResponseEntity<List<PipelineActivity>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineBranch", description = "Retrieve branch details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved branch details", content = [Content(schema = Schema(implementation = BranchImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches/{branch}/"], produces = ["application/json"] ) fun getPipelineBranch(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the branch", required = true) @PathVariable("branch") branch: kotlin.String): ResponseEntity<BranchImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineBranchRun", description = "Retrieve branch run details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved run details", content = [Content(schema = Schema(implementation = PipelineRun::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches/{branch}/runs/{run}"], produces = ["application/json"] ) fun getPipelineBranchRun(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the branch", required = true) @PathVariable("branch") branch: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String): ResponseEntity<PipelineRun> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineBranches", description = "Retrieve all branches details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved all branches details", content = [Content(schema = Schema(implementation = MultibranchPipeline::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches"], produces = ["application/json"] ) fun getPipelineBranches(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String): ResponseEntity<MultibranchPipeline> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineFolder", description = "Retrieve pipeline folder for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved folder details", content = [Content(schema = Schema(implementation = PipelineFolderImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{folder}/"], produces = ["application/json"] ) fun getPipelineFolder(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the folder", required = true) @PathVariable("folder") folder: kotlin.String): ResponseEntity<PipelineFolderImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineFolderPipeline", description = "Retrieve pipeline details for an organization folder", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipeline details", content = [Content(schema = Schema(implementation = PipelineImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{folder}/pipelines/{pipeline}"], produces = ["application/json"] ) fun getPipelineFolderPipeline(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the folder", required = true) @PathVariable("folder") folder: kotlin.String): ResponseEntity<PipelineImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineQueue", description = "Retrieve queue details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved queue details", content = [Content(schema = Schema(implementation = QueueItemImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/queue"], produces = ["application/json"] ) fun getPipelineQueue(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String): ResponseEntity<List<QueueItemImpl>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRun", description = "Retrieve run details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved run details", content = [Content(schema = Schema(implementation = PipelineRun::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}"], produces = ["application/json"] ) fun getPipelineRun(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String): ResponseEntity<PipelineRun> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRunLog", description = "Get log for a pipeline run", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipeline run log", content = [Content(schema = Schema(implementation = kotlin.String::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/log"], produces = ["application/json"] ) fun getPipelineRunLog(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String,@Parameter(description = "Start position of the log") @Valid @RequestParam(value = "start", required = false) start: kotlin.Int?,@Parameter(description = "Set to true in order to download the file, otherwise it's passed as a response body") @Valid @RequestParam(value = "download", required = false) download: kotlin.Boolean?): ResponseEntity<kotlin.String> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRunNode", description = "Retrieve run node details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved run node details", content = [Content(schema = Schema(implementation = PipelineRunNode::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}"], produces = ["application/json"] ) fun getPipelineRunNode(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String,@Parameter(description = "Name of the node", required = true) @PathVariable("node") node: kotlin.String): ResponseEntity<PipelineRunNode> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRunNodeStep", description = "Retrieve run node details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved run node step details", content = [Content(schema = Schema(implementation = PipelineStepImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}/steps/{step}"], produces = ["application/json"] ) fun getPipelineRunNodeStep(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String,@Parameter(description = "Name of the node", required = true) @PathVariable("node") node: kotlin.String,@Parameter(description = "Name of the step", required = true) @PathVariable("step") step: kotlin.String): ResponseEntity<PipelineStepImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRunNodeStepLog", description = "Get log for a pipeline run node step", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipeline run node step log", content = [Content(schema = Schema(implementation = kotlin.String::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}/steps/{step}/log"], produces = ["application/json"] ) fun getPipelineRunNodeStepLog(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String,@Parameter(description = "Name of the node", required = true) @PathVariable("node") node: kotlin.String,@Parameter(description = "Name of the step", required = true) @PathVariable("step") step: kotlin.String): ResponseEntity<kotlin.String> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRunNodeSteps", description = "Retrieve run node steps details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved run node steps details", content = [Content(schema = Schema(implementation = PipelineStepImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes/{node}/steps"], produces = ["application/json"] ) fun getPipelineRunNodeSteps(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String,@Parameter(description = "Name of the node", required = true) @PathVariable("node") node: kotlin.String): ResponseEntity<List<PipelineStepImpl>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRunNodes", description = "Retrieve run nodes details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved run nodes details", content = [Content(schema = Schema(implementation = PipelineRunNode::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/nodes"], produces = ["application/json"] ) fun getPipelineRunNodes(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String): ResponseEntity<List<PipelineRunNode>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelineRuns", description = "Retrieve all runs details for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved runs details", content = [Content(schema = Schema(implementation = PipelineRun::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs"], produces = ["application/json"] ) fun getPipelineRuns(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String): ResponseEntity<List<PipelineRun>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getPipelines", description = "Retrieve all pipelines details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved pipelines details", content = [Content(schema = Schema(implementation = Pipeline::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/pipelines/"], produces = ["application/json"] ) fun getPipelines(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String): ResponseEntity<List<Pipeline>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getSCM", description = "Retrieve SCM details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved SCM details", content = [Content(schema = Schema(implementation = GithubScm::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/scm/{scm}"], produces = ["application/json"] ) fun getSCM(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of SCM", required = true) @PathVariable("scm") scm: kotlin.String): ResponseEntity<GithubScm> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getSCMOrganisationRepositories", description = "Retrieve SCM organization repositories details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved SCM organization repositories details", content = [Content(schema = Schema(implementation = GithubOrganization::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/scm/{scm}/organizations/{scmOrganisation}/repositories"], produces = ["application/json"] ) fun getSCMOrganisationRepositories(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of SCM", required = true) @PathVariable("scm") scm: kotlin.String,@Parameter(description = "Name of the SCM organization", required = true) @PathVariable("scmOrganisation") scmOrganisation: kotlin.String,@Parameter(description = "Credential ID") @Valid @RequestParam(value = "credentialId", required = false) credentialId: kotlin.String?,@Parameter(description = "Number of items in a page") @Valid @RequestParam(value = "pageSize", required = false) pageSize: kotlin.Int?,@Parameter(description = "Page number") @Valid @RequestParam(value = "pageNumber", required = false) pageNumber: kotlin.Int?): ResponseEntity<List<GithubOrganization>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getSCMOrganisationRepository", description = "Retrieve SCM organization repository details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved SCM organizations details", content = [Content(schema = Schema(implementation = GithubOrganization::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/scm/{scm}/organizations/{scmOrganisation}/repositories/{repository}"], produces = ["application/json"] ) fun getSCMOrganisationRepository(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of SCM", required = true) @PathVariable("scm") scm: kotlin.String,@Parameter(description = "Name of the SCM organization", required = true) @PathVariable("scmOrganisation") scmOrganisation: kotlin.String,@Parameter(description = "Name of the SCM repository", required = true) @PathVariable("repository") repository: kotlin.String,@Parameter(description = "Credential ID") @Valid @RequestParam(value = "credentialId", required = false) credentialId: kotlin.String?): ResponseEntity<List<GithubOrganization>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getSCMOrganisations", description = "Retrieve SCM organizations details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved SCM organizations details", content = [Content(schema = Schema(implementation = GithubOrganization::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/scm/{scm}/organizations"], produces = ["application/json"] ) fun getSCMOrganisations(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of SCM", required = true) @PathVariable("scm") scm: kotlin.String,@Parameter(description = "Credential ID") @Valid @RequestParam(value = "credentialId", required = false) credentialId: kotlin.String?): ResponseEntity<List<GithubOrganization>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getUser", description = "Retrieve user details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved users details", content = [Content(schema = Schema(implementation = User::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/users/{user}"], produces = ["application/json"] ) fun getUser(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the user", required = true) @PathVariable("user") user: kotlin.String): ResponseEntity<User> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getUserFavorites", description = "Retrieve user favorites details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved users favorites details", content = [Content(schema = Schema(implementation = FavoriteImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/users/{user}/favorites"], produces = ["application/json"] ) fun getUserFavorites(@Parameter(description = "Name of the user", required = true) @PathVariable("user") user: kotlin.String): ResponseEntity<List<FavoriteImpl>> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getUsers", description = "Retrieve users details for an organization", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved users details", content = [Content(schema = Schema(implementation = User::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/organizations/{organization}/users/"], produces = ["application/json"] ) fun getUsers(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String): ResponseEntity<User> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "postPipelineRun", description = "Replay an organization pipeline run", responses = [ ApiResponse(responseCode = "200", description = "Successfully replayed a pipeline run", content = [Content(schema = Schema(implementation = QueueItemImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.POST], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/replay"], produces = ["application/json"] ) fun postPipelineRun(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String): ResponseEntity<QueueItemImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "postPipelineRuns", description = "Start a build for an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully started a build", content = [Content(schema = Schema(implementation = QueueItemImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.POST], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs"], produces = ["application/json"] ) fun postPipelineRuns(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String): ResponseEntity<QueueItemImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "putPipelineFavorite", description = "Favorite/unfavorite a pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully favorited/unfavorited a pipeline", content = [Content(schema = Schema(implementation = FavoriteImpl::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.PUT], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/favorite"], produces = ["application/json"], consumes = ["application/json"] ) fun putPipelineFavorite(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Set JSON string body to {\"favorite\": true} to favorite, set value to false to unfavorite", required = true) @Valid @RequestBody body: kotlin.Boolean): ResponseEntity<FavoriteImpl> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "putPipelineRun", description = "Stop a build of an organization pipeline", responses = [ ApiResponse(responseCode = "200", description = "Successfully stopped a build", content = [Content(schema = Schema(implementation = PipelineRun::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.PUT], value = ["/blue/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}/stop"], produces = ["application/json"] ) fun putPipelineRun(@Parameter(description = "Name of the organization", required = true) @PathVariable("organization") organization: kotlin.String,@Parameter(description = "Name of the pipeline", required = true) @PathVariable("pipeline") pipeline: kotlin.String,@Parameter(description = "Name of the run", required = true) @PathVariable("run") run: kotlin.String,@Parameter(description = "Set to true to make blocking stop, default: false") @Valid @RequestParam(value = "blocking", required = false) blocking: kotlin.String?,@Parameter(description = "Timeout in seconds, default: 10 seconds") @Valid @RequestParam(value = "timeOutInSecs", required = false) timeOutInSecs: kotlin.Int?): ResponseEntity<PipelineRun> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "search", description = "Search for any resource details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved search result", content = [Content(schema = Schema(implementation = kotlin.String::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/search/"], produces = ["application/json"] ) fun search(@NotNull @Parameter(description = "Query string", required = true) @Valid @RequestParam(value = "q", required = true) q: kotlin.String): ResponseEntity<kotlin.String> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "searchClasses", description = "Get classes details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved search result", content = [Content(schema = Schema(implementation = kotlin.String::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/blue/rest/classes/"], produces = ["application/json"] ) fun searchClasses(@NotNull @Parameter(description = "Query string containing an array of class names", required = true) @Valid @RequestParam(value = "q", required = true) q: kotlin.String): ResponseEntity<kotlin.String> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } }
mit
91d2516c9815efdc6f7b61b9aebde93b
66.445531
840
0.695616
4.999068
false
false
false
false
BaristaVentures/debug-artist
lib/src/main/java/debugartist/menu/utils/device/AndroidDevice.kt
1
2567
package debugartist.menu.utils.device import android.app.Activity import android.os.Build import android.os.Process import android.util.Log import com.jraska.falcon.Falcon import java.io.* /** * Know how to pick things from an Android Device. */ class AndroidDevice(val activity: Activity) { val TAG = "AndroidDevice" companion object { /** * Return a map with keys and values referencing environment variables like * app version, android version, model, etc... */ @JvmStatic @JvmOverloads fun getProjectProperties(activity: Activity, extraProperties: HashMap<String, String>? = null) : MutableMap<String, String> { return activity.packageManager.getPackageInfo(activity.packageName, 0).let { mutableMapOf<String, String>( "AppVersion" to it.versionName, "Build" to it.versionCode.toString(), "AndroidVersion" to Build.VERSION.RELEASE, "Manufacturer" to Build.MANUFACTURER, "Model" to Build.MODEL).apply { extraProperties?.let { putAll(extraProperties) } } } } } @Throws(Falcon.UnableToTakeScreenshotException::class) fun takeScreenshot(fileName: String): String { val outFile = File(activity.cacheDir, fileName) Falcon.takeScreenshot(activity, outFile) return outFile.path } /** * Read logcat output, write in [AppCompatActivity.getCacheDir()]. * @return path with the log file * * Source: http://stackoverflow.com/a/22174245/273119 */ fun readLogFile(): String { val fullName = "appLog.log" val file = File(activity.cacheDir, fullName) val pid = Process.myPid().toString() if (file.exists()) { file.delete() } try { val command = String.format("logcat -d -v threadtime *:*") val process = Runtime.getRuntime().exec(command) val reader = BufferedReader(InputStreamReader(process.inputStream)) val result = StringBuilder() var currentLine = reader.readLine() while (currentLine != null) { currentLine = reader.readLine() if (currentLine != null && currentLine.contains(pid)) { result.append(currentLine).append("\n") } } val out = FileWriter(file) out.write(result.toString()) out.close() } catch (e: IOException) { Log.e(TAG, "Reading logcat output", e) } try { Runtime.getRuntime().exec("logcat -c") } catch (e: IOException) { Log.e(TAG, "Closing logcat (logcat -c)", e) } return file.path } }
apache-2.0
6abb3a145e17a63c4553ff13b94d5c8b
26.021053
98
0.643163
4.208197
false
false
false
false
lanhuaguizha/Christian
app/src/main/java/com/christian/util/util.kt
1
25749
package com.christian.util import android.Manifest import android.app.Activity import android.app.Dialog import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.* import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.edit import androidx.customview.widget.ViewDragHelper import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.christian.R import com.christian.common.* import com.christian.common.data.Chat import com.christian.common.data.Gospel import com.christian.nav.NavActivity import com.christian.nav.disciple.DiscipleDetailActivity import com.christian.nav.disciple.DiscipleDetailFragment import com.christian.nav.gospel.GospelDetailActivity import com.christian.nav.nullString import com.christian.nav.toolbarTitle import com.christian.swipe.SwipeBackActivity import com.christian.view.CustomViewPager import com.eightbitlab.supportrenderscriptblur.SupportRenderScriptBlur import com.github.anzewei.parallaxbacklayout.ParallaxHelper import com.google.android.material.appbar.AppBarLayout import com.google.android.material.snackbar.Snackbar import com.google.firebase.firestore.SetOptions import com.kotlinpermissions.KotlinPermissions import eightbitlab.com.blurview.BlurViewExtendsConstraintLayout import io.noties.markwon.* import io.noties.markwon.html.HtmlPlugin import io.noties.markwon.image.AsyncDrawable import io.noties.markwon.image.AsyncDrawableSpan import io.noties.markwon.image.ImageProps import io.noties.markwon.image.ImageSize import io.noties.markwon.image.glide.GlideImagesPlugin import io.noties.markwon.linkify.LinkifyPlugin import kotlinx.android.synthetic.main.card_investigation_plan_detail_member.view.* import org.commonmark.node.Image import org.jetbrains.anko.contentView import org.jetbrains.anko.dip import ren.qinc.markdowneditors.view.EditorActivity import java.util.* import java.util.regex.Pattern fun getLanguageList(): Array<String?> { var languages = arrayOfNulls<String>(0) for (locale in Locale.getAvailableLocales()) { languages = languages.plus(locale.language.toString() + "_" + locale.country + " [" + locale.displayName + "]") } return languages } fun getLanguageNameFromLanguageCode(lanCode: String): String { val loc = Locale(lanCode) return loc.getDisplayLanguage(loc) } fun getLanguageNamesFromLanguageCodes(lanCodes: Array<String>): Array<String?> { var names: Array<String?> = arrayOfNulls<String>(0) for (lc in lanCodes) { val loc = Locale(lc) val name = loc.getDisplayLanguage(loc) names = names.plus(name) } return names } fun fixAppBarLayoutElevation(headerLayout: AppBarLayout) { headerLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset -> if (verticalOffset == -appBarLayout.height) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { appBarLayout.elevation = 0f } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { appBarLayout.elevation = headerLayout.dip(4).toFloat() } } }) } fun requestStoragePermission(editorActivity: EditorActivity, path: String) { KotlinPermissions.with(editorActivity) // where this is an FragmentActivity instance .permissions(Manifest.permission.READ_EXTERNAL_STORAGE) .onAccepted { permissions -> //List of accepted permissions editorActivity.requestStoragePermissionAccepted(path) } .onDenied { permissions -> //List of denied permissions Snackbar.make(editorActivity.mViewPager, editorActivity.getString(R.string.no_acccess_to_read), Snackbar.LENGTH_SHORT).show() requestStoragePermission(editorActivity, path) } .onForeverDenied { permissions -> //List of forever denied permissions Snackbar.make(editorActivity.mViewPager, R.string.no_acccess_to_read_image_to_display, Snackbar.LENGTH_SHORT).show() } .ask() } fun fixToolbarElevation(appBarLayout: AppBarLayout) { appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset -> if (verticalOffset == -appBarLayout.height) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { appBarLayout.elevation = 0f } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { appBarLayout.elevation = appBarLayout.dip(4).toFloat() } } }) } fun SwipeBackActivity.setToolbarAsUp(toolbar: androidx.appcompat.widget.Toolbar, title: String) { this.setSupportActionBar(toolbar) this.supportActionBar?.title = title this.supportActionBar?.setDisplayHomeAsUpEnabled(true) } private fun imageSize(props: RenderProps): ImageSize { val imageSize = ImageProps.IMAGE_SIZE[props] return imageSize ?: ImageSize( ImageSize.Dimension(100f, "%"), null ) } fun setMarkdownToTextView(context: Context, textView: TextView, gospelContent: String) { textView.movementMethod = LinkMovementMethod.getInstance() val markdownView = Markwon.builder(context) // automatically create Glide instance .usePlugin(GlideImagesPlugin.create(context)) .usePlugin(GlideImagesPlugin.create(Glide.with(context))) .usePlugin(object : AbstractMarkwonPlugin() { override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) { builder.setFactory( Image::class.java ) { configuration: MarkwonConfiguration, props: RenderProps -> AsyncDrawableSpan( configuration.theme(), AsyncDrawable( ImageProps.DESTINATION.require(props), configuration.asyncDrawableLoader(), configuration.imageSizeResolver(), imageSize(props) ), AsyncDrawableSpan.ALIGN_CENTER, ImageProps.REPLACEMENT_TEXT_IS_LINK[props, false] ) } } }) .usePlugin(LinkifyPlugin.create()) .usePlugin(HtmlPlugin.create()) // // if you need more control /*.usePlugin(object : AbstractMarkwonPlugin() { override fun configureConfiguration(builder: MarkwonConfiguration.Builder) { builder.imageSizeResolver(object : ImageSizeResolverDef() { override fun resolveImageSize(imageSize: ImageSize?, imageBounds: Rect, canvasWidth: Int, textSize: Float): Rect { return if (imageSize == null) fitWidth(imageBounds, canvasWidth) else super.resolveImageSize(imageSize, imageBounds, canvasWidth, attr.textSize.toFloat()) } @NonNull fun fitWidth(@NonNull imageBounds: Rect, canvasWidth: Int): Rect { val ratio = imageBounds.width().toFloat() / imageBounds.height() val height = canvasWidth / ratio + .5F return Rect(0, 0, canvasWidth, height.toInt()) } }) } })*/ .build() markdownView.setMarkdown(textView, gospelContent) } var actionArray: Array<String> = arrayOf() private var lastPosition = 0//位置 private var lastOffset = 0//偏移量 fun recordScrolledPositionOfDetailPage(context: AppCompatActivity, recyclerView: RecyclerView) { recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val topView = recyclerView.layoutManager?.getChildAt(0) //获取可视的第一个view lastOffset = topView?.top ?: 0//获取与该view的顶部的偏移量 lastPosition = topView?.let { recyclerView.layoutManager?.getPosition(it) } ?: 0 //得到该View的数组位置 } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) val topView = recyclerView.layoutManager?.getChildAt(0) //获取可视的第一个view lastOffset = topView?.top ?: 0//获取与该view的顶部的偏移量 lastPosition = topView?.let { recyclerView.layoutManager?.getPosition(it) } ?: 0 //得到该View的数组位置 val sharedPreferences = context.getSharedPreferences(context.intent?.extras?.getString(toolbarTitle) ?: nullString, Activity.MODE_PRIVATE) sharedPreferences.edit { putInt("lastPosition", lastPosition) putInt("lastOffset", lastOffset) } } }) } fun restoreScrolledPositionOfDetailPage( context: AppCompatActivity, recyclerView: RecyclerView, // activityDetailMask: View, activity_detail_gospel_pb: ProgressBar ) { // 恢复位置 val sharedPreferences = context.getSharedPreferences( context.intent?.extras?.getString(toolbarTitle) ?: nullString, Activity.MODE_PRIVATE ) (recyclerView.layoutManager as LinearLayoutManager).scrollToPositionWithOffset( sharedPreferences.getInt( "lastPosition", 0 ), sharedPreferences.getInt("lastOffset", 0) ) // activityDetailMask.visibility = View.GONE activity_detail_gospel_pb.isIndeterminate = false /*recyclerView.postDelayed({ val sharedPreferences = context.getSharedPreferences(context.intent?.extras?.getString(toolbarTitle) ?: nullString, Activity.MODE_PRIVATE) (recyclerView.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(sharedPreferences.getInt("lastPosition", 0), sharedPreferences.getInt("lastOffset", 0)) activityDetailMask.visibility = View.GONE activity_detail_gospel_pb.isIndeterminate = false }, 0)*/ } fun filterImageUrlThroughDetailPageContent(gospelContent: String): String { // val pattern = "(https[^\\)]+\\))" val pattern = "https.+\\)" val p = Pattern.compile(pattern) val m = p.matcher(gospelContent) if (m.find()) { return m.group(0).replace(")", "") } return "" } private var lastX: Float = 0f private var mActivePointerId: Int = ViewDragHelper.INVALID_POINTER // used for enable back gesture fun dispatchTouchEvent(activity: SwipeBackActivity, ev: MotionEvent) { var isMovingRight = true // true不会崩溃,进入nav detail左滑的时候 when (ev.action) { MotionEvent.ACTION_DOWN -> { lastX = ev.x mActivePointerId = ev.getPointerId(0) } MotionEvent.ACTION_MOVE -> { try { isMovingRight = ev.getX(ev.findPointerIndex(mActivePointerId)) - lastX > 0 } catch (e: Exception) { e.printStackTrace() } } MotionEvent.ACTION_UP -> { mActivePointerId = ViewDragHelper.INVALID_POINTER } } enableSwipeBack(activity.pagePosition, activity.pagePositionOffset, activity.findViewById(R.id.bounceBackViewPager), activity, isMovingRight) } fun enableSwipeBack( position: Int, positionOffset: Float, vp_nav: CustomViewPager, activity: Activity, isMovingRight: Boolean ) { if (position == 0 && isMovingRight && positionOffset in 0f..0.3f) { // pagePosition从onPageSelected放到onPageScrolled之后就需要使用pagePositionOffset来限制在Review页面就可以返回的bug if (positionOffset > 0f) // 第一次进入positionOffset == 0f不能禁用viewPager vp_nav.setDisallowInterceptTouchEvent(true) else vp_nav.setDisallowInterceptTouchEvent(false) ParallaxHelper.getParallaxBackLayout(activity).setEnableGesture(true) // 滑动的过程当中,ParallaxBackLayout一直在接管手势 } else { vp_nav.setDisallowInterceptTouchEvent(false) ParallaxHelper.getParallaxBackLayout(activity).setEnableGesture(false) } } class DeleteDialogFragment(private val act: Activity, val navId: Int, val gospelId: String) : DialogFragment() { private lateinit var inflate: View override fun onStart() { // 因为View在添加后,对话框最外层的ViewGroup并不知道我们导入的View所需要的的宽度。 所以我们需要在onStart生命周期里修改对话框尺寸参数 val params = dialog!!.window!!.attributes params.width = ViewGroup.LayoutParams.WRAP_CONTENT dialog!!.window!!.attributes = params as WindowManager.LayoutParams super.onStart() val window = dialog!!.window // window!!.setBackgroundDrawableResource(android.R.color.transparent) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // inflate = // inflater.inflate(R.layout.card_investigation_plan_detail_member, container, false) // inflate.button.text = "取消" dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) makeViewBlurExtendsConstraintLayout( inflate as BlurViewExtendsConstraintLayout, act.window.decorView as ViewGroup, dialog?.window!! ) return super.onCreateView(inflater, container, savedInstanceState) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(act) inflate = act.layoutInflater.inflate(R.layout.card_investigation_plan_detail_member, null) inflate.button.text = "取消" inflate.button.setOnClickListener { dialog?.cancel() } inflate.button2.setOnClickListener { dialog?.dismiss() if (act is GospelDetailActivity) { act.finish() } deleteDocument(navId, gospelId) } // makeViewBlurExtendsConstraintLayout(inflate as BlurViewExtendsConstraintLayout, act.window.decorView as ViewGroup, dialog?.window!!) builder.setView(inflate) return builder // .setTitle("添加人员") .create() } } fun makeViewBlurExtendsConstraintLayout( navView: BlurViewExtendsConstraintLayout, parent: ViewGroup, window: Window, boolean: Boolean = false ) { val windowBackground = window.decorView.background val radius = 25f navView.setupWith(parent) .setFrameClearDrawable(windowBackground) .setBlurAlgorithm(SupportRenderScriptBlur(parent.context)) .setBlurRadius(radius) .setHasFixedTransformationMatrix(boolean) } // action delete fun deleteDocument(navId: Int, gospelId: String) { if (navId == 0) { firestore.collection(GOSPEL_EN).document(gospelId) .delete() .addOnSuccessListener { } .addOnFailureListener { } } else { firestore.collection(GOSPEL_ZH).document(gospelId) .delete() .addOnSuccessListener { } .addOnFailureListener { } } } fun toEditorActivity(activity: Activity, navId: Int, gospelId: String) { val intent = Intent(activity, EditorActivity::class.java) intent.putExtra(ChristianUtil.DOCUMENT_GOSPEL_PATH, gospelId) intent.putExtra(GOSPEL_ID, navId) activity.startActivity(intent) } fun actionFavorite(gospel: Gospel, navId: Int, activity: SwipeBackActivity) { if (auth.currentUser == null) { activity.signIn() if (activity is NavActivity) { activity.snackbar(R.string.please_sign_in) } else { Snackbar.make(activity.contentView as CoordinatorLayout, R.string.please_sign_in, Snackbar.LENGTH_SHORT).show() } return } val gospels = when(navId) { 0 -> GOSPEL_EN 1 -> GOSPEL_ZH else -> GOSPELS } if (gospel.like.contains(auth.currentUser?.uid)) { if (activity is NavActivity) { activity.snackbar(R.string.delete_like) } else { Snackbar.make(activity.contentView as CoordinatorLayout, R.string.delete_like, Snackbar.LENGTH_SHORT).show() } gospel.like.remove(auth.currentUser?.uid) val like = hashMapOf<String, Any>( "like" to gospel.like, ) firestore.collection(gospels).document(gospel.gospelId) .update(like) .addOnCompleteListener { } } else { if (activity is NavActivity) { activity.snackbar(R.string.set_like) } else { Snackbar.make(activity.contentView as CoordinatorLayout, R.string.set_like, Snackbar.LENGTH_SHORT).show() } gospel.like.add(auth.currentUser?.uid ?: "") val like = hashMapOf<String, Any>( "like" to gospel.like, ) firestore.collection(gospels).document(gospel.gospelId) .update(like) .addOnSuccessListener { } .addOnFailureListener { // toast(navActivity, it.message.toString()) } } } fun actionChatDetailFavorite( gospel: Gospel, activity: DiscipleDetailActivity, ) { if (auth.currentUser == null) { activity.signIn() Snackbar.make(activity.contentView as CoordinatorLayout, R.string.please_sign_in, Snackbar.LENGTH_SHORT).show() return } val gospels = when { gospel.classify.contains("en_") -> { GOSPEL_EN } gospel.classify.contains("zh_") -> { GOSPEL_ZH } else -> GOSPELS } // gospel from gospel_xx db var likeFromRemote: MutableList<String> firestore.collection(gospels).document(gospel.gospelId).get().addOnCompleteListener { if (it.isSuccessful) { val doc = it.result if (doc.exists()) { likeFromRemote = doc.get("like") as MutableList<String> gospel.like = likeFromRemote if (gospel.like.contains(auth.currentUser?.uid)) { /* Snackbar.make( activity.contentView as CoordinatorLayout, R.string.delete_like, Snackbar.LENGTH_SHORT ).show() gospel.like.remove(auth.currentUser?.uid) val like = hashMapOf<String, Any>( "like" to gospel.like, ) firestore.collection(gospels).document(gospel.gospelId) .update(like)*/ } else { Snackbar.make( activity.contentView as CoordinatorLayout, R.string.set_like, Snackbar.LENGTH_SHORT ).show() gospel.like.add(auth.currentUser?.uid ?: "") val like = hashMapOf<String, Any>( "like" to gospel.like, ) firestore.collection(gospels).document(gospel.gospelId) // .set(gospel, SetOptions.merge()) .update(like) /*.addOnSuccessListener { toast(activity, "success update") } .addOnFailureListener { toast(activity, it.message.toString()) }*/ } } else { Snackbar.make( activity.contentView as CoordinatorLayout, R.string.sent, Snackbar.LENGTH_SHORT ).show() firestore.collection(gospels).document(gospel.gospelId) .set(gospel, SetOptions.merge()) // .update(like) /*.addOnSuccessListener { toast(activity, "success set") } .addOnFailureListener { toast(activity, it.message.toString()) }*/ } } else { Snackbar.make( activity.contentView as CoordinatorLayout, R.string.no_internet_connection, Snackbar.LENGTH_SHORT ).show() } } } fun actionFollow(gospel: Gospel, navId: Int, activity: SwipeBackActivity) { if (auth.currentUser == null) { activity.signIn() if (activity is NavActivity) { activity.snackbar(R.string.please_sign_in) } else { Snackbar.make(activity.contentView as CoordinatorLayout, R.string.please_sign_in, Snackbar.LENGTH_SHORT).show() } return } val disciples = when(navId) { 0 -> DISCIPLE_EN 1 -> DISCIPLE_ZH else -> DISCIPLES } if (gospel.like.contains(auth.currentUser?.uid)) { if (activity is NavActivity) { activity.snackbar(R.string.delete_like) } else { Snackbar.make(activity.contentView as CoordinatorLayout, R.string.delete_like, Snackbar.LENGTH_SHORT).show() } gospel.like.remove(auth.currentUser?.uid) val like = hashMapOf<String, Any>( "like" to gospel.like, ) firestore.collection(disciples).document(gospel.gospelId) .update(like) .addOnCompleteListener { } } else { if (activity is NavActivity) { activity.snackbar(R.string.set_like) } else { Snackbar.make(activity.contentView as CoordinatorLayout, R.string.set_like, Snackbar.LENGTH_SHORT).show() } gospel.like.add(auth.currentUser?.uid ?: "") val like = hashMapOf<String, Any>( "like" to gospel.like, ) firestore.collection(disciples).document(gospel.gospelId) .update(like) .addOnSuccessListener { } .addOnFailureListener { // toast(navActivity, it.message.toString()) } } } fun actionMute(chat: Chat, activity: DiscipleDetailActivity) { if (auth.currentUser == null) { activity.signIn() Snackbar.make(activity.contentView as CoordinatorLayout, R.string.please_sign_in, Snackbar.LENGTH_SHORT).show() return } if (!chat.mute.contains(auth.currentUser?.uid)) { chat.mute.add(auth.currentUser?.uid ?: "") activity.discipleDetailFragment.db.reference.child(DiscipleDetailFragment.MESSAGES_CHILD).child(chat.chatId).setValue(chat) } } fun actionHide(gospel: Gospel, navId: Int,) { val gospels = when(navId) { 0 -> GOSPEL_EN 1 -> GOSPEL_ZH else -> GOSPELS } gospel.show = 0 val show = hashMapOf<String, Any>( "show" to gospel.show, ) firestore.collection(gospels).document(gospel.gospelId) .update(show) } fun actionShow(gospel: Gospel, navId: Int,) { val gospels = when(navId) { 0 -> GOSPEL_EN 1 -> GOSPEL_ZH else -> GOSPELS } gospel.show = 1 val show = hashMapOf<String, Any>( "show" to gospel.show, ) firestore.collection(gospels).document(gospel.gospelId) .update(show) } fun actionShareText(activity: Activity, s: String) { // val imageUrl = // filterImageUrlThroughDetailPageContent(gospel.content) val sendIntent: Intent = Intent().apply { action = Intent.ACTION_SEND // (Optional) Here we're setting the title of the content // putExtra(Intent.EXTRA_TITLE, gospel.title) // (Optional) Here we're passing a content URI to an image to be displayed /*if (imageUrl.isNotBlank()) { data = Uri.parse(imageUrl) flags = Intent.FLAG_GRANT_READ_URI_PERMISSION }*/ putExtra(Intent.EXTRA_TEXT, s) type = "text/plain" } val shareIntent = Intent.createChooser(sendIntent, null) activity.startActivity(shareIntent) } fun getPopupMenuArray(gospel: Gospel) = if (auth.currentUser?.uid == gospel.userId) { arrayOf( context.getString(R.string.action_share), getFavoriteString(gospel), context.getString(R.string.action_edit), context.getString(R.string.action_hide), context.getString(R.string.action_delete), context.getString(R.string.action_send) ) } else { arrayOf( context.getString(R.string.action_share), getFavoriteString(gospel) ) } fun getFavoriteString(gospel: Gospel): String { return if (gospel.like.contains(auth.currentUser?.uid)) { context.getString(R.string.action_favorite_delete) } else { context.getString(R.string.action_favorite) } }
gpl-3.0
490ad5ec6b5299e307de4702f760781e
35.637807
182
0.627398
4.5713
false
false
false
false
vyo/strakh
src/main/kotlin/io/github/vyo/strakh/goap/engine/Planner.kt
1
1526
package io.github.vyo.strakh.goap.engine import io.github.vyo.strakh.goap.client.Action import io.github.vyo.strakh.goap.client.Agent /** * Created by Manuel Weidmann on 21.11.2015. */ object Planner { fun formulatePlan(agent: Agent): List<Action> { val goals = agent.goals goals.sort() val actions = agent.actions val plan: MutableList<Action> = arrayListOf() println("Formulating plan for: $agent") println("\twith goals: $goals") println("\tand actions: $actions") println() for (goal in goals) { var available: MutableList<Action> = actions available.sort() val iterator: Iterator<Action> = available.iterator() while (iterator.hasNext()) { var action = iterator.next() println("\tNext action to check: $action") if (action.applicable()) { println("\t\tApplying action") action.apply() plan.add(action) } if (goal.reached()) { println() println("\tPlan found for: $goal") println("The plan is: $plan") println() return plan } } } return plan } data class Plan(val actions: Array<Action>, val cost: Int, val steps: Int) fun returnPlan(): Plan { return Plan(arrayOf(), 0, 0) } }
mit
c90f03ff67b82a7154b95fedb81f9d02
26.267857
78
0.514417
4.385057
false
false
false
false
elder-oss/sourcerer
sourcerer-eventstore-test-utils/src/main/kotlin/org/elder/sourcerer/eventstore/tests/utils/ConcurrencyRule.kt
1
1442
package org.elder.sourcerer.eventstore.tests.utils import org.junit.rules.ExternalResource import org.slf4j.LoggerFactory import java.util.concurrent.atomic.AtomicReference import kotlin.concurrent.thread /** * JUnit rule for running blocks of code in a separate thread. * * At the end of the test, it waits for all of them to complete, throwing any exception that * occurred. */ class ConcurrencyRule: ExternalResource(){ private val jobs = mutableListOf<Job>() fun runInThread(name: String, action: () -> Unit) { jobs += Job(name, action) } override fun after() { jobs.forEach { it.awaitCompletion() } } private class Job( name: String, private val action: () -> Unit ) { private val exception = AtomicReference<Throwable>() private val runningThread = thread(start = false, name = name) { action() }.apply { uncaughtExceptionHandler = Thread.UncaughtExceptionHandler { _, e -> exception.set(e) } start() } fun awaitCompletion() { logger.debug("${runningThread.name}: Awaiting completion") runningThread.join() exception.get()?.let { throw it } logger.debug("${runningThread.name}: successfully completed") } } companion object { private val logger = LoggerFactory.getLogger(ConcurrencyRule::class.java) } }
mit
15cb2686353ad997820185e884a6dd37
29.041667
99
0.633842
4.592357
false
false
false
false
xfournet/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/imports.kt
3
2096
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("GroovyImports") package org.jetbrains.plugins.groovy.lang.resolve.imports import com.intellij.openapi.util.Key import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import gnu.trove.THashSet import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement import org.jetbrains.plugins.groovy.lang.psi.util.ErrorUtil import org.jetbrains.plugins.groovy.lang.resolve.imports.impl.GroovyImportCollector import org.jetbrains.plugins.groovy.lang.resolve.imports.impl.RegularImportHashingStrategy import org.jetbrains.plugins.groovy.lang.resolve.imports.impl.StarImportHashingStrategy internal val defaultRegularImports = GroovyFileBase.IMPLICITLY_IMPORTED_CLASSES.map(::RegularImport) internal val defaultStarImports = GroovyFileBase.IMPLICITLY_IMPORTED_PACKAGES.map(::StarImport) internal val defaultImports = defaultStarImports + defaultRegularImports internal val defaultRegularImportsSet = THashSet(defaultRegularImports, RegularImportHashingStrategy) internal val defaultStarImportsSet = THashSet(defaultStarImports, StarImportHashingStrategy) val importedNameKey = Key.create<String>("groovy.imported.via.name") fun GroovyFile.getImports(): GroovyFileImports { return CachedValuesManager.getCachedValue(this) { Result.create(doGetImports(), this) } } private fun GroovyFile.doGetImports(): GroovyFileImports { val collector = GroovyImportCollector(this) for (statement in importStatements) { collector.addImportFromStatement(statement) } for (contributor in GrImportContributor.EP_NAME.extensions) { contributor.getFileImports(this).forEach(collector::addImport) } return collector.build() } val GroovyFile.validImportStatements: List<GrImportStatement> get() = importStatements.filterNot(ErrorUtil::containsError)
apache-2.0
12f1b2bed217d795b39ae653b019023f
44.565217
140
0.831584
4.375783
false
false
false
false
tinypass/piano-sdk-for-android
id/id/src/main/java/io/piano/android/id/PianoId.kt
1
7655
package io.piano.android.id import android.net.Uri import android.os.Build import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import com.squareup.moshi.Moshi import io.piano.android.id.models.PianoIdToken import io.piano.android.id.models.PianoUserInfo import io.piano.android.id.models.PianoUserProfile import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.create import java.util.Locale class PianoId { companion object { @VisibleForTesting @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmStatic private var client: PianoIdClient? = null /** * Initialize {@link PianoIdClient} singleton instance. It doesn't re-init it at next calls. * * @param endpoint Endpoint, which will be used. For example, {@link #ENDPOINT_PRODUCTION}, * {@link #ENDPOINT_SANDBOX} or your custom endpoint * @param aid Your AID * @return {@link PianoIdClient} instance. */ @Suppress("unused") // Public API. @JvmStatic fun init(endpoint: String, aid: String): PianoIdClient = client ?: run { val userAgent = "Piano ID SDK ${BuildConfig.SDK_VERSION} (Android ${Build.VERSION.RELEASE})" val okHttpClient = OkHttpClient.Builder() .addInterceptor(UserAgentInterceptor(userAgent)) .addInterceptor( HttpLoggingInterceptor().setLevel( if (BuildConfig.DEBUG || isLogHttpSet()) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE ) ) .build() val moshi = Moshi.Builder() .add(PianoIdJsonAdapterFactory()) .add(UnixTimeDateAdapter) .build() val retrofit = Retrofit.Builder() .client(okHttpClient) .baseUrl(endpoint) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() PianoIdClient(retrofit.create(), moshi, aid).also { client = it } } /** * Gets preferences for authorization process * * @return {@link PianoIdClient.SignInContext} instance * @throws IllegalStateException If you call it before {@link #init(String, String)} */ @Suppress("unused") // Public API. @Throws(IllegalStateException::class) @JvmStatic fun signIn(): PianoIdClient.SignInContext = getClient().signIn() /** * Sign out user by it's token * * @param accessToken User access token * @param callback callback, which will receive sign-out result */ @Suppress("unused") // Public API. @JvmStatic @JvmOverloads fun signOut(accessToken: String, callback: PianoIdFuncCallback<Any>? = null) { val signOutCallback = callback ?: {} client?.signOut(accessToken, signOutCallback) ?: signOutCallback(Result.failure(IllegalStateException(NOT_INITIALIZED_MSG))) } /** * Refresh user access token * * @param refreshToken User refresh token * @param callback callback, which will receive result */ @Suppress("unused") // Public API. @Throws(IllegalStateException::class) @JvmStatic fun refreshToken(refreshToken: String, callback: PianoIdFuncCallback<PianoIdToken>) { client?.refreshToken(refreshToken, callback) ?: callback(Result.failure(IllegalStateException(NOT_INITIALIZED_MSG))) } @Suppress("unused") // Public API. @JvmStatic fun getUserInfo( accessToken: String, formName: String? = null, callback: PianoIdFuncCallback<PianoUserProfile> ) { client?.getUserInfo(accessToken, formName, callback) ?: callback(Result.failure(IllegalStateException(NOT_INITIALIZED_MSG))) } @Suppress("unused") // Public API. @JvmStatic fun putUserInfo( accessToken: String, newUserInfo: PianoUserInfo, callback: PianoIdFuncCallback<PianoUserProfile> ) { client?.putUserInfo(accessToken, newUserInfo, callback) ?: callback(Result.failure(IllegalStateException(NOT_INITIALIZED_MSG))) } @Suppress("unused") // Public API. @JvmStatic fun Uri?.parsePianoIdToken(callback: PianoIdFuncCallback<PianoIdToken>) = if (isPianoIdUri()) { getClient().parseToken(this!!, callback) } else callback(Result.failure(PianoIdException("It's not Piano ID uri"))) @Suppress("unused") // Public API. @JvmStatic fun Uri?.isPianoIdUri(): Boolean = this?.run { scheme?.lowercase(Locale.ENGLISH)?.startsWith(PianoIdClient.LINK_SCHEME_PREFIX) == true && PianoIdClient.LINK_AUTHORITY.equals(authority, ignoreCase = true) } ?: false @JvmStatic internal fun getClient() = checkNotNull(client) { NOT_INITIALIZED_MSG } /** * Default production endpoint */ @Suppress("unused") // Public API. const val ENDPOINT_PRODUCTION = "https://buy.tinypass.com" /** * Australia production endpoint */ @Suppress("unused") // Public API. const val ENDPOINT_PRODUCTION_AUSTRALIA = "https://buy-au.piano.io" /** * Asia/Pacific production endpoint */ @Suppress("unused") // Public API. const val ENDPOINT_PRODUCTION_ASIA_PACIFIC = "https://buy-ap.piano.io" /** * Europe production endpoint */ @Suppress("unused") // Public API. const val ENDPOINT_PRODUCTION_EUROPE = "https://buy-eu.piano.io" /** * Sandbox endpoint */ @Suppress("unused") // Public API. const val ENDPOINT_SANDBOX = "https://sandbox.tinypass.com" /** * Widget for login screen */ @Suppress("unused") // Public API. const val WIDGET_LOGIN = "login" /** * Widget for registration screen */ @Suppress("unused") // Public API. const val WIDGET_REGISTER = "register" /** * Client ID key for OAuth providers */ @Suppress("unused") // Public API. const val KEY_CLIENT_ID = "io.piano.android.id.CLIENT_ID" /** * Activity result code for error */ @Suppress("unused") // Public API. const val RESULT_ERROR = 1 internal const val KEY_OAUTH_PROVIDER_NAME = "io.piano.android.id.OAUTH_PROVIDER_NAME" internal const val KEY_OAUTH_PROVIDER_TOKEN = "io.piano.android.id.OAUTH_PROVIDER_TOKEN" internal const val KEY_TOKEN = "io.piano.android.id.PianoIdActivity.TOKEN" internal const val KEY_IS_NEW_USER = "io.piano.android.id.PianoIdActivity.IS_NEW_USER" internal const val KEY_ERROR = "io.piano.android.id.PianoIdActivity.ERROR" private const val NOT_INITIALIZED_MSG = "Piano ID SDK is not initialized! Make sure that you " + "initialize it via init()" } }
apache-2.0
2a03adbbb8c353be3e576d0272a97255
36.341463
108
0.5855
4.935525
false
false
false
false
google/ksp
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/kotlin/KSTypeArgumentLiteImpl.kt
1
2306
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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.devtools.ksp.symbol.impl.kotlin import com.google.devtools.ksp.KSObjectCache import com.google.devtools.ksp.findParentOfType import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.KSTypeReference import com.google.devtools.ksp.symbol.Location import com.google.devtools.ksp.symbol.NonExistLocation import com.google.devtools.ksp.symbol.Origin import com.google.devtools.ksp.symbol.Variance import org.jetbrains.kotlin.psi.KtFunctionType import org.jetbrains.kotlin.psi.KtTypeReference class KSTypeArgumentLiteImpl private constructor(override val type: KSTypeReference, override val variance: Variance) : KSTypeArgumentImpl() { companion object : KSObjectCache<Pair<KSTypeReference, Variance>, KSTypeArgumentLiteImpl>() { fun getCached(type: KSTypeReference, variance: Variance) = cache.getOrPut(Pair(type, variance)) { KSTypeArgumentLiteImpl(type, variance) } fun getCached(type: KtTypeReference) = cache.getOrPut( Pair(KSTypeReferenceImpl.getCached(type), Variance.INVARIANT) ) { KSTypeArgumentLiteImpl(KSTypeReferenceImpl.getCached(type), Variance.INVARIANT) } } override val origin = Origin.KOTLIN override val location: Location = NonExistLocation override val parent: KSNode? by lazy { (type as? KSTypeReferenceImpl)?.ktTypeReference ?.findParentOfType<KtFunctionType>()?.let { KSCallableReferenceImpl.getCached(it) } } override val annotations: Sequence<KSAnnotation> = type.annotations }
apache-2.0
d5a6eaf023dc06b51e651debf20e9bf6
40.178571
119
0.758456
4.38403
false
false
false
false
team401/2017-Robot-Code
src/main/java/org/team401/robot/subsystems/OctocanumDrive.kt
1
14918
package org.team401.robot.subsystems import com.ctre.CANTalon import edu.wpi.first.wpilibj.BuiltInAccelerometer import edu.wpi.first.wpilibj.Solenoid import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard import org.team401.lib.ADXRS450_Gyro import org.team401.lib.MathUtils import org.team401.lib.SynchronousPID import org.team401.robot.Constants import org.team401.robot.components.OctocanumGearbox import org.team401.lib.Loop import org.team401.lib.MathUtils.Drive.inchesPerSecondToRpm import org.team401.lib.Rotation2d import org.team401.robot.ControlBoard /** * Drivetrain wrapper class for the octocanum chassis, supports shifting * between drive modes (DriveMode.TRACTION and DriveMode.MECANUM). * * @author Zach Kozar * @version 1/15/17 */ object OctocanumDrive : Subsystem("drive") { enum class DriveControlState { OPEN_LOOP, CLOSED_LOOP, VELOCITY_HEADING_CONTROL, PATH_FOLLOWING_CONTROL } /** * An enum object to represent different drive modes. */ enum class DriveMode { TRACTION, MECANUM } private var controlState = DriveControlState.CLOSED_LOOP /** * Immutable list of gearboxes, will always have a size of 4 */ val gearboxes: Array<OctocanumGearbox> = arrayOf( OctocanumGearbox(CANTalon(Constants.FRONT_LEFT_MASTER), CANTalon(Constants.FRONT_LEFT_SLAVE), true, true), OctocanumGearbox(CANTalon(Constants.FRONT_RIGHT_MASTER), CANTalon(Constants.FRONT_RIGHT_SLAVE), false, true), OctocanumGearbox(CANTalon(Constants.REAR_LEFT_MASTER), CANTalon(Constants.REAR_LEFT_SLAVE), true, true), OctocanumGearbox(CANTalon(Constants.REAR_RIGHT_MASTER), CANTalon(Constants.REAR_RIGHT_SLAVE), false, true) ) val gyro = ADXRS450_Gyro() val accel = BuiltInAccelerometer() val shifter = Solenoid(Constants.GEARBOX_SHIFTER) private var driveSignal = DriveSignal.NEUTRAL val pidVelocityHeading = SynchronousPID() private var velocityHeadingSetpoint: VelocityHeadingSetpoint? = null private var lastHeadingErrorDegrees = 0.0 var brakeModeOn: Boolean = false /** * The current drive mode of the chassis */ var driveMode = DriveMode.TRACTION private var x = 0.0 private var y = 0.0 private var z = 0.0 private val loop = object : Loop { override fun onStart() { } override fun onLoop() { when (controlState) { DriveControlState.OPEN_LOOP -> { if (driveSignal != DriveSignal.NEUTRAL) { gearboxes[Constants.GEARBOX_FRONT_LEFT].setOutput(driveSignal.left) gearboxes[Constants.GEARBOX_REAR_LEFT].setOutput(driveSignal.left) gearboxes[Constants.GEARBOX_FRONT_RIGHT].setOutput(driveSignal.right) gearboxes[Constants.GEARBOX_REAR_RIGHT].setOutput(driveSignal.right) } else { val x: Double if (driveMode == DriveMode.MECANUM) x = ControlBoard.getDriveStrafe() else x = 0.0 val y = ControlBoard.getDrivePitch() val rot = ControlBoard.getDriveRotate() val wheelSpeeds = DoubleArray(4) wheelSpeeds[Constants.GEARBOX_FRONT_LEFT] = -x + y + rot wheelSpeeds[Constants.GEARBOX_REAR_LEFT] = x + y + rot wheelSpeeds[Constants.GEARBOX_FRONT_RIGHT] = x + y - rot wheelSpeeds[Constants.GEARBOX_REAR_RIGHT] = -x + y - rot MathUtils.scale(wheelSpeeds, 0.9) MathUtils.normalize(wheelSpeeds) gearboxes[Constants.GEARBOX_FRONT_LEFT].setOutput(wheelSpeeds[Constants.GEARBOX_FRONT_LEFT]) gearboxes[Constants.GEARBOX_REAR_LEFT].setOutput(wheelSpeeds[Constants.GEARBOX_REAR_LEFT]) gearboxes[Constants.GEARBOX_FRONT_RIGHT].setOutput(wheelSpeeds[Constants.GEARBOX_FRONT_RIGHT]) gearboxes[Constants.GEARBOX_REAR_RIGHT].setOutput(wheelSpeeds[Constants.GEARBOX_REAR_RIGHT]) } } DriveControlState.CLOSED_LOOP -> { val x: Double if (driveMode == DriveMode.MECANUM) x = ControlBoard.getDriveStrafe() else x = 0.0 val y = ControlBoard.getDrivePitch() val rot = ControlBoard.getDriveRotate() val wheelSpeeds = DoubleArray(4) wheelSpeeds[Constants.GEARBOX_FRONT_LEFT] = -x + y + rot wheelSpeeds[Constants.GEARBOX_REAR_LEFT] = x + y + rot wheelSpeeds[Constants.GEARBOX_FRONT_RIGHT] = x + y - rot wheelSpeeds[Constants.GEARBOX_REAR_RIGHT] = -x + y - rot MathUtils.scale(wheelSpeeds, 1.0) MathUtils.normalize(wheelSpeeds) MathUtils.scale(wheelSpeeds, inchesPerSecondToRpm(Constants.MAX_SPEED*12)) gearboxes[Constants.GEARBOX_FRONT_LEFT].setOutput(wheelSpeeds[Constants.GEARBOX_FRONT_LEFT]) gearboxes[Constants.GEARBOX_REAR_LEFT].setOutput(wheelSpeeds[Constants.GEARBOX_REAR_LEFT]) gearboxes[Constants.GEARBOX_FRONT_RIGHT].setOutput(wheelSpeeds[Constants.GEARBOX_FRONT_RIGHT]) gearboxes[Constants.GEARBOX_REAR_RIGHT].setOutput(wheelSpeeds[Constants.GEARBOX_REAR_RIGHT]) } // talons are updating the control loop state DriveControlState.VELOCITY_HEADING_CONTROL -> updateVelocityHeadingSetpoint() DriveControlState.PATH_FOLLOWING_CONTROL -> { println("we shouldn't be in path following mode!!!") /*updatePathFollower() if (isFinishedPath()) { onStop() }*/ } else -> System.out.println("Unexpected drive control state: " + controlState) } SmartDashboard.putNumber("jerk_x", (accel.x - x) / Constants.LOOP_PERIOD) SmartDashboard.putNumber("jerk_y", (accel.y - y) / Constants.LOOP_PERIOD) SmartDashboard.putNumber("jerk_z", (accel.z - z) / Constants.LOOP_PERIOD) x = accel.x y = accel.y z = accel.z } override fun onStop() { } } init { pidVelocityHeading.setPID(Constants.DRIVE_HEADING_VEL_P, Constants.DRIVE_HEADING_VEL_I, Constants.DRIVE_HEADING_VEL_D) zeroSensors() dataLogger.register("left_front_distance", { gearboxes[Constants.GEARBOX_FRONT_LEFT].getDistanceInches() }) dataLogger.register("left_rear_distance", { gearboxes[Constants.GEARBOX_REAR_LEFT].getDistanceInches() }) dataLogger.register("right_front_distance", { gearboxes[Constants.GEARBOX_FRONT_RIGHT].getDistanceInches() }) dataLogger.register("right_rear_distance", { gearboxes[Constants.GEARBOX_REAR_RIGHT].getDistanceInches() }) dataLogger.register("left_front_velocity", { gearboxes[Constants.GEARBOX_FRONT_LEFT].getVelocityInchesPerSecond() }) dataLogger.register("left_rear_velocity", { gearboxes[Constants.GEARBOX_REAR_LEFT].getVelocityInchesPerSecond() }) dataLogger.register("right_front_velocity", { gearboxes[Constants.GEARBOX_FRONT_RIGHT].getVelocityInchesPerSecond() }) dataLogger.register("right_rear_velocity", { gearboxes[Constants.GEARBOX_REAR_RIGHT].getVelocityInchesPerSecond() }) dataLogger.register("left_front_error", { gearboxes[Constants.GEARBOX_FRONT_LEFT].getErrorVelocityInchesPerSecond() }) dataLogger.register("left_rear_error", { gearboxes[Constants.GEARBOX_REAR_LEFT].getErrorVelocityInchesPerSecond() }) dataLogger.register("right_front_error", { gearboxes[Constants.GEARBOX_FRONT_RIGHT].getErrorVelocityInchesPerSecond() }) dataLogger.register("right_rear_error", { gearboxes[Constants.GEARBOX_REAR_RIGHT].getErrorVelocityInchesPerSecond() }) dataLogger.register("left_front_setpoint", { gearboxes[Constants.GEARBOX_FRONT_LEFT].getSetpoint() }) dataLogger.register("left_rear_setpoint", { gearboxes[Constants.GEARBOX_REAR_LEFT].getSetpoint() }) dataLogger.register("right_front_setpoint", { gearboxes[Constants.GEARBOX_FRONT_RIGHT].getSetpoint() }) dataLogger.register("right_rear_setpoint", { gearboxes[Constants.GEARBOX_REAR_RIGHT].getSetpoint() }) dataLogger.register("gyro_angle", { getGyroAngle().degrees }) dataLogger.register("gyro_rate", { gyro.rate }) dataLogger.register("heading_error", { lastHeadingErrorDegrees }) dataLogger.register("strafing_enabled", { driveMode == DriveMode.MECANUM }) dataLogger.register("open_loop_control", { controlState == DriveControlState.OPEN_LOOP }) dataLogger.register("brake_enabled", { brakeModeOn }) } fun stop() { setControlState(DriveControlState.OPEN_LOOP) } /** * Toggle the drive mode */ fun shift() { if (driveMode == DriveMode.TRACTION) shift(DriveMode.MECANUM) else shift(DriveMode.TRACTION) } /** * Set the drive mode to the passed mode. This method does nothing if * the passed drive mode is the currently set drive mode. * * @param driveMode The DriveMode to switch to */ fun shift(driveMode: DriveMode) { if (driveMode == DriveMode.TRACTION && this.driveMode == DriveMode.MECANUM) { shifter.set(false) this.driveMode = DriveMode.TRACTION } else if (driveMode == DriveMode.MECANUM && this.driveMode == DriveMode.TRACTION) { shifter.set(true) this.driveMode = DriveMode.MECANUM } } /** * Changes the drive mode of each gearbox, and runs the lambdas on the * motor CANTalon objects for their respective sides on the robot. */ fun changeControlMode(mode: CANTalon.TalonControlMode, leftFront: (CANTalon) -> Unit, rightFront: (CANTalon) -> Unit, leftRear: (CANTalon) -> Unit, rightRear: (CANTalon) -> Unit) { gearboxes.forEach { it.changeControlMode(mode) } gearboxes[Constants.GEARBOX_FRONT_LEFT].config(leftFront) gearboxes[Constants.GEARBOX_REAR_LEFT].config(leftRear) gearboxes[Constants.GEARBOX_FRONT_RIGHT].config(rightFront) gearboxes[Constants.GEARBOX_REAR_RIGHT].config(rightRear) } fun zeroSensors() { resetEncoders() gyro.reset() } fun configureTalonsForSpeedControl() { if (controlState == DriveControlState.CLOSED_LOOP || controlState == DriveControlState.VELOCITY_HEADING_CONTROL) return changeControlMode(CANTalon.TalonControlMode.Speed, { it.setProfile(Constants.SPEED_CONTROL_PROFILE) }, { it.setProfile(Constants.SPEED_CONTROL_PROFILE) }, { it.setProfile(Constants.SPEED_CONTROL_PROFILE) }, { it.setProfile(Constants.SPEED_CONTROL_PROFILE) }) setBrakeMode(true) } fun configureTalonsForOpenLoopControl() { if (controlState == DriveControlState.OPEN_LOOP) return changeControlMode(CANTalon.TalonControlMode.PercentVbus, { it.set(0.0) }, { it.set(0.0) }, { it.set(0.0) }, { it.set(0.0) }) setBrakeMode(true) driveSignal = DriveSignal.NEUTRAL } fun setDriveSignal(driveSignal: DriveSignal) { if (controlState != DriveControlState.OPEN_LOOP) { configureTalonsForOpenLoopControl() controlState = DriveControlState.OPEN_LOOP } this.driveSignal = driveSignal } fun setVelocityHeadingSetpoint(inchesPerSec: Double, headingSetpoint: Rotation2d) { if (controlState != DriveControlState.VELOCITY_HEADING_CONTROL) { configureTalonsForSpeedControl() controlState = DriveControlState.VELOCITY_HEADING_CONTROL pidVelocityHeading.reset() pidVelocityHeading.setOutputRange(-30.0, 30.0) } velocityHeadingSetpoint = VelocityHeadingSetpoint(-inchesPerSec, -inchesPerSec, headingSetpoint) updateVelocityHeadingSetpoint() } private fun updateVelocitySetpoint(leftInchesPerSec: Double, rightInchesPerSec: Double) { gearboxes[Constants.GEARBOX_FRONT_LEFT].setOutput(inchesPerSecondToRpm(leftInchesPerSec)) gearboxes[Constants.GEARBOX_REAR_LEFT].setOutput(inchesPerSecondToRpm(leftInchesPerSec)) gearboxes[Constants.GEARBOX_FRONT_RIGHT].setOutput(inchesPerSecondToRpm(rightInchesPerSec)) gearboxes[Constants.GEARBOX_REAR_RIGHT].setOutput(inchesPerSecondToRpm(rightInchesPerSec)) } private fun updateVelocityHeadingSetpoint() { val actualGyroAngle = getGyroAngle() val setpoint = velocityHeadingSetpoint!! lastHeadingErrorDegrees = setpoint.heading.rotateBy(actualGyroAngle.inverse()).degrees val deltaSpeed = pidVelocityHeading.calculate(lastHeadingErrorDegrees) updateVelocitySetpoint(setpoint.leftSpeed - deltaSpeed, setpoint.rightSpeed + deltaSpeed) } fun setBrakeMode(on: Boolean) { if (brakeModeOn != on) gearboxes.forEach { it.setBrakeMode(on) } brakeModeOn = on } fun resetEncoders() { gearboxes.forEach { it.config { it.encPosition = 0 it.position = 0.0 } } } fun setControlState(controlState: DriveControlState) { if (controlState == DriveControlState.OPEN_LOOP) configureTalonsForOpenLoopControl() else configureTalonsForSpeedControl() this.controlState = controlState } fun getControlState() = controlState @Synchronized fun getGyroAngle(): Rotation2d { return Rotation2d.fromDegrees(gyro.angle) } override fun getSubsystemLoop(): Loop = loop /** * VelocityHeadingSetpoints are used to calculate the robot's path given the * speed of the robot in each wheel and the polar coordinates. Especially * useful if the robot is negotiating a turn and to forecast the robot's * location. */ data class VelocityHeadingSetpoint(val leftSpeed: Double, val rightSpeed: Double, val heading: Rotation2d) data class DriveSignal(val left: Double, val right: Double) { companion object { val NEUTRAL = DriveSignal(0.0, 0.0) } } }
gpl-3.0
37787f1a89e40c6133ae5105b42e2b19
42.492711
128
0.639764
3.991972
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/serializers/shuttle/FlightPlanParametersStreamSerializer.kt
1
2836
package com.openlattice.hazelcast.serializers.shuttle import com.dataloom.mappers.ObjectMappers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.hazelcast.InternalTestDataFactory import com.openlattice.hazelcast.serializers.StreamSerializers import com.openlattice.hazelcast.serializers.TestableSelfRegisteringStreamSerializer import com.openlattice.shuttle.Flight import com.openlattice.shuttle.FlightPlanParameters import org.springframework.stereotype.Component @Component class FlightPlanParametersStreamSerializer : TestableSelfRegisteringStreamSerializer<FlightPlanParameters> { companion object { private val mapper = ObjectMappers.getJsonMapper() fun serialize(output: ObjectDataOutput, obj: FlightPlanParameters) { output.writeUTF(obj.sql) output.writeUTFArray(obj.source.keys.map { it }.toTypedArray()) output.writeUTFArray(obj.source.values.map { it }.toTypedArray()) output.writeUTFArray(obj.sourcePrimaryKeyColumns.toTypedArray()) StreamSerializers.serializeMaybeValue(output, obj.flightFilePath) { output.writeUTF(obj.flightFilePath!!) } val flightJson = mapper.writeValueAsString(obj.flight) output.writeUTF(flightJson) } fun deserialize(input: ObjectDataInput): FlightPlanParameters { val sql = input.readUTF() val sourceKeys = input.readUTFArray().toList() val sourceValues = input.readUTFArray().toList() val source = sourceKeys.zip(sourceValues) { key, value -> key to value }.toMap() val srcPkeyCols = input.readUTFArray().toList() val flightFilePath = StreamSerializers.deserializeMaybeValue(input) { input.readUTF() } val flightJson = input.readUTF() val flight = mapper.readValue(flightJson, Flight::class.java) return FlightPlanParameters( sql, source, srcPkeyCols, flightFilePath, flight ) } } override fun write(output: ObjectDataOutput, obj: FlightPlanParameters) { serialize(output, obj) } override fun read(input: ObjectDataInput): FlightPlanParameters { return deserialize(input) } override fun getClazz(): Class<out FlightPlanParameters> { return FlightPlanParameters::class.java } override fun getTypeId(): Int { return StreamSerializerTypeIds.FLIGHT_PLAN_PARAMETERS.ordinal } override fun generateTestValue(): FlightPlanParameters { return InternalTestDataFactory.flightPlanParameters() } }
gpl-3.0
b6b66adb5f497881ecd5710fb98a0b9e
37.863014
108
0.68653
5.232472
false
true
false
false
square/moshi
moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/apt/AppliedType.kt
1
2336
/* * Copyright (C) 2018 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi.kotlin.codegen.apt import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.DelicateKotlinPoetApi import com.squareup.kotlinpoet.asClassName import javax.lang.model.element.ElementKind.CLASS import javax.lang.model.element.TypeElement import javax.lang.model.type.DeclaredType import javax.lang.model.util.Types private val OBJECT_CLASS = ClassName("java.lang", "Object") /** * A concrete type like `List<String>` with enough information to know how to resolve its type * variables. */ internal class AppliedType private constructor( val element: TypeElement, private val mirror: DeclaredType ) { /** Returns all supertypes of this, recursively. Only [CLASS] is used as we can't really use other types. */ @OptIn(DelicateKotlinPoetApi::class) fun superclasses( types: Types, result: LinkedHashSet<AppliedType> = LinkedHashSet() ): LinkedHashSet<AppliedType> { result.add(this) for (supertype in types.directSupertypes(mirror)) { val supertypeDeclaredType = supertype as DeclaredType val supertypeElement = supertypeDeclaredType.asElement() as TypeElement if (supertypeElement.kind != CLASS) { continue } else if (supertypeElement.asClassName() == OBJECT_CLASS) { // Don't load properties for java.lang.Object. continue } val appliedSuperclass = AppliedType(supertypeElement, supertypeDeclaredType) appliedSuperclass.superclasses(types, result) } return result } override fun toString() = mirror.toString() companion object { operator fun invoke(typeElement: TypeElement): AppliedType { return AppliedType(typeElement, typeElement.asType() as DeclaredType) } } }
apache-2.0
d9c5d6dc32e6dfaf8e7494613f07cd05
34.938462
110
0.739726
4.350093
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/cameras/PerspectiveCameraProjectionBuilder.kt
1
1153
package glimpse.cameras import glimpse.Angle import glimpse.degrees /** * Builder of a [PerspectiveCameraProjection]. */ class PerspectiveCameraProjectionBuilder { private var fovY: () -> Angle = { 60.degrees } private var aspect: () -> Float = { 1f } private var near: Float = 1f private var far: Float = 100f /** * Sets camera field of view angle for Y-axis (viewport height axis) lambda. */ fun fov(fovY: () -> Angle) { this.fovY = fovY } /** * Sets camera aspect ratio lambda. */ fun aspect(aspect: () -> Float) { this.aspect = aspect } /** * Sets camera near and far clipping planes. */ fun distanceRange(range: Pair<Float, Float>) { near = range.first far = range.second } internal fun build(): PerspectiveCameraProjection = PerspectiveCameraProjection(fovY, aspect, near, far) } /** * Builds perspective camera projecion initialized with an [init] function. */ fun CameraBuilder.perspective(init: PerspectiveCameraProjectionBuilder.() -> Unit) { val cameraProjectionBuilder = PerspectiveCameraProjectionBuilder() cameraProjectionBuilder.init() cameraProjection = cameraProjectionBuilder.build() }
apache-2.0
875fdcd8df32ca756878a11470c320b0
23.020833
105
0.712923
3.707395
false
false
false
false
SerCeMan/datanucleus-intellij-plugin
jps-plugin/src/main/kotlin/me/serce/datanucleus/build/DanucleusModuleLevelBuilder.kt
1
5103
package me.serce.datanucleus.build import com.intellij.compiler.instrumentation.InstrumentationClassFinder import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import org.jetbrains.jps.ModuleChunk import org.jetbrains.jps.ProjectPaths import org.jetbrains.jps.builders.DirtyFilesHolder import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor import org.jetbrains.jps.incremental.* import org.jetbrains.jps.incremental.messages.CompilerMessage import org.jetbrains.jps.incremental.messages.ProgressMessage import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JpsJavaSdkType import java.io.File import java.io.IOException import java.net.URL import java.net.URLClassLoader import java.util.* class DatanucleusModuleLevelBuilder : ModuleLevelBuilder(BuilderCategory.CLASS_INSTRUMENTER) { private val LOG = Logger.getInstance(DatanucleusModuleLevelBuilder::class.java) @Throws(ProjectBuildException::class, IOException::class) override fun build(context: CompileContext, chunk: ModuleChunk, dirtyFilesHolder: DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>, outputConsumer: ModuleLevelBuilder.OutputConsumer): ModuleLevelBuilder.ExitCode { if (outputConsumer.compiledClasses.isEmpty()) { return ModuleLevelBuilder.ExitCode.NOTHING_DONE } val progress = getProgressMessage() val shouldShowProgress = !StringUtil.isEmptyOrSpaces(progress) if (shouldShowProgress) { context.processMessage(ProgressMessage(progress + " [" + chunk.presentableShortName + "]")) } var exitCode: ModuleLevelBuilder.ExitCode = ModuleLevelBuilder.ExitCode.NOTHING_DONE try { val platformCp = ProjectPaths.getPlatformCompilationClasspath(chunk, false) val classpath = ArrayList<File>() classpath.addAll(ProjectPaths.getCompilationClasspath(chunk, false)) classpath.addAll(ProjectPaths.getSourceRootsWithDependents(chunk).keys) val sdk = chunk.representativeTarget().module.getSdk(JpsJavaSdkType.INSTANCE) val platformUrls = ArrayList<URL>() if (sdk != null && JpsJavaSdkType.getJavaVersion(sdk) >= 9) { platformUrls.add(InstrumentationClassFinder.createJDKPlatformUrl(sdk.homePath)) } for (file in platformCp) { platformUrls.add(file.toURI().toURL()) } val urls = ArrayList<URL>() for (file in classpath) { urls.add(file.toURI().toURL()) } val buildClassLoader = URLClassLoader(platformUrls.plus(urls).toTypedArray(), this.javaClass.classLoader) try { for (moduleChunk in chunk.targets) { val persistense = moduleChunk.module.sourceRoots .firstOrNull { it.rootType == JavaResourceRootType.RESOURCE } ?.file ?.absolutePath ?.plus("/META-INF/persistence.xml") if (persistense != null && File(persistense).exists()) { context.processMessage(ProgressMessage("Enhancing ${moduleChunk.presentableName}")) val cl = Thread.currentThread().contextClassLoader try { Thread.currentThread().contextClassLoader = buildClassLoader val c = buildClassLoader.loadClass("org.datanucleus.enhancer.DataNucleusEnhancer") val m = c.getMethod("main", Array<String>::class.java) val compiledClassesList = File("dn-out${UUID.randomUUID()}.txt") compiledClassesList.bufferedWriter().use { out -> outputConsumer.compiledClasses.forEach { out.write("${it.value.outputFile.absolutePath}\n") } } m.isAccessible = true m.invoke(null, arrayOf("-api", "JPA", "-flf", compiledClassesList.absolutePath)) exitCode = ExitCode.OK } catch (e: Exception) { LOG.error("Enhancing failed", e) context.processMessage(CompilerMessage("Enhancing failed", e)) } finally { Thread.currentThread().contextClassLoader = cl } } } } finally { buildClassLoader.close() } } finally { if (shouldShowProgress) { context.processMessage(ProgressMessage("")) // cleanup progress } } return exitCode } override fun getPresentableName() = "Datanucleus enhancer" fun getProgressMessage() = "Enhancing classes..." }
apache-2.0
cf33ddddc2ba2f5005409ca7c84e4850
46.25
230
0.612385
5.417197
false
false
false
false
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/di/ActivitiesModule.kt
1
3404
/* Copyright 2018 charlag * * This file is a part of Tusky. * * 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. * * Tusky 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 Tusky; if not, * see <http://www.gnu.org/licenses>. */ package com.keylesspalace.tusky.di import com.keylesspalace.tusky.* import dagger.Module import dagger.android.ContributesAndroidInjector /** * Created by charlag on 3/24/18. */ @Module abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesBaseActivity(): BaseActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesMainActivity(): MainActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesAccountActivity(): AccountActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesListsActivity(): ListsActivity @ContributesAndroidInjector abstract fun contributesComposeActivity(): ComposeActivity @ContributesAndroidInjector abstract fun contributesEditProfileActivity(): EditProfileActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesAccountListActivity(): AccountListActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesModalTimelineActivity(): ModalTimelineActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesViewTagActivity(): ViewTagActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesViewThreadActivity(): ViewThreadActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesFavouritesActivity(): FavouritesActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contribtutesSearchAvtivity(): SearchActivity @ContributesAndroidInjector abstract fun contributesAboutActivity(): AboutActivity @ContributesAndroidInjector abstract fun contributesLoginActivity(): LoginActivity @ContributesAndroidInjector abstract fun contributesSplashActivity(): SplashActivity @ContributesAndroidInjector abstract fun contributesReportActivity(): ReportActivity @ContributesAndroidInjector abstract fun contributesSavedTootActivity(): SavedTootActivity @ContributesAndroidInjector(modules = [FragmentBuildersModule::class]) abstract fun contributesPreferencesActivity(): PreferencesActivity @ContributesAndroidInjector abstract fun contributesViewMediaActivity(): ViewMediaActivity @ContributesAndroidInjector abstract fun contributesLicenseActivity(): LicenseActivity @ContributesAndroidInjector abstract fun contributesTabPreferenceActivity(): TabPreferenceActivity }
gpl-3.0
d953234e4fdcaa5efd7ea62482ea66e8
36.01087
99
0.796416
6.046181
false
false
false
false
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/viewmodel/ReportDetailsViewModel.kt
1
1123
package lt.vilnius.tvarkau.viewmodel import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import io.reactivex.Scheduler import io.reactivex.rxkotlin.subscribeBy import lt.vilnius.tvarkau.dagger.UiScheduler import lt.vilnius.tvarkau.entity.ReportEntity import lt.vilnius.tvarkau.repository.ReportsRepository import javax.inject.Inject class ReportDetailsViewModel @Inject constructor( private val reportsRepository: ReportsRepository, @UiScheduler private val uiScheduler: Scheduler ) : BaseViewModel() { private val _report = MutableLiveData<ReportEntity>() val report: LiveData<ReportEntity> get() = _report fun initWith(reportId: Int) { reportsRepository.getReportById(reportId) .observeOn(uiScheduler) .subscribeBy( onSuccess = ::handleSuccess, onError = ::handleError ).bind() } private fun handleSuccess(report: ReportEntity) { _report.value = report } private fun handleError(throwable: Throwable) { _errorEvents.value = throwable } }
mit
6c8f21c2ef68873213fff57b537ffde3
28.552632
57
0.712378
4.698745
false
false
false
false
rock3r/detekt
detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/internal/CyclomaticComplexitySpec.kt
1
6905
package io.gitlab.arturbosch.detekt.api.internal import io.gitlab.arturbosch.detekt.test.compileContentForTest import io.gitlab.arturbosch.detekt.test.getFunctionByName import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class CyclomaticComplexitySpec : Spek({ val defaultFunctionComplexity = 1 describe("basic function expressions are tested") { it("counts for safe navigation") { val code = compileContentForTest(""" fun test() = null as? String ?: "" """.trimIndent()) val actual = CyclomaticComplexity.calculate(code) assertThat(actual).isEqualTo(defaultFunctionComplexity + 1) } it("counts if and && and || expressions") { val code = compileContentForTest(""" fun test() = if (true || true && false) 1 else 0 """.trimIndent()) val actual = CyclomaticComplexity.calculate(code) assertThat(actual).isEqualTo(defaultFunctionComplexity + 3) } it("counts while, continue and break") { val code = compileContentForTest(""" fun test(i: Int) { var j = i while(true) { // 1 if (j == 5) { // 1 continue // 1 } else if (j == 2) { // 1 break // 1 } else { j += i } } println("finished") } """.trimIndent()) val actual = CyclomaticComplexity.calculate(code) assertThat(actual).isEqualTo(defaultFunctionComplexity + 5) } } describe("counts function calls used for nesting") { val code = compileContentForTest(""" fun test(i: Int) { (1..10).forEach { println(it) } } """.trimIndent() ) it("counts them by default") { assertThat( CyclomaticComplexity.calculate(code) ).isEqualTo(defaultFunctionComplexity + 1) } it("does not count them when ignored") { assertThat( CyclomaticComplexity.calculate(code) { ignoreNestingFunctions = true } ).isEqualTo(defaultFunctionComplexity) } it("does not count when forEach is not specified") { assertThat( CyclomaticComplexity.calculate(code) { nestingFunctions = setOf() } ).isEqualTo(defaultFunctionComplexity) } it("counts them by default") { assertThat( CyclomaticComplexity.calculate(code) { nestingFunctions = setOf("forEach") } ).isEqualTo(defaultFunctionComplexity + 1) } } describe("ignoreSimpleWhenEntries is false") { it("counts simple when branches as 1") { val function = compileContentForTest(""" fun test() { when (System.currentTimeMillis()) { 0 -> println("Epoch!") 1 -> println("1 past epoch.") else -> println("Meh") } } """).getFunctionByName("test") val actual = CyclomaticComplexity.calculate(function) { ignoreSimpleWhenEntries = false } assertThat(actual).isEqualTo(defaultFunctionComplexity + 3) } it("counts block when branches as 1") { val function = compileContentForTest(""" fun test() { when (System.currentTimeMillis()) { 0 -> { println("Epoch!") } 1 -> println("1 past epoch.") else -> println("Meh") } } """).getFunctionByName("test") val actual = CyclomaticComplexity.calculate(function) { ignoreSimpleWhenEntries = false } assertThat(actual).isEqualTo(defaultFunctionComplexity + 3) } } describe("ignoreSimpleWhenEntries is true") { it("counts a when with only simple branches as 1") { val function = compileContentForTest(""" fun test() { when (System.currentTimeMillis()) { 0 -> println("Epoch!") 1 -> println("1 past epoch.") else -> println("Meh") } } """).getFunctionByName("test") val actual = CyclomaticComplexity.calculate(function) { ignoreSimpleWhenEntries = true } assertThat(actual).isEqualTo(defaultFunctionComplexity + 1) } it("does not count simple when branches") { val function = compileContentForTest(""" fun test() { when (System.currentTimeMillis()) { 0 -> { println("Epoch!") println("yay") } 1 -> { println("1 past epoch!") } else -> println("Meh") } } """).getFunctionByName("test") val actual = CyclomaticComplexity.calculate(function) { ignoreSimpleWhenEntries = true } assertThat(actual).isEqualTo(defaultFunctionComplexity + 2) } it("counts block when branches as 1") { val function = compileContentForTest(""" fun test() { when (System.currentTimeMillis()) { 0 -> { println("Epoch!") println("yay!") } 1 -> { println("1 past epoch.") println("yay?") } 2 -> println("shrug") else -> println("Meh") } } """).getFunctionByName("test") val actual = CyclomaticComplexity.calculate(function) { ignoreSimpleWhenEntries = true } assertThat(actual).isEqualTo(defaultFunctionComplexity + 2) } } })
apache-2.0
a86a75aca5831d08ce9e1f6b2acee39c
32.519417
71
0.453874
5.988725
false
true
false
false
rock3r/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/BaseRule.kt
1
2517
package io.gitlab.arturbosch.detekt.api.internal import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Context import io.gitlab.arturbosch.detekt.api.DefaultContext import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.api.RuleId import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext abstract class BaseRule( protected val context: Context = DefaultContext() ) : DetektVisitor(), Context by context { open val ruleId: RuleId = javaClass.simpleName var bindingContext: BindingContext = BindingContext.EMPTY /** * Before starting visiting kotlin elements, a check is performed if this rule should be triggered. * Pre- and post-visit-hooks are executed before/after the visiting process. * BindingContext holds the result of the semantic analysis of the source code by the Kotlin compiler. Rules that * rely on symbols and types being resolved can use the BindingContext for this analysis. Note that detekt must * receive the correct compile classpath for the code being analyzed otherwise the default value * BindingContext.EMPTY will be used and it will not be possible for detekt to resolve types or symbols. */ fun visitFile(root: KtFile, bindingContext: BindingContext = BindingContext.EMPTY) { this.bindingContext = bindingContext if (visitCondition(root)) { clearFindings() preVisit(root) visit(root) postVisit(root) } } /** * Init function to start visiting the [KtFile]. * Can be overridden to start a different visiting process. */ open fun visit(root: KtFile) { root.accept(this) } /** * Basic mechanism to decide if a rule should run or not. * * By default any rule which is declared 'active' in the [Config] * or not suppressed by a [Suppress] annotation on file level should run. */ abstract fun visitCondition(root: KtFile): Boolean /** * Could be overridden by subclasses to specify a behaviour which should be done before * visiting kotlin elements. */ protected open fun preVisit(root: KtFile) { // nothing to do by default } /** * Could be overridden by subclasses to specify a behaviour which should be done after * visiting kotlin elements. */ protected open fun postVisit(root: KtFile) { // nothing to do by default } }
apache-2.0
923d9c5350f79a071d0d8aac109f9ba2
36.567164
117
0.700834
4.731203
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/render/common/components/gl/GLViewport.kt
1
1438
package com.fracturedskies.render.common.components.gl import com.fracturedskies.engine.collections.* import com.fracturedskies.engine.jeact.* import com.fracturedskies.render.common.style.Padding import org.lwjgl.opengl.GL11.* class GLViewport : Component<Unit>(Unit) { companion object { fun (Node.Builder<*>).viewport(padding: Padding = Padding(), additionalProps: MultiTypeMap = MultiTypeMap(), block: Node.Builder<Unit>.() -> (Unit) = {}) { nodes.add(Node(GLViewport::class, MultiTypeMap( PADDING to padding ).with(additionalProps), block)) } val PADDING = TypedKey<Padding>("padding") } private val padding get() = props[PADDING] override fun glPreferredWidth(parentWidth: Int, parentHeight: Int): Int { return padding.left + padding.right + super.glPreferredWidth(parentWidth, parentHeight) } override fun glPreferredHeight(parentWidth: Int, parentHeight: Int): Int { return padding.top + padding.bottom + super.glPreferredHeight(parentWidth, parentHeight) } override fun glRender(bounds: Bounds) { val paddedBounds = Bounds( bounds.x + padding.left, bounds.y + padding.top, bounds.width - padding.left - padding.right, bounds.height - padding.top - padding.bottom ) glViewport(paddedBounds.x, paddedBounds.y, paddedBounds.width, paddedBounds.height) glClear(GL_DEPTH_BUFFER_BIT) super.glRender(paddedBounds) } }
unlicense
e3eba19f836f8de80d90e50947449dd8
34.975
159
0.716273
3.994444
false
false
false
false
MichaelRocks/Sunny
app/src/main/kotlin/io/michaelrocks/forecast/model/repository/sqlite/LocationStorage.kt
1
1393
/* * Copyright 2016 Michael Rozumyanskiy * * 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.michaelrocks.forecast.model.repository.sqlite import android.content.Context import javax.inject.Inject private const val LATITUDE_KEY = "latitude" private const val LONGITUDE_KEY = "longitude" internal class LocationStorage @Inject private constructor( context: Context ) { val preferences = context.getSharedPreferences("location", Context.MODE_PRIVATE) val latitude: Double get() = preferences.getFloat(LATITUDE_KEY, Float.NaN).toDouble() val longitude: Double get() = preferences.getFloat(LONGITUDE_KEY, Float.NaN).toDouble() fun updateCoordinates(latitude: Double, longitude: Double) { preferences .edit() .putFloat(LATITUDE_KEY, latitude.toFloat()) .putFloat(LONGITUDE_KEY, longitude.toFloat()) .apply() } }
apache-2.0
237d128d74738d47b91876017289d9eb
32.166667
82
0.735104
4.259939
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/DataFragment.kt
1
6117
package com.boardgamegeek.ui import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContract import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.boardgamegeek.databinding.FragmentDataBinding import com.boardgamegeek.export.Constants import com.boardgamegeek.extensions.toast import com.boardgamegeek.ui.viewmodel.DataPortViewModel import com.boardgamegeek.ui.widget.DataStepRow import com.boardgamegeek.util.FileUtils import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import timber.log.Timber class DataFragment : Fragment() { private var _binding: FragmentDataBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<DataPortViewModel>() @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentDataBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.collectionViewsRow.onExport { registerForCollectionViewsExport.launch(Constants.TYPE_COLLECTION_VIEWS_DESCRIPTION) } binding.collectionViewsRow.onImport { registerForCollectionViewsImport.launch(null) } binding.gamesRow.onExport { registerForGamesExport.launch(Constants.TYPE_GAMES_DESCRIPTION) } binding.gamesRow.onImport { registerForGamesImport.launch(null) } binding.usersRow.onExport { registerForUsersExport.launch(Constants.TYPE_USERS_DESCRIPTION) } binding.usersRow.onImport { registerForUsersImport.launch(null) } viewModel.message.observe(viewLifecycleOwner) { event -> event.getContentIfNotHandled()?.let { content -> toast(content) } } viewModel.collectionViewProgress.observe(viewLifecycleOwner) { binding.collectionViewsRow.updateProgressBar(it) } viewModel.gameProgress.observe(viewLifecycleOwner) { binding.gamesRow.updateProgressBar(it) } viewModel.userProgress.observe(viewLifecycleOwner) { binding.usersRow.updateProgressBar(it) } } override fun onDestroyView() { super.onDestroyView() _binding = null } private val registerForCollectionViewsExport = registerForActivityResult(ExportFileContract()) { uri -> doExport(uri, binding.collectionViewsRow) { viewModel.exportCollectionViews(it) } } private val registerForCollectionViewsImport = registerForActivityResult(ImportFileContract()) { uri -> doImport(uri, binding.collectionViewsRow) { viewModel.importCollectionViews(it) } } private val registerForGamesExport = registerForActivityResult(ExportFileContract()) { uri -> doExport(uri, binding.gamesRow) { viewModel.exportGames(it) } } private val registerForGamesImport = registerForActivityResult(ImportFileContract()) { uri -> doImport(uri, binding.gamesRow) { viewModel.importGames(it) } } private val registerForUsersExport = registerForActivityResult(ExportFileContract()) { uri -> doExport(uri, binding.usersRow) { viewModel.exportUsers(it) } } private val registerForUsersImport = registerForActivityResult(ImportFileContract()) { uri -> doImport(uri, binding.usersRow) { viewModel.importUsers(it) } } private fun doExport(uri: Uri?, dataStepRow: DataStepRow, export: (Uri) -> Unit) { uri?.let { tryUriPermission(it) dataStepRow.initProgressBar() export(it) logAction("Export") } } private fun doImport(uri: Uri?, dataStepRow: DataStepRow, import: (Uri) -> Unit) { uri?.let { tryUriPermission(it) dataStepRow.initProgressBar() import(it) logAction("Import") } } private fun tryUriPermission(uri: Uri) { try { requireContext().contentResolver.takePersistableUriPermission( uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) } catch (e: SecurityException) { Timber.e(e, "Could not persist URI permissions for '%s'.", uri.toString()) } } private fun logAction(action: String) { Firebase.analytics.logEvent("DataManagement") { param("Action", action) } } class ExportFileContract : ActivityResultContract<String, Uri?>() { override fun createIntent(context: Context, typeDescription: String): Intent { return Intent(Intent.ACTION_CREATE_DOCUMENT) .addCategory(Intent.CATEGORY_OPENABLE) .setType("application/*") .putExtra(Intent.EXTRA_TITLE, FileUtils.getExportFileName(typeDescription)) } override fun parseResult(resultCode: Int, intent: Intent?): Uri? { return if (resultCode == Activity.RESULT_OK) intent?.data else null } } class ImportFileContract : ActivityResultContract<Unit, Uri?>() { override fun createIntent(context: Context, input: Unit?): Intent { return Intent(Intent.ACTION_OPEN_DOCUMENT) .addCategory(Intent.CATEGORY_OPENABLE) .setType("application/*") } override fun parseResult(resultCode: Int, intent: Intent?): Uri? { return if (resultCode == Activity.RESULT_OK) intent?.data else null } } }
gpl-3.0
dd1fecb171fad5afb5f1e2985d6e7014
36.29878
121
0.674187
4.897518
false
false
false
false
LanternPowered/LanternServer
src/main/java/org/lanternpowered/server/block/entity/vanilla/ContainerBlockEntityBase.kt
1
3427
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.block.entity.vanilla import org.lanternpowered.api.world.Location import org.lanternpowered.server.block.entity.BlockEntityCreationData import org.lanternpowered.server.block.entity.LanternBlockEntity import org.lanternpowered.server.block.vanilla.container.action.ContainerAnimationAction import org.lanternpowered.server.inventory.AbstractContainer import org.lanternpowered.server.inventory.InventoryViewerListener import org.lanternpowered.server.world.LanternWorldNew import org.spongepowered.api.entity.living.player.Player import java.util.HashSet import kotlin.time.Duration import kotlin.time.seconds abstract class ContainerBlockEntityBase(creationData: BlockEntityCreationData) : LanternBlockEntity(creationData), InventoryViewerListener { protected val viewers = HashSet<Player>() /** * The delay that will be used to play the open/close sounds. */ private var soundDelay = 0.seconds /** * Gets the delay that should be used to * play the open sound. * * @return The open sound delay */ protected val openSoundDelay: Duration get() = 0.25.seconds /** * Gets the delay that should be used to * play the open sound. * * @return The open sound delay */ protected val closeSoundDelay: Duration get() = 0.5.seconds override fun onViewerAdded(viewer: Player, container: AbstractContainer, callback: InventoryViewerListener.Callback) { if (!this.viewers.add(viewer) || this.viewers.size != 1) return this.soundDelay = this.openSoundDelay val location = this.location val world = location.world as LanternWorldNew world.addBlockAction(location.blockPosition, this.block.type, ContainerAnimationAction.OPEN) } override fun onViewerRemoved(viewer: Player, container: AbstractContainer, callback: InventoryViewerListener.Callback) { if (!this.viewers.remove(viewer) || this.viewers.size != 0) return this.soundDelay = this.closeSoundDelay val location = this.location val world = location.world as LanternWorldNew world.addBlockAction(location.blockPosition, block.type, ContainerAnimationAction.CLOSE) } /** * Plays the open sound at the [Location]. * * @param location The location */ protected abstract fun playOpenSound(location: Location) /** * Plays the close sound at the [Location]. * * @param location The location */ protected abstract fun playCloseSound(location: Location) override fun update(deltaTime: Duration) { super.update(deltaTime) if (this.soundDelay > Duration.ZERO) { this.soundDelay -= deltaTime if (this.soundDelay <= Duration.ZERO) { val location = this.location if (this.viewers.size > 0) { this.playOpenSound(location) } else { this.playCloseSound(location) } } } } }
mit
a9089a42c191891e9fba1173a5e2911f
33.27
124
0.681938
4.439119
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/scoreboard/LanternTeamBuilder.kt
1
4491
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.scoreboard import org.lanternpowered.api.scoreboard.ScoreboardTeam import org.lanternpowered.api.scoreboard.ScoreboardTeamBuilder import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.emptyText import org.lanternpowered.api.text.format.NamedTextColor import org.lanternpowered.api.text.textOf import org.lanternpowered.api.text.toPlain import org.lanternpowered.api.util.collections.toImmutableSet import org.spongepowered.api.scoreboard.CollisionRule import org.spongepowered.api.scoreboard.CollisionRules import org.spongepowered.api.scoreboard.Visibilities import org.spongepowered.api.scoreboard.Visibility class LanternTeamBuilder : ScoreboardTeamBuilder { private var name: String? = null private var displayName: Text? = null private var prefix: Text = emptyText() private var suffix: Text = emptyText() private var color: NamedTextColor = NamedTextColor.WHITE private var allowFriendlyFire = false private var showFriendlyInvisibles = false private var nameTagVisibility: Visibility = Visibilities.ALWAYS.get() private var deathMessageVisibility: Visibility = Visibilities.ALWAYS.get() private var collisionRule: CollisionRule = CollisionRules.NEVER.get() private var members: Set<Text> = emptySet() override fun displayName(displayName: Text): LanternTeamBuilder = apply { val length = displayName.toPlain().length check(length <= 32) { "Display name is $length characters long! It must be at most 32." } this.displayName = displayName } override fun color(color: NamedTextColor): LanternTeamBuilder = apply { this.color = color } override fun name(name: String): LanternTeamBuilder = apply { this.name = name } override fun prefix(prefix: Text): LanternTeamBuilder = apply { this.prefix = prefix } override fun suffix(suffix: Text): LanternTeamBuilder = apply { this.suffix = suffix } override fun allowFriendlyFire(enabled: Boolean): LanternTeamBuilder = apply { this.allowFriendlyFire = enabled } override fun canSeeFriendlyInvisibles(enabled: Boolean): LanternTeamBuilder = apply { this.showFriendlyInvisibles = enabled } override fun nameTagVisibility(visibility: Visibility): LanternTeamBuilder = apply { this.nameTagVisibility = visibility } override fun deathTextVisibility(visibility: Visibility): LanternTeamBuilder = apply { this.deathMessageVisibility = visibility } override fun collisionRule(rule: CollisionRule): LanternTeamBuilder = apply { this.collisionRule = rule } override fun members(members: Set<Text>): LanternTeamBuilder = apply { this.members = members.toImmutableSet() } override fun from(value: ScoreboardTeam): LanternTeamBuilder = name(value.name) .displayName(value.displayName) .color(value.color) .allowFriendlyFire(value.allowFriendlyFire()) .canSeeFriendlyInvisibles(value.canSeeFriendlyInvisibles()) .nameTagVisibility(value.nameTagVisibility) .deathTextVisibility(value.deathMessageVisibility) .members(value.members) override fun reset(): LanternTeamBuilder = apply { this.name = null this.displayName = null this.prefix = emptyText() this.suffix = emptyText() this.allowFriendlyFire = false this.showFriendlyInvisibles = false this.color = NamedTextColor.WHITE this.nameTagVisibility = Visibilities.ALWAYS.get() this.deathMessageVisibility = Visibilities.ALWAYS.get() this.collisionRule = CollisionRules.NEVER.get() this.members = emptySet() } override fun build(): ScoreboardTeam { val name = checkNotNull(this.name) { "The name must be set" } val displayName = this.displayName ?: textOf(name) val team = LanternTeam(name, this.color, displayName, this.prefix, this.suffix, this.allowFriendlyFire, this.showFriendlyInvisibles, this.nameTagVisibility, this.deathMessageVisibility, this.collisionRule) this.members.forEach { member -> team.addMember(member) } return team } }
mit
51b7ca11d9354aaaa73304022e6b5de7
49.460674
133
0.735471
4.513568
false
false
false
false
raatiniemi/worker
core/src/main/java/me/raatiniemi/worker/domain/model/TimesheetItem.kt
1
2864
/* * Copyright (C) 2018 Tobias Raatiniemi * * 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, version 2 of the License. * * 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 me.raatiniemi.worker.domain.model import me.raatiniemi.worker.domain.comparator.TimesheetItemComparator import me.raatiniemi.worker.domain.util.CalculateTime import me.raatiniemi.worker.domain.util.HoursMinutesFormat import java.text.SimpleDateFormat import java.util.* data class TimesheetItem(private val timeInterval: TimeInterval) : Comparable<TimesheetItem> { private val timeFormat = SimpleDateFormat("HH:mm", Locale.forLanguageTag("en_US")) val hoursMinutes: HoursMinutes = CalculateTime.calculateHoursMinutes(timeInterval.interval) val id = timeInterval.id val title: String get() { val title = buildTitleFromStartTime() if (!timeInterval.isActive) { appendStopTimeWithSeparator(title) } return title.toString() } val isRegistered = timeInterval.isRegistered fun asTimeInterval(): TimeInterval { return timeInterval } private fun buildTitleFromStartTime(): StringBuilder { val builder = StringBuilder() builder.append(timeFormat.format(buildDateFromStartTime())) return builder } private fun buildDateFromStartTime(): Date { return buildDateFromMilliseconds(timeInterval.startInMilliseconds) } private fun appendStopTimeWithSeparator(title: StringBuilder) { title.append(TIME_SEPARATOR) title.append(timeFormat.format(buildDateFromStopTime())) } private fun buildDateFromStopTime(): Date { return buildDateFromMilliseconds(timeInterval.stopInMilliseconds) } fun getTimeSummaryWithFormatter(formatter: HoursMinutesFormat): String { return formatter.apply(hoursMinutes) } override fun compareTo(other: TimesheetItem): Int { return comparator.compare(this, other) } companion object { private const val TIME_SEPARATOR = " - " private val comparator = TimesheetItemComparator() private fun buildDateFromMilliseconds(milliseconds: Long): Date { return Date(milliseconds) } @JvmStatic fun with(time: TimeInterval): TimesheetItem { return TimesheetItem(time) } } }
gpl-2.0
fe26198c7f2c9a86cd33bba3209f2be0
31.179775
95
0.707402
4.955017
false
false
false
false
wzhxyz/ACManager
src/main/java/com/zzkun/controller/api/UserApi.kt
1
1778
package com.zzkun.controller.api import com.alibaba.fastjson.JSONObject import com.zzkun.model.User import com.zzkun.service.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import java.util.* fun User.toJson(): JSONObject { val user = this val res = LinkedHashMap<String, Any?>() res["id"] = user.id res["username"] = user.username res["realName"] = user.realName res["uvaId"] = user.uvaId res["cfname"] = user.cfname res["vjname"] = user.vjname res["bcname"] = user.bcname res["hduName"] = user.hduName res["pojName"] = user.pojName res["major"] = user.major res["blogUrl"] = user.blogUrl res["type"] = user.type.toString() res["typeChs"] = user.type.toShortStr() return JSONObject(res) } @RestController @RequestMapping("/api/user") class UserApi( @Autowired val userService: UserService) { @RequestMapping(value = "/{username}/detail", method = arrayOf(RequestMethod.GET), produces = arrayOf("text/html;charset=UTF-8")) fun detail(@PathVariable username: String): String { return userService.getUserByUsername(username).toJson().toString() } @RequestMapping(value = "/{userId}/detailById", method = arrayOf(RequestMethod.GET), produces = arrayOf("text/html;charset=UTF-8")) fun detailById(@PathVariable userId: Int): String { return userService.getUserById(userId).toJson().toString() } }
gpl-3.0
41af6e53556fa4fd36828d9ff5e75da9
32.901961
74
0.67829
3.96875
false
false
false
false
Kotlin/kotlinx.serialization
formats/json-tests/commonTest/src/kotlinx/serialization/features/PolymorphismWithAnyTest.kt
1
4739
/* * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.features import kotlinx.serialization.* import kotlinx.serialization.json.Json import kotlinx.serialization.modules.* import kotlinx.serialization.modules.plus import kotlinx.serialization.test.assertStringFormAndRestored import kotlin.test.* class PolymorphismWithAnyTest { @Serializable data class MyPolyData(val data: Map<String, @Polymorphic Any>) @Serializable data class MyPolyDataWithPolyBase( val data: Map<String, @Polymorphic Any>, @Polymorphic val polyBase: PolyBase ) // KClass.toString() on JS prints simple name, not FQ one @Suppress("NAME_SHADOWING") private fun checkNotRegisteredMessage(className: String, scopeName: String, exception: SerializationException) { val className = className.substringAfterLast('.') val scopeName = scopeName.substringAfterLast('.') val expectedText = "Class '$className' is not registered for polymorphic serialization in the scope of '$scopeName'" assertTrue(exception.message!!.startsWith(expectedText), "Found $exception, but expected to start with: $expectedText") } @Test fun testFailWithoutModulesWithCustomClass() { checkNotRegisteredMessage( "kotlinx.serialization.IntData", "kotlin.Any", assertFailsWith<SerializationException>("not registered") { Json.encodeToString( MyPolyData.serializer(), MyPolyData(mapOf("a" to IntData(42))) ) } ) } @Test fun testWithModules() { val json = Json { serializersModule = SerializersModule { polymorphic(Any::class) { subclass(IntData.serializer()) } } } assertStringFormAndRestored( expected = """{"data":{"a":{"type":"kotlinx.serialization.IntData","intV":42}}}""", original = MyPolyData(mapOf("a" to IntData(42))), serializer = MyPolyData.serializer(), format = json ) } /** * This test should fail because PolyDerived registered in the scope of PolyBase, not kotlin.Any */ @Test fun testFailWithModulesNotInAnyScope() { val json = Json { serializersModule = BaseAndDerivedModule } checkNotRegisteredMessage( "kotlinx.serialization.PolyDerived", "kotlin.Any", assertFailsWith<SerializationException> { json.encodeToString( MyPolyData.serializer(), MyPolyData(mapOf("a" to PolyDerived("foo"))) ) } ) } private val baseAndDerivedModuleAtAny = SerializersModule { polymorphic(Any::class) { subclass(PolyDerived.serializer()) } } @Test fun testRebindModules() { val json = Json { serializersModule = baseAndDerivedModuleAtAny } assertStringFormAndRestored( expected = """{"data":{"a":{"type":"kotlinx.serialization.PolyDerived","id":1,"s":"foo"}}}""", original = MyPolyData(mapOf("a" to PolyDerived("foo"))), serializer = MyPolyData.serializer(), format = json ) } /** * This test should fail because PolyDerived registered in the scope of kotlin.Any, not PolyBase */ @Test fun testFailWithModulesNotInParticularScope() { val json = Json { serializersModule = baseAndDerivedModuleAtAny } checkNotRegisteredMessage( "kotlinx.serialization.PolyDerived", "kotlinx.serialization.PolyBase", assertFailsWith { json.encodeToString( MyPolyDataWithPolyBase.serializer(), MyPolyDataWithPolyBase( mapOf("a" to PolyDerived("foo")), PolyDerived("foo") ) ) } ) } @Test fun testBindModules() { val json = Json { serializersModule = (baseAndDerivedModuleAtAny + BaseAndDerivedModule) } assertStringFormAndRestored( expected = """{"data":{"a":{"type":"kotlinx.serialization.PolyDerived","id":1,"s":"foo"}}, |"polyBase":{"type":"kotlinx.serialization.PolyDerived","id":1,"s":"foo"}}""".trimMargin().lines().joinToString( "" ), original = MyPolyDataWithPolyBase( mapOf("a" to PolyDerived("foo")), PolyDerived("foo") ), serializer = MyPolyDataWithPolyBase.serializer(), format = json ) } }
apache-2.0
68b0a90e7f67f65129c61bab2f7bed0c
34.631579
128
0.600971
4.993678
false
true
false
false
lllllT/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/realm/RealmAccount.kt
2
769
package com.bl_lia.kirakiratter.domain.entity.realm import com.bl_lia.kirakiratter.domain.entity.Account import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class RealmAccount( @PrimaryKey open var id: Int = -1, open var userName: String? = null, open var displayName: String? = null, open var avatar: String? = null, open var header: String? = null, open var note: String? = null ): RealmObject() { fun toAccount(): Account = Account( id = id, userName = userName, displayName = displayName, avatar = avatar, header = header, note = note ) }
mit
129a6e7e8200d64e8f6e00e0bcbc069b
28.615385
52
0.548765
4.746914
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateDuchyMeasurementLogEntry.kt
1
6500
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers import com.google.cloud.spanner.Statement import com.google.cloud.spanner.Struct import com.google.cloud.spanner.Value import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.singleOrNull import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation import org.wfanet.measurement.gcloud.spanner.set import org.wfanet.measurement.gcloud.spanner.setJson import org.wfanet.measurement.internal.kingdom.CreateDuchyMeasurementLogEntryRequest import org.wfanet.measurement.internal.kingdom.DuchyMeasurementLogEntry import org.wfanet.measurement.internal.kingdom.copy import org.wfanet.measurement.internal.kingdom.duchyMeasurementLogEntry import org.wfanet.measurement.internal.kingdom.measurementLogEntry import org.wfanet.measurement.kingdom.deploy.common.DuchyIds import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementNotFoundByComputationException /** * Creates a DuchyMeasurementLogEntry and MeasurementLogEntry in the database. * * Throws a subclass of [KingdomInternalException] on [execute]. * @throws [MeasurementNotFoundByComputationException] Measurement not found * @throws [DuchyNotFoundException] Duchy not found */ class CreateDuchyMeasurementLogEntry(private val request: CreateDuchyMeasurementLogEntryRequest) : SpannerWriter<DuchyMeasurementLogEntry, DuchyMeasurementLogEntry>() { data class MeasurementIds( val measurementId: InternalId, val measurementConsumerId: InternalId, val externalMeasurementId: ExternalId, val externalMeasurementConsumerId: ExternalId ) override suspend fun TransactionScope.runTransaction(): DuchyMeasurementLogEntry { val measurementIds = readMeasurementIds() ?: throw MeasurementNotFoundByComputationException( ExternalId(request.externalComputationId) ) { "Measurement for external computation ID ${request.externalComputationId} not found" } val duchyId = DuchyIds.getInternalId(request.externalDuchyId) ?: throw DuchyNotFoundException(request.externalDuchyId) insertMeasurementLogEntry(measurementIds.measurementId, measurementIds.measurementConsumerId) val externalComputationLogEntryId = insertDuchyMeasurementLogEntry( measurementIds.measurementId, measurementIds.measurementConsumerId, InternalId(duchyId) ) return duchyMeasurementLogEntry { this.externalComputationLogEntryId = externalComputationLogEntryId.value details = request.details externalDuchyId = request.externalDuchyId logEntry = measurementLogEntry { details = request.measurementLogEntryDetails externalMeasurementId = measurementIds.externalMeasurementId.value externalMeasurementConsumerId = measurementIds.externalMeasurementConsumerId.value } } } private fun TransactionScope.insertMeasurementLogEntry( measurementId: InternalId, measurementConsumerId: InternalId, ) { transactionContext.bufferInsertMutation("MeasurementLogEntries") { set("MeasurementConsumerId" to measurementConsumerId) set("MeasurementId" to measurementId) set("CreateTime" to Value.COMMIT_TIMESTAMP) set("MeasurementLogDetails" to request.measurementLogEntryDetails) setJson("MeasurementLogDetailsJson" to request.measurementLogEntryDetails) } } private fun TransactionScope.insertDuchyMeasurementLogEntry( measurementId: InternalId, measurementConsumerId: InternalId, duchyId: InternalId ): ExternalId { val externalComputationLogEntryId = idGenerator.generateExternalId() transactionContext.bufferInsertMutation("DuchyMeasurementLogEntries") { set("MeasurementConsumerId" to measurementConsumerId) set("MeasurementId" to measurementId) set("CreateTime" to Value.COMMIT_TIMESTAMP) set("DuchyId" to duchyId) set("ExternalComputationLogEntryId" to externalComputationLogEntryId) set("DuchyMeasurementLogDetails" to request.details) setJson("DuchyMeasurementLogDetailsJson" to request.details) } return externalComputationLogEntryId } fun translateToInternalIds(struct: Struct): MeasurementIds = MeasurementIds( InternalId(struct.getLong("MeasurementId")), InternalId(struct.getLong("MeasurementConsumerId")), ExternalId(struct.getLong("ExternalMeasurementId")), ExternalId(struct.getLong("ExternalMeasurementConsumerId")) ) private suspend fun TransactionScope.readMeasurementIds(): MeasurementIds? { return transactionContext .executeQuery( Statement.newBuilder( """ SELECT Measurements.MeasurementId, Measurements.MeasurementConsumerId, Measurements.ExternalMeasurementId, Measurements.ExternalComputationId, MeasurementConsumers.ExternalMeasurementConsumerId, FROM Measurements JOIN MeasurementConsumers USING (MeasurementConsumerId) WHERE ExternalComputationId = ${request.externalComputationId} LIMIT 1 """ .trimIndent() ) .build() ) .map(::translateToInternalIds) .singleOrNull() } override fun ResultScope<DuchyMeasurementLogEntry>.buildResult(): DuchyMeasurementLogEntry { val duchMeasurementLogEntry = checkNotNull(transactionResult) return duchMeasurementLogEntry.copy { logEntry = duchMeasurementLogEntry.logEntry.copy { createTime = commitTimestamp.toProto() } } } }
apache-2.0
02c0829acffc5d5c09481d85d0f8efd1
39.880503
108
0.769846
5.271695
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/action/preview/InkscapePreviewer.kt
1
6445
package nl.hannahsten.texifyidea.action.preview import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import nl.hannahsten.texifyidea.settings.sdk.LatexSdkUtil import nl.hannahsten.texifyidea.ui.PreviewForm import nl.hannahsten.texifyidea.util.SystemEnvironment import nl.hannahsten.texifyidea.util.runCommandWithExitCode import java.io.File import java.io.IOException import java.io.PrintWriter import java.nio.file.Paths import javax.imageio.ImageIO import javax.swing.SwingUtilities /** * Preview based on Inkscape. */ class InkscapePreviewer : Previewer { override fun preview(input: String, previewForm: PreviewForm, project: Project, preamble: String, waitTime: Long) { runBlocking { launch { try { // Snap apps are confined to the users home directory if (SystemEnvironment.isInkscapeInstalledAsSnap) { @Suppress("BlockingMethodInNonBlockingContext") setPreviewCodeInTemp( FileUtil.createTempDirectory(File(System.getProperty("user.home")), "preview", null), input, project, preamble, previewForm, waitTime ) } else { @Suppress("BlockingMethodInNonBlockingContext") setPreviewCodeInTemp(FileUtil.createTempDirectory("preview", null), input, project, preamble, previewForm, waitTime) } } catch (exception: AccessDeniedException) { previewForm.setLatexErrorMessage("${exception.message}") } catch (exception: IOException) { previewForm.setLatexErrorMessage("${exception.message}") } } } } /** * First define the function that actually does stuff in a temp folder. The usual temp directory might not be * accessible by inkscape (e.g., when inkscape is a snap), and using function we can specify an alternative * temp directory in case the usual fails. */ private fun setPreviewCodeInTemp( tempDirectory: File, previewCode: String, project: Project, preamble: String, previewForm: PreviewForm, waitTime: Long ) { try { val tempBasename = Paths.get(tempDirectory.path.toString(), "temp").toString() val writer = PrintWriter("$tempBasename.tex", "UTF-8") val tmpContent = """\documentclass{article} $preamble \begin{document} $previewCode \end{document}""" writer.println(tmpContent) writer.close() val latexStdoutText = runPreviewFormCommand( LatexSdkUtil.getExecutableName("pdflatex", project), arrayOf( "-interaction=nonstopmode", "-halt-on-error", "$tempBasename.tex" ), tempDirectory, waitTime, previewForm ) ?: return runInkscape(tempBasename, tempDirectory, waitTime, previewForm) val image = ImageIO.read(File("$tempBasename.png")) SwingUtilities.invokeLater { previewForm.setPreview(image, latexStdoutText) } } finally { // Delete all the created temp files in the default temp directory. tempDirectory.deleteRecursively() } } private fun runPreviewFormCommand( command: String, args: Array<String>, workDirectory: File, waitTime: Long, previewForm: PreviewForm ): String? { val result = runCommandWithExitCode(command, *args, workingDirectory = workDirectory, timeout = waitTime) if (result.second != 0) { previewForm.setLatexErrorMessage("$command exited with ${result.second}\n${result.first ?: ""}") return null } return result.first } /** * Run inkscape command to convert pdf to png, depending on the version of inkscape. */ private fun runInkscape(tempBasename: String, tempDirectory: File, waitTime: Long, previewForm: PreviewForm) { // If 1.0 or higher if (SystemEnvironment.inkscapeMajorVersion >= 1) { runPreviewFormCommand( inkscapeExecutable(), arrayOf( "$tempBasename.pdf", "--export-area-drawing", "--export-dpi", "1000", "--export-background", "#FFFFFF", "--export-background-opacity", "1.0", "--export-filename", "$tempBasename.png" ), tempDirectory, waitTime, previewForm ) ?: throw AccessDeniedException(tempDirectory) } else { runPreviewFormCommand( pdf2svgExecutable(), arrayOf( "$tempBasename.pdf", "$tempBasename.svg" ), tempDirectory, waitTime, previewForm ) ?: return runPreviewFormCommand( inkscapeExecutable(), arrayOf( "$tempBasename.svg", "--export-area-drawing", "--export-dpi", "1000", "--export-background", "#FFFFFF", "--export-png", "$tempBasename.png" ), tempDirectory, waitTime, previewForm ) ?: throw AccessDeniedException(tempDirectory) } } private fun inkscapeExecutable(): String { var suffix = "" if (SystemInfo.isWindows) { suffix = ".exe" } return "inkscape$suffix" } private fun pdf2svgExecutable(): String { var suffix = "" if (SystemInfo.isWindows) { suffix = ".exe" } return "pdf2svg$suffix" } }
mit
f8aaab14c2dd54a64dc1f34dcd1697c3
33.470588
140
0.543522
5.330852
false
false
false
false
FHannes/intellij-community
java/compiler/impl/src/com/intellij/compiler/chainsSearch/MethodIncompleteSignature.kt
1
4447
/* * 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.compiler.chainsSearch import com.intellij.compiler.backwardRefs.CompilerReferenceServiceEx import com.intellij.compiler.chainsSearch.context.ChainSearchTarget import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.PsiUtil import org.jetbrains.jps.backwardRefs.LightRef import org.jetbrains.jps.backwardRefs.SignatureData import java.util.function.Predicate class MethodIncompleteSignature(val ref: LightRef.JavaLightMethodRef, private val signatureData: SignatureData, private val refService: CompilerReferenceServiceEx) { companion object { val CONSTRUCTOR_METHOD_NAME = "<init>" } val name: String by lazy { refService.getName(ref.name) } val owner: String by lazy { refService.getName(ref.owner.name) } val rawReturnType: String by lazy { refService.getName(signatureData.rawReturnType) } val parameterCount: Int get() = ref.parameterCount val isStatic: Boolean get() = signatureData.isStatic fun resolveQualifier(project: Project, resolveScope: GlobalSearchScope, accessValidator: Predicate<PsiMember>): PsiClass? { val clazz = JavaPsiFacade.getInstance(project).findClass(owner, resolveScope) return if (clazz != null && accessValidator.test(clazz)) clazz else null } fun resolve(project: Project, resolveScope: GlobalSearchScope, accessValidator: Predicate<PsiMember>): Array<PsiMethod> { if (CONSTRUCTOR_METHOD_NAME == name) { return PsiMethod.EMPTY_ARRAY } val aClass = resolveQualifier(project, resolveScope, accessValidator) ?: return PsiMethod.EMPTY_ARRAY return aClass.findMethodsByName(name, true) .filter { it.hasModifierProperty(PsiModifier.STATIC) == isStatic } .filter { !it.isDeprecated } .filter { accessValidator.test(it) } .filter { val returnType = it.returnType when (signatureData.iteratorKind) { SignatureData.ARRAY_ONE_DIM -> { when (returnType) { is PsiArrayType -> { val componentType = returnType.componentType componentType is PsiClassType && componentType.resolve()?.qualifiedName == rawReturnType } else -> false } } SignatureData.ITERATOR_ONE_DIM -> { val iteratorKind = ChainSearchTarget.getIteratorKind(PsiUtil.resolveClassInClassTypeOnly(returnType)) when { iteratorKind != null -> PsiUtil.resolveClassInClassTypeOnly(PsiUtil.substituteTypeParameter(returnType, iteratorKind, 0, false))?.qualifiedName == rawReturnType else -> false } } SignatureData.ZERO_DIM -> returnType is PsiClassType && returnType.resolve()?.qualifiedName == rawReturnType else -> throw IllegalStateException("kind is unsupported ${signatureData.iteratorKind}") } } .sortedBy({ it.parameterList.parametersCount }) .toTypedArray() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as MethodIncompleteSignature if (ref.owner != other.ref.owner) return false if (ref.name != other.ref.name) return false if (signatureData != other.signatureData) return false return true } override fun hashCode(): Int { var result = ref.owner.hashCode() result = 31 * result + ref.name.hashCode() result = 31 * result + signatureData.hashCode() return result } override fun toString(): String { return owner + (if (isStatic) "" else "#") + name + "(" + parameterCount + ")" } }
apache-2.0
5c940fead62fb8c16b54cc82876e57ae
35.760331
174
0.679559
4.786868
false
false
false
false
pushtorefresh/push-ci
push-ci-boss/src/main/kotlin/com/pushtorefresh/push_ci/boss/db/SQLiteOpenHelper.kt
1
2253
package com.pushtorefresh.push_ci.boss.db import com.fasterxml.jackson.databind.ObjectMapper import com.pushtorefresh.push_ci.boss.BossApp import com.pushtorefresh.push_ci.boss.db.tables.UsersTable import com.pushtorefresh.push_ci.boss.util.FileAccessor import com.pushtorefresh.push_ci.boss.util.JDBCDriver import java.io.File import java.io.FileOutputStream import java.sql.Connection import java.sql.DriverManager import javax.inject.Inject class SQLiteOpenHelper(val pathToTheDbFile: String, val dbVersion: Int, val fileAccessor: FileAccessor, val jdbcDriver: JDBCDriver, val objectMapper: ObjectMapper) { fun init() { // load the sqlite-JDBC driver using the current class loader Class.forName("org.sqlite.JDBC") val dbMetaInfo = readDbMetaInfo() if (dbMetaInfo == null) { onCreate() } else { onUpgrade(dbMetaInfo.dbVersion, dbVersion) } } fun getDbMetaInfoFile(): File { return fileAccessor.file(fileAccessor.file(pathToTheDbFile).parentFile, "db_meta_info.json") } fun getConnection(): Connection { return jdbcDriver.getConnection("jdbc:sqlite:$pathToTheDbFile") } fun readDbMetaInfo(): DbMetaInfo? { val dbMetaInfoFile = getDbMetaInfoFile() if (dbMetaInfoFile.exists()) { return objectMapper.readValue(dbMetaInfoFile, DbMetaInfo::class.java) } else { return null } } fun onCreate() { // try to delete db file if exists (probably user decided to drop db config, so we need to drop db too) fileAccessor.file(pathToTheDbFile).delete() val connection = getConnection() // Open transaction connection.autoCommit = false try { // Write new DbMetaInfo to the file objectMapper.writeValue(getDbMetaInfoFile(), DbMetaInfo(dbVersion)) val statement = connection.createStatement() statement.execute(UsersTable.CREATE_QUERY) connection.commit() } finally { connection.close() } } fun onUpgrade(oldVersion: Int, newVersion: Int) { val connection = getConnection() // Open transaction connection.autoCommit = false try { // TODO add upgrade stuff in future connection.commit() } finally { connection.close() } } }
apache-2.0
a92f79addf637350f826df6f3d21e5f6
26.487805
107
0.705726
4.203358
false
false
false
false
sys1yagi/mastodon4j
mastodon4j/src/test/java/com/sys1yagi/mastodon4j/api/method/TimelinesTest.kt
1
784
package com.sys1yagi.mastodon4j.api.method import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException import com.sys1yagi.mastodon4j.testtool.MockClient import org.amshove.kluent.shouldEqualTo import org.junit.Assert import org.junit.Test class TimelinesTest { @Test fun getHome() { val client = MockClient.mock("timelines.json") val timelines = Timelines(client) val pageable = timelines.getHome().execute() val status = pageable.part.first() status.id shouldEqualTo 11111L } @Test(expected = Mastodon4jRequestException::class) fun homeWithException() { val client = MockClient.ioException() val timelines = Timelines(client) timelines.getHome().execute() } // TODO 401 }
mit
2d3adc8f8cca4722eeec57b53b9669e1
26.034483
71
0.704082
4
false
true
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/app/view/AlertView.kt
1
11495
/* Copyright 2015 Andreas Würl 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.blitzortung.android.app.view import android.content.Context import android.graphics.* import android.graphics.Paint.Align import android.graphics.Paint.Style import android.location.Location import android.util.AttributeSet import android.util.Log import android.view.View import org.blitzortung.android.alert.AlertResult import org.blitzortung.android.alert.data.AlertSector import org.blitzortung.android.alert.event.AlertEvent import org.blitzortung.android.alert.event.AlertResultEvent import org.blitzortung.android.app.Main import org.blitzortung.android.app.R import org.blitzortung.android.location.LocationEvent import org.blitzortung.android.map.overlay.color.ColorHandler import org.blitzortung.android.util.TabletAwareView class AlertView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : TabletAwareView(context, attrs, defStyle) { private val arcArea = RectF() private val background = Paint() private val sectorPaint = Paint() private val lines = Paint(Paint.ANTI_ALIAS_FLAG) private val textStyle = Paint(Paint.ANTI_ALIAS_FLAG) private val warnText = Paint(Paint.ANTI_ALIAS_FLAG) private val transfer = Paint() private val alarmNotAvailableTextLines: Array<String> private var colorHandler: ColorHandler? = null private var intervalDuration: Int = 0 private var temporaryBitmap: Bitmap? = null private var temporaryCanvas: Canvas? = null private var alertResult: AlertResult? = null private var location: Location? = null private var enableDescriptionText = false val alertEventConsumer: (AlertEvent?) -> Unit = { event -> Log.v(Main.LOG_TAG, "AlertView alertEventConsumer received $event") if (event is AlertResultEvent) { alertResult = event.alertResult } else { alertResult = null } invalidate() } val locationEventConsumer: (LocationEvent) -> Unit = { locationEvent -> location = locationEvent.location val visibility = if (location != null) View.VISIBLE else View.INVISIBLE setVisibility(visibility) invalidate() } init { alarmNotAvailableTextLines = context.getString(R.string.alarms_not_available) .split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() with(lines) { color = 0xff404040.toInt() style = Style.STROKE } with(textStyle) { color = 0xff404040.toInt() textSize = 0.8f * [email protected] * TabletAwareView.textSizeFactor(context) } background.color = 0xffb0b0b0.toInt() } fun enableDescriptionText() { enableDescriptionText = true } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val getSize = fun(spec: Int) = View.MeasureSpec.getSize(spec) val parentWidth = getSize(widthMeasureSpec) * sizeFactor val parentHeight = getSize(heightMeasureSpec) * sizeFactor val size = Math.min(parentWidth.toInt(), parentHeight.toInt()) super.onMeasure(View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY)) } override fun onAttachedToWindow() { super.onAttachedToWindow() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() } override fun onDraw(canvas: Canvas) { val size = Math.max(width, height) val pad = 4 val center = size / 2.0f val radius = center - pad prepareTemporaryBitmap(size) val alertResult = alertResult val temporaryCanvas = temporaryCanvas if (temporaryCanvas != null) { if (alertResult != null && intervalDuration != 0) { val alertParameters = alertResult.parameters val rangeSteps = alertParameters.rangeSteps val rangeStepCount = rangeSteps.size val radiusIncrement = radius / rangeStepCount val sectorWidth = (360 / alertParameters.sectorLabels.size).toFloat() with(lines) { color = colorHandler!!.lineColor strokeWidth = (size / 150).toFloat() } with(textStyle) { textAlign = Align.CENTER color = colorHandler!!.textColor } val actualTime = System.currentTimeMillis() for (alertSector in alertResult.sectors) { val startAngle = alertSector.minimumSectorBearing + 90f + 180f val ranges = alertSector.ranges for (rangeIndex in ranges.indices.reversed()) { val alertSectorRange = ranges[rangeIndex] val sectorRadius = (rangeIndex + 1) * radiusIncrement val leftTop = center - sectorRadius val bottomRight = center + sectorRadius val drawColor = alertSectorRange.strikeCount > 0 if (drawColor) { val color = colorHandler!!.getColor(actualTime, alertSectorRange.latestStrikeTimestamp, intervalDuration) sectorPaint.color = color } arcArea.set(leftTop, leftTop, bottomRight, bottomRight) temporaryCanvas.drawArc(arcArea, startAngle, sectorWidth, true, if (drawColor) sectorPaint else background) } } for (alertSector in alertResult.sectors) { val bearing = alertSector.minimumSectorBearing.toDouble() temporaryCanvas.drawLine(center, center, center + (radius * Math.sin(bearing / 180.0f * Math.PI)).toFloat(), center + (radius * -Math.cos(bearing / 180.0f * Math.PI)).toFloat(), lines) if (enableDescriptionText && size > TEXT_MINIMUM_SIZE) { drawSectorLabel(center, radiusIncrement, alertSector, bearing + sectorWidth / 2.0) } } textStyle.textAlign = Align.RIGHT val textHeight = textStyle.getFontMetrics(null) for (radiusIndex in 0..rangeStepCount - 1) { val leftTop = center - (radiusIndex + 1) * radiusIncrement val bottomRight = center + (radiusIndex + 1) * radiusIncrement arcArea.set(leftTop, leftTop, bottomRight, bottomRight) temporaryCanvas.drawArc(arcArea, 0f, 360f, false, lines) if (enableDescriptionText && size > TEXT_MINIMUM_SIZE) { val text = "%.0f".format(rangeSteps[radiusIndex]) temporaryCanvas.drawText(text, center + (radiusIndex + 0.85f) * radiusIncrement, center + textHeight / 3f, textStyle) if (radiusIndex == rangeStepCount - 1) { temporaryCanvas.drawText(alertParameters.measurementSystem.unitName, center + (radiusIndex + 0.85f) * radiusIncrement, center + textHeight * 1.33f, textStyle) } } } } else { if (enableDescriptionText && size > TEXT_MINIMUM_SIZE) { drawAlertOrLocationMissingMessage(center, temporaryCanvas) } else { if (location != null) { drawOwnLocationSymbol(center, radius, size, temporaryCanvas) } } } } canvas.drawBitmap(temporaryBitmap, 0f, 0f, transfer) } private fun drawAlertOrLocationMissingMessage(center: Float, canvas: Canvas) { with(warnText) { color = 0xffa00000.toInt() textAlign = Align.CENTER textSize = DEFAULT_FONT_SIZE.toFloat() val maxWidth = alarmNotAvailableTextLines.map { warnText.measureText(it) }.max() ?: width.toFloat() - 20 val scale = (width - 20).toFloat() / maxWidth //Now scale the text so we can use the whole width of the canvas textSize = scale * DEFAULT_FONT_SIZE } for (line in alarmNotAvailableTextLines.indices) { canvas.drawText(alarmNotAvailableTextLines[line], center, center + (line - 1) * warnText.getFontMetrics(null), warnText) } } private fun drawOwnLocationSymbol(center: Float, radius: Float, size: Int, temporaryCanvas: Canvas) { with(lines) { color = colorHandler!!.lineColor strokeWidth = (size / 80).toFloat() } val largeRadius = radius * 0.8f val leftTop = center - largeRadius val bottomRight = center + largeRadius arcArea.set(leftTop, leftTop, bottomRight, bottomRight) temporaryCanvas.drawArc(arcArea, 0f, 360f, false, lines) val smallRadius = radius * 0.6f temporaryCanvas.drawLine(center - smallRadius, center, center + smallRadius, center, lines) temporaryCanvas.drawLine(center, center - smallRadius, center, center + smallRadius, lines) } private fun drawSectorLabel(center: Float, radiusIncrement: Float, sector: AlertSector, bearing: Double) { if (bearing != 90.0) { val text = sector.label val textRadius = (sector.ranges.size - 0.5f) * radiusIncrement temporaryCanvas!!.drawText(text, center + (textRadius * Math.sin(bearing / 180.0 * Math.PI)).toFloat(), center + (textRadius * -Math.cos(bearing / 180.0 * Math.PI)).toFloat() + textStyle.getFontMetrics(null) / 3f, textStyle) } } private fun prepareTemporaryBitmap(size: Int) { if (temporaryBitmap == null) { temporaryBitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) temporaryCanvas = Canvas(temporaryBitmap) } background.color = colorHandler!!.backgroundColor background.xfermode = XFERMODE_CLEAR temporaryCanvas!!.drawPaint(background) background.xfermode = XFERMODE_SRC } fun setColorHandler(colorHandler: ColorHandler, intervalDuration: Int) { this.colorHandler = colorHandler this.intervalDuration = intervalDuration } override fun setBackgroundColor(backgroundColor: Int) { background.color = backgroundColor } fun setAlpha(alpha: Int) { transfer.alpha = alpha } companion object { private val TEXT_MINIMUM_SIZE = 300 private val DEFAULT_FONT_SIZE = 20 private val XFERMODE_CLEAR = PorterDuffXfermode(PorterDuff.Mode.CLEAR) private val XFERMODE_SRC = PorterDuffXfermode(PorterDuff.Mode.SRC) } }
apache-2.0
181da737608610dace1af0605c4bb5a0
39.188811
236
0.625022
4.922484
false
false
false
false