content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.filter import android.app.AlertDialog import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import com.vrem.wifianalyzer.wifi.filter.adapter.EnumFilterAdapter internal abstract class EnumFilter<T : Enum<*>, U : EnumFilterAdapter<T>>(internal val ids: Map<T, Int>, private val filter: U, alertDialog: AlertDialog, id: Int) { private fun setColor(view: View, value: T) { this.filter.color(value).let { val color = ContextCompat.getColor(view.context, it) when (view) { is TextView -> view.setTextColor(color) is ImageView -> view.setColorFilter(color) } } } init { ids.keys.forEach { value -> ids[value]?.let { process(alertDialog, it, value) } } alertDialog.findViewById<View>(id).visibility = View.VISIBLE } private fun process(alertDialog: AlertDialog, id: Int, value: T) { val view = alertDialog.findViewById<View>(id) view.setOnClickListener { onClickListener(value, it) } setColor(view, value) } private fun onClickListener(value: T, view: View) { filter.toggle(value) setColor(view, value) } }
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/filter/EnumFilter.kt
1027115260
package com.tristanwiley.chatse.chat.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView import com.tristanwiley.chatse.R /** * Adapter for DialogPlus to display the different uploading options * @param context: Application context */ class UploadImageAdapter(context: Context) : BaseAdapter() { private val layoutInflater: LayoutInflater = LayoutInflater.from(context) override fun getCount(): Int { return 2 } override fun getItem(position: Int): Any { return position } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { val viewHolder: UploadImageAdapter.ViewHolder var view = convertView if (view == null) { view = layoutInflater.inflate(R.layout.simple_grid_item, parent, false) viewHolder = UploadImageAdapter.ViewHolder() viewHolder.textView = view.findViewById(R.id.text_view) viewHolder.imageView = view.findViewById(R.id.image_view) view.tag = viewHolder } else { viewHolder = view.tag as UploadImageAdapter.ViewHolder } val context = parent.context when (position) { 0 -> { viewHolder.textView?.text = context.getString(R.string.take_photo) viewHolder.imageView?.setImageResource(R.drawable.ic_camera) } 1 -> { viewHolder.textView?.text = context.getString(R.string.choose_from_gallery) viewHolder.imageView?.setImageResource(R.drawable.ic_gallery_pick) } } return view } internal class ViewHolder { var textView: TextView? = null var imageView: ImageView? = null } }
app/src/main/java/com/tristanwiley/chatse/chat/adapters/UploadImageAdapter.kt
2521168625
package com.github.triplet.gradle.play.tasks import com.github.triplet.gradle.androidpublisher.FakePlayPublisher import com.github.triplet.gradle.androidpublisher.UploadInternalSharingArtifactResponse import com.github.triplet.gradle.androidpublisher.newUploadInternalSharingArtifactResponse import com.github.triplet.gradle.play.helpers.IntegrationTestBase import com.github.triplet.gradle.play.helpers.SharedIntegrationTest.Companion.DEFAULT_TASK_VARIANT import com.github.triplet.gradle.play.tasks.shared.ArtifactIntegrationTests import com.github.triplet.gradle.play.tasks.shared.LifecycleIntegrationTests import com.github.triplet.gradle.play.tasks.shared.PublishInternalSharingArtifactIntegrationTests import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.TaskOutcome.SUCCESS import org.junit.jupiter.api.Test import java.io.File class PublishInternalSharingBundleIntegrationTest : IntegrationTestBase(), ArtifactIntegrationTests, PublishInternalSharingArtifactIntegrationTests, LifecycleIntegrationTests { override fun taskName(taskVariant: String) = ":upload${taskVariant.ifEmpty { DEFAULT_TASK_VARIANT }}PrivateBundle" override fun customArtifactName(name: String) = "$name.aab" override fun assertCustomArtifactResults(result: BuildResult, executed: Boolean) { assertThat(result.task(":packageReleaseBundle")).isNull() if (executed) { assertThat(result.output).contains("uploadInternalSharingBundle(") } } override fun outputFile() = "build/outputs/internal-sharing/bundle/release" @Test fun `Builds bundle on-the-fly by default`() { val result = execute("", "uploadReleasePrivateBundle") result.requireTask(":packageReleaseBundle", outcome = SUCCESS) assertThat(result.output).contains("uploadInternalSharingBundle(") assertThat(result.output).contains(".aab") } companion object { @JvmStatic fun installFactories() { val publisher = object : FakePlayPublisher() { override fun uploadInternalSharingBundle( bundleFile: File, ): UploadInternalSharingArtifactResponse { println("uploadInternalSharingBundle($bundleFile)") return newUploadInternalSharingArtifactResponse( "json-payload", "https://google.com") } } publisher.install() } } }
play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/PublishInternalSharingBundleIntegrationTest.kt
3624563444
// WITH_RUNTIME class A class B(val items: Collection<A>) class C { fun foo(p: Int) { when (p) { 1 -> arrayListOf<Int>().add(1) } } fun bar() = B(listOf<A>().map { it }) } fun box(): String { C().foo(1) if (C().bar().items.isNotEmpty()) return "fail" return "OK" }
backend.native/tests/external/codegen/box/when/kt5448.kt
1377701615
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2020 Richard Harrah * * 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 com.tealcube.minecraft.bukkit.mythicdrops.utils import org.bukkit.Bukkit import java.lang.reflect.Constructor import java.lang.reflect.Field import java.lang.reflect.Method /** * Reflection utilities for NMS/CraftBukkit. */ object ReflectionUtil { /** * Version string for NMS and CraftBukkit classes. */ @JvmStatic val version: String by lazy { Bukkit.getServer().javaClass.`package`.name.let { it.substring(it.lastIndexOf('.') + 1) + "." } } // cache of loaded NMS classes private val loadedNmsClasses = mutableMapOf<String, Class<*>?>() // cache of loaded CraftBukkit classes private val loadedCbClasses = mutableMapOf<String, Class<*>?>() // cache of loaded methods private val loadedMethods = mutableMapOf<Class<*>, MutableMap<String, Method?>>() // cache of loaded fields private val loadedFields = mutableMapOf<Class<*>, MutableMap<String, Field?>>() /** * Attempts to get an NMS class from the cache if in the cache, tries to put it in the cache if it's not already * there. */ @JvmStatic @Synchronized fun getNmsClass(nmsClassName: String): Class<*>? = loadedNmsClasses.getOrPut(nmsClassName) { val clazzName = "net.minecraft.server.${version}$nmsClassName" try { Class.forName(clazzName) } catch (ex: ClassNotFoundException) { null } } /** * Attempts to get a CraftBukkit class from the cache if in the cache, tries to put it in the cache if it's not * already there. */ @JvmStatic @Synchronized fun getCbClass(nmsClassName: String): Class<*>? = loadedCbClasses.getOrPut(nmsClassName) { val clazzName = "org.bukkit.craftbukkit.${version}$nmsClassName" try { Class.forName(clazzName) } catch (ex: ClassNotFoundException) { null } } /** * Attempts to find the constructor on the class that has the same types of parameters. */ @Suppress("detekt.SpreadOperator") fun getConstructor(clazz: Class<*>, vararg params: Class<*>): Constructor<*>? = try { clazz.getConstructor(*params) } catch (ex: NoSuchMethodException) { null } /** * Attempts to find the method on the class that has the same types of parameters and same name. */ @Suppress("detekt.SpreadOperator") fun getMethod(clazz: Class<*>, methodName: String, vararg params: Class<*>): Method? { val methods = loadedMethods[clazz] ?: mutableMapOf() if (methods.containsKey(methodName)) { return methods[methodName] } val method = try { clazz.getMethod(methodName, *params) } catch (ex: NoSuchMethodException) { null } methods[methodName] = method loadedMethods[clazz] = methods return method } /** * Attempts to find the field on the class that has the same name. */ @Suppress("detekt.SpreadOperator") fun getField(clazz: Class<*>, fieldName: String): Field? { val fields = loadedFields[clazz] ?: mutableMapOf() if (fields.containsKey(fieldName)) { return fields[fieldName] } val method = try { clazz.getField(fieldName) } catch (ex: NoSuchFieldException) { null } fields[fieldName] = method loadedFields[clazz] = fields return method } }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/ReflectionUtil.kt
2828225513
package au.com.codeka.warworlds.common import java.util.* class NormalRandom : Random() { /** * Gets a random double between -1..1, but with a normal distribution around 0.0 (i.e. the * majority of values will be close to 0.0, falling off in both directions). */ operator fun next(): Double { return normalRandom(1000).toDouble() / 500.0 - 1.0 } private fun normalRandom(max: Int): Int { val rounds = 5 var n = 0 val step = max / rounds for (i in 0 until rounds) { n += nextInt(step - 1) } return n } companion object { private const val serialVersionUID = 1L } }
common/src/main/kotlin/au/com/codeka/warworlds/common/NormalRandom.kt
3760582194
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input.key import androidx.compose.ui.ExperimentalComposeUiApi import android.view.KeyEvent.KEYCODE_A as KeyCodeA import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalComposeUiApi::class) class KeyTest { @Test fun androidKeyCode_to_composeKey() { // Arrange. val androidKeyCode = KeyCodeA // Act. val composeKey = Key(androidKeyCode) // Assert. assertThat(composeKey).isEqualTo(Key.A) } @Test fun composeKey_to_androidKeyCode() { // Arrange. val composeKey = Key.A // Act. val androidKeyCode = composeKey.nativeKeyCode // Assert. assertThat(androidKeyCode).isEqualTo(KeyCodeA) } }
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/key/KeyTest.kt
882708861
/* * Copyright 2017 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.work.impl import android.content.Context import androidx.annotation.RestrictTo import androidx.room.AutoMigration import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.work.Data import androidx.work.impl.WorkDatabaseVersions.VERSION_10 import androidx.work.impl.WorkDatabaseVersions.VERSION_11 import androidx.work.impl.WorkDatabaseVersions.VERSION_2 import androidx.work.impl.WorkDatabaseVersions.VERSION_3 import androidx.work.impl.WorkDatabaseVersions.VERSION_5 import androidx.work.impl.WorkDatabaseVersions.VERSION_6 import androidx.work.impl.model.Dependency import androidx.work.impl.model.DependencyDao import androidx.work.impl.model.Preference import androidx.work.impl.model.PreferenceDao import androidx.work.impl.model.RawWorkInfoDao import androidx.work.impl.model.SystemIdInfo import androidx.work.impl.model.SystemIdInfoDao import androidx.work.impl.model.WorkName import androidx.work.impl.model.WorkNameDao import androidx.work.impl.model.WorkProgress import androidx.work.impl.model.WorkProgressDao import androidx.work.impl.model.WorkSpec import androidx.work.impl.model.WorkSpecDao import androidx.work.impl.model.WorkTag import androidx.work.impl.model.WorkTagDao import androidx.work.impl.model.WorkTypeConverters import androidx.work.impl.model.WorkTypeConverters.StateIds.COMPLETED_STATES import java.util.concurrent.Executor import java.util.concurrent.TimeUnit /** * A Room database for keeping track of work states. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Database( entities = [Dependency::class, WorkSpec::class, WorkTag::class, SystemIdInfo::class, WorkName::class, WorkProgress::class, Preference::class], autoMigrations = [ AutoMigration(from = 13, to = 14), AutoMigration(from = 14, to = 15, spec = AutoMigration_14_15::class), ], version = 16 ) @TypeConverters(value = [Data::class, WorkTypeConverters::class]) abstract class WorkDatabase : RoomDatabase() { /** * @return The Data Access Object for [WorkSpec]s. */ abstract fun workSpecDao(): WorkSpecDao /** * @return The Data Access Object for [Dependency]s. */ abstract fun dependencyDao(): DependencyDao /** * @return The Data Access Object for [WorkTag]s. */ abstract fun workTagDao(): WorkTagDao /** * @return The Data Access Object for [SystemIdInfo]s. */ abstract fun systemIdInfoDao(): SystemIdInfoDao /** * @return The Data Access Object for [WorkName]s. */ abstract fun workNameDao(): WorkNameDao /** * @return The Data Access Object for [WorkProgress]. */ abstract fun workProgressDao(): WorkProgressDao /** * @return The Data Access Object for [Preference]. */ abstract fun preferenceDao(): PreferenceDao /** * @return The Data Access Object which can be used to execute raw queries. */ abstract fun rawWorkInfoDao(): RawWorkInfoDao companion object { /** * Creates an instance of the WorkDatabase. * * @param context A context (this method will use the application context from it) * @param queryExecutor An [Executor] that will be used to execute all async Room * queries. * @param useTestDatabase `true` to generate an in-memory database that allows main thread * access * @return The created WorkDatabase */ @JvmStatic fun create( context: Context, queryExecutor: Executor, useTestDatabase: Boolean ): WorkDatabase { val builder = if (useTestDatabase) { Room.inMemoryDatabaseBuilder(context, WorkDatabase::class.java) .allowMainThreadQueries() } else { Room.databaseBuilder(context, WorkDatabase::class.java, WORK_DATABASE_NAME) .openHelperFactory { configuration -> val configBuilder = SupportSQLiteOpenHelper.Configuration.builder(context) configBuilder.name(configuration.name) .callback(configuration.callback) .noBackupDirectory(true) .allowDataLossOnRecovery(true) FrameworkSQLiteOpenHelperFactory().create(configBuilder.build()) } } return builder.setQueryExecutor(queryExecutor) .addCallback(CleanupCallback) .addMigrations(Migration_1_2) .addMigrations(RescheduleMigration(context, VERSION_2, VERSION_3)) .addMigrations(Migration_3_4) .addMigrations(Migration_4_5) .addMigrations(RescheduleMigration(context, VERSION_5, VERSION_6)) .addMigrations(Migration_6_7) .addMigrations(Migration_7_8) .addMigrations(Migration_8_9) .addMigrations(WorkMigration9To10(context)) .addMigrations(RescheduleMigration(context, VERSION_10, VERSION_11)) .addMigrations(Migration_11_12) .addMigrations(Migration_12_13) .addMigrations(Migration_15_16) .fallbackToDestructiveMigration() .build() } } } // Delete rows in the workspec table that... private const val PRUNE_SQL_FORMAT_PREFIX = // are completed... "DELETE FROM workspec WHERE state IN $COMPLETED_STATES AND " + // and the minimum retention time has expired... "(last_enqueue_time + minimum_retention_duration) < " // and all dependents are completed. private const val PRUNE_SQL_FORMAT_SUFFIX = " AND " + "(SELECT COUNT(*)=0 FROM dependency WHERE " + " prerequisite_id=id AND " + " work_spec_id NOT IN " + " (SELECT id FROM workspec WHERE state IN $COMPLETED_STATES))" private val PRUNE_THRESHOLD_MILLIS = TimeUnit.DAYS.toMillis(1) internal object CleanupCallback : RoomDatabase.Callback() { private val pruneSQL: String get() = "$PRUNE_SQL_FORMAT_PREFIX$pruneDate$PRUNE_SQL_FORMAT_SUFFIX" val pruneDate: Long get() = System.currentTimeMillis() - PRUNE_THRESHOLD_MILLIS override fun onOpen(db: SupportSQLiteDatabase) { super.onOpen(db) db.beginTransaction() try { // Prune everything that is completed, has an expired retention time, and has no // active dependents: db.execSQL(pruneSQL) db.setTransactionSuccessful() } finally { db.endTransaction() } } }
work/work-runtime/src/main/java/androidx/work/impl/WorkDatabase.kt
4221913621
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.model.solverGenerator.transformations import de.sudoq.model.sudoku.Sudoku import de.sudoq.model.sudoku.sudokuTypes.PermutationProperties class Rotate270 : Permutation { override fun permutate(sudoku: Sudoku) { rotate270(sudoku) } override val condition: PermutationProperties get() = PermutationProperties.rotate90 }
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/transformations/Rotate270.kt
2229704504
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.utils import androidx.annotation.StringRes data class ErrorMessage(val id: Long, @StringRes val messageId: Int)
JetNews/app/src/main/java/com/example/jetnews/utils/ErrorMessage.kt
3674158674
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.gridLayout import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.checkComponent import com.intellij.ui.dsl.checkConstraints import com.intellij.ui.dsl.gridLayout.impl.GridImpl import com.intellij.ui.dsl.gridLayout.impl.PreferredSizeData import org.jetbrains.annotations.ApiStatus import java.awt.* import javax.swing.JComponent /** * Layout manager represented as a table, where some cells can be merged in one cell (resulting cell occupies several columns and rows) * and every cell (or merged cells) can contain a sub-table inside. [Constraints] specifies all possible settings for every cell. * Root grid [rootGrid] and all sub-grids have own columns and rows settings placed in [Grid] */ @ApiStatus.Experimental class GridLayout : LayoutManager2 { /** * Root grid of layout */ val rootGrid: Grid get() = _rootGrid private val _rootGrid = GridImpl() override fun addLayoutComponent(comp: Component?, constraints: Any?) { val jbConstraints = checkConstraints(constraints) (jbConstraints.grid as GridImpl).register(checkComponent(comp), jbConstraints) } /** * Creates sub grid in the specified cell */ fun addLayoutSubGrid(constraints: Constraints): Grid { return (constraints.grid as GridImpl).registerSubGrid(constraints) } override fun addLayoutComponent(name: String?, comp: Component?) { throw UiDslException("Method addLayoutComponent(name: String?, comp: Component?) is not supported") } override fun removeLayoutComponent(comp: Component?) { if (!_rootGrid.unregister(checkComponent(comp))) { throw UiDslException("Component has not been registered: $comp") } } override fun preferredLayoutSize(parent: Container?): Dimension { if (parent == null) { throw UiDslException("Parent is null") } synchronized(parent.treeLock) { return getPreferredSizeData(parent).preferredSize } } override fun minimumLayoutSize(parent: Container?): Dimension { // May be we need to implement more accurate calculation later return preferredLayoutSize(parent) } override fun maximumLayoutSize(target: Container?) = Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE) override fun layoutContainer(parent: Container?) { if (parent == null) { throw UiDslException("Parent is null") } synchronized(parent.treeLock) { _rootGrid.layout(parent.width, parent.height, parent.insets) } } override fun getLayoutAlignmentX(target: Container?) = // Just like other layout managers, no special meaning here 0.5f override fun getLayoutAlignmentY(target: Container?) = // Just like other layout managers, no special meaning here 0.5f override fun invalidateLayout(target: Container?) { // Nothing to do } fun getConstraints(component: JComponent): Constraints? { return _rootGrid.getConstraints(component) } internal fun getPreferredSizeData(parent: Container): PreferredSizeData { return _rootGrid.getPreferredSizeData(parent.insets) } }
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/GridLayout.kt
2843332398
package org.jetbrains.plugins.notebooks.visualization import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import kotlin.math.min class CaretBasedCellSelectionModel(private val editor: Editor) : NotebookCellSelectionModel { override val primarySelectedCell: NotebookCellLines.Interval get() = editor.getCell(editor.caretModel.primaryCaret.logicalPosition.line) override val primarySelectedRegion: List<NotebookCellLines.Interval> get() { val primary = primarySelectedCell return selectedRegions.find { primary in it }!! } override val selectedRegions: List<List<NotebookCellLines.Interval>> get() = groupNeighborCells(selectedCells) override val selectedCells: List<NotebookCellLines.Interval> get() { val notebookCellLines = NotebookCellLines.get(editor) return editor.caretModel.allCarets.flatMap { caret -> notebookCellLines.getCells(editor.document.getSelectionLines(caret)) }.distinct() } override fun isSelectedCell(cell: NotebookCellLines.Interval): Boolean = editor.caretModel.allCarets.any { caret -> editor.document.getSelectionLines(caret).hasIntersectionWith(cell.lines) } override fun selectCell(cell: NotebookCellLines.Interval, makePrimary: Boolean) { editor.caretModel.addCaret(cell.startLogicalPosition, makePrimary) } override fun removeSecondarySelections() { editor.caretModel.removeSecondaryCarets() } override fun removeSelection(cell: NotebookCellLines.Interval) { for (caret in editor.caretModel.allCarets) { if (caret.logicalPosition.line in cell.lines) { editor.caretModel.removeCaret(caret) } } } } private fun Document.getSelectionLines(caret: Caret): IntRange = IntRange(getLineNumber(caret.selectionStart), getLineNumber(caret.selectionEnd)) private val NotebookCellLines.Interval.startLogicalPosition: LogicalPosition get() = LogicalPosition(min(firstContentLine, lines.last), 0)
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/CaretBasedCellSelectionModel.kt
2925901531
fun test4() { }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/constructors/secondaryConstructor/WithoutUsages.kt
2285068344
package one.two fun read() { val c = KotlinObject.Nested.property }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/nestedObject/property/Read.kt
2571575710
package foo fun <R> bar(block: () -> R): R = TODO() fun <T, R> T.bar(block: T.() -> R): R = TODO() class X { val b = ba<caret> } // TAIL_TEXT: " {...} (block: X.() -> R) for T in foo"
plugins/kotlin/completion/tests/testData/handlers/basic/ReceiverParam.kt
2885123434
package ftl.client.google.run.android import com.google.testing.model.AndroidTestLoop import com.google.testing.model.FileReference import ftl.api.TestMatrixAndroid internal fun createGameLoopTest(config: TestMatrixAndroid.Type.GameLoop) = AndroidTestLoop().apply { appApk = FileReference().setGcsPath(config.appApkGcsPath) scenarioLabels = config.scenarioLabels scenarios = config.scenarioNumbers.map { it.toInt() } }
test_runner/src/main/kotlin/ftl/client/google/run/android/CreateAndroidLoopTest.kt
3061103828
package com.habitrpg.android.habitica.helpers.notifications import android.app.PendingIntent import android.content.Context import android.content.Intent import android.media.RingtoneManager import androidx.annotation.CallSuper import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.ui.activities.MainActivity import java.util.* /** * Created by keithholliday on 6/28/16. */ abstract class HabiticaLocalNotification(protected var context: Context, protected var identifier: String) { protected var data: Map<String, String>? = null protected var title: String? = null protected var message: String? = null protected var notificationBuilder = NotificationCompat.Builder(context, "default") .setSmallIcon(R.drawable.ic_gryphon_white) .setAutoCancel(true) open fun configureNotificationBuilder(data: MutableMap<String, String>): NotificationCompat.Builder { val path = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) return notificationBuilder .setSound(path) } @CallSuper open fun notifyLocally(title: String?, message: String?, data: MutableMap<String, String>) { this.title = title this.message = message var notificationBuilder = configureNotificationBuilder(data) if (this.title != null) { notificationBuilder = notificationBuilder.setContentTitle(title) } if (this.message != null) { notificationBuilder = notificationBuilder.setContentText(message) } this.setNotificationActions(data) val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(getNotificationID(data), notificationBuilder.build()) } fun setExtras(data: Map<String, String>) { this.data = data } protected open fun setNotificationActions(data: Map<String, String>) { val intent = Intent(context, MainActivity::class.java) intent.putExtra("notificationIdentifier", identifier) configureMainIntent(intent) val pendingIntent = PendingIntent.getActivity( context, 3000, intent, PendingIntent.FLAG_UPDATE_CURRENT ) notificationBuilder.setContentIntent(pendingIntent) } protected open fun configureMainIntent(intent: Intent) { } protected open fun getNotificationID(data: MutableMap<String, String>): Int { return Date().time.toInt() } }
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/notifications/HabiticaLocalNotification.kt
2972726805
package ftl.adapter.google import ftl.api.FileReference internal fun String.toApiModel(fileReference: FileReference) = fileReference.copy(local = this)
test_runner/src/main/kotlin/ftl/adapter/google/FileReferenceAdapter.kt
108760038
// IS_APPLICABLE: false fun foo(i: (Int) -> Int) = 0 val x = foo { it -> i<caret>t + 1 }
plugins/kotlin/idea/tests/testData/intentions/replaceItWithExplicitFunctionLiteralParam/notApplicable_parameterExplicitlyNamedIt.kt
2691729688
/** * Copyright 2010 - 2022 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 * * 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 jetbrains.exodus.tree.patricia import jetbrains.exodus.ByteIterable import jetbrains.exodus.ExodusException import jetbrains.exodus.kotlin.notNull import jetbrains.exodus.log.* import jetbrains.exodus.log.Loggable.NULL_ADDRESS import java.util.* internal val Byte.unsigned: Int get() = this.toInt() and 0xff const val CHILDREN_BITSET_SIZE_LONGS = 4 const val CHILDREN_BITSET_SIZE_BYTES = CHILDREN_BITSET_SIZE_LONGS * Long.SIZE_BYTES /** * In V2 database format, a Patricia node with children can be encoded in 3 different ways depending * on number of children. Each of the ways is optimal for the number of children it represents. */ private enum class V2ChildrenFormat { Complete, // the node has all 256 children Sparse, // the number of children is in the range 1..32 Bitset // the number of children is in the range 33..255 } internal class MultiPageImmutableNode : NodeBase, ImmutableNode { private val loggable: RandomAccessLoggable private val log: Log private val data: ByteIterableWithAddress private val childrenCount: Short private val childAddressLength: Byte private val baseAddress: Long // if it is not equal to NULL_ADDRESS then the node is saved in the v2 format constructor(log: Log, loggable: RandomAccessLoggable, data: ByteIterableWithAddress) : this(log, loggable.type, loggable, data, data.iterator()) private constructor( log: Log, type: Byte, loggable: RandomAccessLoggable, data: ByteIterableWithAddress, it: ByteIteratorWithAddress ) : super(type, data, it) { this.log = log this.loggable = loggable var baseAddress = NULL_ADDRESS if (PatriciaTreeBase.nodeHasChildren(type)) { val i = it.compressedUnsignedInt val childrenCount = i ushr 3 if (childrenCount < VERSION2_CHILDREN_COUNT_BOUND) { this.childrenCount = childrenCount.toShort() } else { this.childrenCount = (childrenCount - VERSION2_CHILDREN_COUNT_BOUND).toShort() baseAddress = it.compressedUnsignedLong } checkAddressLength(((i and 7) + 1).also { len -> childAddressLength = len.toByte() }) } else { childrenCount = 0.toShort() childAddressLength = 0.toByte() } this.baseAddress = baseAddress this.data = data.cloneWithAddressAndLength(it.address, it.available()) } override fun getLoggable(): RandomAccessLoggable { return loggable } override fun getAddress() = loggable.address override fun asNodeBase(): NodeBase { return this } public override fun isMutable() = false public override fun getMutableCopy(mutableTree: PatriciaTreeMutable): MutableNode { return mutableTree.mutateNode(this) } public override fun getChild(tree: PatriciaTreeBase, b: Byte): NodeBase? { if (v2Format) { getV2Child(b)?.let { searchResult -> return tree.loadNode(addressByOffsetV2(searchResult.offset)) } } else { val key = b.unsigned var low = 0 var high = childrenCount - 1 while (low <= high) { val mid = low + high ushr 1 val offset = mid * (childAddressLength + 1) val cmp = byteAt(offset).unsigned - key when { cmp < 0 -> low = mid + 1 cmp > 0 -> high = mid - 1 else -> { return tree.loadNode(nextLong(offset + 1)) } } } } return null } public override fun getChildren(): NodeChildren { return object : NodeChildren { override fun iterator(): NodeChildrenIterator { val childrenCount = getChildrenCount() return if (childrenCount == 0) EmptyNodeChildrenIterator() else { if (v2Format) { when (childrenCount) { 256 -> ImmutableNodeCompleteChildrenV2Iterator(-1, null) in 1..32 -> ImmutableNodeSparseChildrenV2Iterator(-1, null) else -> ImmutableNodeBitsetChildrenV2Iterator(-1, null) } } else { ImmutableNodeChildrenIterator(-1, null) } } } } } public override fun getChildren(b: Byte): NodeChildrenIterator { if (v2Format) { getV2Child(b)?.let { searchResult -> val index = searchResult.index val node = ChildReference(b, addressByOffsetV2(searchResult.offset)) return when (searchResult.childrenFormat) { V2ChildrenFormat.Complete -> ImmutableNodeCompleteChildrenV2Iterator(index, node) V2ChildrenFormat.Sparse -> ImmutableNodeSparseChildrenV2Iterator(index, node) V2ChildrenFormat.Bitset -> ImmutableNodeBitsetChildrenV2Iterator(index, node) } } } else { val key = b.unsigned var low = 0 var high = childrenCount - 1 while (low <= high) { val mid = low + high ushr 1 val offset = mid * (childAddressLength + 1) val cmp = byteAt(offset).unsigned - key when { cmp < 0 -> low = mid + 1 cmp > 0 -> high = mid - 1 else -> { val suffixAddress = nextLong(offset + 1) return ImmutableNodeChildrenIterator(mid, ChildReference(b, suffixAddress)) } } } } return EmptyNodeChildrenIterator() } public override fun getChildrenRange(b: Byte): NodeChildrenIterator { val ub = b.unsigned if (v2Format) { when (val childrenCount = getChildrenCount()) { 0 -> return EmptyNodeChildrenIterator() 256 -> return ImmutableNodeCompleteChildrenV2Iterator( ub, ChildReference(b, addressByOffsetV2(ub * childAddressLength)) ) in 1..32 -> { for (i in 0 until childrenCount) { val nextByte = byteAt(i) val next = nextByte.unsigned if (ub <= next) { return ImmutableNodeSparseChildrenV2Iterator( i, ChildReference(nextByte, addressByOffsetV2(childrenCount + i * childAddressLength)) ) } } } else -> { val bitsetIdx = ub / Long.SIZE_BITS val bitset = data.nextLong(bitsetIdx * Long.SIZE_BYTES, Long.SIZE_BYTES) val bit = ub % Long.SIZE_BITS val bitmask = 1L shl bit var index = (bitset and (bitmask - 1L)).countOneBits() if (bitsetIdx > 0) { for (i in 0 until bitsetIdx) { index += data.nextLong(i * Long.SIZE_BYTES, Long.SIZE_BYTES).countOneBits() } } val offset = CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength if ((bitset and bitmask) != 0L) { return ImmutableNodeBitsetChildrenV2Iterator( index, ChildReference(b, addressByOffsetV2(offset)) ) } if (index < childrenCount) { return ImmutableNodeBitsetChildrenV2Iterator( index - 1, ChildReference(b, addressByOffsetV2(offset)) ).apply { next() } } } } } else { var low = -1 var high = getChildrenCount() var offset = -1 var resultByte = 0.toByte() while (high - low > 1) { val mid = low + high + 1 ushr 1 val off = mid * (childAddressLength + 1) val actual = byteAt(off) if (actual.unsigned >= ub) { offset = off resultByte = actual high = mid } else { low = mid } } if (offset >= 0) { val suffixAddress = nextLong(offset + 1) return ImmutableNodeChildrenIterator(high, ChildReference(resultByte, suffixAddress)) } } return EmptyNodeChildrenIterator() } public override fun getChildrenCount() = childrenCount.toInt() public override fun getChildrenLast(): NodeChildrenIterator { val childrenCount = getChildrenCount() return if (childrenCount == 0) EmptyNodeChildrenIterator() else { if (v2Format) { when (childrenCount) { 256 -> ImmutableNodeCompleteChildrenV2Iterator(childrenCount, null) in 1..32 -> ImmutableNodeSparseChildrenV2Iterator(childrenCount, null) else -> ImmutableNodeBitsetChildrenV2Iterator(childrenCount, null) } } else { ImmutableNodeChildrenIterator(childrenCount, null) } } } private val v2Format: Boolean get() = baseAddress != NULL_ADDRESS // if specified byte is found the returns index of child, offset of suffixAddress and type of children format private fun getV2Child(b: Byte): SearchResult? { val ub = b.unsigned when (val childrenCount = getChildrenCount()) { 0 -> return null 256 -> return SearchResult( index = ub, offset = ub * childAddressLength, childrenFormat = V2ChildrenFormat.Complete ) in 1..32 -> { for (i in 0 until childrenCount) { val next = byteAt(i).unsigned if (ub < next) break if (ub == next) { return SearchResult( index = i, offset = childrenCount + i * childAddressLength, childrenFormat = V2ChildrenFormat.Sparse ) } } } else -> { val bitsetIdx = ub / Long.SIZE_BITS val bitset = data.nextLong(bitsetIdx * Long.SIZE_BYTES, Long.SIZE_BYTES) val bit = ub % Long.SIZE_BITS val bitmask = 1L shl bit if ((bitset and bitmask) == 0L) return null var index = (bitset and (bitmask - 1L)).countOneBits() if (bitsetIdx > 0) { for (i in 0 until bitsetIdx) { index += data.nextLong(i * Long.SIZE_BYTES, Long.SIZE_BYTES).countOneBits() } } return SearchResult( index = index, offset = CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength, childrenFormat = V2ChildrenFormat.Bitset ) } } return null } private fun byteAt(offset: Int): Byte { return data.byteAt(offset) } private fun nextLong(offset: Int): Long { return data.nextLong(offset, childAddressLength.toInt()) } private fun addressByOffsetV2(offset: Int) = nextLong(offset) + baseAddress private fun childReferenceV1(index: Int) = (index * (childAddressLength + 1)).let { offset -> ChildReference(byteAt(offset), nextLong(offset + 1)) } // get child reference in case of v2 format with complete children (the node has all 256 children) private fun childReferenceCompleteV2(index: Int) = ChildReference(index.toByte(), addressByOffsetV2(index * childAddressLength)) // get child reference in case of v2 format with sparse children (the number of children is in the range 1..32) private fun childReferenceSparseV2(index: Int) = ChildReference(byteAt(index), addressByOffsetV2(getChildrenCount() + index * childAddressLength)) // get child reference in case of v2 format with bitset children representation // (the number of children is in the range 33..255) private fun childReferenceBitsetV2(index: Int, bit: Int) = ChildReference(bit.toByte(), addressByOffsetV2(CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength)) private fun fillChildReferenceV1(index: Int, node: ChildReference) = (index * (childAddressLength + 1)).let { offset -> node.firstByte = byteAt(offset) node.suffixAddress = nextLong(offset + 1) } private fun fillChildReferenceCompleteV2(index: Int, node: ChildReference) { node.firstByte = index.toByte() node.suffixAddress = addressByOffsetV2(index * childAddressLength) } private fun fillChildReferenceSparseV2(index: Int, node: ChildReference) { node.firstByte = byteAt(index) node.suffixAddress = addressByOffsetV2(getChildrenCount() + index * childAddressLength) } private fun fillChildReferenceBitsetV2(index: Int, bit: Int, node: ChildReference) { node.firstByte = bit.toByte() node.suffixAddress = addressByOffsetV2(CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength) } private abstract inner class NodeChildrenIteratorBase(override var index: Int, override var node: ChildReference?) : NodeChildrenIterator { override val isMutable: Boolean get() = false override fun hasNext() = index < childrenCount - 1 override fun hasPrev() = index > 0 override fun remove() = throw ExodusException("Can't remove manually Patricia node child, use Store.delete() instead") override val parentNode: NodeBase get() = this@MultiPageImmutableNode override val key: ByteIterable get() = keySequence } private inner class ImmutableNodeChildrenIterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { override fun next(): ChildReference = childReferenceV1(++index).also { node = it } override fun prev(): ChildReference = childReferenceV1(--index).also { node = it } override fun nextInPlace() = fillChildReferenceV1(++index, node.notNull) override fun prevInPlace() = fillChildReferenceV1(--index, node.notNull) } // v2 format complete children (the node has all 256 children) private inner class ImmutableNodeCompleteChildrenV2Iterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { override fun next() = childReferenceCompleteV2(++index).also { node = it } override fun prev() = childReferenceCompleteV2(--index).also { node = it } override fun nextInPlace() = fillChildReferenceCompleteV2(++index, node.notNull) override fun prevInPlace() = fillChildReferenceCompleteV2(--index, node.notNull) } // v2 format sparse children (the number of children is in the range 1..32) private inner class ImmutableNodeSparseChildrenV2Iterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { override fun next() = childReferenceSparseV2(++index).also { node = it } override fun prev() = childReferenceSparseV2(--index).also { node = it } override fun nextInPlace() = fillChildReferenceSparseV2(++index, node.notNull) override fun prevInPlace() = fillChildReferenceSparseV2(--index, node.notNull) } // v2 format bitset children (the number of children is in the range 33..255) private inner class ImmutableNodeBitsetChildrenV2Iterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { private val bitset = LongArray(CHILDREN_BITSET_SIZE_LONGS).let { array -> array.indices.forEach { i -> array[i] = data.nextLong(i * Long.SIZE_BYTES, Long.SIZE_BYTES) } BitSet.valueOf(array) } private var bit = -1 override fun next(): ChildReference { incIndex() return childReferenceBitsetV2(index, bit).also { node = it } } override fun prev(): ChildReference { decIndex() return childReferenceBitsetV2(index, bit).also { node = it } } override fun nextInPlace() { incIndex() fillChildReferenceBitsetV2(index, bit, node.notNull) } override fun prevInPlace() { decIndex() fillChildReferenceBitsetV2(index, bit, node.notNull) } private fun incIndex() { ++index if (bit < 0) { for (i in 0..index) { bit = bitset.nextSetBit(bit + 1) } } else { bit = bitset.nextSetBit(bit + 1) } if (bit < 0) { throw ExodusException("Inconsistent children bitset in Patricia node") } } private fun decIndex() { --index if (bit < 0) { bit = 256 for (i in index until getChildrenCount()) { bit = bitset.previousSetBit(bit - 1) } } else { if (bit == 0) { throw ExodusException("Inconsistent children bitset in Patricia node") } bit = bitset.previousSetBit(bit - 1) } if (bit < 0) { throw ExodusException("Inconsistent children bitset in Patricia node") } } } } private data class SearchResult(val index: Int, val offset: Int, val childrenFormat: V2ChildrenFormat) private fun checkAddressLength(addressLen: Int) { if (addressLen < 0 || addressLen > 8) { throw ExodusException("Invalid length of address: $addressLen") } }
environment/src/main/kotlin/jetbrains/exodus/tree/patricia/MultiPageImmutableNode.kt
761524807
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: usages, constructorUsages class <caret>A(a: Int = 1) fun test() { A(0) A() }
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/primaryConstructorWithDefaultParams.0.kt
2329479912
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.itachi1706.droideggs.PieEgg.EasterEgg.paint import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.View import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.WindowInsets import android.widget.LinearLayout import androidx.annotation.RequiresApi @RequiresApi(24) class CutoutAvoidingToolbar : LinearLayout { private var _insets: WindowInsets? = null constructor(context: Context) : super(context) { init(null, 0) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs, 0) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(attrs, defStyle) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) adjustLayout() } override fun onApplyWindowInsets(insets: WindowInsets?): WindowInsets { _insets = insets if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) adjustLayout() return super.onApplyWindowInsets(insets) } @RequiresApi(28) fun adjustLayout() { _insets?.displayCutout?.boundingRects?.let { var cutoutCenter = 0 var cutoutLeft = 0 var cutoutRight = 0 // collect at most three cutouts for (r in it) { if (r.top > 0) continue if (r.left == left) { cutoutLeft = r.width() } else if (r.right == right) { cutoutRight = r.width() } else { cutoutCenter = r.width() } } // apply to layout (findViewWithTag("cutoutLeft") as View?)?.let { it.layoutParams = LayoutParams(cutoutLeft, MATCH_PARENT) } (findViewWithTag("cutoutCenter") as View?)?.let { it.layoutParams = LayoutParams(cutoutCenter, MATCH_PARENT) } (findViewWithTag("cutoutRight") as View?)?.let { it.layoutParams = LayoutParams(cutoutRight, MATCH_PARENT) } requestLayout() } } @Suppress("UNUSED_PARAMETER") private fun init(attrs: AttributeSet?, defStyle: Int) { } }
app/src/main/java/com/itachi1706/droideggs/PieEgg/EasterEgg/paint/CutoutAvoidingToolbar.kt
4064988746
// 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.intellij.plugins.markdown.editor.lists import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler import com.intellij.psi.PsiDocumentManager import com.intellij.refactoring.suggested.endOffset import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAtLine import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItemImpl /** * This is a base class for classes, handling indenting/unindenting of list items. * It collects selected items (or the ones the carets are inside) and calls [doIndentUnindent] and [updateNumbering] on them one by one. */ internal abstract class ListItemIndentUnindentHandlerBase(private val baseHandler: EditorActionHandler?) : EditorWriteActionHandler.ForEachCaret() { override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean = baseHandler?.isEnabled(editor, caret, dataContext) == true override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) { if (caret == null || !doExecuteAction(editor, caret)) { baseHandler?.execute(editor, caret, dataContext) } } private fun doExecuteAction(editor: Editor, caret: Caret): Boolean { val project = editor.project ?: return false val psiDocumentManager = PsiDocumentManager.getInstance(project) val document = editor.document val file = psiDocumentManager.getPsiFile(document) as? MarkdownFile ?: return false val firstLinesOfSelectedItems = getFirstLinesOfSelectedItems(caret, document, file) // use lines instead of items, because items may become invalid before used for (line in firstLinesOfSelectedItems) { psiDocumentManager.commitDocument(document) val item = file.getListItemAtLine(line, document)!! if (!doIndentUnindent(item, file, document)) continue psiDocumentManager.commitDocument(document) run { @Suppress("name_shadowing") // item is not valid anymore, but line didn't change val item = file.getListItemAtLine(line, document)!! updateNumbering(item, file, document) } } return firstLinesOfSelectedItems.isNotEmpty() } private fun getFirstLinesOfSelectedItems(caret: Caret, document: Document, file: MarkdownFile): List<Int> { var line = document.getLineNumber(caret.selectionStart) val lastLine = if (caret.hasSelection()) document.getLineNumber(caret.selectionEnd - 1) else line val lines = mutableListOf<Int>() while (line <= lastLine) { val item = file.getListItemAtLine(line, document) if (item == null) { line++ continue } lines.add(line) line = document.getLineNumber(item.endOffset) + 1 } return lines } /** If this method returns `true`, then the document is committed and [updateNumbering] is called */ protected abstract fun doIndentUnindent(item: MarkdownListItemImpl, file: MarkdownFile, document: Document): Boolean protected abstract fun updateNumbering(item: MarkdownListItemImpl, file: MarkdownFile, document: Document) }
plugins/markdown/src/org/intellij/plugins/markdown/editor/lists/ListItemIndentUnindentHandlerBase.kt
2382834460
/* * 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.flourprod import cc.altruix.econsimtr01.DefaultAgent import cc.altruix.econsimtr01.ch03.AgriculturalSimParametersProvider import cc.altruix.econsimtr01.ch03.Shack import cc.altruix.econsimtr01.millisToSimulationDateTime import org.fest.assertions.Assertions import org.junit.Test import org.mockito.Mockito import java.io.File /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ class FlourProductionTests { @Test fun timeToRunWiring() { timeToRunWiringTestLogic( businessDay = false, evenHourAndMinute = false, wheatInSack = false, expectedResult = false ) timeToRunWiringTestLogic( businessDay = true, evenHourAndMinute = false, wheatInSack = false, expectedResult = false ) timeToRunWiringTestLogic( businessDay = true, evenHourAndMinute = true, wheatInSack = false, expectedResult = false ) timeToRunWiringTestLogic( businessDay = true, evenHourAndMinute = true, wheatInSack = true, expectedResult = true ) } @Test fun wheatInShack() { wheatInShackTestLogic( amountInShack = 10.0, expectedResult = false ) wheatInShackTestLogic( amountInShack = 105.7172, expectedResult = false ) wheatInShackTestLogic( amountInShack = 105.7173, expectedResult = true ) wheatInShackTestLogic( amountInShack = 105.7174, expectedResult = true ) } @Test fun runDoesTheTransactionIfEnoughGrainInShack() { runWiringTestLogic( grainToProcess = 10.0, expectedNumberOfConversionCalls = 1 ) } @Test fun runDoesntDoTheTransactionIfNotEnoughGrainInShack() { runWiringTestLogic( grainToProcess = 0.0, expectedNumberOfConversionCalls = 0 ) } @Test fun calculateGrainToProcessCorrectlyCalculatesMaxPossibleGrainInput() { // Prepare val simParamProv = FlourProductionSimulationParametersProvider( File("src/test/resources/flourprod/flourprodRye.properties") ) simParamProv.initAndValidate() val shack = simParamProv.agents.find { it.id() == Shack.ID } as DefaultAgent shack.remove(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, shack.amount(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id)) Assertions.assertThat(shack.amount(AgriculturalSimParametersProvider .RESOURCE_SEEDS.id)).isZero shack.put(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, 1000.0) val out = Mockito.spy(FlourProduction(simParamProv)) // Run method under test val res = out.calculateGrainToProcess() // Verify Assertions.assertThat(res).isEqualTo(105.7173 * 8.0) } @Test fun calculateGrainToProcessSelectsTheRightMinimum() { // Prepare val simParamProv = FlourProductionSimulationParametersProvider( File("src/test/resources/flourprod/flourprodRye.properties") ) simParamProv.initAndValidate() val shack = simParamProv.agents.find { it.id() == Shack.ID } as DefaultAgent shack.remove(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, shack.amount(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id)) Assertions.assertThat(shack.amount(AgriculturalSimParametersProvider .RESOURCE_SEEDS.id)).isZero shack.put(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, 10.0) val out = Mockito.spy(FlourProduction(simParamProv)) // Run method under test val res = out.calculateGrainToProcess() // Verify Assertions.assertThat(res).isEqualTo(10.0) } @Test fun convertGrainToFlour() { // Prepare val simParamProv = FlourProductionSimulationParametersProvider( File("src/test/resources/flourprod/flourprodRye.properties") ) simParamProv.initAndValidate() val shack = simParamProv.agents.find { it.id() == Shack.ID } as DefaultAgent shack.remove(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, shack.amount(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id)) Assertions.assertThat(shack.amount(AgriculturalSimParametersProvider .RESOURCE_SEEDS.id)).isZero shack.put(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, 100.0) val out = Mockito.spy(FlourProduction(simParamProv)) // Run method under test out.convertGrainToFlour(100.0) // Verify Assertions.assertThat(shack.amount(AgriculturalSimParametersProvider .RESOURCE_SEEDS.id)).isZero Assertions.assertThat(shack.amount( FlourProductionSimulationParametersProvider.RESOURCE_FLOUR.id)) .isEqualTo(90.0) } fun runWiringTestLogic(grainToProcess: Double, expectedNumberOfConversionCalls:Int) { // Prepare val simParamProv = FlourProductionSimulationParametersProvider( File("src/test/resources/flourprod/flourprodRye.properties") ) simParamProv.initAndValidate() val out = Mockito.spy(FlourProduction(simParamProv)) Mockito.doReturn(grainToProcess).`when`(out).calculateGrainToProcess() Mockito.doNothing().`when`(out).convertGrainToFlour(grainToProcess) val time = 0L.millisToSimulationDateTime() // Run method under test out.run(time) // Verify Mockito.verify(out, Mockito.times(expectedNumberOfConversionCalls)). convertGrainToFlour(grainToProcess) } private fun wheatInShackTestLogic( amountInShack: Double, expectedResult: Boolean ) { // Prepare val simParamProv = FlourProductionSimulationParametersProvider( File("src/test/resources/flourprod/flourprodRye.properties") ) simParamProv.initAndValidate() val shack = simParamProv.agents.find { it.id() == Shack.ID } as DefaultAgent shack.remove(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, shack.amount(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id)) Assertions.assertThat(shack.amount(AgriculturalSimParametersProvider .RESOURCE_SEEDS.id)).isZero shack.put(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id, amountInShack) val out = Mockito.spy(FlourProduction(simParamProv)) // Run method under test val res = out.wheatInShack(shack) // Verify Assertions.assertThat(res).isEqualTo(expectedResult) } fun timeToRunWiringTestLogic( businessDay:Boolean, evenHourAndMinute:Boolean, wheatInSack:Boolean, expectedResult:Boolean ) { // Prepare val simParamProv = FlourProductionSimulationParametersProvider(File("someFile")) val shack = Shack() simParamProv.agents.add(shack) val out = Mockito.spy(FlourProduction(simParamProv)) val time = 0L.millisToSimulationDateTime() Mockito.doReturn(businessDay).`when`(out).businessDay(time) Mockito.doReturn(evenHourAndMinute).`when`(out).evenHourAndMinute(time) Mockito.doReturn(wheatInSack).`when`(out).wheatInShack(shack) // Run method under test val res = out.timeToRun(time) // Verify Assertions.assertThat(res).isEqualTo(expectedResult) } }
src/test/java/cc/altruix/econsimtr01/flourprod/FlourProductionTests.kt
3443915312
package com.lucas.collapsedtoolbar import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
CollapsedToolbar/app/src/test/java/com/lucas/collapsedtoolbar/ExampleUnitTest.kt
2241767202
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertEnumToSealedClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("convert.to.sealed.class") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.getClassKeyword() == null) return null val nameIdentifier = element.nameIdentifier ?: return null val enumKeyword = element.modifierList?.getModifier(KtTokens.ENUM_KEYWORD) ?: return null return TextRange(enumKeyword.startOffset, nameIdentifier.endOffset) } override fun applyTo(element: KtClass, editor: Editor?) { val name = element.name ?: return if (name.isEmpty()) return for (klass in element.withExpectedActuals()) { klass as? KtClass ?: continue val classDescriptor = klass.resolveToDescriptorIfAny() ?: continue val isExpect = classDescriptor.isExpect val isActual = classDescriptor.isActual klass.removeModifier(KtTokens.ENUM_KEYWORD) klass.addModifier(KtTokens.SEALED_KEYWORD) val psiFactory = KtPsiFactory(klass) val objects = mutableListOf<KtObjectDeclaration>() for (member in klass.declarations) { if (member !is KtEnumEntry) continue val obj = psiFactory.createDeclaration<KtObjectDeclaration>("object ${member.name}") val initializers = member.initializerList?.initializers ?: emptyList() if (initializers.isNotEmpty()) { initializers.forEach { obj.addSuperTypeListEntry(psiFactory.createSuperTypeCallEntry("${klass.name}${it.text}")) } } else { val defaultEntry = if (isExpect) psiFactory.createSuperTypeEntry(name) else psiFactory.createSuperTypeCallEntry("$name()") obj.addSuperTypeListEntry(defaultEntry) } if (isActual) { obj.addModifier(KtTokens.ACTUAL_KEYWORD) } member.body?.let { body -> obj.add(body) } member.delete() klass.addDeclaration(obj) objects.add(obj) } if (element.platform.isJvm()) { val enumEntryNames = objects.map { it.nameAsSafeName.asString() } val targetClassName = klass.name if (enumEntryNames.isNotEmpty() && targetClassName != null) { val companionObject = klass.getOrCreateCompanionObject() companionObject.addValuesFunction(targetClassName, enumEntryNames, psiFactory) companionObject.addValueOfFunction(targetClassName, classDescriptor, enumEntryNames, psiFactory) } } klass.body?.let { body -> body.allChildren .takeWhile { it !is KtDeclaration } .firstOrNull { it.node.elementType == KtTokens.SEMICOLON } ?.let { semicolon -> val nonWhiteSibling = semicolon.siblings(forward = true, withItself = false).firstOrNull { it !is PsiWhiteSpace } body.deleteChildRange(semicolon, nonWhiteSibling?.prevSibling ?: semicolon) if (nonWhiteSibling != null) { CodeStyleManager.getInstance(klass.project).reformat(nonWhiteSibling.firstChild ?: nonWhiteSibling) } } } } } private fun KtObjectDeclaration.addValuesFunction(targetClassName: String, enumEntryNames: List<String>, psiFactory: KtPsiFactory) { val functionText = "fun values(): Array<${targetClassName}> { return arrayOf(${enumEntryNames.joinToString()}) }" addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addValueOfFunction( targetClassName: String, classDescriptor: ClassDescriptor, enumEntryNames: List<String>, psiFactory: KtPsiFactory ) { val classFqName = classDescriptor.fqNameSafe.asString() val functionText = buildString { append("fun valueOf(value: String): $targetClassName {") append("return when(value) {") enumEntryNames.forEach { append("\"$it\" -> $it\n") } append("else -> throw IllegalArgumentException(\"No object $classFqName.\$value\")") append("}") append("}") } addDeclaration(psiFactory.createFunction(functionText)) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertEnumToSealedClassIntention.kt
803369276
package com.kingz.base import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.zeke.kangaroo.utils.ZLog /** * 实现Fragment懒加载控制的Base类,支持复杂的 Fragment 嵌套组合。 * 比如 Fragment+Fragment、Fragment+ViewPager、ViewPager+ViewPager….等等。 * * Fragment 完整生命周期: * onAttach -> onCreate -> * onCreatedView -> onActivityCreated -> onStart -> onResume * -> onPause -> onStop -> onDestroyView -> onDestroy -> onDetach * */ abstract class BaseLazyFragment : Fragment() { /** * 当使用ViewPager+Fragment形式时,setUserVisibleHint会优先Fragment生命周期函数调用, * 所以这个时候就,会导致在setUserVisibleHint方法执行时就执行了懒加载, * 而不是在onResume方法实际调用的时候执行懒加载。所以需要这个变量进行控制 */ private var isActive = false /** * 是否对用户可见,即是否调用了setUserVisibleHint(boolean)方法 */ private var isVisibleToUser = false /** * 是否调用了setUserVisibleHint方法。 * 处理show+add+hide模式下,默认可见Fragment不调用 * onHiddenChanged方法,进而不执行懒加载方法的问题。 */ private var isCallUserVisibleHint = false /** * 是否已执行懒加载 */ private var isLoaded = false /** * 进行页面懒加载 */ abstract fun lazyInit() override fun onPause() { super.onPause() isActive = false } override fun onResume() { super.onResume() isActive = true if(!isCallUserVisibleHint) isVisibleToUser = !isHidden tryLazyInit() } /** * androidX版本推荐使用 FragmentTransaction#setMaxLifecycle(Fragment, Lifecycle.State)代替 */ override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) this.isVisibleToUser = isVisibleToUser isCallUserVisibleHint = true tryLazyInit() } /** * 当 Fragment隐藏的状态发生改变时,该函数将会被调用. * 隐藏:hidden为true * 显示:hidden为false */ override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) isVisibleToUser = !hidden tryLazyInit() } /** * 尝试进行懒加载初始化 */ private fun tryLazyInit(){ // if(!isLoaded && isVisibleToUser && isParentVisible() && isActive){ if(!isLoaded && isVisibleToUser && isActive){ ZLog.d("lazyInit:!!!") lazyInit() isLoaded = true //通知子Fragment进行懒加载 dispatchParentVisibleState() } } /** * ViewPager场景下,判断父fragment是否可见 */ private fun isParentVisible(): Boolean { val fragment = parentFragment return fragment == null || (fragment is BaseLazyFragment && fragment.isVisibleToUser) } /** * ViewPager嵌套场景下,当前fragment可见时, * 如果其子fragment也可见,则让子fragment请求数据 */ private fun dispatchParentVisibleState() { val fragmentManager: FragmentManager = childFragmentManager val fragments: List<Fragment> = fragmentManager.fragments if (fragments.isEmpty()) { return } for (child in fragments) { if (child is BaseLazyFragment && child.isVisibleToUser) { child.tryLazyInit() } } } override fun onDestroyView() { super.onDestroyView() isLoaded = false isActive = false isVisibleToUser = false isCallUserVisibleHint = false } }
base/src/main/java/com/kingz/base/BaseLazyFragment.kt
1661161930
package com.intellij.configurationStore import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.StateStorageManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus import java.nio.file.Paths import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean class StorageVirtualFileTracker(private val messageBus: MessageBus) { private val filePathToStorage: ConcurrentMap<String, TrackedStorage> = ContainerUtil.newConcurrentMap() private @Volatile var hasDirectoryBasedStorages = false private val vfsListenerAdded = AtomicBoolean() interface TrackedStorage : StateStorage { val storageManager: StateStorageManagerImpl } fun put(path: String, storage: TrackedStorage) { filePathToStorage.put(path, storage) if (storage is DirectoryBasedStorage) { hasDirectoryBasedStorages = true } if (vfsListenerAdded.compareAndSet(false, true)) { addVfsChangesListener() } } fun remove(path: String) { filePathToStorage.remove(path) } fun remove(processor: (TrackedStorage) -> Boolean) { val iterator = filePathToStorage.values.iterator() for (storage in iterator) { if (processor(storage)) { iterator.remove() } } } private fun addVfsChangesListener() { messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener.Adapter() { override fun after(events: MutableList<out VFileEvent>) { eventLoop@ for (event in events) { var storage: StateStorage? if (event is VFilePropertyChangeEvent && VirtualFile.PROP_NAME.equals(event.propertyName)) { val oldPath = event.oldPath storage = filePathToStorage.remove(oldPath) if (storage != null) { filePathToStorage.put(event.path, storage) if (storage is FileBasedStorage) { storage.setFile(null, Paths.get(event.path)) } // we don't support DirectoryBasedStorage renaming // StoragePathMacros.MODULE_FILE -> old path, we must update value storage.storageManager.pathRenamed(oldPath, event.path, event) } } else { val path = event.path storage = filePathToStorage.get(path) // we don't care about parent directory create (because it doesn't affect anything) and move (because it is not supported case), // but we should detect deletion - but again, it is not supported case. So, we don't check if some of registered storages located inside changed directory. // but if we have DirectoryBasedStorage, we check - if file located inside it if (storage == null && hasDirectoryBasedStorages && path.endsWith(FileStorageCoreUtil.DEFAULT_EXT, ignoreCase = true)) { storage = filePathToStorage.get(VfsUtil.getParentDir(path)) } } if (storage == null) { continue } when (event) { is VFileMoveEvent -> { if (storage is FileBasedStorage) { storage.setFile(null, Paths.get(event.path)) } } is VFileCreateEvent -> { if (storage is FileBasedStorage) { storage.setFile(event.file, null) } } is VFileDeleteEvent -> { if (storage is FileBasedStorage) { storage.setFile(null, null) } else { (storage as DirectoryBasedStorage).setVirtualDir(null) } } is VFileCopyEvent -> continue@eventLoop } val componentManager = storage.storageManager.componentManager!! componentManager.messageBus.syncPublisher(StateStorageManager.STORAGE_TOPIC).storageFileChanged(event, storage, componentManager) } } }) } }
platform/configuration-store-impl/src/StorageVirtualFileTracker.kt
2606679519
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.tensorflow.lite.examples.iapoptimizer import android.content.Context import android.util.Log import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks.call import com.google.firebase.analytics.FirebaseAnalytics import org.json.JSONObject import org.tensorflow.lite.Interpreter import org.tensorflow.lite.support.metadata.MetadataExtractor import java.io.File import java.io.RandomAccessFile import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.util.concurrent.Callable import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class IapOptimizer(private val context: Context) { val testInput = mapOf( "coins_spent" to 2048f, "distance_avg" to 1234f, "device_os" to "ANDROID", "game_day" to 10f, "geo_country" to "Canada", "last_run_end_reason" to "laser" ) private var interpreter: Interpreter? = null private var preprocessingSummary : JSONObject? = null var isInitialized = false private set /** Executor to run inference task in the background */ private val executorService: ExecutorService = Executors.newCachedThreadPool() private var modelInputSize: Int = 0 // will be inferred from TF Lite model fun initialize(model: File): Task<Void> { return call( executorService, Callable<Void> { initializeInterpreter(model) null } ) } private fun initializeInterpreter(model: File) { // Initialize TF Lite Interpreter with NNAPI enabled val options = Interpreter.Options() options.setUseNNAPI(true) val interpreter: Interpreter interpreter = Interpreter(model, options) val aFile = RandomAccessFile(model, "r") val inChannel: FileChannel = aFile.getChannel() val fileSize: Long = inChannel.size() val buffer = ByteBuffer.allocate(fileSize.toInt()) inChannel.read(buffer) buffer.flip() val metaExecutor = MetadataExtractor(buffer) // Get associated preprocessing metadata JSON file from the TFLite file. // This is not yet supported on TFLite's iOS library, // consider bundling this file separately instead. val inputStream = metaExecutor.getAssociatedFile("preprocess.json") val inputAsString = inputStream.bufferedReader().use { it.readText() } preprocessingSummary = JSONObject(inputAsString) // Read input shape from model file val inputShape = interpreter.getInputTensor(0).shape() modelInputSize = inputShape[1] // Finish interpreter initialization this.interpreter = interpreter isInitialized = true Log.d(TAG, "Initialized TFLite interpreter.") } fun predict(): String { if (!isInitialized) { throw IllegalStateException("TF Lite Interpreter is not initialized yet.") } val preprocessedInput = preprocessModelInput(testInput) val byteBuffer = Array(1) { preprocessedInput } val result = Array(1) { FloatArray(OUTPUT_ACTIONS_COUNT) } interpreter?.run(byteBuffer, result) return mapOutputToAction(result[0]) } private fun preprocessModelInput(input : Map<String, Any>) : FloatArray { val result = mutableListOf<Float>() for ((k, v) in input) { if(!preprocessingSummary!!.has(k)) { continue } val channelSummary = preprocessingSummary!!.getJSONObject(k) if (channelSummary.getString("type") == "numerical") { val mean =channelSummary.getDouble("mean") val std =channelSummary.getDouble("std") if (v is Float) { result.add((v - mean.toFloat())/std.toFloat()) } else { throw Exception("Invalid input") } } if (channelSummary.getString("type") == "categorical") { val allValues = channelSummary.getJSONArray("all_values") for (i in 0 until allValues.length()) { val possibleValue = allValues.getString(i) if (v == possibleValue) { result.add(1f) } else { result.add(0f) } } } } return result.toFloatArray() } private fun mapOutputToAction(output: FloatArray) : String { val mapping = preprocessingSummary!!.getJSONArray("output_mapping") val maxIndex = output.indexOf(output.max()!!) return mapping[maxIndex] as String } fun close() { call( executorService, Callable<String> { interpreter?.close() Log.d(TAG, "Closed TFLite interpreter.") null } ) } companion object { private const val TAG = "IapOptimizer" private const val OUTPUT_ACTIONS_COUNT = 8 } }
app/app/src/main/java/org/tensorflow/lite/examples/iapoptimizer/IapOptimizer.kt
2958427858
package org.penella.index import io.vertx.core.AbstractVerticle import io.vertx.core.Future import io.vertx.core.Handler import io.vertx.core.Vertx import io.vertx.core.eventbus.Message import org.penella.MailBoxes import org.penella.codecs.IndexAddCodec import org.penella.codecs.IndexGetFirstLayerCodec import org.penella.codecs.IndexGetSecondLayerCodec import org.penella.codecs.IndexResultSetCodec import org.penella.messages.* /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created by alisle on 1/25/17. */ class IndexVertical(val name: String, val index: IIndex) : AbstractVerticle() { companion object { fun registerCodecs(vertx: Vertx) { vertx.eventBus().registerDefaultCodec(IndexAdd::class.java, IndexAddCodec()) vertx.eventBus().registerDefaultCodec(IndexGetFirstLayer::class.java, IndexGetFirstLayerCodec()) vertx.eventBus().registerDefaultCodec(IndexGetSecondLayer::class.java, IndexGetSecondLayerCodec()) vertx.eventBus().registerDefaultCodec(IndexResultSet::class.java, IndexResultSetCodec()) } } private val addTripleHandler = Handler<Message<IndexAdd>> { msg -> val triple = msg.body().triple index.add(triple) msg.reply(StatusMessage(Status.SUCESSFUL, "OK")) } private val getFirstLayerHandler = Handler<Message<IndexGetFirstLayer>> { msg -> val first = msg.body().first val type = msg.body().type val results = index.get(type, first) msg.reply(results) } private val getSecondLayerHandler = Handler<Message<IndexGetSecondLayer>> { msg -> val firstType = msg.body().firstType val firstValue = msg.body().firstValue val secondType = msg.body().secondType val secondValue = msg.body().secondValue val results = index.get(firstType, secondType, firstValue, secondValue) msg.reply(results) } override fun start(startFuture: Future<Void>?) { vertx.eventBus().consumer<IndexAdd>(MailBoxes.INDEX_ADD_TRIPLE.mailbox + name).handler(addTripleHandler) vertx.eventBus().consumer<IndexGetFirstLayer>(MailBoxes.INDEX_GET_FIRST.mailbox + name).handler(getFirstLayerHandler) vertx.eventBus().consumer<IndexGetSecondLayer>(MailBoxes.INDEX_GET_SECOND.mailbox + name).handler(getSecondLayerHandler) startFuture?.complete() } }
src/main/java/org/penella/index/IndexVertical.kt
1602387484
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.branching.when4 import kotlin.test.* fun when5(i: Int): Int { when (i) { 0 -> return 42 1 -> return 4 2 -> return 3 3 -> return 2 4 -> return 1 } return 24 }
backend.native/tests/codegen/branching/when4.kt
3849976491
// "Create object 'NotExistent'" "false" // ACTION: Create class 'NotExistent' // ACTION: Create interface 'NotExistent' // ACTION: Create test // ACTION: Create type parameter 'NotExistent' in class 'TPB' // ACTION: Do not show return expression hints // ACTION: Enable a trailing comma by default in the formatter // ERROR: Unresolved reference: NotExistent class TPB<X : <caret>NotExistent>
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/noObjectForTypeBound.kt
215556687
package info.dvkr.screenstream.ui.activity import android.os.Bundle import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import com.elvishew.xlog.XLog import info.dvkr.screenstream.common.getLog abstract class BaseActivity(@LayoutRes contentLayoutId: Int) : AppCompatActivity(contentLayoutId) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) XLog.d(getLog("onCreate")) } override fun onStart() { super.onStart() XLog.d(getLog("onStart")) } override fun onResume() { super.onResume() XLog.d(getLog("onResume")) } override fun onPause() { XLog.d(getLog("onPause")) super.onPause() } override fun onStop() { XLog.d(getLog("onStop")) super.onStop() } override fun onDestroy() { XLog.d(getLog("onDestroy")) super.onDestroy() } }
app/src/main/kotlin/info/dvkr/screenstream/ui/activity/BaseActivity.kt
3895303610
package com.ninjahoahong.unstoppable.utils import io.reactivex.Scheduler interface SchedulerProvider { fun computation(): Scheduler fun io(): Scheduler fun ui(): Scheduler }
app/src/main/java/com/ninjahoahong/unstoppable/utils/SchedulerProvider.kt
1227582724
package xyz.dowenliu.ketcd.client import org.slf4j.Logger import org.slf4j.LoggerFactory import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.Test import org.testng.asserts.Assertion import xyz.dowenliu.ketcd.Endpoint import xyz.dowenliu.ketcd.api.AlarmResponse import xyz.dowenliu.ketcd.api.DefragmentResponse import xyz.dowenliu.ketcd.api.StatusResponse import xyz.dowenliu.ketcd.endpoints import xyz.dowenliu.ketcd.version.EtcdVersion import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference /** * create at 2017/4/14 * @author liufl * @since 0.1.0 */ class EtcdMaintenanceServiceImplTest { private val logger: Logger = LoggerFactory.getLogger(javaClass) private val assertion = Assertion() private val etcdClient = EtcdClient.newBuilder() .withEndpoint(*endpoints.map { Endpoint.of(it) }.toTypedArray()) .build() private val service = etcdClient.newMaintenanceService() @BeforeClass fun assertIsImpl() { assertion.assertTrue(service is EtcdMaintenanceServiceImpl) } @AfterClass fun closeImpl() { service as EtcdMaintenanceServiceImpl service.close() } @Test fun testListAlarms() { val response = service.listAlarms() assertion.assertNotNull(response.header) } @Test fun testListAlarmsFuture() { val response = service.listAlarmsInFuture().get(5, TimeUnit.SECONDS) assertion.assertNotNull(response.header) } @Test fun testListAlarmsAsync() { val responseRef = AtomicReference<AlarmResponse?>() val errorRef = AtomicReference<Throwable?>() val finishLatch = CountDownLatch(1) service.listAlarmsAsync(object : ResponseCallback<AlarmResponse> { override fun onResponse(response: AlarmResponse) { responseRef.set(response) logger.debug("Alarm response received.") } override fun onError(throwable: Throwable) { errorRef.set(throwable) } override fun completeCallback() { logger.debug("Asynchronous listing alarms complete.") finishLatch.countDown() } }) finishLatch.await(10, TimeUnit.SECONDS) val response = responseRef.get() val throwable = errorRef.get() assertion.assertTrue(response != null || throwable != null) if (response != null) { assertion.assertNotNull(response.header) } else { throw throwable!! } } @Test(enabled = false) fun testDeactiveAlarm() { // TEST_THIS how to test deactiveAlarm()? } @Test(enabled = false) fun testDeactiveAlarmFuture() { // TEST_THIS how to test deactiveAlarmInFuture()? } @Test(enabled = false) fun testDeactiveAlarmAsync() { // TEST_THIS how to test deactiveAlarmAsync()? } @Test fun testDefragmentMember() { val response = service.defragmentMember() assertion.assertNotNull(response.header) } @Test fun testDefragmentMemberFuture() { val response = service.defragmentMemberInFuture().get(5, TimeUnit.SECONDS) assertion.assertNotNull(response.header) } @Test fun testDefragmentMemberAsync() { val responseRef = AtomicReference<DefragmentResponse?>() val errorRef = AtomicReference<Throwable?>() val finishLatch = CountDownLatch(1) service.defragmentMemberAsync(object : ResponseCallback<DefragmentResponse> { override fun onResponse(response: DefragmentResponse) { responseRef.set(response) logger.debug("Defragment response received.") } override fun onError(throwable: Throwable) { errorRef.set(throwable) } override fun completeCallback() { logger.debug("Asynchronous member defragmentation complete.") finishLatch.countDown() } }) finishLatch.await(10, TimeUnit.SECONDS) val response = responseRef.get() val throwable = errorRef.get() assertion.assertTrue(response != null || throwable != null) if (response != null) { assertion.assertNotNull(response.header) } else { throw throwable!! } } @Test(groups = arrayOf("Maintenance.status")) fun testStatusMember() { val response = service.statusMember() assertion.assertNotNull(response.header) val version = response.version logger.info(version) assertion.assertTrue(version.startsWith("3.")) assertion.assertNotNull(EtcdVersion.ofValue(version)) } @Test(groups = arrayOf("Maintenance.status")) fun testStatusMemberFuture() { val response = service.statusMemberInFuture().get(5, TimeUnit.SECONDS) assertion.assertNotNull(response.header) val version = response.version logger.info(version) assertion.assertTrue(version.startsWith("3.")) assertion.assertNotNull(EtcdVersion.ofValue(version)) } @Test(groups = arrayOf("Maintenance.status")) fun testStatusMemberAsync() { val responseRef = AtomicReference<StatusResponse?>() val errorRef = AtomicReference<Throwable?>() val finishLatch = CountDownLatch(1) service.statusMemberAsync(object : ResponseCallback<StatusResponse> { override fun onResponse(response: StatusResponse) { responseRef.set(response) logger.debug("Status response received.") } override fun onError(throwable: Throwable) { errorRef.set(throwable) } override fun completeCallback() { logger.debug("Asynchronous member status complete.") finishLatch.countDown() } }) finishLatch.await(10, TimeUnit.SECONDS) val response = responseRef.get() val throwable = errorRef.get() assertion.assertTrue(response != null || throwable != null) if (response != null) { assertion.assertNotNull(response.header) val version = response.version logger.info(version) assertion.assertTrue(version.startsWith("3.")) assertion.assertNotNull(EtcdVersion.ofValue(version)) } else { throw throwable!! } } }
ketcd-core/src/test/kotlin/xyz/dowenliu/ketcd/client/EtcdMaintenanceServiceImplTest.kt
2637351255
// FIR_IDENTICAL // FIR_COMPARISON interface Interface { fun funA() } expect class SClass : Interface { // there is no error highlighting about unimplemented members, see KT-25044 override fu<caret> } // ELEMENT_TEXT: "override fun funA() {...}"
plugins/kotlin/completion/tests/testData/handlers/basic/override/kt25312.kt
293943864
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.getFunctionalClassKind import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor import org.jetbrains.kotlin.resolve.calls.model.ReceiverKotlinCallArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedLambdaAtom import org.jetbrains.kotlin.resolve.calls.model.unwrap import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl import org.jetbrains.kotlin.resolve.calls.tower.SubKotlinCallArgumentImpl import org.jetbrains.kotlin.resolve.calls.tower.receiverValue import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun KotlinType.isFunctionOfAnyKind() = constructor.declarationDescriptor?.getFunctionalClassKind() != null fun KotlinType?.isMap(builtIns: KotlinBuiltIns): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.name.asString().endsWith("Map") && classDescriptor.isSubclassOf(builtIns.map) } fun KotlinType?.isIterable(builtIns: KotlinBuiltIns): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.isListOrSet(builtIns) || classDescriptor.isSubclassOf(builtIns.iterable) } fun KotlinType?.isCollection(builtIns: KotlinBuiltIns): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.isListOrSet(builtIns) || classDescriptor.isSubclassOf(builtIns.collection) } private fun ClassDescriptor.isListOrSet(builtIns: KotlinBuiltIns): Boolean { val className = name.asString() return className.endsWith("List") && isSubclassOf(builtIns.list) || className.endsWith("Set") && isSubclassOf(builtIns.set) } fun KtCallExpression.isCalling(fqName: FqName, context: BindingContext? = null): Boolean { return isCalling(listOf(fqName), context) } fun KtCallExpression.isCalling(fqNames: List<FqName>, context: BindingContext? = null): Boolean { val calleeText = calleeExpression?.text ?: return false val targetFqNames = fqNames.filter { it.shortName().asString() == calleeText } if (targetFqNames.isEmpty()) return false val resolvedCall = getResolvedCall(context ?: safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return false return targetFqNames.any { resolvedCall.isCalling(it) } } fun ResolvedCall<out CallableDescriptor>.isCalling(fqName: FqName): Boolean { return resultingDescriptor.fqNameSafe == fqName } fun ResolvedCall<*>.hasLastFunctionalParameterWithResult(context: BindingContext, predicate: (KotlinType) -> Boolean): Boolean { val lastParameter = resultingDescriptor.valueParameters.lastOrNull() ?: return false val lastArgument = valueArguments[lastParameter]?.arguments?.singleOrNull() ?: return false if (this is NewResolvedCallImpl<*>) { // TODO: looks like hack resolvedCallAtom.subResolvedAtoms?.firstOrNull { it is ResolvedLambdaAtom }.safeAs<ResolvedLambdaAtom>()?.let { lambdaAtom -> return lambdaAtom.unwrap().resultArgumentsInfo!!.nonErrorArguments.filterIsInstance<ReceiverKotlinCallArgument>().all { val type = it.receiverValue?.type?.let { type -> if (type.constructor is TypeVariableTypeConstructor) { it.safeAs<SubKotlinCallArgumentImpl>()?.valueArgument?.getArgumentExpression()?.getType(context) ?: type } else { type } } ?: return@all false predicate(type) } } } val functionalType = lastArgument.getArgumentExpression()?.getType(context) ?: return false // Both Function & KFunction must pass here if (!functionalType.isFunctionOfAnyKind()) return false val resultType = functionalType.arguments.lastOrNull()?.type ?: return false return predicate(resultType) } fun KtCallExpression.implicitReceiver(context: BindingContext): ImplicitReceiver? { return getResolvedCall(context)?.getImplicitReceiverValue() } fun KtCallExpression.receiverType(context: BindingContext): KotlinType? { return (getQualifiedExpressionForSelector())?.receiverExpression?.getResolvedCall(context)?.resultingDescriptor?.returnType ?: implicitReceiver(context)?.type }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/FunctionUtils.kt
235851890
package com.tungnui.dalatlaptop.ux.adapters import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.travijuu.numberpicker.library.Enums.ActionEnum import com.travijuu.numberpicker.library.Interface.ValueChangedListener import com.tungnui.dalatlaptop.R import com.tungnui.dalatlaptop.interfaces.CartRecyclerInterface import com.tungnui.dalatlaptop.listeners.OnSingleClickListener import com.tungnui.dalatlaptop.models.Cart import com.tungnui.dalatlaptop.models.ProductReview import com.tungnui.dalatlaptop.utils.inflate import kotlinx.android.synthetic.main.list_item_customer_review.view.* import java.util.ArrayList class ProductReviewRecyclerAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val productReviews = ArrayList<ProductReview>() override fun getItemCount(): Int { return productReviews.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = ViewHolderProduct(parent.inflate(R.layout.list_item_customer_review)) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder as ViewHolderProduct).blind(productReviews[position]) } fun refreshItems(proRes: List<ProductReview>) { productReviews.clear() productReviews.addAll(proRes) notifyDataSetChanged() } fun cleatCart() { productReviews.clear() notifyDataSetChanged() } class ViewHolderProduct(itemView: View) : RecyclerView.ViewHolder(itemView) { fun blind(productReview: ProductReview) = with(itemView){ productReview.rating?.let{list_item_customer_review_rating.rating=it.toFloat()} list_item_customer_review_date.text = productReview.dateCreated list_item_customer_review_name.text = productReview.name list_item_customer_review_content.text = productReview.review } } }
app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/ProductReviewRecyclerAdapter.kt
986079067
package com.jjc.mailshop.service.imp import com.jjc.mailshop.common.ServerResponse import com.jjc.mailshop.service.IFileService import org.springframework.stereotype.Service import org.springframework.web.multipart.MultipartFile import java.io.File import java.util.* import com.qiniu.common.QiniuException import com.qiniu.storage.model.DefaultPutRet import com.google.gson.Gson import com.qiniu.util.Auth import com.qiniu.storage.UploadManager import com.qiniu.common.Zone import com.qiniu.storage.Configuration /** * Created by Administrator on 2017/6/13 0013. */ @Service class FileServiceImp : IFileService { override fun uploadImage(file: MultipartFile, realFilePath: String): ServerResponse<String> { //1.先存放到本地 //查看文件夹是否存在 var mFile = File(realFilePath) if (!mFile.exists()) { //可写 mFile.setWritable(true) //创建文件夹 mFile.mkdir() } // 获取拓展名 val fileName = file.originalFilename // 获取拓展名 val mExtName = fileName.subSequence(fileName.indexOfLast { it == '.' } + 1, fileName.length) //创建文件 val targetFile = File("$realFilePath/${UUID.randomUUID()}.$mExtName") //写入文件 try { file.transferTo(targetFile) } catch(e: Exception) { e.printStackTrace() return ServerResponse.createByErrorMessage("文件上传失败") } //2.上传到七牛 //构造一个带指定Zone对象的配置类 val cfg = Configuration(Zone.zone2()) //...其他参数参考类注释 val uploadManager = UploadManager(cfg) //...生成上传凭证,然后准备上传 val accessKey = "4pEFhEobGofwwHN2wDlk_z7X-DyHdqli7bBnH2nj" val secretKey = "bXRxAo7Tar2yqvi1tTbAA4pONPZZbRUhiOFUdlMW" //目标名称 val bucket = "mal-shop-image" //如果是Windows情况下,格式是 D:\\qiniu\\test.png val localFilePath = targetFile.path //默认不指定key的情况下,以文件内容的hash值作为文件名 val key: String? = null val auth = Auth.create(accessKey, secretKey) val upToken = auth.uploadToken(bucket) try { val response = uploadManager.put(localFilePath, key, upToken) //解析上传成功的结果 val putRet = Gson().fromJson(response.bodyString(), DefaultPutRet::class.java) //3.删除本地 targetFile.delete() //返回结果 return ServerResponse.createBySuccess("上传成功", "http://orfgrfzku.bkt.clouddn.com/${putRet.key}") } catch (ex: QiniuException) { val r = ex.response //返回错误 return ServerResponse.createBySuccessMessage(r.toString()) } } }
code/ServerCode/CodeMallServer/src/main/java/com/jjc/mailshop/service/imp/FileServiceImp.kt
1130878723
import kotlin.test.Test import kotlin.test.assertEquals class WasmTestClient { @Test fun testGreet() { assertEquals("world", greet()) } }
plugins/kotlin/idea/tests/testData/gradle/wasmSmokeTestProjects/checkWasmPlatformImported/src/wasmTest/kotlin/wTest.kt
3066432544
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.viewpager2.widget.swipe import android.app.Activity import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.viewpager2.test.R private val PAGE_COLOR_EVEN = Color.parseColor("#FFAAAA") private val PAGE_COLOR_ODD = Color.parseColor("#AAAAFF") object PageView { fun inflatePage(layoutInflater: LayoutInflater, parent: ViewGroup?): View = layoutInflater.inflate(R.layout.item_test_layout, parent, false) fun findPageInActivity(activity: Activity): View? = activity.findViewById(R.id.text_view) fun getPageText(page: View): String = (page as TextView).text.toString() fun setPageText(page: View, text: String) { (page as TextView).text = text } fun setPageColor(page: View, position: Int) { page.setBackgroundColor(if (position % 2 == 0) PAGE_COLOR_EVEN else PAGE_COLOR_ODD) } }
viewpager2/viewpager2/src/androidTest/java/androidx/viewpager2/widget/swipe/PageView.kt
512479523
package org.thoughtcrime.securesms.components.settings.app.chats.sms import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.os.Build import android.provider.Settings import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.navigation.fragment.findNavController import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.components.settings.models.OutlinedLearnMore import org.thoughtcrime.securesms.exporter.flow.SmsExportActivity import org.thoughtcrime.securesms.exporter.flow.SmsExportDialogs import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.keyvalue.SmsExportPhase import org.thoughtcrime.securesms.util.SmsUtil import org.thoughtcrime.securesms.util.Util import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.navigation.safeNavigate private const val SMS_REQUEST_CODE: Short = 1234 class SmsSettingsFragment : DSLSettingsFragment(R.string.preferences__sms_mms) { private lateinit var viewModel: SmsSettingsViewModel private lateinit var smsExportLauncher: ActivityResultLauncher<Intent> override fun onResume() { super.onResume() viewModel.checkSmsEnabled() } override fun bindAdapter(adapter: MappingAdapter) { OutlinedLearnMore.register(adapter) smsExportLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { SmsExportDialogs.showSmsRemovalDialog(requireContext(), requireView()) } } viewModel = ViewModelProvider(this)[SmsSettingsViewModel::class.java] viewModel.state.observe(viewLifecycleOwner) { adapter.submitList(getConfiguration(it).toMappingModelList()) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (Util.isDefaultSmsProvider(requireContext())) { SignalStore.settings().setDefaultSms(true) } else { SignalStore.settings().setDefaultSms(false) if (SignalStore.misc().smsExportPhase.isAtLeastPhase1()) { findNavController().navigateUp() } } } private fun getConfiguration(state: SmsSettingsState): DSLConfiguration { return configure { if (state.useAsDefaultSmsApp && SignalStore.misc().smsExportPhase.isAtLeastPhase1()) { customPref( OutlinedLearnMore.Model( summary = DSLSettingsText.from(R.string.SmsSettingsFragment__sms_support_will_be_removed_soon_to_focus_on_encrypted_messaging), learnMoreUrl = getString(R.string.sms_export_url) ) ) } when (state.smsExportState) { SmsExportState.FETCHING -> Unit SmsExportState.HAS_UNEXPORTED_MESSAGES -> { clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__export_sms_messages), summary = DSLSettingsText.from(R.string.SmsSettingsFragment__you_can_export_your_sms_messages_to_your_phones_sms_database), onClick = { smsExportLauncher.launch(SmsExportActivity.createIntent(requireContext())) } ) dividerPref() } SmsExportState.ALL_MESSAGES_EXPORTED -> { clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__remove_sms_messages), summary = DSLSettingsText.from(R.string.SmsSettingsFragment__remove_sms_messages_from_signal_to_clear_up_storage_space), onClick = { SmsExportDialogs.showSmsRemovalDialog(requireContext(), requireView()) } ) clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__export_sms_messages_again), summary = DSLSettingsText.from(R.string.SmsSettingsFragment__exporting_again_can_result_in_duplicate_messages), onClick = { SmsExportDialogs.showSmsReExportDialog(requireContext()) { smsExportLauncher.launch(SmsExportActivity.createIntent(requireContext(), isReExport = true)) } } ) dividerPref() } SmsExportState.NO_SMS_MESSAGES_IN_DATABASE -> Unit SmsExportState.NOT_AVAILABLE -> Unit } if (state.useAsDefaultSmsApp || SignalStore.misc().smsExportPhase == SmsExportPhase.PHASE_0) { @Suppress("DEPRECATION") clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__use_as_default_sms_app), summary = DSLSettingsText.from(if (state.useAsDefaultSmsApp) R.string.arrays__enabled else R.string.arrays__disabled), onClick = { if (state.useAsDefaultSmsApp) { startDefaultAppSelectionIntent() } else { startActivityForResult(SmsUtil.getSmsRoleIntent(requireContext()), SMS_REQUEST_CODE.toInt()) } } ) } switchPref( title = DSLSettingsText.from(R.string.preferences__sms_delivery_reports), summary = DSLSettingsText.from(R.string.preferences__request_a_delivery_report_for_each_sms_message_you_send), isChecked = state.smsDeliveryReportsEnabled, onClick = { viewModel.setSmsDeliveryReportsEnabled(!state.smsDeliveryReportsEnabled) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__support_wifi_calling), summary = DSLSettingsText.from(R.string.preferences__enable_if_your_device_supports_sms_mms_delivery_over_wifi), isChecked = state.wifiCallingCompatibilityEnabled, onClick = { viewModel.setWifiCallingCompatibilityEnabled(!state.wifiCallingCompatibilityEnabled) } ) if (Build.VERSION.SDK_INT < 21) { clickPref( title = DSLSettingsText.from(R.string.preferences__advanced_mms_access_point_names), onClick = { Navigation.findNavController(requireView()).safeNavigate(R.id.action_smsSettingsFragment_to_mmsPreferencesFragment) } ) } } } // Linter isn't smart enough to figure out the else only happens if API >= 24 @SuppressLint("InlinedApi") @Suppress("DEPRECATION") private fun startDefaultAppSelectionIntent() { val intent: Intent = when { Build.VERSION.SDK_INT < 23 -> Intent(Settings.ACTION_WIRELESS_SETTINGS) Build.VERSION.SDK_INT < 24 -> Intent(Settings.ACTION_SETTINGS) else -> Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS) } startActivityForResult(intent, SMS_REQUEST_CODE.toInt()) } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/chats/sms/SmsSettingsFragment.kt
238180653
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room import androidx.annotation.IntDef import androidx.annotation.RequiresApi /** * Allows specific customization about the column associated with this field. * * For example, you can specify a column name for the field or change the column's type affinity. */ @Target(AnnotationTarget.FIELD, AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.BINARY) public annotation class ColumnInfo( /** * Name of the column in the database. Defaults to the field name if not set. * * @return Name of the column in the database. */ val name: String = INHERIT_FIELD_NAME, /** * The type affinity for the column, which will be used when constructing the database. * * If it is not specified, the value defaults to [UNDEFINED] and Room resolves it based * on the field's type and available TypeConverters. * * See [SQLite types documentation](https://www.sqlite.org/datatype3.html) for details. * * @return The type affinity of the column. This is either [UNDEFINED], [TEXT], * [INTEGER], [REAL], or [BLOB]. */ @SuppressWarnings("unused") @get:SQLiteTypeAffinity val typeAffinity: Int = UNDEFINED, /** * Convenience method to index the field. * * If you would like to create a composite index instead, see: [Index]. * * @return True if this field should be indexed, false otherwise. Defaults to false. */ val index: Boolean = false, /** * The collation sequence for the column, which will be used when constructing the database. * * The default value is [UNSPECIFIED]. In that case, Room does not add any * collation sequence to the column, and SQLite treats it like [BINARY]. * * @return The collation sequence of the column. This is either [UNSPECIFIED], * [BINARY], [NOCASE], [RTRIM], [LOCALIZED] or [UNICODE]. */ @get:Collate val collate: Int = UNSPECIFIED, /** * The default value for this column. * * ``` * @ColumnInfo(defaultValue = "No name") * public name: String * * @ColumnInfo(defaultValue = "0") * public flag: Int * ``` * * Note that the default value you specify here will _NOT_ be used if you simply * insert the [Entity] with [Insert]. In that case, any value assigned in * Java/Kotlin will be used. Use [Query] with an `INSERT` statement * and skip this column there in order to use this default value. * * NULL, CURRENT_TIMESTAMP and other SQLite constant values are interpreted as such. If you want * to use them as strings for some reason, surround them with single-quotes. * * ``` * @ColumnInfo(defaultValue = "NULL") * public description: String? * * @ColumnInfo(defaultValue = "'NULL'") * public name: String * ``` * * You can also use constant expressions by surrounding them with parentheses. * * ``` * @ColumnInfo(defaultValue = "('Created at' || CURRENT_TIMESTAMP)") * public notice: String * ``` * * @return The default value for this column. * @see [VALUE_UNSPECIFIED] */ val defaultValue: String = VALUE_UNSPECIFIED, ) { /** * The SQLite column type constants that can be used in [typeAffinity()] */ @IntDef(UNDEFINED, TEXT, INTEGER, REAL, BLOB) @Retention(AnnotationRetention.BINARY) public annotation class SQLiteTypeAffinity @RequiresApi(21) @IntDef(UNSPECIFIED, BINARY, NOCASE, RTRIM, LOCALIZED, UNICODE) @Retention(AnnotationRetention.BINARY) public annotation class Collate public companion object { /** * Constant to let Room inherit the field name as the column name. If used, Room will use * the field name as the column name. */ public const val INHERIT_FIELD_NAME: String = "[field-name]" /** * Undefined type affinity. Will be resolved based on the type. * * @see typeAffinity() */ public const val UNDEFINED: Int = 1 /** * Column affinity constant for strings. * * @see typeAffinity() */ public const val TEXT: Int = 2 /** * Column affinity constant for integers or booleans. * * @see typeAffinity() */ public const val INTEGER: Int = 3 /** * Column affinity constant for floats or doubles. * * @see typeAffinity() */ public const val REAL: Int = 4 /** * Column affinity constant for binary data. * * @see typeAffinity() */ public const val BLOB: Int = 5 /** * Collation sequence is not specified. The match will behave like [BINARY]. * * @see collate() */ public const val UNSPECIFIED: Int = 1 /** * Collation sequence for case-sensitive match. * * @see collate() */ public const val BINARY: Int = 2 /** * Collation sequence for case-insensitive match. * * @see collate() */ public const val NOCASE: Int = 3 /** * Collation sequence for case-sensitive match except that trailing space characters are * ignored. * * @see collate() */ public const val RTRIM: Int = 4 /** * Collation sequence that uses system's current locale. * * @see collate() */ @RequiresApi(21) public const val LOCALIZED: Int = 5 /** * Collation sequence that uses Unicode Collation Algorithm. * * @see collate() */ @RequiresApi(21) public const val UNICODE: Int = 6 /** * A constant for [defaultValue()] that makes the column to have no default value. */ public const val VALUE_UNSPECIFIED: String = "[value-unspecified]" } }
room/room-common/src/main/java/androidx/room/ColumnInfo.kt
4071361133
package data.tinder.recommendation import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity internal class RecommendationUserSchoolEntity( @PrimaryKey var name: String, var id: String?)
data/src/main/kotlin/data/tinder/recommendation/RecommendationUserSchoolEntity.kt
2258564454
// 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.codeInsight.codeVision import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectPostStartupActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext open class CodeVisionInitializer(project: Project) { companion object { fun getInstance(project: Project): CodeVisionInitializer = project.service<CodeVisionInitializer>() } protected open val host: CodeVisionHost = CodeVisionHost(project) open fun getCodeVisionHost(): CodeVisionHost = host internal class CodeVisionInitializerStartupActivity : ProjectPostStartupActivity { override suspend fun execute(project: Project) { withContext(Dispatchers.EDT) { getInstance(project).host.initialize() } } } }
platform/lang-impl/src/com/intellij/codeInsight/codeVision/CodeVisionInitializer.kt
1743486734
// "Remove useless elvis operator" "true" fun test() { ((({ "" } <caret>?: null))) }
plugins/kotlin/idea/tests/testData/quickfix/expressions/uselessElvisForLambdaInNestedParens.kt
3698123244
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vfs.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.pointers.VirtualFilePointer open class LightFilePointer : VirtualFilePointer { private val myUrl: String @Volatile private var myFile: VirtualFile? = null @Volatile private var isRefreshed = false constructor(url: String) { myUrl = url } constructor(file: VirtualFile) { myUrl = file.url myFile = file } override fun getFile(): VirtualFile? { refreshFile() return myFile } override fun getUrl(): String = myUrl override fun getFileName(): String { myFile?.let { return it.name } val index = myUrl.lastIndexOf('/') return if (index >= 0) myUrl.substring(index + 1) else myUrl } override fun getPresentableUrl(): String { return file?.presentableUrl ?: toPresentableUrl(myUrl) } override fun isValid(): Boolean = file != null private fun refreshFile() { val file = myFile if (file != null && file.isValid) { return } val virtualFileManager = VirtualFileManager.getInstance() var virtualFile = virtualFileManager.findFileByUrl(myUrl) if (virtualFile == null && !isRefreshed) { isRefreshed = true val app = ApplicationManager.getApplication() if (app.isDispatchThread || !app.isReadAccessAllowed) { virtualFile = virtualFileManager.refreshAndFindFileByUrl(myUrl) } else { app.executeOnPooledThread { virtualFileManager.refreshAndFindFileByUrl(myUrl) } } } myFile = if (virtualFile != null && virtualFile.isValid) virtualFile else null } override fun equals(other: Any?): Boolean { if (this === other) { return true } return if (other is LightFilePointer) myUrl == other.myUrl else false } override fun hashCode(): Int = myUrl.hashCode() } private fun toPresentableUrl(url: String): String { val fileSystem = VirtualFileManager.getInstance().getFileSystem(VirtualFileManager.extractProtocol(url)) return (fileSystem ?: StandardFileSystems.local()).extractPresentableUrl(VirtualFileManager.extractPath(url)) }
platform/core-impl/src/com/intellij/openapi/vfs/impl/LightFilePointer.kt
1119913781
package kt25220 fun main() { //Breakpoint! val a = 5 }
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/kt25220.kt
1612325604
package com.jetbrains.packagesearch.intellij.plugin.ui.util import com.jetbrains.packagesearch.intellij.plugin.util.AppUI import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.swing.JTable import javax.swing.table.TableColumn internal suspend fun JTable.autosizeColumnsAt(indices: Iterable<Int>) { val (columns, preferredWidths) = withContext(Dispatchers.Default) { val columns = indices.map { columnModel.getColumn(it) } columns to getColumnDataWidths(columns) } columns.forEachIndexed { index, column -> column.width = preferredWidths[index] } } private fun JTable.getColumnDataWidths(columns: Iterable<TableColumn>): IntArray { val preferredWidth = IntArray(columns.count()) val separatorSize = intercellSpacing.width for ((index, column) in columns.withIndex()) { val maxWidth = column.maxWidth val columnIndex = column.modelIndex for (row in 0 until rowCount) { val width = getCellDataWidth(row, columnIndex) + separatorSize preferredWidth[index] = preferredWidth[index].coerceAtLeast(width) if (preferredWidth[index] >= maxWidth) break } } return preferredWidth } private fun JTable.getCellDataWidth(row: Int, column: Int): Int { val renderer = getCellRenderer(row, column) val cellWidth = prepareRenderer(renderer, row, column).preferredSize.width return cellWidth + intercellSpacing.width }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/JTableExtensions.kt
3246036191
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.unified.UnifiedDependency import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.logWarn import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank internal class ModuleOperationExecutor { /** This **MUST** run on EDT */ fun doOperation(operation: PackageSearchOperation<*>) = try { when (operation) { is PackageSearchOperation.Package.Install -> installPackage(operation) is PackageSearchOperation.Package.Remove -> removePackage(operation) is PackageSearchOperation.Package.ChangeInstalled -> changePackage(operation) is PackageSearchOperation.Repository.Install -> installRepository(operation) is PackageSearchOperation.Repository.Remove -> removeRepository(operation) } null } catch (e: OperationException) { logWarn("ModuleOperationExecutor#doOperation()", e) { "Failure while performing operation $operation" } PackageSearchOperationFailure(operation, e) } private fun installPackage(operation: PackageSearchOperation.Package.Install) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#installPackage()") { "Installing package ${operation.model.displayName} in ${projectModule.name}" } operationProvider.addDependencyToModule( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model, operation.newVersion, operation.newScope), module = projectModule ).throwIfAnyFailures() PackageSearchEventsLogger.logPackageInstalled(operation.model, operation.projectModule) logTrace("ModuleOperationExecutor#installPackage()") { "Package ${operation.model.displayName} installed in ${projectModule.name}" } } private fun removePackage(operation: PackageSearchOperation.Package.Remove) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#removePackage()") { "Removing package ${operation.model.displayName} from ${projectModule.name}" } operationProvider.removeDependencyFromModule( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model), module = projectModule ).throwIfAnyFailures() PackageSearchEventsLogger.logPackageRemoved(operation.model, operation.projectModule) logTrace("ModuleOperationExecutor#removePackage()") { "Package ${operation.model.displayName} removed from ${projectModule.name}" } } private fun changePackage(operation: PackageSearchOperation.Package.ChangeInstalled) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#changePackage()") { "Changing package ${operation.model.displayName} in ${projectModule.name}" } operationProvider.updateDependencyInModule( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model, operation.newVersion, operation.newScope), module = projectModule ).throwIfAnyFailures() PackageSearchEventsLogger.logPackageUpdated(operation.model, operation.projectModule) logTrace("ModuleOperationExecutor#changePackage()") { "Package ${operation.model.displayName} changed in ${projectModule.name}" } } private fun dependencyOperationMetadataFrom( projectModule: ProjectModule, dependency: UnifiedDependency, newVersion: PackageVersion? = null, newScope: PackageScope? = null ) = DependencyOperationMetadata( module = projectModule, groupId = dependency.coordinates.groupId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), artifactId = dependency.coordinates.artifactId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), currentVersion = dependency.coordinates.version.nullIfBlank(), currentScope = dependency.scope.nullIfBlank(), newVersion = newVersion?.versionName.nullIfBlank() ?: dependency.coordinates.version.nullIfBlank(), newScope = newScope?.scopeName.nullIfBlank() ?: dependency.scope.nullIfBlank() ) private fun installRepository(operation: PackageSearchOperation.Repository.Install) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#installRepository()") { "Installing repository ${operation.model.displayName} in ${projectModule.name}" } operationProvider.addRepositoryToModule(operation.model, projectModule) .throwIfAnyFailures() PackageSearchEventsLogger.logRepositoryAdded(operation.model) logTrace("ModuleOperationExecutor#installRepository()") { "Repository ${operation.model.displayName} installed in ${projectModule.name}" } } private fun removeRepository(operation: PackageSearchOperation.Repository.Remove) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#removeRepository()") { "Removing repository ${operation.model.displayName} from ${projectModule.name}" } operationProvider.removeRepositoryFromModule(operation.model, projectModule) .throwIfAnyFailures() PackageSearchEventsLogger.logRepositoryRemoved(operation.model) logTrace("ModuleOperationExecutor#removeRepository()") { "Repository ${operation.model.displayName} removed from ${projectModule.name}" } } private fun List<OperationFailure<*>>.throwIfAnyFailures() { when { isEmpty() -> return size > 1 -> throw IllegalStateException("A single operation resulted in multiple failures") } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/ModuleOperationExecutor.kt
1733055385
// WITH_RUNTIME // PROBLEM: none class Foo { fun test() { Bar().apply { <caret>[email protected]() } } } class Bar fun Foo.s() {} fun Bar.s() {}
plugins/kotlin/idea/tests/testData/inspectionsLocal/explicitThis/differentReceiverTypeExtension.kt
611505517
package io.mironov.sento.compiler.common import org.objectweb.asm.Type internal val Type.simpleName: String get() = if (className.contains(".")) { className.substring(className.lastIndexOf(".") + 1) } else { className }
sento-compiler/src/main/kotlin/io/mironov/sento/compiler/common/TypeExtensions.kt
1537546283
import BExtSpace.aaa // "Import" "true" // WITH_STDLIB // ERROR: Unresolved reference: aaa // COMPILER_ARGUMENTS: -XXLanguage:-NewInference fun test() { AAA().apply { sub { aaa<caret>() } } } /* IGNORE_FIR */
plugins/kotlin/idea/tests/testData/quickfix/autoImports/dslMarkersOnReceiver.after.kt
3819915043
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.highlighter import com.intellij.lang.annotation.HighlightSeverity import gnu.trove.THashSet import gnu.trove.TObjectHashingStrategy import org.jetbrains.kotlin.codeMetaInfo.model.CodeMetaInfo import org.jetbrains.kotlin.idea.codeMetaInfo.CodeMetaInfoTestCase import org.jetbrains.kotlin.idea.codeMetaInfo.models.HighlightingCodeMetaInfo import org.jetbrains.kotlin.idea.codeMetaInfo.renderConfigurations.HighlightingConfiguration import org.jetbrains.kotlin.idea.codeMetaInfo.renderConfigurations.HighlightingConfiguration.DescriptionRenderingOption import org.jetbrains.kotlin.idea.codeMetaInfo.renderConfigurations.HighlightingConfiguration.SeverityRenderingOption import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import java.io.File import java.util.* abstract class AbstractHighlightingMetaInfoTest : KotlinLightCodeInsightFixtureTestCase() { protected val HIGHLIGHTING_EXTENSION = "highlighting" open fun doTest(unused: String) { myFixture.configureByFile(fileName()) val expectedHighlighting = testDataFile().getExpectedHighlightingFile() checkHighlighting(expectedHighlighting) } private fun checkHighlighting(expectedHighlightingFile: File) { val highlightingRenderConfiguration = HighlightingConfiguration( descriptionRenderingOption = DescriptionRenderingOption.IF_NOT_NULL, renderSeverityOption = SeverityRenderingOption.ONLY_NON_INFO, ) val codeMetaInfoTestCase = CodeMetaInfoTestCase( codeMetaInfoTypes = listOf(highlightingRenderConfiguration), filterMetaInfo = createMetaInfoFilter() ) codeMetaInfoTestCase.checkFile(myFixture.file.virtualFile, expectedHighlightingFile, project) } /** * This filter serves two purposes: * - Fail the test on ERRORS, since we don't want to have ERRORS in the tests for a regular highlighting * - Filter WARNINGS, since they are provided by the compiler and (usually) are not interesting to us in the context of highlighting * - Filter exact highlightings duplicates. It is a workaround about a bug in old FE10 highlighting, which sometimes highlights * something twice */ private fun createMetaInfoFilter(): (CodeMetaInfo) -> Boolean { val forbiddenSeverities = setOf(HighlightSeverity.ERROR) val ignoredSeverities = setOf(HighlightSeverity.WARNING, HighlightSeverity.WEAK_WARNING) val seenMetaInfos = THashSet(object : TObjectHashingStrategy<HighlightingCodeMetaInfo> { override fun equals(left: HighlightingCodeMetaInfo, right: HighlightingCodeMetaInfo): Boolean = left.start == right.start && left.end == right.end && left.tag == right.tag && left.highlightingInfo == right.highlightingInfo override fun computeHashCode(metaInfo: HighlightingCodeMetaInfo): Int = Objects.hash(metaInfo.start, metaInfo.end, metaInfo.tag) }) return { metaInfo -> require(metaInfo is HighlightingCodeMetaInfo) val highlightingInfo = metaInfo.highlightingInfo require(highlightingInfo.severity !in forbiddenSeverities) { """ |Severity ${highlightingInfo.severity} should never appear in highlighting tests. Please, correct the testData. |HighlightingInfo=$highlightingInfo """.trimMargin() } highlightingInfo.severity !in ignoredSeverities && seenMetaInfos.add(metaInfo) } } protected fun File.getExpectedHighlightingFile(suffix: String = highlightingFileNameSuffix(this)): File { return resolveSibling("$name.$suffix") } protected open fun highlightingFileNameSuffix(ktFilePath: File): String = HIGHLIGHTING_EXTENSION }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightingMetaInfoTest.kt
3547287408
import kotlinx.cinterop.* import kotlinx.cinterop.internal.* @CStruct(spelling = "struct { }") class Z constructor(rawPtr: NativePtr) : CStructVar(rawPtr) { var x: Pair<Int, Int>? = null @CStruct.MemberAt(offset = 0L) get @CStruct.MemberAt(offset = 0L) set } fun foo(z: Z) { z.x = 42 to 117 } fun main() { }
backend.native/tests/compilerChecks/t38.kt
2791008441
// FIR_IDENTICAL // FIR_COMPARISON fun globalFun(){} interface T { fun fromTrait(){} } abstract class Base : T { fun fromBase(){} } class Derived : Base() { override fun fromTrait() { } fun fromDerived(){} fun foo(d: Derived) { <caret> } } // EXIST: { itemText: "foo", attributes: "bold" } // EXIST: { itemText: "fromTrait", attributes: "" } // EXIST: { itemText: "fromDerived", attributes: "bold" } // EXIST: { itemText: "fromBase", attributes: "" } // EXIST: { itemText: "hashCode", attributes: "" } // EXIST: { itemText: "equals", attributes: "" } // EXIST: { itemText: "globalFun", attributes: "" }
plugins/kotlin/completion/tests/testData/basic/common/boldOrGrayed/ImmediateMembers5.kt
3156809291
// 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.tools.projectWizard import com.intellij.ide.JavaUiBundle import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logAddSampleCodeChanged import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkChanged import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.INTELLIJ import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep import com.intellij.ide.starters.local.StandardAssetsProvider import com.intellij.ide.wizard.AbstractNewProjectWizardStep import com.intellij.ide.wizard.GitNewProjectWizardData.Companion.gitData import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.ide.wizard.chain import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.observable.util.bindBooleanStorage import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.projectRoots.impl.DependentSdkType import com.intellij.openapi.roots.ui.configuration.sdkComboBox import com.intellij.ui.UIBundle.* import com.intellij.ui.dsl.builder.* import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType internal class IntelliJKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard { override val name = INTELLIJ override val ordinal = 0 override fun createStep(parent: KotlinNewProjectWizard.Step) = Step(parent).chain(::AssetsStep) class Step(parent: KotlinNewProjectWizard.Step) : AbstractNewProjectWizardStep(parent), BuildSystemKotlinNewProjectWizardData by parent { private val sdkProperty = propertyGraph.property<Sdk?>(null) private val addSampleCodeProperty = propertyGraph.property(false) .bindBooleanStorage("NewProjectWizard.addSampleCodeState") private val sdk by sdkProperty private val addSampleCode by addSampleCodeProperty override fun setupUI(builder: Panel) { with(builder) { row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) { val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType } sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter) .columns(COLUMNS_MEDIUM) .whenItemSelectedFromUi { logSdkChanged(sdk) } } row { checkBox(message("label.project.wizard.new.project.add.sample.code")) .bindSelected(addSampleCodeProperty) .whenStateChangedFromUi { logAddSampleCodeChanged(it) } }.topGap(TopGap.SMALL) kmpWizardLink(context) } } override fun setupProject(project: Project) = KotlinNewProjectWizard.generateProject( project = project, projectPath = "$path/$name", projectName = name, sdk = sdk, buildSystemType = BuildSystemType.Jps, addSampleCode = addSampleCode ) } private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) { override fun setupAssets(project: Project) { outputDirectory = "$path/$name" if (gitData?.git == true) { addAssets(StandardAssetsProvider().getIntelliJIgnoreAssets()) } } } }
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/IntelliJKotlinNewProjectWizard.kt
3769266393
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.index import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasByExpansionShortNameIndex import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.runAll import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.junit.Assert import kotlin.reflect.KMutableProperty0 abstract class AbstractKotlinTypeAliasByExpansionShortNameIndexTest : KotlinLightCodeInsightFixtureTestCase() { private lateinit var scope: GlobalSearchScope override fun setUp() { super.setUp() scope = GlobalSearchScope.allScope(project) } override fun tearDown() { runAll( ThrowableRunnable { @Suppress("UNCHECKED_CAST") (this::scope as KMutableProperty0<GlobalSearchScope?>).set(null) }, ThrowableRunnable { super.tearDown() } ) } override fun getProjectDescriptor() = super.getProjectDescriptorFromTestName() fun doTest(file: String) { myFixture.configureByFile(file) val fileText = myFixture.file.text InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "CONTAINS").forEach { assertIndexContains(it) } } private val regex = "\\(key=\"(.*?)\"[, ]*value=\"(.*?)\"\\)".toRegex() fun assertIndexContains(record: String) { val index = KotlinTypeAliasByExpansionShortNameIndex val (_, key, value) = regex.find(record)!!.groupValues val result = index.get(key, project, scope) if (value !in result.map { it.name }) { Assert.fail(buildString { appendLine("Record $record not found in index") appendLine("Index contents:") index.getAllKeys(project).asSequence().forEach { appendLine("KEY: $it") index.get(it, project, scope).forEach { appendLine(" ${it.name}") } } }) } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/index/AbstractKotlinTypeAliasByExpansionShortNameIndexTest.kt
3219295829
package a object A { fun <caret>foo() {} }
plugins/kotlin/idea/tests/testData/multiFileIntentions/moveMemberToTopLevel/function/before/a/A.kt
1360995095
// IS_APPLICABLE: true fun foo() { bar(2) <caret>{ val x = 3 it * x } } fun bar(a: Int, b: (Int) -> Int) { b(a) }
plugins/kotlin/idea/tests/testData/intentions/moveLambdaInsideParentheses/moveLambda3.kt
2156105715
// 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.compiler.impl import com.intellij.build.BuildContentManager import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeLater import com.intellij.openapi.compiler.JavaCompilerBundle import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.util.NlsContexts.NotificationContent import com.intellij.openapi.wm.ToolWindowManager import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference @Service //project class CompileDriverNotifications( private val project: Project ) : Disposable { private val currentNotification = AtomicReference<Notification>(null) companion object { @JvmStatic fun getInstance(project: Project) = project.service<CompileDriverNotifications>() } override fun dispose() { currentNotification.set(null) } fun createCannotStartNotification() : LightNotification { return LightNotification() } inner class LightNotification { private val isShown = AtomicBoolean() private val notificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("jps configuration error") private val baseNotification = notificationGroup .createNotification(JavaCompilerBundle.message("notification.title.jps.cannot.start.compiler"), NotificationType.ERROR) .setImportant(true) fun withExpiringAction(@NotificationContent title : String, handler: () -> Unit) = apply { baseNotification.addAction(NotificationAction.createSimpleExpiring(title, handler)) } @JvmOverloads fun withOpenSettingsAction(moduleNameToSelect: String? = null, tabNameToSelect: String? = null) = withExpiringAction(JavaCompilerBundle.message("notification.action.jps.open.configuration.dialog")) { val service = ProjectSettingsService.getInstance(project) if (moduleNameToSelect != null) { service.showModuleConfigurationDialog(moduleNameToSelect, tabNameToSelect) } else { service.openProjectSettings() } } fun withContent(@NotificationContent content: String): LightNotification = apply { baseNotification.setContent(content) } /** * This wrapper helps to make sure we have only one active unresolved notification per project */ fun showNotification() { if (ApplicationManager.getApplication().isUnitTestMode) { thisLogger().error("" + baseNotification.content) return } if (!isShown.compareAndSet(false, true)) return val showNotification = Runnable { baseNotification.whenExpired { currentNotification.compareAndExchange(baseNotification, null) } currentNotification.getAndSet(baseNotification)?.expire() baseNotification.notify(project) } showNotification.run() } } }
java/compiler/impl/src/com/intellij/compiler/impl/CompileDriverNotifications.kt
3468026257
// 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 git4idea.history import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.EventDispatcher import com.intellij.vcs.log.* import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.index.IndexDataGetter import com.intellij.vcs.log.data.index.IndexedDetails.Companion.createMetadata import com.intellij.vcs.log.data.index.VcsLogIndex import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.graph.utils.BfsWalk import com.intellij.vcs.log.graph.utils.DfsWalk import com.intellij.vcs.log.graph.utils.LinearGraphUtils import com.intellij.vcs.log.graph.utils.impl.BitSetFlags import com.intellij.vcs.log.impl.TimedVcsCommitImpl import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import git4idea.GitCommit import git4idea.GitUtil import git4idea.GitVcs import git4idea.history.GitHistoryTraverser.Traverse import git4idea.history.GitHistoryTraverser.TraverseCommitInfo import java.util.* internal class GitHistoryTraverserImpl(private val project: Project, private val logData: VcsLogData) : GitHistoryTraverser { private val requestedRootsIndexingListeners = EventDispatcher.create(RequestedRootsIndexingListener::class.java) private val indexListener = VcsLogIndex.IndexingFinishedListener { requestedRootsIndexingListeners.multicaster.indexingFinished(it) } init { logData.index.addListener(indexListener) Disposer.register(logData, this) } override fun toHash(id: TraverseCommitId) = logData.getCommitId(id)!!.hash private fun startSearch( start: Hash, root: VirtualFile, walker: (startId: TraverseCommitId, graph: LiteLinearGraph, visited: BitSetFlags, handler: (id: TraverseCommitId) -> Boolean) -> Unit, commitHandler: Traverse.(id: TraverseCommitInfo) -> Boolean ) { val dataPack = logData.dataPack val hashIndex = logData.getCommitIndex(start, root) val permanentGraph = dataPack.permanentGraph as PermanentGraphImpl<Int> val hashNodeId = permanentGraph.permanentCommitsInfo.getNodeId(hashIndex).takeIf { it != -1 } ?: throw IllegalArgumentException("Hash '${start.asString()}' doesn't exist in repository: $root") val graph = LinearGraphUtils.asLiteLinearGraph(permanentGraph.linearGraph) val visited = BitSetFlags(graph.nodesCount()) val traverse = TraverseImpl(this) walker(hashNodeId, graph, visited) { ProgressManager.checkCanceled() if (Disposer.isDisposed(this)) { throw ProcessCanceledException() } val commitId = permanentGraph.permanentCommitsInfo.getCommitId(it) val parents = graph.getNodes(it, LiteLinearGraph.NodeFilter.DOWN) traverse.commitHandler(TraverseCommitInfo(commitId, parents)) } traverse.loadDetails() } override fun traverse( root: VirtualFile, start: GitHistoryTraverser.StartNode, type: GitHistoryTraverser.TraverseType, commitHandler: Traverse.(id: TraverseCommitInfo) -> Boolean ) { fun findBranchHash(branchName: String) = VcsLogUtil.findBranch(logData.dataPack.refsModel, root, branchName)?.commitHash ?: throw IllegalArgumentException("Branch '$branchName' doesn't exist in the repository: $root") val hash = when (start) { is GitHistoryTraverser.StartNode.CommitHash -> start.hash GitHistoryTraverser.StartNode.Head -> findBranchHash(GitUtil.HEAD) is GitHistoryTraverser.StartNode.Branch -> findBranchHash(start.branchName) } startSearch( hash, root, walker = { hashNodeId, graph, visited, handler -> when (type) { GitHistoryTraverser.TraverseType.DFS -> DfsWalk(listOf(hashNodeId), graph, visited).walk(true, handler) GitHistoryTraverser.TraverseType.BFS -> BfsWalk(hashNodeId, graph, visited).walk(handler) } }, commitHandler = commitHandler ) } override fun addIndexingListener( roots: Collection<VirtualFile>, disposable: Disposable, listener: GitHistoryTraverser.IndexingListener ) { val indexingListener = RequestedRootsIndexingListenerImpl(roots, this, listener) requestedRootsIndexingListeners.addListener(indexingListener, disposable) val indexedRoot = roots.firstOrNull { logData.index.isIndexed(it) } ?: return indexingListener.indexingFinished(indexedRoot) } override fun loadMetadata(ids: List<TraverseCommitId>): List<VcsCommitMetadata> = ids.groupBy { getRoot(it) }.map { (root, commits) -> GitLogUtil.collectMetadata(project, GitVcs.getInstance(project), root, commits.map { toHash(it).asString() }) }.flatten() override fun loadFullDetails( ids: List<TraverseCommitId>, requirements: GitCommitRequirements, fullDetailsHandler: (GitCommit) -> Unit ) { ids.groupBy { getRoot(it) }.forEach { (root, commits) -> GitLogUtil.readFullDetailsForHashes(project, root, commits.map { toHash(it).asString() }, requirements, Consumer { fullDetailsHandler(it) }) } } override fun getCurrentUser(root: VirtualFile): VcsUser? = logData.currentUser[root] override fun dispose() { logData.index.removeListener(indexListener) } private fun getRoot(id: TraverseCommitId): VirtualFile = logData.getCommitId(id)!!.root private class IndexedRootImpl( private val traverser: GitHistoryTraverser, private val project: Project, override val root: VirtualFile, private val dataGetter: IndexDataGetter ) : GitHistoryTraverser.IndexedRoot { override fun filterCommits(filter: GitHistoryTraverser.IndexedRoot.TraverseCommitsFilter): Collection<TraverseCommitId> { val logFilter = when (filter) { is GitHistoryTraverser.IndexedRoot.TraverseCommitsFilter.Author -> VcsLogFilterObject.fromUser(filter.author) is GitHistoryTraverser.IndexedRoot.TraverseCommitsFilter.File -> VcsLogFilterObject.fromPaths(setOf(filter.file)) } return dataGetter.filter(listOf(logFilter)) } override fun loadTimedCommit(id: TraverseCommitId): TimedVcsCommit { val parents = dataGetter.getParents(id)!! val timestamp = dataGetter.getCommitTime(id)!! val hash = traverser.toHash(id) return TimedVcsCommitImpl(hash, parents, timestamp) } override fun loadMetadata(id: TraverseCommitId): VcsCommitMetadata { val storage = dataGetter.logStorage val factory = project.service<VcsLogObjectsFactory>() return createMetadata(id, dataGetter, storage, factory)!! } } private class RequestedRootsIndexingListenerImpl( private val requestedRoots: Collection<VirtualFile>, private val traverser: GitHistoryTraverserImpl, private val listener: GitHistoryTraverser.IndexingListener ) : RequestedRootsIndexingListener { override fun indexingFinished(root: VirtualFile) { val index = traverser.logData.index val dataGetter = index.dataGetter ?: return val indexedRoots = requestedRoots.filter { index.isIndexed(it) }.map { IndexedRootImpl(traverser, traverser.project, it, dataGetter) } if (indexedRoots.isNotEmpty()) { listener.indexedRootsUpdated(indexedRoots) } } } private interface RequestedRootsIndexingListener : VcsLogIndex.IndexingFinishedListener, EventListener private class TraverseImpl(private val traverser: GitHistoryTraverser) : Traverse { val requests = mutableListOf<Request>() override fun loadMetadataLater(id: TraverseCommitId, onLoad: (VcsCommitMetadata) -> Unit) { requests.add(Request.LoadMetadata(id, onLoad)) } override fun loadFullDetailsLater(id: TraverseCommitId, requirements: GitCommitRequirements, onLoad: (GitCommit) -> Unit) { requests.add(Request.LoadFullDetails(id, requirements, onLoad)) } fun loadDetails() { loadMetadata(requests.filterIsInstance<Request.LoadMetadata>()) loadFullDetails(requests.filterIsInstance<Request.LoadFullDetails>()) } private fun loadMetadata(loadMetadataRequests: List<Request.LoadMetadata>) { val commitsMetadata = traverser.loadMetadata(loadMetadataRequests.map { it.id }).associateBy { it.id } for (request in loadMetadataRequests) { val hash = traverser.toHash(request.id) val details = commitsMetadata[hash] ?: continue request.onLoad(details) } } private fun loadFullDetails(loadFullDetailsRequests: List<Request.LoadFullDetails>) { val handlers = mutableMapOf<Hash, MutableMap<GitCommitRequirements, MutableList<(GitCommit) -> Unit>>>() loadFullDetailsRequests.forEach { request -> traverser.toHash(request.id).let { hash -> val requirementsToHandlers = handlers.getOrPut(hash) { mutableMapOf() } requirementsToHandlers.getOrPut(request.requirements) { mutableListOf() }.add(request.onLoad) } } val requirementTypes = loadFullDetailsRequests.map { it.requirements }.distinct() requirementTypes.forEach { requirements -> traverser.loadFullDetails(loadFullDetailsRequests.map { it.id }, requirements) { details -> handlers[details.id]?.get(requirements)?.forEach { onLoad -> onLoad(details) } } } } sealed class Request(val id: TraverseCommitId) { class LoadMetadata(id: TraverseCommitId, val onLoad: (VcsCommitMetadata) -> Unit) : Request(id) class LoadFullDetails(id: TraverseCommitId, val requirements: GitCommitRequirements, val onLoad: (GitCommit) -> Unit) : Request(id) } } }
plugins/git4idea/src/git4idea/history/GitHistoryTraverserImpl.kt
3665109901
// "Remove initializer from property" "true" abstract class A { abstract var i : Int = 0<caret> }
plugins/kotlin/idea/tests/testData/quickfix/abstract/abstractPropertyWIthInitializer3.kt
1970696319
// 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.plugins.gradle.execution import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.externalSystem.task.TaskCallback import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.Test import org.junit.runners.Parameterized import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit class GradleTasksExecutionTest : GradleImportingTestCase() { @Test fun `run task with specified build file test`() { createProjectSubFile("build.gradle", """ task myTask() { doLast { print 'Hi!' } } """.trimIndent()) createProjectSubFile("build007.gradle", """ task anotherTask() { doLast { print 'Hi, James!' } } """.trimIndent()) assertThat(runTaskAndGetErrorOutput(projectPath, "myTask")).isEmpty() assertThat(runTaskAndGetErrorOutput("$projectPath/build.gradle", "myTask")).isEmpty() assertThat(runTaskAndGetErrorOutput(projectPath, "anotherTask")).contains("Task 'anotherTask' not found in root project 'project'.") assertThat(runTaskAndGetErrorOutput("$projectPath/build007.gradle", "anotherTask")).isEmpty() assertThat(runTaskAndGetErrorOutput("$projectPath/build007.gradle", "myTask")).contains( "Task 'myTask' not found in root project 'project'.") assertThat(runTaskAndGetErrorOutput("$projectPath/build.gradle", "myTask", "-b foo")).contains("The specified build file", "foo' does not exist.") } private fun runTaskAndGetErrorOutput(projectPath: String, taskName: String, scriptParameters: String = ""): String { val taskErrOutput = StringBuilder() val stdErrListener = object : ExternalSystemTaskNotificationListenerAdapter() { override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { if (!stdOut) { taskErrOutput.append(text) } } } val notificationManager = ExternalSystemProgressNotificationManager.getInstance() notificationManager.addNotificationListener(stdErrListener) try { val settings = ExternalSystemTaskExecutionSettings() settings.externalProjectPath = projectPath settings.taskNames = listOf(taskName) settings.scriptParameters = scriptParameters settings.externalSystemIdString = GradleConstants.SYSTEM_ID.id val future = CompletableFuture<String>() ExternalSystemUtil.runTask(settings, DefaultRunExecutor.EXECUTOR_ID, myProject, GradleConstants.SYSTEM_ID, object : TaskCallback { override fun onSuccess() { future.complete(taskErrOutput.toString()) } override fun onFailure() { future.complete(taskErrOutput.toString()) } }, ProgressExecutionMode.IN_BACKGROUND_ASYNC) return future.get(10, TimeUnit.SECONDS) } finally { notificationManager.removeNotificationListener(stdErrListener) } } companion object { /** * It's sufficient to run the test against one gradle version */ @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(BASE_GRADLE_VERSION)) } }
plugins/gradle/java/testSources/execution/GradleTasksExecutionTest.kt
1891788102
package oldPackage fun <caret>foo() { } fun other() { }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/moveFunctionToPackageUsedInJava/before/oldPackage/fun.kt
2294618101
package other public val String.extensionPropNotImported: Int get() = 1
plugins/kotlin/completion/tests/testData/basic/multifile/ExtensionsForSmartCast/ExtensionsForSmartCast.dependency.kt
1712604198
package co.early.fore.kt.core.ui import co.early.fore.kt.core.ui.trigger.StateChange import co.early.fore.kt.core.ui.trigger.TriggerOnChange import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.verify import org.junit.Before import org.junit.Test class TriggerOnChangeTest { private data class TestData( val message: String, val count: Int, ) @MockK private lateinit var mockCurrentState: () -> Int @MockK private lateinit var mockDoThisWhenTriggered: (StateChange<Int>) -> Unit @MockK private lateinit var mockNullDoThisWhenTriggered: (StateChange<String?>) -> Unit @MockK private lateinit var mockDataClassCurrentState: () -> TestData @MockK private lateinit var mockDataClassDoThisWhenTriggered: (StateChange<TestData>) -> Unit private val TEST_1 = TestData("yes", 1) private val TEST_2 = TestData("no", 0) @Before fun setup() = MockKAnnotations.init(this, relaxed = true) @Test fun `when initial state changes, check() triggers`() { // arrange every { mockCurrentState.invoke() } returns 1 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.check() // assert verify(exactly = 1) { mockDoThisWhenTriggered(any()) } } @Test fun `when initial state stays null, check() does not trigger`() { // arrange val trigger = TriggerOnChange({ null }, mockNullDoThisWhenTriggered) // act trigger.check() // assert verify(exactly = 0) { mockDoThisWhenTriggered(any()) } } @Test fun `when initial state changes, check() triggers with new state value`() { // arrange every { mockCurrentState.invoke() } returns 3 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.check() // assert verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(null, 3))) } } @Test fun `when state changes multiple times, check() triggers only on change`() { // arrange every { mockCurrentState.invoke() } returns 3 andThen 5 andThen 6 andThen 6 andThen 3 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.check() trigger.check() trigger.check() trigger.check() trigger.check() // assert verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(null,3))) } verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(3, 5))) } verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(5, 6))) } verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(6,3))) } } @Test fun `when initial state changes, first checkLazy() does not trigger`() { // arrange every { mockCurrentState.invoke() } returns 1 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.checkLazy() // assert verify(exactly = 0) { mockDoThisWhenTriggered(any()) } } @Test fun `when initial state stays null, checkLazy() does not trigger`() { // arrange val trigger = TriggerOnChange<String?>({ null }, mockNullDoThisWhenTriggered) // act trigger.checkLazy() trigger.checkLazy() // assert verify(exactly = 0) { mockDoThisWhenTriggered(any()) } } @Test fun `when initial state changes, second checkLazy() does not trigger`() { // arrange every { mockCurrentState.invoke() } returns 3 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.checkLazy() trigger.checkLazy() // assert verify(exactly = 0) { mockDoThisWhenTriggered(any()) } } @Test fun `when state changes multiple times, checkLazy() triggers only on change`() { // arrange every { mockCurrentState.invoke() } returns 3 andThen 5 andThen 6 andThen 6 andThen 3 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.checkLazy() trigger.checkLazy() trigger.checkLazy() trigger.checkLazy() trigger.checkLazy() // assert verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(3, 5))) } verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(5, 6))) } verify(exactly = 1) { mockDoThisWhenTriggered(eq(StateChange(6, 3))) } } @Test fun `when first and second state changes are the same, second checkLazy() does not trigger`() { // arrange every { mockCurrentState.invoke() } returns 3 andThen 3 val trigger = TriggerOnChange(mockCurrentState, mockDoThisWhenTriggered) // act trigger.checkLazy() trigger.checkLazy() // assert verify(exactly = 0) { mockDoThisWhenTriggered(any()) } } @Test fun `when data class state changes, second check() does trigger`() { // arrange every { mockDataClassCurrentState.invoke() } returns TEST_1 andThen TEST_2 val trigger = TriggerOnChange(mockDataClassCurrentState, mockDataClassDoThisWhenTriggered) // act trigger.check() trigger.check() // assert verify(exactly = 1) { mockDataClassDoThisWhenTriggered(eq(StateChange(null, TEST_1))) } verify(exactly = 1) { mockDataClassDoThisWhenTriggered(eq(StateChange(TEST_1, TEST_2))) } } @Test fun `when data class state does not change, second check() does not trigger`() { // arrange every { mockDataClassCurrentState.invoke() } returns TEST_1 andThen TEST_1 val trigger = TriggerOnChange(mockDataClassCurrentState, mockDataClassDoThisWhenTriggered) // act trigger.checkLazy() trigger.checkLazy() // assert verify(exactly = 0) { mockDataClassDoThisWhenTriggered(any()) } } } //fun MockKMatcherScope.eq(other: StateChange<Int>) = match<StateChange<Int>> { // it.pre == other.pre && it.now == other.now //}
fore-kt-android/src/test/java/co/early/fore/kt/core/ui/TriggerOnChangeTest.kt
2797263202
package net.benwoodworth.fastcraft.bukkit.tools import org.bukkit.Bukkit import org.bukkit.Material import java.io.File internal object MaterialOrderGenerator { private val nmsVersion = Bukkit.getServer()::class.java.`package`.name.substring("org.bukkit.craftbukkit.".length) private val nms = "net.minecraft.server.$nmsVersion" private val obc = "org.bukkit.craftbukkit.$nmsVersion" /** * For use with CraftBukkit 1.13+. * * Lists materials in the order they appear in the Minecraft item registry. (Same as in the creative menu) * * For new Minecraft releases, use this to generate a new file into bukkit/item-order/<version>.txt. */ fun generate(out: File) { val IRegistry = Class.forName("$nms.IRegistry") val IRegistry_ITEM = IRegistry.getDeclaredField("ITEM") val IRegistry_getKey = IRegistry.getDeclaredMethod("getKey", Any::class.java) val itemRegistry = IRegistry_ITEM.get(null) as Iterable<*> val Material_getKey = Material::class.java.getDeclaredMethod("getKey") val itemIdsToMaterials = enumValues<Material>() .map { Material_getKey.invoke(it).toString() to it } .toMap() val orderedItemIds = itemRegistry.asSequence() .map { item -> IRegistry_getKey.invoke(itemRegistry, item) } .map { it.toString() } val orderedMaterials = orderedItemIds .mapNotNull { itemId -> itemIdsToMaterials[itemId] .also { if (it == null) println("ID doesn't match a material: $it") } } out.writer().buffered().use { writer -> orderedMaterials.forEach { material -> writer.append("${material.name}\n") } } } }
fastcraft-bukkit/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/tools/MaterialOrderGenerator.kt
2042523834
package co.early.fore.kt.adapters.mutable import co.early.fore.adapters.mutable.ChangeAwareList import co.early.fore.adapters.mutable.UpdateSpec import co.early.fore.adapters.mutable.Updateable import co.early.fore.core.time.SystemTimeWrapper import co.early.fore.kt.core.delegate.Fore import java.util.* import java.util.function.UnaryOperator /** * <p>Basic Android adapters use notifyDataSetChanged() to trigger a redraw of the list UI. * * <code> * adapter.notifyDataSetChanged(); * </code> * * <p>In order to take advantage of insert and remove animations, we can provide the adapter with * more information about how the list has changed (eg: there was an item inserted at position 5 * or the item at position 3 has changed etc), for that we call a selection of notifyXXX methods() * indicating what sort of change happened and which rows were effected. * * <p>This list class will automatically generate an update specification for each change you make * to it, suitable for deciding how to call the various notifyXXX methods: * * <code> * * UpdateSpec updateSpec = list.getMostRecentUpdateSpec(); * * switch (updateSpec.type) { * case FULL_UPDATE: * adapter.notifyDataSetChanged(); * break; * case ITEM_CHANGED: * adapter.notifyItemChanged(updateSpec.rowPosition); * break; * case ITEM_REMOVED: * adapter.notifyItemRemoved(updateSpec.rowPosition); * break; * case ITEM_INSERTED: * adapter.notifyItemInserted(updateSpec.rowPosition); * break; * } * * </code> * * <p>This class only supports one type of change at a time (you can't handle a cell update; * two removals; and three inserts, all in the same notify round trip - each has to be handled one at a time) * */ class ChangeAwareArrayList<T>( private val systemTimeWrapper: SystemTimeWrapper? = null ) : ArrayList<T>(), ChangeAwareList<T>, Updateable { private var updateSpec: UpdateSpec = createFullUpdateSpec(Fore.getSystemTimeWrapper(systemTimeWrapper)) override fun add(element: T): Boolean { val temp = super.add(element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, size - 1, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun add(index: Int, element: T) { super.add(index, element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } override fun set(index: Int, element: T): T { val temp = super.set(index, element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_CHANGED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun removeAt(index: Int): T { val temp = super.removeAt(index) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun clear() { updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, 0, size, Fore.getSystemTimeWrapper(systemTimeWrapper) ) super.clear() } override fun addAll(elements: Collection<T>): Boolean { val temp = super.addAll(elements) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, size - 1, elements.size, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun addAll(index: Int, elements: Collection<T>): Boolean { val temp = super.addAll(index, elements) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, index, elements.size, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } /** * Standard AbstractList and ArrayList have this method protected as you * are supposed to remove a range by doing this: * list.subList(start, end).clear(); * (clear() ends up calling removeRange() behind the scenes). * This won't work for these change aware lists (plus it's a ball ache), * so this gets made public */ override fun removeRange(fromIndex: Int, toIndex: Int) { super.removeRange(fromIndex, toIndex) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, fromIndex, toIndex - fromIndex, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } override fun remove(element: T): Boolean { val index = super.indexOf(element) return if (index != -1) { val temp = super.remove(element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) temp } else { false } } override fun removeAll(elements: Collection<T>): Boolean { val temp = super.removeAll(elements) if (temp) { updateSpec = createFullUpdateSpec( Fore.getSystemTimeWrapper(systemTimeWrapper) ) } return temp } override fun replaceAll(operator: UnaryOperator<T>) { throw UnsupportedOperationException("Not supported by this class") } /** * Inform the list that the content of one of its rows has * changed. * * Without calling this, the list may not be aware of * any changes made to this row and the updateSpec will * be incorrect as a result (you won't get default * animations on your recyclerview) * * @param rowIndex index of the row that had its data changed */ override fun makeAwareOfDataChange(rowIndex: Int) { updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_CHANGED, rowIndex, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } /** * Inform the list that the content of a range of its rows has * changed. * * Without calling this, the list will not be aware of * any changes made to these rows and the updateSpec will * be incorrect as a result (you won't get default * animations on your recyclerview) * * @param rowStartIndex index of the row that had its data changed * @param rowsAffected how many rows have been affected */ override fun makeAwareOfDataChange(rowStartIndex: Int, rowsAffected: Int) { updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_CHANGED, rowStartIndex, rowsAffected, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } /** * Make sure you understand the limitations of this method! * * It essentially only supports one recycleView at a time, * in the unlikely event that you want two different list * views animating the same changes to this list, you will * need to store the updateSpec returned here so that both * recycleView adapters get a copy, otherwise the second * adapter will always get a FULL_UPDATE (meaning no * fancy animations for the second one) * * If the updateSpec is old, then we assume that whatever changes * were made to the Updateable last time were never picked up by a * recyclerView (maybe because the list was not visible at the time). * In this case we clear the updateSpec and create a fresh one with a * full update spec. * * @return the latest update spec for the list */ override fun getAndClearLatestUpdateSpec(maxAgeMs: Long): UpdateSpec { val latestUpdateSpecAvailable = updateSpec updateSpec = createFullUpdateSpec(Fore.getSystemTimeWrapper(systemTimeWrapper)) return if (Fore.getSystemTimeWrapper(systemTimeWrapper).currentTimeMillis() - latestUpdateSpecAvailable.timeStamp < maxAgeMs) { latestUpdateSpecAvailable } else { updateSpec } } private fun createFullUpdateSpec(stw: SystemTimeWrapper): UpdateSpec { return UpdateSpec(UpdateSpec.UpdateType.FULL_UPDATE, 0, 0, stw) } }
fore-kt-android-adapters/src/main/java/co/early/fore/kt/adapters/mutable/ChangeAwareArrayList.kt
1126515329
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.netvars data class ClassOffset(val className: String, val variableName: String, val offset: Long)
src/main/kotlin/com/charlatano/game/netvars/ClassOffset.kt
773834512
package org.andreych.workcalendar.storage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.model.Calendar import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper import java.io.ByteArrayOutputStream import java.sql.ResultSet import java.util.zip.GZIPOutputStream /** * Хранит актуальные данные iCalendar. */ class CalendarStorage(private val jdbcTemplate: JdbcTemplate) { companion object { //@formatter:off private const val INSERT_NEWS = "INSERT INTO calendar (original_json, compressed_ical) " + "VALUES (?,?) " + "ON CONFLICT DO NOTHING" //@formatter:on private const val SELECT_NEWS = "SELECT compressed_ical FROM calendar ORDER BY id DESC LIMIT 1" } suspend fun update(data: Pair<String?, Calendar>) { val bytes = withContext(Dispatchers.Default) { val calendarBytes = ByteArrayOutputStream().use { baos -> GZIPOutputStream(baos).use { gzos -> CalendarOutputter().output(data.second, gzos) } baos.toByteArray() } calendarBytes } withContext(Dispatchers.IO) { jdbcTemplate.update { con -> val ps = con.prepareStatement(INSERT_NEWS) ps.setString(1, data.first) ps.setBytes(2, bytes) ps } } } suspend fun getBytes(): ByteArray? = withContext(Dispatchers.IO) { return@withContext jdbcTemplate.query(SELECT_NEWS, RowMapper { rs: ResultSet, _: Int -> return@RowMapper rs.getBytes(1) })[0] } }
src/main/kotlin/org/andreych/workcalendar/storage/CalendarStorage.kt
3454474858
/* * Copyright 2018 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.push.fcm.troubleshoot import android.app.ActivityManager import android.content.Context import androidx.fragment.app.Fragment import im.vector.R import im.vector.VectorApp import im.vector.fragments.troubleshoot.TroubleshootTest import im.vector.services.EventStreamService import java.util.* import kotlin.concurrent.timerTask /** * Stop the event stream service and check that it is restarted */ // Not used anymore class TestServiceRestart(val fragment: Fragment) : TroubleshootTest(R.string.settings_troubleshoot_test_service_restart_title) { var timer: Timer? = null override fun perform() { status = TestStatus.RUNNING EventStreamService.getInstance()?.stopSelf() timer = Timer() timer?.schedule(timerTask { if (isMyServiceRunning(EventStreamService::class.java)) { fragment.activity?.runOnUiThread { description = fragment.getString(R.string.settings_troubleshoot_test_service_restart_success) quickFix = null status = TestStatus.SUCCESS } timer?.cancel() } }, 0, 1000) timer?.schedule(timerTask { fragment.activity?.runOnUiThread { status = TestStatus.FAILED description = fragment.getString(R.string.settings_troubleshoot_test_service_restart_failed) } timer?.cancel() }, 15000) } private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = VectorApp.getInstance().baseContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.name == service.service.className) { return true } } return false } override fun cancel() { super.cancel() timer?.cancel() } }
vector/src/appfdroid/java/im/vector/push/fcm/troubleshoot/TestServiceRestart.kt
2389048733
package com.softmotions.ncms.asm /** * @author Adamansky Anton ([email protected]) */ class TestAsmRenderer { }
ncms-engine/ncms-engine-tests/src/test/java/com/softmotions/ncms/asm/TestAsmRenderer.kt
2894578660
package ru.ok.android.sdk import android.app.Activity import android.app.AlertDialog import android.content.Context import android.net.http.SslError import android.os.Bundle import android.view.KeyEvent import android.webkit.SslErrorHandler import android.webkit.WebView import ru.ok.android.sdk.util.Utils import ru.ok.android.sdk.util.OkRequestUtil import java.util.* private val DEFAULT_OPTIONS = mapOf( "st.popup" to "on", "st.silent" to "on" ) internal abstract class AbstractWidgetActivity : Activity() { protected var mAppId: String? = null protected var mAccessToken: String? = null protected var mSessionSecretKey: String? = null protected val args = HashMap<String, String>() protected var retryAllowed = true protected open val layoutId: Int get() = R.layout.oksdk_webview_activity protected abstract val widgetId: String protected val baseUrl: String get() = REMOTE_WIDGETS + "dk?st.cmd=" + widgetId + "&st.access_token=" + mAccessToken + "&st.app=" + mAppId + "&st.return=" + returnUrl protected val returnUrl: String get() = "okwidget://" + widgetId.toLowerCase() protected abstract val cancelledMessageId: Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(layoutId) args.clear() val bundle = intent.extras if (bundle != null) { mAppId = bundle.getString(PARAM_APP_ID) mAccessToken = bundle.getString(PARAM_ACCESS_TOKEN) mSessionSecretKey = bundle.getString(PARAM_SESSION_SECRET_KEY) if (bundle.containsKey(PARAM_WIDGET_ARGS)) { @Suppress("UNCHECKED_CAST") val map = bundle.getSerializable(PARAM_WIDGET_ARGS) as? HashMap<String, String> if (map != null) { args.putAll(map) } } if (bundle.containsKey(PARAM_WIDGET_RETRY_ALLOWED)) { retryAllowed = bundle.getBoolean(PARAM_WIDGET_RETRY_ALLOWED, true) } } } protected abstract fun processResult(result: String?) protected fun processError(error: String) { if (!retryAllowed) { processResult(error) return } try { AlertDialog.Builder(this) .setMessage(error) .setPositiveButton(getString(R.string.retry)) { _, _ -> findViewById<WebView>(R.id.web_view).loadUrl(prepareUrl()) } .setNegativeButton(getString(R.string.cancel)) { _, _ -> processResult(error) } .show() } catch (ignore: RuntimeException) { // this usually happens during fast back. avoid crash in such a case processResult(error) } } /** * Prepares widget URL based on widget parameters * * @param options widget options (if null, default options are being sent) * @return widget url * @see .args * * @see .DEFAULT_OPTIONS */ protected fun prepareUrl(options: Map<String, String>? = null): String { val params = TreeMap<String, String>() for ((key, value) in args) params[key] = value params["st.return"] = returnUrl val sigSource = StringBuilder(200) val url = StringBuilder(baseUrl) for ((key, value) in params) { if (WIDGET_SIGNED_ARGS.contains(key)) sigSource.append(key).append('=').append(value) if (key != "st.return") url.append('&').append(key).append('=').append(OkRequestUtil.encode(value)) } val signature = Utils.toMD5(sigSource.toString() + mSessionSecretKey) for ((key, value) in options ?: DEFAULT_OPTIONS) url.append('&').append(key).append('=').append(value) url.append("&st.signature=").append(signature) return url.toString() } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (KeyEvent.KEYCODE_BACK == keyCode) { processError(getString(cancelledMessageId)) return true } return false } @Suppress("OverridingDeprecatedMember", "DEPRECATION") inner class OkWidgetViewClient(context: Context) : OkWebViewClient(context) { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (url.startsWith(returnUrl)) { val parameters = OkRequestUtil.getUrlParameters(url) val result = parameters.getString("result") processResult(result) return true } return super.shouldOverrideUrlLoading(view, url) } override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) processError(getErrorMessage(errorCode)) } override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) { super.onReceivedSslError(view, handler, error) processError(getErrorMessage(error)) } } }
odnoklassniki-android-sdk/src/main/java/ru/ok/android/sdk/AbstractWidgetActivity.kt
1646444576
package com.github.kerubistan.kerub.planner.steps.storage.block.copy.local import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.planner.StepExecutor import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.utils.junix.dd.Dd class LocalBlockCopyExecutor( private val hostCommandExecutor: HostCommandExecutor, private val stepExecutor: StepExecutor<AbstractOperationalStep> ) : StepExecutor<LocalBlockCopy> { override fun execute(step: LocalBlockCopy) { stepExecutor.execute(step.allocationStep) hostCommandExecutor.execute(step.allocationStep.host) { session -> Dd.copy( session, step.sourceAllocation.getPath(step.sourceDevice.id), step.allocationStep.allocation.getPath(step.targetDevice.id)) } } }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/local/LocalBlockCopyExecutor.kt
2136675558
package com.quran.labs.androidquran.bridge import com.quran.data.model.SuraAyah import com.quran.reading.common.AudioEventPresenter import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach class AudioEventPresenterBridge constructor( audioEventPresenter: AudioEventPresenter, onPlaybackAyahChanged: ((SuraAyah?) -> Unit) ) { private val scope = MainScope() private val audioPlaybackAyahFlow = audioEventPresenter.audioPlaybackAyahFlow init { audioPlaybackAyahFlow .onEach { onPlaybackAyahChanged(it) } .launchIn(scope) } fun dispose() { scope.cancel() } }
app/src/main/java/com/quran/labs/androidquran/bridge/AudioEventPresenterBridge.kt
3685571926
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.settings import com.charlatano.game.CSGO.clientDLL import com.charlatano.game.offsets.ClientOffsets.dwSensitivity import com.charlatano.game.offsets.ClientOffsets.dwSensitivityPtr import com.charlatano.utils.extensions.uint /** * These should be set the same as your in-game "m_pitch" and "m_yaw" values. */ var GAME_PITCH = 0.022 // m_pitch var GAME_YAW = 0.022 // m_yaw val GAME_SENSITIVITY by lazy(LazyThreadSafetyMode.NONE) { val pointer = clientDLL.address + dwSensitivityPtr val value = clientDLL.uint(dwSensitivity) xor pointer java.lang.Float.intBitsToFloat(value.toInt()).toDouble() } /** * The tick ratio of the server. */ var SERVER_TICK_RATE = 64 /** * The maximum amount of entities that can be managed by the cached list. */ var MAX_ENTITIES = 1024 /** * The intervar in milliseconds to recycle entities in the cached list. */ var CLEANUP_TIME = 10_000
src/main/kotlin/com/charlatano/settings/Advanced.kt
408277960
/* * Copyright 2016 Ross 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.chat.bukkit.database.table import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatgroup.RPKChatGroup import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupImpl import com.rpkit.chat.bukkit.database.jooq.rpkit.Tables.RPKIT_CHAT_GROUP import com.rpkit.core.database.Database import com.rpkit.core.database.Table import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents the chat group table. */ class RPKChatGroupTable(database: Database, private val plugin: RPKChatBukkit): Table<RPKChatGroup>(database, RPKChatGroup::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_chat_group.id.enabled")) { database.cacheManager.createCache("rpk-chat-bukkit.rpkit_chat_group.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKChatGroup::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_chat_group.id.size")))) } else { null } private val nameCache = if (plugin.config.getBoolean("caching.rpkit_chat_group.name.enabled")) { database.cacheManager.createCache("rpk-chat-bukkit.rpkit_chat_group.name", CacheConfigurationBuilder.newCacheConfigurationBuilder(String::class.java, Int::class.javaObjectType, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_chat_group.name.size")))) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_CHAT_GROUP) .column(RPKIT_CHAT_GROUP.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_CHAT_GROUP.NAME, SQLDataType.VARCHAR(256)) .constraints( constraint("pk_rpkit_chat_group").primaryKey(RPKIT_CHAT_GROUP.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.4.0") } } override fun insert(entity: RPKChatGroup): Int { database.create .insertInto( RPKIT_CHAT_GROUP, RPKIT_CHAT_GROUP.NAME ) .values(entity.name) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) nameCache?.put(entity.name, id) return id } override fun update(entity: RPKChatGroup) { database.create .update(RPKIT_CHAT_GROUP) .set(RPKIT_CHAT_GROUP.NAME, entity.name) .where(RPKIT_CHAT_GROUP.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) nameCache?.put(entity.name, entity.id) } override fun get(id: Int): RPKChatGroup? { if (cache?.containsKey(id) == true) { return cache.get(id) } else { val result = database.create .select(RPKIT_CHAT_GROUP.NAME) .from(RPKIT_CHAT_GROUP) .where(RPKIT_CHAT_GROUP.ID.eq(id)) .fetchOne() ?: return null val chatGroup = RPKChatGroupImpl( plugin, id, result.get(RPKIT_CHAT_GROUP.NAME) ) cache?.put(id, chatGroup) nameCache?.put(chatGroup.name, id) return chatGroup } } /** * Gets a chat group by name. * If no chat group exists with the given name, null is returned. * * @param name The name * @return The chat group, or null if there is no chat group with the given name */ fun get(name: String): RPKChatGroup? { if (nameCache?.containsKey(name) == true) { return get(nameCache.get(name)) } else { val result = database.create .select(RPKIT_CHAT_GROUP.ID) .from(RPKIT_CHAT_GROUP) .where(RPKIT_CHAT_GROUP.NAME.eq(name)) .fetchOne() ?: return null val chatGroup = RPKChatGroupImpl( plugin, result.get(RPKIT_CHAT_GROUP.ID), name ) cache?.put(chatGroup.id, chatGroup) nameCache?.put(name, chatGroup.id) return chatGroup } } override fun delete(entity: RPKChatGroup) { database.create .deleteFrom(RPKIT_CHAT_GROUP) .where(RPKIT_CHAT_GROUP.ID.eq(entity.id)) .execute() cache?.remove(entity.id) nameCache?.remove(entity.name) } }
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/database/table/RPKChatGroupTable.kt
4209564740
package com.github.badoualy.telegram.sample import com.github.badoualy.telegram.api.Kotlogram import com.github.badoualy.telegram.api.utils.id import com.github.badoualy.telegram.api.utils.title import com.github.badoualy.telegram.sample.config.Config import com.github.badoualy.telegram.sample.config.FileApiStorage import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty import com.github.badoualy.telegram.tl.api.TLMessage import com.github.badoualy.telegram.tl.api.TLMessageService import com.github.badoualy.telegram.tl.api.TLUser import com.github.badoualy.telegram.tl.exception.RpcErrorException import java.io.IOException object GetDialogsSample { @JvmStatic fun main(args: Array<String>) { // This is a synchronous client, that will block until the response arrive (or until timeout) val client = Kotlogram.getDefaultClient(Config.application, FileApiStorage()) // Number of recent conversation you want to get // (Telegram has an internal max, your value will be capped) val count = 10 // You can start making requests try { val tlAbsDialogs = client.messagesGetDialogs(true, 0, 0, TLInputPeerEmpty(), count) // Create a map of id to name map val nameMap = HashMap<Int, String>() tlAbsDialogs.users.filterIsInstance<TLUser>() .map { Pair(it.id, "${it.firstName} ${it.lastName}") } .toMap(nameMap) tlAbsDialogs.chats.map { Pair(it.id, it.title ?: "") }.toMap(nameMap) val messageMap = tlAbsDialogs.messages.map { Pair(it.id, it) }.toMap() tlAbsDialogs.dialogs.forEach { dialog -> val topMessage = messageMap[dialog.topMessage]!! val topMessageContent = if (topMessage is TLMessage) topMessage.message else if (topMessage is TLMessageService) "Service: ${topMessage.action}" else "Empty message (TLMessageEmpty)" println("${nameMap[dialog.peer.id]}: $topMessageContent") } } catch (e: RpcErrorException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } finally { client.close() // Important, do not forget this, or your process won't finish } } }
sample/src/main/kotlin/com/github/badoualy/telegram/sample/GetDialogsSample.kt
1934196477
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.hle.* import com.soywiz.kpspemu.hle.manager.* @Suppress("UNUSED_PARAMETER", "MemberVisibilityCanPrivate") class InterruptManager(emulator: Emulator) : SceModule(emulator, "InterruptManager", 0x40000011, "interruptman.prx", "sceInterruptManager") { val interruptManager = emulator.interruptManager fun sceKernelRegisterSubIntrHandler( thread: PspThread, interrupt: Int, handlerIndex: Int, callbackAddress: Int, callbackArgument: Int ): Int { val intr = interruptManager.get(interrupt, handlerIndex) intr.address = callbackAddress intr.argument = callbackArgument intr.enabled = true intr.cpuState = thread.state return 0 } fun sceKernelEnableSubIntr(interrupt: Int, handlerIndex: Int): Int { val intr = interruptManager.get(interrupt, handlerIndex) intr.enabled = true return 0 } fun sceKernelDisableSubIntr(interrupt: Int, handlerIndex: Int): Int { val intr = interruptManager.get(interrupt, handlerIndex) intr.enabled = false return 0 } fun sceKernelSuspendSubIntr(cpu: CpuState): Unit = UNIMPLEMENTED(0x5CB5A78B) fun sceKernelResumeSubIntr(cpu: CpuState): Unit = UNIMPLEMENTED(0x7860E0DC) fun QueryIntrHandlerInfo(cpu: CpuState): Unit = UNIMPLEMENTED(0xD2E8363F) fun sceKernelReleaseSubIntrHandler(cpu: CpuState): Unit = UNIMPLEMENTED(0xD61E6961) fun sceKernelRegisterUserSpaceIntrStack(cpu: CpuState): Unit = UNIMPLEMENTED(0xEEE43F47) fun sceKernelIsSubInterruptOccurred(cpu: CpuState): Unit = UNIMPLEMENTED(0xFC4374B8) override fun registerModule() { registerFunctionInt( "sceKernelRegisterSubIntrHandler", 0xCA04A2B9, since = 150 ) { sceKernelRegisterSubIntrHandler(thread, int, int, int, int) } registerFunctionInt("sceKernelEnableSubIntr", 0xFB8E22EC, since = 150) { sceKernelEnableSubIntr(int, int) } registerFunctionInt("sceKernelDisableSubIntr", 0x8A389411, since = 150) { sceKernelDisableSubIntr(int, int) } registerFunctionRaw("sceKernelSuspendSubIntr", 0x5CB5A78B, since = 150) { sceKernelSuspendSubIntr(it) } registerFunctionRaw("sceKernelResumeSubIntr", 0x7860E0DC, since = 150) { sceKernelResumeSubIntr(it) } registerFunctionRaw("QueryIntrHandlerInfo", 0xD2E8363F, since = 150) { QueryIntrHandlerInfo(it) } registerFunctionRaw("sceKernelReleaseSubIntrHandler", 0xD61E6961, since = 150) { sceKernelReleaseSubIntrHandler( it ) } registerFunctionRaw( "sceKernelRegisterUserSpaceIntrStack", 0xEEE43F47, since = 150 ) { sceKernelRegisterUserSpaceIntrStack(it) } registerFunctionRaw( "sceKernelIsSubInterruptOccurred", 0xFC4374B8, since = 150 ) { sceKernelIsSubInterruptOccurred(it) } } }
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/InterruptManager.kt
2593636025
package au.com.outware.neanderthal.data.model /** * @author timmutton */ data class Variant(var name: String?, var configuration: Any?)
neanderthal/src/main/kotlin/au/com/outware/neanderthal/data/model/Variant.kt
2939666994
/* * Copyright 2019-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.multitenant.service import org.junit.Test import java.nio.file.Path import java.nio.file.Paths import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertTrue val BUILD_FILE_DIRECTORY: Path = Paths.get("foo") class MapDiffTest { @Test fun emptyRulesShouldHaveNoDeltas() { val oldRules = mapOf<String, BuildTargetSet>() val newRules = mapOf<String, BuildTargetSet>() val deltas = diffRules(oldRules, newRules, BUILD_FILE_DIRECTORY) assertTrue(deltas.isEmpty()) } @Test fun emptyOldRulesWithNewRules() { val oldRules = mapOf<String, BuildTargetSet>() val newRules = mapOf("one" to intArrayOf(1), "two" to intArrayOf(2, 3)) val deltas = diffRules(oldRules, newRules, BUILD_FILE_DIRECTORY) assertEquals(setOf( RuleDelta.Updated(BUILD_FILE_DIRECTORY, "one", intArrayOf(1)), RuleDelta.Updated(BUILD_FILE_DIRECTORY, "two", intArrayOf(2, 3)) ), deltas.toSet()) } @Test fun nonEmptyOldRulesWithEmptyNewRules() { val oldRules = mapOf("one" to intArrayOf(1), "two" to intArrayOf(2, 3)) val newRules = mapOf<String, BuildTargetSet>() val deltas = diffRules(oldRules, newRules, BUILD_FILE_DIRECTORY) assertEquals(setOf( RuleDelta.Removed(BUILD_FILE_DIRECTORY, "one"), RuleDelta.Removed(BUILD_FILE_DIRECTORY, "two") ), deltas.toSet()) } @Test fun detectModifiedRulesWithSameSizeMaps() { val oldRules = mapOf( "foo" to intArrayOf(1), "bar" to intArrayOf(2), "baz" to intArrayOf(4, 5)) val newRules = mapOf( "foo" to intArrayOf(1), "bar" to intArrayOf(2, 3), "baz" to intArrayOf(5)) val deltas = diffRules(oldRules, newRules, BUILD_FILE_DIRECTORY) assertEquals(setOf( RuleDelta.Updated(BUILD_FILE_DIRECTORY, "bar", intArrayOf(2, 3)), RuleDelta.Updated(BUILD_FILE_DIRECTORY, "baz", intArrayOf(5)) ), deltas.toSet()) } @Test fun detectModifiedRulesWithMoreOldRules() { val oldRules = mapOf( "foo" to intArrayOf(1), "bar" to intArrayOf(2), "baz" to intArrayOf(4, 5), "foobazbar" to intArrayOf(0)) val newRules = mapOf( "foo" to intArrayOf(1), "bar" to intArrayOf(2, 3), "baz" to intArrayOf(5)) val deltas = diffRules(oldRules, newRules, BUILD_FILE_DIRECTORY) assertEquals(setOf( RuleDelta.Updated(BUILD_FILE_DIRECTORY, "bar", intArrayOf(2, 3)), RuleDelta.Updated(BUILD_FILE_DIRECTORY, "baz", intArrayOf(5)), RuleDelta.Removed(BUILD_FILE_DIRECTORY, "foobazbar") ), deltas.toSet()) } @Test fun detectModifiedRulesWithMoreNewRules() { val oldRules = mapOf( "foo" to intArrayOf(1), "bar" to intArrayOf(2), "baz" to intArrayOf(4, 5)) val newRules = mapOf( "foo" to intArrayOf(1), "bar" to intArrayOf(2, 3), "baz" to intArrayOf(5), "foobazbar" to intArrayOf(0)) val deltas = diffRules(oldRules, newRules, BUILD_FILE_DIRECTORY) assertEquals(setOf( RuleDelta.Updated(BUILD_FILE_DIRECTORY, "bar", intArrayOf(2, 3)), RuleDelta.Updated(BUILD_FILE_DIRECTORY, "baz", intArrayOf(5)), RuleDelta.Updated(BUILD_FILE_DIRECTORY, "foobazbar", intArrayOf(0)) ), deltas.toSet()) } @Test fun deltasWithSameContentsAreNotDotEqualsToOneAnother() { val buildRules1 = mapOf("one" to intArrayOf(1), "two" to intArrayOf(2)) val buildRules2 = mapOf("one" to intArrayOf(1), "two" to intArrayOf(2)) assertNotEquals(buildRules1, buildRules2, "Because IntArray.equals() uses reference " + "equality, these two maps are not .equals() to one another even though they are " + "'contentEquals' to one another.") } }
test/com/facebook/buck/multitenant/service/MapDiffTest.kt
882333343
fun main(args: Array<String>) { println("hello world!") }
src/main/kotlin/HelloWorld.kt
1815991177
package chat.rocket.android.authentication.presentation import android.content.Intent import chat.rocket.android.R import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.authentication.domain.model.DeepLinkInfo import chat.rocket.android.authentication.ui.AuthenticationActivity import chat.rocket.android.main.ui.MainActivity import chat.rocket.android.server.ui.changeServerIntent import chat.rocket.android.util.extensions.addFragment import chat.rocket.android.util.extensions.addFragmentBackStack import chat.rocket.android.util.extensions.toPreviousView import chat.rocket.android.webview.ui.webViewIntent class AuthenticationNavigator(internal val activity: AuthenticationActivity) { private var savedDeepLinkInfo: DeepLinkInfo? = null fun saveDeepLinkInfo(deepLinkInfo: DeepLinkInfo) { savedDeepLinkInfo = deepLinkInfo } fun toOnBoarding() { activity.addFragment( ScreenViewEvent.OnBoarding.screenName, R.id.fragment_container, allowStateLoss = true ) { chat.rocket.android.authentication.onboarding.ui.newInstance() } } fun toSignInToYourServer(deepLinkInfo: DeepLinkInfo? = null, addToBackStack: Boolean = true) { if (addToBackStack) { activity.addFragmentBackStack( ScreenViewEvent.Server.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.server.ui.newInstance(deepLinkInfo) } } else { activity.addFragment( ScreenViewEvent.Server.screenName, R.id.fragment_container, allowStateLoss = true ) { chat.rocket.android.authentication.server.ui.newInstance(deepLinkInfo) } } } fun toLoginOptions( serverUrl: String, state: String? = null, facebookOauthUrl: String? = null, githubOauthUrl: String? = null, googleOauthUrl: String? = null, linkedinOauthUrl: String? = null, gitlabOauthUrl: String? = null, wordpressOauthUrl: String? = null, casLoginUrl: String? = null, casToken: String? = null, casServiceName: String? = null, casServiceNameTextColor: Int = 0, casServiceButtonColor: Int = 0, customOauthUrl: String? = null, customOauthServiceName: String? = null, customOauthServiceNameTextColor: Int = 0, customOauthServiceButtonColor: Int = 0, samlUrl: String? = null, samlToken: String? = null, samlServiceName: String? = null, samlServiceNameTextColor: Int = 0, samlServiceButtonColor: Int = 0, totalSocialAccountsEnabled: Int = 0, isLoginFormEnabled: Boolean = true, isNewAccountCreationEnabled: Boolean = true, deepLinkInfo: DeepLinkInfo? = null ) { activity.addFragmentBackStack( ScreenViewEvent.LoginOptions.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.loginoptions.ui.newInstance( serverUrl, state, facebookOauthUrl, githubOauthUrl, googleOauthUrl, linkedinOauthUrl, gitlabOauthUrl, wordpressOauthUrl, casLoginUrl, casToken, casServiceName, casServiceNameTextColor, casServiceButtonColor, customOauthUrl, customOauthServiceName, customOauthServiceNameTextColor, customOauthServiceButtonColor, samlUrl, samlToken, samlServiceName, samlServiceNameTextColor, samlServiceButtonColor, totalSocialAccountsEnabled, isLoginFormEnabled, isNewAccountCreationEnabled, deepLinkInfo ) } } fun toTwoFA(username: String, password: String) { activity.addFragmentBackStack(ScreenViewEvent.TwoFa.screenName, R.id.fragment_container) { chat.rocket.android.authentication.twofactor.ui.newInstance(username, password) } } fun toCreateAccount() { activity.addFragmentBackStack(ScreenViewEvent.SignUp.screenName, R.id.fragment_container) { chat.rocket.android.authentication.signup.ui.newInstance() } } fun toLogin(serverUrl: String) { activity.addFragmentBackStack(ScreenViewEvent.Login.screenName, R.id.fragment_container) { chat.rocket.android.authentication.login.ui.newInstance(serverUrl) } } fun toForgotPassword() { activity.addFragmentBackStack( ScreenViewEvent.ResetPassword.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.resetpassword.ui.newInstance() } } fun toPreviousView() { activity.toPreviousView() } fun toRegisterUsername(userId: String, authToken: String) { activity.addFragmentBackStack( ScreenViewEvent.RegisterUsername.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.registerusername.ui.newInstance(userId, authToken) } } fun toWebPage(url: String, toolbarTitle: String? = null) { activity.startActivity(activity.webViewIntent(url, toolbarTitle)) activity.overridePendingTransition(R.anim.slide_up, R.anim.hold) } fun toChatList(serverUrl: String) { activity.startActivity(activity.changeServerIntent(serverUrl)) activity.finish() } fun toChatList(passedDeepLinkInfo: DeepLinkInfo? = null) { val deepLinkInfo = passedDeepLinkInfo ?: savedDeepLinkInfo savedDeepLinkInfo = null if (deepLinkInfo != null) { activity.startActivity(Intent(activity, MainActivity::class.java).also { it.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP it.putExtra( chat.rocket.android.authentication.domain.model.DEEP_LINK_INFO_KEY, deepLinkInfo ) }) } else { activity.startActivity(Intent(activity, MainActivity::class.java)) } activity.finish() } }
app/src/main/java/chat/rocket/android/authentication/presentation/AuthenticationNavigator.kt
2143524873
package com.antonioleiva.weatherapp.data.db import android.content.Context import android.database.sqlite.SQLiteDatabase import com.antonioleiva.weatherapp.ui.App import org.jetbrains.anko.db.* class ForecastDbHelper(ctx: Context = App.instance) : ManagedSQLiteOpenHelper(ctx, ForecastDbHelper.DB_NAME, null, ForecastDbHelper.DB_VERSION) { companion object { const val DB_NAME = "forecast.db" const val DB_VERSION = 1 val instance by lazy { ForecastDbHelper() } } override fun onCreate(db: SQLiteDatabase) { db.createTable(CityForecastTable.NAME, true, CityForecastTable.ID to INTEGER + PRIMARY_KEY, CityForecastTable.CITY to TEXT, CityForecastTable.COUNTRY to TEXT) db.createTable(DayForecastTable.NAME, true, DayForecastTable.ID to INTEGER + PRIMARY_KEY + AUTOINCREMENT, DayForecastTable.DATE to INTEGER, DayForecastTable.DESCRIPTION to TEXT, DayForecastTable.HIGH to INTEGER, DayForecastTable.LOW to INTEGER, DayForecastTable.ICON_URL to TEXT, DayForecastTable.CITY_ID to INTEGER) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.dropTable(CityForecastTable.NAME, true) db.dropTable(DayForecastTable.NAME, true) onCreate(db) } }
app/src/main/java/com/antonioleiva/weatherapp/data/db/ForecastDbHelper.kt
4125005656
package org.abimon.visi.collections class LateArray<T : Any> constructor(private val backing: Array<T?>, override val size: Int): List<T> { companion object { inline operator fun <reified T : Any> invoke(size: Int): LateArray<T> = LateArray(Array(size, { null as T? }), size) } override fun contains(element: T): Boolean = element in backing override fun containsAll(elements: Collection<T>): Boolean = elements.all { t -> t in backing } override fun get(index: Int): T = backing[index] ?: throw UninitializedPropertyAccessException() override fun indexOf(element: T): Int = backing.indexOf(element) override fun isEmpty(): Boolean = size == 0 override fun iterator(): Iterator<T> = object : Iterator<T> { var index: Int = 0 override fun hasNext(): Boolean = index < size override fun next(): T = this@LateArray[index++] } override fun lastIndexOf(element: T): Int = backing.lastIndexOf(element) override fun listIterator(): ListIterator<T> = listIterator(0) override fun listIterator(index: Int): ListIterator<T> = object : ListIterator<T> { var currIndex: Int = index override fun previousIndex(): Int = currIndex - 1 override fun hasNext(): Boolean = currIndex < size override fun hasPrevious(): Boolean = currIndex > 0 override fun next(): T = this@LateArray[currIndex++] override fun previous(): T = this@LateArray[currIndex--] override fun nextIndex(): Int = currIndex + 1 } override fun subList(fromIndex: Int, toIndex: Int): List<T> = backing.copyOfRange(fromIndex, toIndex).map { t -> t ?: throw UninitializedPropertyAccessException() } operator fun set(index: Int, element: T): Unit = backing.set(index, element) fun finalise(): Array<T> { if(backing.any { t -> t == null }) throw UninitializedPropertyAccessException() return backing.requireNoNulls() } }
src/main/kotlin/org/abimon/visi/collections/LateArray.kt
483757910
/** * Copyright (c) 2017-present, Team Bucket 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.github.luks91.teambucket.util import java.text.SimpleDateFormat import java.util.Locale fun Long.toMMMddDateString(): String { return SimpleDateFormat("MMM dd", Locale.getDefault()).format(this) }
app/src/main/java/com/github/luks91/teambucket/util/DateUtils.kt
2308655802
package com.lovejjfg.swiperefreshrecycleview.activity import android.os.Bundle import android.util.Log import androidx.core.widget.toast import com.lovejjfg.powerrecycle.AdapterSelect.OnItemSelectedListener import com.lovejjfg.powerrecycle.SelectPowerAdapter import com.lovejjfg.powerrecycle.holder.PowerHolder import com.lovejjfg.powerrecycle.model.ISelect /** * Created by joe on 2018/11/20. * Email: [email protected] */ abstract class BaseSelectActivity<T : ISelect> : BaseActivity<T>() { protected lateinit var selectAdapter: SelectPowerAdapter<T> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) selectAdapter = adapter as SelectPowerAdapter<T> selectAdapter.setOnItemSelectListener(object : OnItemSelectedListener<T> { override fun onNothingSelected() { Log.e(this@BaseSelectActivity::class.java.simpleName, "onNothingSelected:...") // toast("一个都没有") } override fun onItemSelectChange(holder: PowerHolder<T>, position: Int, isSelected: Boolean) { Log.e( this@BaseSelectActivity::class.java.simpleName, "onItemSelectChange:$position;isSelected:$isSelected" ) // toast("选中:$position,total:${selectAdapter.selectedItems.size}") } }) } override fun onBackPressed() { if (selectAdapter.isSelectMode) { // selectAdapter.notifyItemChanged(0, "xxxx0") // selectAdapter.notifyItemChanged(1, "xxxx1") // selectAdapter.clearSelectList(true) selectAdapter.updateSelectMode(false) toast("已推出选择模式") } else { super.onBackPressed() } } }
app/src/main/java/com/lovejjfg/swiperefreshrecycleview/activity/BaseSelectActivity.kt
674444362
/* * The MIT License (MIT) * * Copyright (c) 2016 QAware GmbH, Munich, Germany * * 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 de.qaware.oss.cloud.control.midi import javax.inject.Qualifier /** * The annotation class used as qualifier for button pressed device events. */ @Qualifier @Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) annotation class Pressed
src/main/kotlin/de/qaware/oss/cloud/control/midi/Pressed.kt
281354601
package dev.katanagari7c1.wolverine.infrastructure.dagger2 import android.content.Context import dagger.Module import dagger.Provides import dev.katanagari7c1.wolverine.domain.util.ImageLoader import dev.katanagari7c1.wolverine.infrastructure.glide.GlideImageLoader @Module class ImageLoaderModule { @Provides fun provideImageLoader(context: Context):ImageLoader { return GlideImageLoader(context) } }
app/src/main/kotlin/dev/katanagari7c1/wolverine/infrastructure/dagger2/ImageLoaderModule.kt
337501199
package edu.kit.iti.formal.automation.ide.services import edu.kit.iti.formal.automation.ide.FontAwesomeRegular import edu.kit.iti.formal.automation.ide.FontAwesomeSolid import edu.kit.iti.formal.automation.ide.FontIcon import edu.kit.iti.formal.util.info import java.io.File import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* import javax.swing.ImageIcon import javax.swing.KeyStroke import kotlin.reflect.KProperty /** * * @author Alexander Weigl * @version 1 (04.05.19) */ object ConfigurationPaths { val operationSystem by lazy { val os = System.getProperty("os.name") when { os.contains("Mac") -> "mac" os.contains("Windows") -> "win" os.contains("Linux") -> "lin" else -> "" } } val applicationName = "verifaps-ide" val configFolder by lazy { val home = System.getProperty("user.home") val p = when (operationSystem) { "mac" -> Paths.get(home, "Library", "Application Support", applicationName) "win" -> { val version = System.getProperty("os.version") Paths.get(System.getenv("APPDATA"), applicationName) } "lin" -> { Paths.get(home, ".config", applicationName) } else -> Paths.get(applicationName) } Files.createDirectories(p) info("Configuration folder: $p") p } val layoutFile by lazy { configFolder.resolve("layout.data") } val configuration by lazy { configFolder.resolve("config.properties") } val recentFiles by lazy { configFolder.resolve("recentfiles") } } class PropertiesProperty<T>( val default: T, val read: (String) -> T?, val write: (T) -> String = { it.toString() }) { operator fun getValue(config: Configuration, prop: KProperty<*>): T = config.properties.getProperty(config.prefix + prop.name)?.let(read) ?: default operator fun setValue(config: Configuration, prop: KProperty<*>, v: T) { config.properties.setProperty(config.prefix + prop.name, write(v)) } } abstract class Configuration(val properties: Properties = Properties(), val prefix: String = "") { protected fun integer(default: Int = 0) = PropertiesProperty(default, { it.toIntOrNull() }) protected fun string(default: String = "") = PropertiesProperty<String>(default, { it }) protected fun boolean(default: Boolean) = PropertiesProperty(default, { it.equals("true", true) }) fun save(path: Path) { properties.store(path.bufferedWriter(), "") } fun load(path: Path) { if (path.exists()) properties.load(path.bufferedReader()) } fun load(resource: URL?) { resource?.openStream()?.use { properties.load(it) } } fun write(configuration: Path) { configuration.bufferedWriter().use { properties.store(it, "automatically saved, do not change.") } } } object ApplicationConfiguration : Configuration() { var posX by integer(10) var posY by integer(10) var windowHeight by integer(400) var windowWidth by integer(600) var maximized by boolean(false) var lastNavigatorPath by string(File(".").absolutePath) } object UserConfiguration : Configuration() { init { load(javaClass.getResource("/ide.properties")) load(Paths.get(System.getenv()["user.home"], ".verifaps-ide.properties")) load(Paths.get("verifaps-ide.properties")) } val verbose: Boolean by boolean(false) fun getActionMenuPath(actionName: String) = getValue("$actionName.menu") ?: "" private fun getValue(s: String): String? { val v = properties[s]?.toString() if (v.isNullOrBlank()) return null return v } fun getActionKeyStroke(actionName: String) = getValue("$actionName.key")?.let { KeyStroke.getKeyStroke(it) } fun getActionPrio(actionName: String): Int = getValue("$actionName.priority")?.toInt() ?: 0 fun getActionShortDesc(actionName: String) = getValue("$actionName.shortdesc") ?: "" fun getActionLongDesc(actionName: String) = getValue("$actionName.longdesc") ?: "" fun getActionSmallIcon(actionName: String) = getValue("$actionName.smallIcon")?.let { ImageIcon(it) } fun getActionLargeIcon(actionName: String) = getValue("$actionName.largeIcon")?.let { ImageIcon(it) } fun getActionFontIcon(actionName: String): FontIcon? = getValue("$actionName.fontIcon")?.let { try { return FontAwesomeRegular.valueOf(it) } catch (e: IllegalArgumentException) { try { return FontAwesomeSolid.valueOf(it) } catch (e: IllegalArgumentException) { error(e.message!!) } } } fun getActionText(actionName: String): String = getValue("$actionName.text") ?: "$actionName.text n/a" }
ide/src/main/kotlin/edu/kit/iti/formal/automation/ide/services/config.kt
3317069371
package com.example.simpleproject import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
SimpleProject/app/src/test/java/com/example/simpleproject/ExampleUnitTest.kt
3762169046
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.ui import javafx.scene.text.Font /** * A convenience wrapper for native JavaFX Font. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ class FontFactory constructor(private val font: Font) { /** * Construct new native JavaFX font with given size. * The font used is the same as the one used in factory * construction. * * @param size font size * @return font */ fun newFont(size: Double) = Font(font.name, size) }
fxgl-scene/src/main/kotlin/com/almasb/fxgl/ui/FontFactory.kt
396152335
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.conm /** * Bean representing an "IDSCP Connection" . * * @author Gerd Brost ([email protected]) */ class IDSCPIncomingConnection { var endpointIdentifier: String? = null var attestationResult: RatResult? = null var endpointKey: String? = null var remoteHostName: String? = null var metaData: String? = null private var dynamicAttributeToken: String? = null override fun toString(): String { return ( "IDSCPConnection [endpoint_identifier=" + endpointIdentifier + ", attestationResult=" + attestationResult + "]" ) } fun setDynamicAttributeToken(dynamicAttributeToken: String?) { this.dynamicAttributeToken = dynamicAttributeToken } }
ids-api/src/main/java/de/fhg/aisec/ids/api/conm/IDSCPIncomingConnection.kt
3420207808
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.action.movement import org.joml.Vector2d import uk.co.nickthecoder.tickle.Game import uk.co.nickthecoder.tickle.action.Action open class Accelerate( val velocity: Vector2d, val acceleration: Vector2d) : Action { private var previousTime = Game.instance.seconds override fun begin(): Boolean { previousTime = Game.instance.seconds return super.begin() } override fun act(): Boolean { val diff = Game.instance.seconds - previousTime velocity.x += acceleration.x * diff velocity.y += acceleration.y * diff previousTime = Game.instance.seconds return false } }
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/Accelerate.kt
1353820747
package com.itachi1706.cheesecakeutilities.modules.ordCountdown.json /** * Created by Kenneth on 15/10/2017. * for com.itachi1706.cheesecakeutilities.modules.ORDCountdown.json in CheesecakeUtilities */ class GCalHoliday { val startYear: String? = null val endYear: String? = null val yearRange: String? = null val timestamp: String? = null val msg: String? = null val size: Int = 0 val error: Int = 0 val isCache: Boolean = false val output: Array<GCalHolidayItem>? = null val timestampLong: Long get() = timestamp?.toLong() ?: 0 }
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/ordCountdown/json/GCalHoliday.kt
3967344358
package coil.size import android.content.Context import android.view.View import android.view.ViewGroup import androidx.core.view.setPadding import androidx.test.core.app.ApplicationProvider import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) class ViewSizeResolverTest { private lateinit var context: Context private lateinit var view: View private lateinit var resolver: ViewSizeResolver<View> private lateinit var scope: CoroutineScope @Before fun before() { context = ApplicationProvider.getApplicationContext() view = View(context) resolver = ViewSizeResolver(view) scope = CoroutineScope(Dispatchers.Main.immediate) } @After fun after() { scope.cancel() } @Test fun `view is already measured`() = runTest { view.layoutParams = ViewGroup.LayoutParams(100, 100) view.setPadding(10) val size = resolver.size() assertEquals(Size(80, 80), size) } @Test fun `view padding is ignored`() = runTest { resolver = ViewSizeResolver(view, subtractPadding = false) view.layoutParams = ViewGroup.LayoutParams(100, 100) view.setPadding(10) val size = resolver.size() assertEquals(Size(100, 100), size) } @Test fun `suspend until view is measured`() = runTest { val deferred = scope.async(Dispatchers.Main.immediate) { resolver.size() } // Predraw passes should be ignored until the view is measured. view.viewTreeObserver.dispatchOnPreDraw() assertTrue(deferred.isActive) view.viewTreeObserver.dispatchOnPreDraw() assertTrue(deferred.isActive) view.setPadding(20) view.layoutParams = ViewGroup.LayoutParams(160, 160) view.measure(160, 160) view.layout(0, 0, 160, 160) view.viewTreeObserver.dispatchOnPreDraw() val size = deferred.await() assertEquals(Size(120, 120), size) } @Test fun `wrap_content is resolved to the size of the image`() = runTest { val deferred = scope.async(Dispatchers.Main.immediate) { resolver.size() } view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 100) view.measure(ViewGroup.LayoutParams.WRAP_CONTENT, 100) view.layout(0, 0, 0, 100) view.viewTreeObserver.dispatchOnPreDraw() val size = deferred.await() assertEquals(Size(Dimension.Undefined, 100), size) } }
coil-base/src/test/java/coil/size/ViewSizeResolverTest.kt
854629271
package backcompat import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Computable /** * Wrapper util to run [runnable] under WL * * Copy pasted from IDEA for backwards compatibility with 15.0.4 */ fun <T> runWriteAction(runnable: () -> T): T = ApplicationManager.getApplication().runWriteAction(Computable { runnable() }) /** * Wrapper util to run [runnable] under RL * * Copy pasted from IDEA for backwards compatibility with 15.0.4 */ fun <T> runReadAction(runnable: () -> T): T = ApplicationManager.getApplication().runReadAction(Computable { runnable() })
src/main/kotlin/backcompat/Utils.kt
3670724510
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.profile import dev.kord.core.entity.User import net.perfectdreams.discordinteraktions.common.modals.components.textInput import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ButtonExecutorDeclaration import net.perfectdreams.loritta.cinnamon.discord.interactions.components.CinnamonButtonExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds import net.perfectdreams.loritta.i18n.I18nKeysData class ChangeAboutMeButtonExecutor(loritta: LorittaBot) : CinnamonButtonExecutor(loritta) { companion object : ButtonExecutorDeclaration(ComponentExecutorIds.CHANGE_ABOUT_ME_BUTTON_EXECUTOR) override suspend fun onClick(user: User, context: ComponentContext) { val data = context.decodeDataFromComponentOrFromDatabaseAndRequireUserToMatch<ChangeAboutMeButtonData>() // Because we are storing the interaction token, we will store it on the database val encodedData = loritta.encodeDataForComponentOnDatabase( ChangeAboutMeModalData(context.interaKTionsContext.discordInteraction.token) ).serializedData context.sendModal( ChangeAboutMeModalExecutor, encodedData, context.i18nContext.get(I18nKeysData.Commands.Command.Profileview.ChangeAboutMe) ) { actionRow { textInput(ChangeAboutMeModalExecutor.options.aboutMe, context.i18nContext.get(I18nKeysData.Profiles.AboutMe)) { this.value = data.currentAboutMe } } } } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/social/profile/ChangeAboutMeButtonExecutor.kt
3978651375
package io.dwak.sleepcyclealarm import android.app.TimePickerDialog import android.content.Intent import android.os.Bundle import android.provider.AlarmClock import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import butterknife.bindView import io.dwak.sleepcyclealarm.extension.fromDate import io.dwak.sleepcyclealarm.extension.hourOfDay import io.dwak.sleepcyclealarm.extension.minute import io.dwak.sleepcyclealarm.extension.navigateTo import io.dwak.sleepcyclealarm.ui.options.OptionsFragment import io.dwak.sleepcyclealarm.ui.times.WakeUpTimesFragment import java.util.ArrayList import java.util.Calendar import java.util.Date public class MainActivity : AppCompatActivity(), OptionsFragment.OptionsFragmentInteractionListener, WakeUpTimesFragment.WakeUpTimesFragmentListener { val toolbar : Toolbar by bindView(R.id.toolbar) override fun onCreate(savedInstanceState : Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) navigateTo(OptionsFragment.newInstance(), addToBackStack = false) } override fun navigateToWakeUpTimes(sleepNow : Boolean) { when { sleepNow -> { navigateTo(WakeUpTimesFragment.newInstance(sleepNow), tag = "SleepNow") { setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right) } } else -> { with(Calendar.getInstance()) { TimePickerDialog(this@MainActivity, { v, h, m-> hourOfDay = h minute = m navigateTo(WakeUpTimesFragment.newInstance(time), tag = "SleepLater") { setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right) } }, hourOfDay, minute, false) .show() } } } } override fun setAlarm(wakeUpTime : Date) { val calendar = Calendar.getInstance().fromDate(wakeUpTime) with(Intent(AlarmClock.ACTION_SET_ALARM)) { putExtra(AlarmClock.EXTRA_MESSAGE, ""); putExtra(AlarmClock.EXTRA_HOUR, calendar.hourOfDay); putExtra(AlarmClock.EXTRA_MINUTES, calendar.minute); startActivity(this); } } }
mobile/src/main/kotlin/io/dwak/sleepcyclealarm/MainActivity.kt
462836147