content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.todoroo.andlib.sql abstract class Criterion(val operator: Operator) { protected abstract fun populate(): String override fun toString() = "(${populate()})" companion object { @JvmStatic fun and(criterion: Criterion?, vararg criterions: Criterion?): Criterion { return object : Criterion(Operator.and) { override fun populate() = criterion.plus(criterions).joinToString(" AND ") } } @JvmStatic fun or(criterion: Criterion?, vararg criterions: Criterion): Criterion { return object : Criterion(Operator.or) { override fun populate() = criterion.plus(criterions).joinToString(" OR ") } } fun exists(query: Query): Criterion { return object : Criterion(Operator.exists) { override fun populate() = "EXISTS ($query)" } } operator fun <T> T.plus(tail: Array<out T>): List<T> { val list = ArrayList<T>(1 + tail.size) list.add(this) list.addAll(tail) return list } } }
app/src/main/java/com/todoroo/andlib/sql/Criterion.kt
2940560547
package com.ternaryop.photoshelf.service import android.app.job.JobParameters import android.app.job.JobService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlin.coroutines.CoroutineContext interface Job { fun runJob(jobService: AbsJobService, params: JobParameters?): Boolean } abstract class AbsJobService : JobService(), CoroutineScope { protected lateinit var job: Job override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun onCreate() { super.onCreate() job = Job() } override fun onDestroy() { super.onDestroy() job.cancel() } override fun onStopJob(params: JobParameters?): Boolean { job.cancel() return false } }
core/src/main/java/com/ternaryop/photoshelf/service/AbsJobService.kt
3792284106
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.beam.learning.katas.triggers.eventtimetriggers import org.apache.beam.learning.katas.util.Log import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.options.PipelineOptionsFactory import org.apache.beam.sdk.transforms.Combine import org.apache.beam.sdk.transforms.Count import org.apache.beam.sdk.transforms.windowing.AfterWatermark import org.apache.beam.sdk.transforms.windowing.FixedWindows import org.apache.beam.sdk.transforms.windowing.Window import org.apache.beam.sdk.values.PCollection import org.joda.time.Duration object Task { @JvmStatic fun main(args: Array<String>) { val options = PipelineOptionsFactory.fromArgs(*args).create() val pipeline = Pipeline.create(options) val events = pipeline.apply(GenerateEvent.everySecond()) val output = applyTransform(events) output.apply(Log.ofElements()) pipeline.run() } @JvmStatic fun applyTransform(events: PCollection<String>): PCollection<Long> { return events .apply( Window.into<String>(FixedWindows.of(Duration.standardSeconds(5))) .triggering(AfterWatermark.pastEndOfWindow()) .withAllowedLateness(Duration.ZERO) .discardingFiredPanes() ) .apply(Combine.globally(Count.combineFn<String>()).withoutDefaults()) } }
learning/katas/kotlin/Triggers/Event Time Triggers/Event Time Triggers/src/org/apache/beam/learning/katas/triggers/eventtimetriggers/Task.kt
384236112
package com.doodeec.alertdialog import android.content.Context import android.content.DialogInterface import android.support.annotation.ColorRes import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.widget.ListAdapter import com.doodeec.alertdialog.AlertBuilderInterface.AlertBuilder /** * @author Dusan Bartos * Created on 21.06.2017. */ class AlertBuilderImpl : AlertBuilderInterface { override fun init(context: Context, theme: Int): AlertBuilder { return AlertImpl(context, theme) } class AlertImpl internal constructor(context: Context, theme: Int) : AlertBuilder { val builder: AlertDialog.Builder = AlertDialog.Builder(context, theme) private var colorMap = hashMapOf<@DialogButtonType Int, @ColorRes Int>() override fun title(title: Int): AlertBuilder { builder.setTitle(title) return this } override fun title(title: String): AlertBuilder { builder.setTitle(title) return this } override fun message(msg: Int): AlertBuilder { builder.setMessage(msg) return this } override fun message(msg: String): AlertBuilder { builder.setMessage(msg) return this } override fun adapter(adapter: ListAdapter, listener: DialogInterface.OnClickListener?): AlertBuilder { builder.setAdapter(adapter, listener) return this } override fun button(@DialogButtonType type: Int, btn: Int, listener: DialogInterface.OnClickListener?): AlertBuilder { when (type) { DialogInterface.BUTTON_POSITIVE -> builder.setPositiveButton(btn, listener) DialogInterface.BUTTON_NEGATIVE -> builder.setNegativeButton(btn, listener) DialogInterface.BUTTON_NEUTRAL -> builder.setNeutralButton(btn, listener) } return this } override fun button(@DialogButtonType type: Int, btn: Int, listener: DialogInterface.OnClickListener?, color: Int): AlertBuilder { colorMap[type] = color when (type) { DialogInterface.BUTTON_POSITIVE -> builder.setPositiveButton(btn, listener) DialogInterface.BUTTON_NEGATIVE -> builder.setNegativeButton(btn, listener) DialogInterface.BUTTON_NEUTRAL -> builder.setNeutralButton(btn, listener) } return this } override fun onDismiss(listener: DialogInterface.OnDismissListener): AlertBuilder { builder.setOnDismissListener(listener) return this } override fun show() { val d = builder.show() // colorMap.forEach { type, color -> d.getButton(type)?.setTextColor(ContextCompat.getColor(d.context, color)) } //foreach crashes on old APIs (kitkat) for ((type, color) in colorMap) { d.getButton(type)?.setTextColor(ContextCompat.getColor(d.context, color)) } //release map, it is no longer needed colorMap.clear() } } }
lib/src/main/java/com/doodeec/alertdialog/AlertBuilderImpl.kt
4082823715
package com.jraska.github.client.analytics import okhttp3.HttpUrl fun HttpUrl.toAnalyticsString(): String { val builder = newBuilder() for (parameterName in queryParameterNames) { builder.removeAllQueryParameters(parameterName) } return builder.build().toString() }
core-api/src/main/java/com/jraska/github/client/analytics/HttpUrl.kt
3922030521
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlinx.cli import kotlin.annotation.AnnotationTarget.* /** * This annotation marks the experimental API for working with command line arguments. * * > Beware using the annotated API especially if you're developing a library, since your library might become binary incompatible * with the future versions of the CLI library. * * Any usage of a declaration annotated with `@ExperimentalCli` must be accepted either by * annotating that usage with the [OptIn] annotation, e.g. `@OptIn(ExperimentalCli::class)`, * or by using the compiler argument `-opt-in=kotlinx.cli.ExperimentalCli`. */ @RequiresOptIn("This API is experimental. It may be changed in the future without notice.", RequiresOptIn.Level.WARNING) @Retention(AnnotationRetention.BINARY) @Target( CLASS, ANNOTATION_CLASS, PROPERTY, FIELD, LOCAL_VARIABLE, VALUE_PARAMETER, CONSTRUCTOR, FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER, TYPEALIAS ) public annotation class ExperimentalCli
core/commonMain/src/ExperimentalCli.kt
1146474381
/* * Copyright 2018 Olivér Falvai * * 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.ofalvai.bpinfo.notifications import android.content.Context import androidx.concurrent.futures.CallbackToFutureAdapter import androidx.work.ListenableWorker import androidx.work.WorkerFactory import androidx.work.WorkerParameters import com.android.volley.VolleyError import com.google.common.util.concurrent.ListenableFuture import com.ofalvai.bpinfo.api.subscription.SubscriptionClient import com.ofalvai.bpinfo.util.Analytics import timber.log.Timber class TokenUploadWorker( appContext: Context, private val params: WorkerParameters, private val subscriptionClient: SubscriptionClient, private val analytics: Analytics ) : ListenableWorker(appContext, params) { companion object { const val TAG = "TokenUploadWorker" const val KEY_NEW_TOKEN = "new_token" const val KEY_OLD_TOKEN = "old_token" } class Factory( private val subscriptionClient: SubscriptionClient, private val analytics: Analytics ) : WorkerFactory() { override fun createWorker( appContext: Context, workerClassName: String, workerParameters: WorkerParameters ): ListenableWorker? { return if (workerClassName == TokenUploadWorker::class.java.name) { TokenUploadWorker(appContext, workerParameters, subscriptionClient, analytics) } else { null } } } override fun startWork(): ListenableFuture<Result> { val newToken: String? = params.inputData.getString(KEY_NEW_TOKEN) val oldToken: String? = params.inputData.getString(KEY_OLD_TOKEN) return CallbackToFutureAdapter.getFuture { completer -> if (newToken != null && oldToken != null) { subscriptionClient.replaceToken( oldToken, newToken, object : SubscriptionClient.TokenReplaceCallback { override fun onTokenReplaceSuccess() { Timber.d("New token successfully uploaded") completer.set(Result.success()) } override fun onTokenReplaceError(error: VolleyError) { completer.set(Result.failure()) Timber.d(error, "New token upload unsuccessful") analytics.logException(error) } }) } else { Timber.w("Not uploading invalid tokens; old: %s, new: %s", oldToken, newToken) completer.set(Result.failure()) } } } }
app/src/main/java/com/ofalvai/bpinfo/notifications/TokenUploadWorker.kt
2173061275
package net.bjoernpetersen.musicbot.api.auth import org.mindrot.jbcrypt.BCrypt import java.security.SecureRandom import java.util.Random /** * Provides basic crypto features. */ object Crypto { private const val SIGNATURE_KEY_SIZE = 128 private val random: Random = SecureRandom() /** * Creates a hash string from a clear-text [password]. */ fun hash(password: String): String { return BCrypt.hashpw(password, BCrypt.gensalt()) } /** * Creates a key with the specified [length] which can be used for cryptographic signatures. * * @param length the key size in bytes */ fun createRandomBytes(length: Int = SIGNATURE_KEY_SIZE): ByteArray { val bytes = ByteArray(length) random.nextBytes(bytes) return bytes } }
src/main/kotlin/net/bjoernpetersen/musicbot/api/auth/Crypto.kt
535888369
package net.nemerosa.ontrack.extension.vault import java.beans.ConstructorProperties data class Key @ConstructorProperties("payload") constructor( val payload: ByteArray )
ontrack-extension-vault/src/main/java/net/nemerosa/ontrack/extension/vault/Key.kt
788439134
package io.dico.parcels2.command import io.dico.dicore.command.* import io.dico.dicore.command.registration.reflect.ICommandInterceptor import io.dico.dicore.command.registration.reflect.ICommandReceiver import io.dico.parcels2.* import io.dico.parcels2.PlayerProfile.Real import io.dico.parcels2.PlayerProfile.Unresolved import io.dico.parcels2.util.ext.hasPermAdminManage import io.dico.parcels2.util.ext.parcelLimit import org.bukkit.entity.Player import org.bukkit.plugin.Plugin import java.lang.reflect.Method abstract class AbstractParcelCommands(val plugin: ParcelsPlugin) : ICommandInterceptor { override fun getReceiver(context: ExecutionContext, target: Method, cmdName: String): ICommandReceiver { return getParcelCommandReceiver(plugin.parcelProvider, context, target, cmdName) } override fun getCoroutineContext(context: ExecutionContext?, target: Method?, cmdName: String?): Any { return plugin.coroutineContext } protected fun checkConnected(action: String) { if (!plugin.storage.isConnected) err("Parcels cannot $action right now because of a database error") } protected suspend fun checkParcelLimit(player: Player, world: ParcelWorld) { if (player.hasPermAdminManage) return val numOwnedParcels = plugin.storage.getOwnedParcels(PlayerProfile(player)).await() .filter { it.worldId.equals(world.id) }.size val limit = player.parcelLimit if (numOwnedParcels >= limit) { err("You have enough plots for now") } } protected suspend fun toPrivilegeKey(profile: PlayerProfile): PrivilegeKey = when (profile) { is Real -> profile is Unresolved -> profile.tryResolveSuspendedly(plugin.storage) ?: throw CommandException() else -> throw CommandException() } protected fun areYouSureMessage(context: ExecutionContext): String { val command = (context.route + context.original).joinToString(" ") + " -sure" return "Are you sure? You cannot undo this action!\n" + "Run \"/$command\" if you want to go through with this." } protected fun Job.reportProgressUpdates(context: ExecutionContext, action: String): Job = onProgressUpdate(1000, 1000) { progress, elapsedTime -> val alt = context.getFormat(EMessageType.NUMBER) val main = context.getFormat(EMessageType.INFORMATIVE) context.sendMessage( EMessageType.INFORMATIVE, false, "$action progress: $alt%.02f$main%%, $alt%.2f${main}s elapsed" .format(progress * 100, elapsedTime / 1000.0) ) } } fun err(message: String): Nothing = throw CommandException(message)
src/main/kotlin/io/dico/parcels2/command/AbstractParcelCommands.kt
3146467502
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2020 Tobias Kaminsky * Copyright (C) 2020 Nextcloud GmbH * * 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 <https://www.gnu.org/licenses/>. */ package com.owncloud.android.datamodel import org.junit.Assert import org.junit.Test class FileDataStorageManagerContentResolverIT : FileDataStorageManagerIT() { companion object { private const val MANY_FILES_AMOUNT = 5000 } override fun before() { sut = FileDataStorageManager(user, targetContext.contentResolver) super.before() } /** * only on FileDataStorageManager */ @Test fun testFolderWithManyFiles() { // create folder val folderA = OCFile("/folderA/") folderA.setFolder().parentId = sut.getFileByDecryptedRemotePath("/")!!.fileId sut.saveFile(folderA) Assert.assertTrue(sut.fileExists("/folderA/")) Assert.assertEquals(0, sut.getFolderContent(folderA, false).size) val folderAId = sut.getFileByDecryptedRemotePath("/folderA/")!!.fileId // create files val newFiles = (1..MANY_FILES_AMOUNT).map { val file = OCFile("/folderA/file$it") file.parentId = folderAId sut.saveFile(file) val storedFile = sut.getFileByDecryptedRemotePath("/folderA/file$it") Assert.assertNotNull(storedFile) storedFile } // save files in folder sut.saveFolder( folderA, newFiles, ArrayList() ) // check file count is correct Assert.assertEquals(MANY_FILES_AMOUNT, sut.getFolderContent(folderA, false).size) } }
app/src/androidTest/java/com/owncloud/android/datamodel/FileDataStorageManagerContentResolverIT.kt
2095806090
package info.jdavid.asynk.server import info.jdavid.asynk.core.asyncConnect import info.jdavid.asynk.core.asyncRead import info.jdavid.asynk.core.asyncWrite import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.produce import kotlinx.coroutines.channels.toList import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.net.InetAddress import java.net.InetSocketAddress import java.net.StandardSocketOptions import java.nio.ByteBuffer import java.nio.channels.AsynchronousSocketChannel import kotlin.coroutines.coroutineContext class EchoTests { @Test fun echo() { Server(object: Handler<Unit> { override suspend fun context(others: Collection<*>?) = Unit override suspend fun connect(remoteAddress: InetSocketAddress) = true override suspend fun handle(socket: AsynchronousSocketChannel, remoteAddress: InetSocketAddress, buffer: ByteBuffer, context: Unit) { while (withTimeout(5000L) { socket.asyncRead(buffer) } > -1) { (buffer.flip() as ByteBuffer).apply { while (remaining() > 0) this.also { withTimeout(5000L) { socket.asyncWrite(it) } } } buffer.flip() } } }).use { //Thread.sleep(20000L) runBlocking { awaitAll( async { AsynchronousSocketChannel.open().use { it.setOption(StandardSocketOptions.TCP_NODELAY, true) it.setOption(StandardSocketOptions.SO_REUSEADDR, true) it.asyncConnect(InetSocketAddress(InetAddress.getLoopbackAddress(), 8080)) ByteBuffer.wrap("abc\r\ndef\r\n".toByteArray()).apply { while (remaining() > 0) it.asyncWrite(this) } delay(100) ByteBuffer.wrap("ghi\r\njkl\r\nmno".toByteArray()).apply { while (remaining() > 0) it.asyncWrite(this) } it.shutdownOutput() val buffer = ByteBuffer.allocate(128) assertEquals(23, aRead(it, buffer)) assertEquals("abc\r\ndef\r\nghi\r\njkl\r\nmno", String(ByteArray(23).apply { (buffer.flip() as ByteBuffer).get(this) })) } }, async { AsynchronousSocketChannel.open().use { it.setOption(StandardSocketOptions.TCP_NODELAY, true) it.setOption(StandardSocketOptions.SO_REUSEADDR, true) it.asyncConnect(InetSocketAddress(InetAddress.getLoopbackAddress(), 8080)) ByteBuffer.wrap("123\r\n".toByteArray()).apply { while (remaining() > 0) it.asyncWrite(this) } delay(50) ByteBuffer.wrap("456\r\n789".toByteArray()).apply { while (remaining() > 0) it.asyncWrite(this) } it.shutdownOutput() val buffer = ByteBuffer.allocate(128) assertEquals(13, aRead(it, buffer)) assertEquals("123\r\n456\r\n789", String(ByteArray(13).apply { (buffer.flip() as ByteBuffer).get(this) })) } } ) } } } @Suppress("EXPERIMENTAL_API_USAGE") private suspend fun aRead(socket: AsynchronousSocketChannel, buffer: ByteBuffer) = CoroutineScope(coroutineContext).produce { while (true) { val n = socket.asyncRead(buffer) if (n > 0) send(n) else break } close() }.toList().sum() }
src/test/kotlin/info/jdavid/asynk/server/EchoTests.kt
1737856910
package be.florien.anyflow.injection import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.media.AudioManager import android.os.Build import android.os.Environment import androidx.lifecycle.LiveData import be.florien.anyflow.AnyFlowApp import be.florien.anyflow.data.DataRepository import be.florien.anyflow.data.local.LibraryDatabase import be.florien.anyflow.data.server.AmpacheConnection import be.florien.anyflow.data.user.AuthPersistence import be.florien.anyflow.data.user.AuthPersistenceKeystore import be.florien.anyflow.feature.alarms.AlarmActivity import be.florien.anyflow.feature.alarms.AlarmsSynchronizer import be.florien.anyflow.player.PlayerService import com.facebook.stetho.okhttp3.StethoInterceptor import com.google.android.exoplayer2.database.ExoDatabaseProvider import com.google.android.exoplayer2.offline.DownloadManager import com.google.android.exoplayer2.upstream.DefaultHttpDataSource import com.google.android.exoplayer2.upstream.cache.Cache import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor import com.google.android.exoplayer2.upstream.cache.SimpleCache import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import java.util.concurrent.Executor import javax.inject.Named import javax.inject.Singleton /** * Provide elements used through all the application state */ @Module class ApplicationModule { companion object { private const val PREFERENCE_NAME = "anyflow_preferences" } @Singleton @Provides fun providePreferences(context: Context): SharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE) @Singleton @Provides fun provideOkHttp(): OkHttpClient = OkHttpClient.Builder().addNetworkInterceptor(StethoInterceptor()).build() @Singleton @Provides fun provideAuthPersistence(preferences: SharedPreferences, context: Context): AuthPersistence = AuthPersistenceKeystore(preferences, context) @Singleton @Provides fun provideAmpacheConnection(authPersistence: AuthPersistence, context: Context, sharedPreferences: SharedPreferences): AmpacheConnection = AmpacheConnection(authPersistence, (context.applicationContext as AnyFlowApp), sharedPreferences) @Provides fun provideAmpacheConnectionStatus(connection: AmpacheConnection): LiveData<AmpacheConnection.ConnectionStatus> = connection.connectionStatusUpdater @Singleton @Provides fun provideLibrary(context: Context): LibraryDatabase = LibraryDatabase.getInstance(context) @Singleton @Provides fun provideCacheDataBaseProvider(context: Context): ExoDatabaseProvider = ExoDatabaseProvider(context) @Singleton @Provides fun provideCache(context: Context, dbProvider: ExoDatabaseProvider): Cache = SimpleCache( context.getExternalFilesDir(Environment.DIRECTORY_MUSIC) ?: context.noBackupFilesDir, NoOpCacheEvictor(), dbProvider) @Singleton @Provides fun provideDownloadManager(context: Context, databaseProvider: ExoDatabaseProvider, cache: Cache): DownloadManager { val dataSourceFactory = DefaultHttpDataSource.Factory() val downloadExecutor = Executor { obj: Runnable -> obj.run() } return DownloadManager( context, databaseProvider, cache, dataSourceFactory, downloadExecutor) } @Provides fun provideAlarmManager(context: Context): AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager @Provides @Named("player") fun providePlayerPendingIntent(context: Context): PendingIntent { val intent = Intent(context, PlayerService::class.java) intent.action = "ALARM" if (Build.VERSION.SDK_INT >= 26) { return PendingIntent.getForegroundService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } @Provides @Named("alarm") fun provideAlarmPendingIntent(context: Context): PendingIntent { val intent = Intent(context, AlarmActivity::class.java) return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) } @Provides fun provideAlarmsSynchronizer(alarmManager: AlarmManager, dataRepository: DataRepository, @Named("player") playerIntent: PendingIntent, @Named("alarm") alarmIntent: PendingIntent): AlarmsSynchronizer = AlarmsSynchronizer(alarmManager, dataRepository, alarmIntent, playerIntent) @Provides fun provideAudioManager(context: Context) = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager }
app/src/main/java/be/florien/anyflow/injection/ApplicationModule.kt
1345470183
package com.engineer.imitate import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.annotation.SuppressLint import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.text.TextUtils import android.util.Log import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.PopupMenu import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.engineer.imitate.model.FragmentItem import com.engineer.imitate.ui.activity.ReverseGifActivity import com.engineer.imitate.ui.widget.opensource.text.ActionMenu import com.engineer.imitate.util.* import com.example.cpp_native.app.NativeRoot import com.gyf.immersionbar.ImmersionBar import com.list.rados.fast_list.FastListAdapter import com.list.rados.fast_list.bind import com.skydoves.transformationlayout.onTransformationStartContainer import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_kotlin_root.* import kotlinx.android.synthetic.main.content_kotlin_root.* import kotlinx.android.synthetic.main.view_item.view.* import org.apache.commons.io.FileUtils import org.json.JSONArray import org.json.JSONObject import java.io.File import java.util.concurrent.TimeUnit @Route(path = Routes.INDEX) @SuppressLint("LogNotTimber") class KotlinRootActivity : AppCompatActivity() { private val TAG = KotlinRootActivity::class.java.simpleName private val ORIGINAL_URL = "file:///android_asset/index.html" private lateinit var hybridHelper: HybridHelper private var currentFragment: Fragment? = null private lateinit var mLinearManager: LinearLayoutManager private lateinit var mGridLayoutManager: GridLayoutManager private lateinit var mLayoutManager: RecyclerView.LayoutManager private var adapter: FastListAdapter<FragmentItem>? = null override fun onCreate(savedInstanceState: Bundle?) { onTransformationStartContainer() super.onCreate(savedInstanceState) ImmersionBar.with(this) .fitsSystemWindows(true) .statusBarColor(R.color.colorPrimary).init() setContentView(R.layout.activity_kotlin_root) setSupportActionBar(toolbar) loadView() jsonTest() // autoStartPage() NativeRoot.init() NativeRoot.test() val patchViewModel = ViewModelProvider(this)[PatchViewModel::class.java] patchViewModel.copyFile() } private fun autoStartPage() { val fragment: Fragment = ARouter.getInstance().build("/anim/fresco").navigation(this) as Fragment currentFragment = fragment content.visibility = View.VISIBLE index.visibility = View.GONE val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.content, fragment).commit() } private fun loadView() { mLinearManager = LinearLayoutManager(this) mGridLayoutManager = GridLayoutManager(this, 2) mLayoutManager = mLinearManager // if (isNetworkConnected()) { // loadWebView() // } else { // } loadRecyclerView() // loadWebView() gif.setOnClickListener { // startActivity(Intent(this, ReverseGifActivity::class.java)) val bundle = transformationLayout.withView(transformationLayout, "myTransitionName") val intent = Intent(this, ReverseGifActivity::class.java) intent.putExtra("TransformationParams", transformationLayout.getParcelableParams()) startActivity(intent, bundle) } } // <editor-fold defaultstate="collapsed" desc="拷贝一些文件到特定目录,不是每个手机都需要"> /** * 拷贝一些文件到特定目录,不是每个手机都需要 */ private fun personalCopy() { val path = filesDir.absolutePath + "/gif/" val fileDir = File(path) val files = fileDir.listFiles() files?.apply { if (fileDir.exists()) { val destDir = Environment.getExternalStorageDirectory() for (file in this) { Log.e(TAG, ": " + file.absolutePath) Observable.just("") .subscribeOn(Schedulers.io()) .subscribe { FileUtils.copyFileToDirectory(file, destDir) } } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="init fragments"> private fun initList(): MutableList<FragmentItem> { return mutableListOf( FragmentItem("/anim/entrance", "entrance"), FragmentItem("/anim/dependency_injection", "dependency_injection"), FragmentItem("/anim/rx_play", "rx_play"), FragmentItem("/anim/motion_layout", "motion_layout"), FragmentItem("/anim/github", "github features"), FragmentItem("/anim/pure_3d_share", "3D shape"), FragmentItem("/anim/circleLoading", "circle-loading"), FragmentItem("/anim/coroutines", "coroutines"), FragmentItem("/anim/recycler_view", "RecyclerView"), FragmentItem("/anim/slide", "slide"), FragmentItem("/anim/drawable_example", "drawable_example"), FragmentItem("/anim/elevation", "elevation"), FragmentItem("/anim/fresco", "fresco"), FragmentItem("/anim/constraint", "constraint animation"), FragmentItem("/anim/scroller", "scroller"), FragmentItem("/anim/vh_fragment", "vh_fragment"), FragmentItem("/anim/parallax", "parallax") ) } // </editor-fold> private fun loadRecyclerView() { hybrid.animate().alpha(0f).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) hybrid.visibility = View.GONE recyclerView.visibility = View.VISIBLE } }).start() val list = initList() adapter = recyclerView.bind(list, R.layout.view_item) { item: FragmentItem, _: Int -> desc.text = item.name path.text = item.path path.setOnClickListener { AnimDelegate.apply(context, path, gif, shell_root) } more_menu.setOnClickListener { showMenu(more_menu) } shell.setOnClickListener { gif.hide() val fragment: Fragment = ARouter.getInstance().build(item.path).navigation(context) as Fragment currentFragment = fragment content.visibility = View.VISIBLE index.visibility = View.GONE val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.content, fragment).commit() updateState() } }.layoutManager(mLayoutManager) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) Log.e(TAG, "dy==$dy") Log.e(TAG, "是否可以 scroll up==${recyclerView.canScrollVertically(-1)}") Log.e(TAG, "是否可以 scroll down==${recyclerView.canScrollVertically(1)}") } }) } } private fun showMenu(view: View) { val popupMenu = PopupMenu(this, view, Gravity.END) popupMenu.menuInflater.inflate(R.menu.index_setting_menu, popupMenu.menu) popupMenu.show() } @SuppressLint("SetJavaScriptEnabled") private fun loadWebView() { hybrid.animate().alpha(1f).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) hybrid.visibility = View.VISIBLE recyclerView.visibility = View.GONE } }).start() hybrid.settings.javaScriptEnabled = true hybrid.settings.allowFileAccess = true hybridHelper = HybridHelper(this) hybridHelper.setOnItemClickListener(SimpleClickListener()) hybrid.addJavascriptInterface(hybridHelper, "hybrid") hybrid.loadUrl(ORIGINAL_URL) } private inner class SimpleClickListener : HybridHelper.OnItemClickListener { override fun reload() { runOnUiThread { loadRecyclerView() } } @SuppressLint("RestrictedApi") override fun onClick(fragment: Fragment, title: String) { runOnUiThread { if (!TextUtils.isEmpty(title)) { setTitle(title) } content.visibility = View.VISIBLE index.visibility = View.GONE gif.hide() currentFragment = fragment val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.content, fragment).commit() } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_kotlin_root, menu) return true } private fun isNightMode(): Boolean { val flag = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK return flag == Configuration.UI_MODE_NIGHT_YES } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { val item = menu?.findItem(R.id.theme_switch) if (isNightMode()) { item?.setIcon(R.drawable.ic_brightness_low_white_24dp) item?.setTitle("日间模式") } else { item?.setIcon(R.drawable.ic_brightness_high_white_24dp) item?.title = "夜间模式" } val change = menu?.findItem(R.id.action_change) change?.isVisible = (recyclerView.visibility == View.VISIBLE) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { if (content.visibility == View.VISIBLE) { releaseFragment() } else { finish() } } else if (item.itemId == R.id.action_refresh) { if (recyclerView.visibility == View.VISIBLE) { loadWebView() } else { loadRecyclerView() } return true } else if (item.itemId == R.id.action_change) { if (recyclerView.visibility == View.VISIBLE) { if (recyclerView.layoutManager == mLinearManager) { mLayoutManager = mGridLayoutManager } else { mLayoutManager = mLinearManager } adapter?.layoutManager(mLayoutManager)?.notifyDataSetChanged() return true } } else if (item.itemId == R.id.theme_switch) { if (isNightMode()) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) SpUtil(this).saveBool(SpUtil.KEY_THEME_NIGHT_ON, false) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) SpUtil(this).saveBool(SpUtil.KEY_THEME_NIGHT_ON, true) } // recreate() } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (content.visibility == View.VISIBLE) { releaseFragment() } else { super.onBackPressed() } } private fun releaseFragment() { content.visibility = View.GONE index.visibility = View.VISIBLE gif.show() Log.e(TAG, "fragments size = " + supportFragmentManager.fragments.size) currentFragment?.let { if (supportFragmentManager.fragments.size > 0) { supportFragmentManager.beginTransaction() .remove(it) .commitAllowingStateLoss() currentFragment = null updateState() } } } private fun updateState() { Observable.just(1) .delay(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { Log.e(TAG, "updateState: ======================================================\n") Log.e(TAG, "fragments size = " + supportFragmentManager.fragments.size) supportFragmentManager.fragments.forEach { Log.e( TAG, "fragment [ ${it.javaClass.name} ] in activity [ ${it.activity?.javaClass?.simpleName} ]" ) } Log.e(TAG, "updateState: ======================================================\n") } .subscribe() } private fun jsonTest() { val uri = "https://www.zhihu.com/search?q=%E5%88%A9%E7%89%A9%E6%B5%A6&type=content" val parseUri = Uri.parse(uri) Log.e(TAG, "type : " + parseUri::class.java.canonicalName) Log.e(TAG, "query: ${parseUri.query}") Log.e(TAG, "isOpaque: ${parseUri.isOpaque}") val jsonArray = JSONArray() for (i in 0..3) { val jsonObj = JSONObject() jsonObj.put("name", "name_$i") jsonArray.put(jsonObj) } Log.e(TAG, "result ==$jsonArray") } override fun onDestroy() { super.onDestroy() hybrid.removeJavascriptInterface("hybrid") } }
imitate/src/main/java/com/engineer/imitate/KotlinRootActivity.kt
665020888
package io.mockk.proxy.jvm.transformation import io.mockk.proxy.MockKAgentLogger import io.mockk.proxy.MockKInvocationHandler import io.mockk.proxy.common.transformation.ClassTransformationSpecMap import io.mockk.proxy.jvm.advice.ProxyAdviceId import io.mockk.proxy.jvm.advice.jvm.JvmMockKConstructorProxyAdvice import io.mockk.proxy.jvm.advice.jvm.JvmMockKHashMapStaticProxyAdvice import io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyAdvice import io.mockk.proxy.jvm.advice.jvm.JvmMockKStaticProxyAdvice import io.mockk.proxy.jvm.advice.jvm.MockHandlerMap import io.mockk.proxy.jvm.dispatcher.JvmMockKDispatcher import net.bytebuddy.ByteBuddy import net.bytebuddy.asm.Advice import net.bytebuddy.asm.AsmVisitorWrapper import net.bytebuddy.description.ModifierReviewable.OfByteCodeElement import net.bytebuddy.description.method.MethodDescription import net.bytebuddy.dynamic.ClassFileLocator.Simple.of import net.bytebuddy.matcher.ElementMatchers.* import java.io.File import java.lang.instrument.ClassFileTransformer import java.security.ProtectionDomain import java.util.concurrent.atomic.AtomicLong internal class InliningClassTransformer( private val log: MockKAgentLogger, private val specMap: ClassTransformationSpecMap, private val handlers: MockHandlerMap, private val staticHandlers: MockHandlerMap, private val constructorHandlers: MockHandlerMap, private val byteBuddy: ByteBuddy ) : ClassFileTransformer { private val restrictedMethods = setOf( "java.lang.System.getSecurityManager" ) private lateinit var advice: JvmMockKProxyAdvice private lateinit var staticAdvice: JvmMockKStaticProxyAdvice private lateinit var staticHashMapAdvice: JvmMockKHashMapStaticProxyAdvice private lateinit var constructorAdvice: JvmMockKConstructorProxyAdvice init { class AdviceBuilder { fun build() { advice = JvmMockKProxyAdvice(handlers) staticAdvice = JvmMockKStaticProxyAdvice(staticHandlers) staticHashMapAdvice = JvmMockKHashMapStaticProxyAdvice(staticHandlers) constructorAdvice = JvmMockKConstructorProxyAdvice(constructorHandlers) JvmMockKDispatcher.set(advice.id, advice) JvmMockKDispatcher.set(staticAdvice.id, staticAdvice) JvmMockKDispatcher.set(staticHashMapAdvice.id, staticHashMapAdvice) JvmMockKDispatcher.set(constructorAdvice.id, constructorAdvice) } } AdviceBuilder().build() } override fun transform( loader: ClassLoader?, className: String, classBeingRedefined: Class<*>, protectionDomain: ProtectionDomain?, classfileBuffer: ByteArray? ): ByteArray? { val spec = specMap[classBeingRedefined] ?: return classfileBuffer try { val builder = byteBuddy.redefine(classBeingRedefined, of(classBeingRedefined.name, classfileBuffer)) .visit(FixParameterNamesVisitor(classBeingRedefined)) val type = builder .run { if (spec.shouldDoSimpleIntercept) visit(simpleAdvice()) else this } .run { if (spec.shouldDoStaticIntercept) visit(staticAdvice(className)) else this } .run { if (spec.shouldDoConstructorIntercept) visit(constructorAdvice()) else this } .make() try { val property = System.getProperty("io.mockk.classdump.path") if (property != null) { val nextIndex = classDumpIndex.incrementAndGet().toString() val storePath = File(File(property, "inline"), nextIndex) type.saveIn(storePath) } } catch (ex: Exception) { log.trace(ex, "Failed to save file to a dump"); } return type.bytes } catch (e: Throwable) { log.warn(e, "Failed to transform class $className") return null } } private fun simpleAdvice() = Advice.withCustomMapping() .bind<ProxyAdviceId>(ProxyAdviceId::class.java, advice.id) .to(JvmMockKProxyAdvice::class.java) .on( isMethod<MethodDescription>() .and(not<OfByteCodeElement>(isStatic<OfByteCodeElement>())) .and(not<MethodDescription>(isDefaultFinalizer<MethodDescription>())) ) private fun staticAdvice(className: String) = Advice.withCustomMapping() .bind<ProxyAdviceId>(ProxyAdviceId::class.java, staticProxyAdviceId(className)) .to(staticProxyAdvice(className)) .on( isStatic<OfByteCodeElement>() .and(not<MethodDescription>(isTypeInitializer<MethodDescription>())) .and(not<MethodDescription>(isConstructor<MethodDescription>())) .and(not<MethodDescription>(this::matchRestrictedMethods)) ) private fun matchRestrictedMethods(desc: MethodDescription) = desc.declaringType.typeName + "." + desc.name in restrictedMethods private fun constructorAdvice(): AsmVisitorWrapper.ForDeclaredMethods? { return Advice.withCustomMapping() .bind<ProxyAdviceId>(ProxyAdviceId::class.java, constructorAdvice.id) .to(JvmMockKConstructorProxyAdvice::class.java) .on(isConstructor()) } // workaround #35 private fun staticProxyAdviceId(className: String) = when (className) { "java/util/HashMap" -> staticHashMapAdvice.id else -> staticAdvice.id } // workaround #35 private fun staticProxyAdvice(className: String) = when (className) { "java/util/HashMap" -> JvmMockKHashMapStaticProxyAdvice::class.java else -> JvmMockKStaticProxyAdvice::class.java } companion object { val classDumpIndex = AtomicLong(); } }
modules/mockk-agent/src/jvmMain/kotlin/io/mockk/proxy/jvm/transformation/InliningClassTransformer.kt
1930492190
package de.xikolo.controllers.main import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import butterknife.BindView import butterknife.ButterKnife import de.xikolo.App import de.xikolo.R import de.xikolo.controllers.helper.DownloadViewHelper import de.xikolo.models.Course import de.xikolo.models.DownloadAsset import de.xikolo.models.dao.EnrollmentDao class CertificateListAdapter(private val fragment: CertificateListFragment, private val callback: OnCertificateCardClickListener) : RecyclerView.Adapter<CertificateListAdapter.CertificateViewHolder>() { companion object { val TAG: String = CertificateListAdapter::class.java.simpleName } private val courseList: MutableList<Course> = mutableListOf() fun update(courseList: List<Course>) { this.courseList.clear() this.courseList.addAll(courseList) notifyDataSetChanged() } override fun getItemCount(): Int { return courseList.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CertificateViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_certificate_list, parent, false) return CertificateViewHolder(view) } override fun onBindViewHolder(holder: CertificateViewHolder, position: Int) { val course = courseList[position] holder.textTitle.text = course.title holder.textTitle.setOnClickListener { _ -> callback.onCourseClicked(course.id) } holder.container.removeAllViews() fragment.activity?.let { activity -> EnrollmentDao.Unmanaged.findForCourse(course.id)?.let { enrollment -> if (course.certificates.confirmationOfParticipation.available) { val dvh = DownloadViewHelper( activity, DownloadAsset.Certificate.ConfirmationOfParticipation( enrollment.certificates.confirmationOfParticipationUrl, course ), App.instance.getString(R.string.course_confirmation_of_participation), null, App.instance.getString(R.string.course_certificate_not_achieved) ) holder.container.addView(dvh.view) } if (course.certificates.recordOfAchievement.available) { val dvh = DownloadViewHelper( activity, DownloadAsset.Certificate.RecordOfAchievement( enrollment.certificates.recordOfAchievementUrl, course ), App.instance.getString(R.string.course_record_of_achievement), null, App.instance.getString(R.string.course_certificate_not_achieved) ) holder.container.addView(dvh.view) } if (course.certificates.qualifiedCertificate.available) { val dvh = DownloadViewHelper( activity, DownloadAsset.Certificate.QualifiedCertificate( enrollment.certificates.qualifiedCertificateUrl, course ), App.instance.getString(R.string.course_qualified_certificate), null, App.instance.getString(R.string.course_certificate_not_achieved) ) holder.container.addView(dvh.view) } } } } interface OnCertificateCardClickListener { fun onCourseClicked(courseId: String) } class CertificateViewHolder(view: View) : RecyclerView.ViewHolder(view) { @BindView(R.id.textTitle) lateinit var textTitle: TextView @BindView(R.id.container) lateinit var container: LinearLayout init { ButterKnife.bind(this, view) } } }
app/src/main/java/de/xikolo/controllers/main/CertificateListAdapter.kt
4131165782
package com.adgvcxz.viewmodel.sample import android.view.View import com.adgvcxz.IModel import com.adgvcxz.IMutation import com.adgvcxz.add import com.adgvcxz.bindModel import com.adgvcxz.recyclerviewmodel.* import com.adgvcxz.viewmodel.sample.databinding.ItemTextViewBinding import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import kotlinx.android.synthetic.main.item_loading.view.* import java.util.* import java.util.concurrent.TimeUnit /** * zhaowei * Created by zhaowei on 2017/6/6. */ var initId = 0 class SimpleRecyclerViewModel : RecyclerViewModel() { override var initModel: RecyclerModel = RecyclerModel(null, hasLoadingItem = true, isAnim = true) override fun request(refresh: Boolean): Observable<IMutation> { return if (refresh) { Observable.timer(3, TimeUnit.SECONDS) .map { (0 until 10).map { TextItemViewModel() } } .flatMap { if (!refresh && currentModel().items.size > 30) { Observable.concat( Observable.just(UpdateData(it)), Observable.just(RemoveLoadingItem) ) } else { Observable.just(UpdateData(it)) } } } else { Observable.timer(100, TimeUnit.MILLISECONDS).map { LoadFailure } } } } class TextItemView : ItemBindingView<ItemTextViewBinding, TextItemViewModel> { override val layoutId: Int = R.layout.item_text_view override fun generateViewBinding(view: View): ItemTextViewBinding { return ItemTextViewBinding.bind(view) } override fun bind( binding: ItemTextViewBinding, viewModel: TextItemViewModel, position: Int, disposable: CompositeDisposable ) { viewModel.bindModel(disposable) { add({ content }, { binding.textView.text = this }) } } } class TextItemViewModel : RecyclerItemViewModel<TextItemViewModel.Model>() { override var initModel: Model = Model() class ValueChangeMutation(val value: String) : IMutation override fun transformMutation(mutation: Observable<IMutation>): Observable<IMutation> { val value = RxBus.instance.toObservable(ValueChangeEvent::class.java) .filter { it.id == currentModel().id } .map { ValueChangeMutation(it.value) } return Observable.merge(value, mutation) } override fun scan(model: Model, mutation: IMutation): Model { when (mutation) { is ValueChangeMutation -> model.content = mutation.value } return model } class Model : IModel { var content: String = UUID.randomUUID().toString() + "==== $initId" var id = initId++ } } class LoadingItemView : IDefaultView<LoadingItemViewModel> { override val layoutId: Int = R.layout.item_loading override fun bind(viewHolder: ItemViewHolder, viewModel: LoadingItemViewModel, position: Int) { with(viewHolder.itemView) { viewModel.bindModel(viewHolder.disposables) { add({ state != LoadingItemViewModel.Failure }, { loading.visibility = if (this) View.VISIBLE else View.GONE failed.visibility = if (this) View.GONE else View.VISIBLE }) } } } }
app/src/main/kotlin/com/adgvcxz/viewmodel/sample/SimpleRecyclerViewModel.kt
2583784392
package com.mobapphome.appcrosspromoter.tools import android.content.Context import java.util.Locale object LocaleUpdater { @JvmStatic fun updateLocale(context: Context, language: String) { val locale = Locale(language) Locale.setDefault(locale) val resources = context.resources val configuration = resources.configuration configuration.locale = locale resources.updateConfiguration(configuration, resources.displayMetrics) } }
app-cross-promoter/src/main/java/com/mobapphome/appcrosspromoter/tools/LocaleUpdater.kt
3233907911
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * 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 dev.yuriel.kotmvp.layout import android.graphics.YuvImage import com.badlogic.gdx.scenes.scene2d.Actor import dev.yuriel.kotmvp.LayoutWrongException import java.util.* /** * Created by yuriel on 8/10/16. */ abstract class LayoutElement { companion object { val children = mutableMapOf<String, LayoutElement>() var unit: Number = 1 } abstract val id: String protected val attributes = hashMapOf<String, String>() open val attr = LayoutPosition(0F, 0F, 0F, 0F) open var actor: Actor? = null set(value) { field = value if (attr.size.width == 0F && attr.size.height == 0F) { attr.size.width = value?.width?: 0F attr.size.height = value?.height?: 0F } } var top: Number? = null get() = attr.top() private set var right: Number? = null get() = attr.right() private set var bottom: Number? = null get() = attr.bottom() private set var left: Number? = null get() = attr.left() private set var width: Number? = null get() = attr.size.width set(value) { field = value?.toFloat()?: 0L * unit.toFloat() setW(value?: field?: 0) } var height: Number? = null get() = attr.size.height set(value) { field = value?.toFloat()?: 0L * unit.toFloat() setH(value?: field?: 0) } fun actor(init: Actor.() -> Unit) { actor?.init() } private fun setW(width: Number) { attr.size.width = width.toFloat() * unit.toFloat() } private fun setH(height: Number) { attr.size.height = height.toFloat() * unit.toFloat() } protected operator fun get(name: String): LayoutElement? = children[name] protected fun <T: LayoutElement> layout(layout: T, init: T.() -> Unit): T { if (children.containsKey(layout.id)) { throw LayoutWrongException() } layout.init() children.put(layout.id, layout) layout.actor?.setPosition(layout.attr.ghostOrigin.first!!, layout.attr.ghostOrigin.second!!) layout.actor?.setSize(layout.attr.size.width, layout.attr.size.height) return layout } }
app/src/main/java/dev/yuriel/kotmvp/layout/LayoutElement.kt
535070331
package com.esorokin.lantector.utils.ext import io.reactivex.disposables.Disposable interface AutoDisposableContainer { fun autoDispose(disposable: Disposable) }
app/src/main/java/com/esorokin/lantector/utils/ext/AutoDisposableContainer.kt
1288579708
package siarhei.luskanau.example.workmanager.monitor import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.work.WorkInfo import siarhei.luskanau.example.workmanager.databinding.ListItemWorkStatusBinding class WorkInfoAdapter : ListAdapter<WorkInfo, WorkInfoAdapter.ViewHolder>(WorkInfoDiffCallback()) { override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position)) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder( ListItemWorkStatusBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) class ViewHolder( private val binding: ListItemWorkStatusBinding ) : RecyclerView.ViewHolder(binding.root) { @SuppressLint("SetTextI18n") fun bind(item: WorkInfo) { binding.workInfoTextView.text = "${item.id}\n ${item.state} ${item.tags}\n${item.outputData.keyValueMap}" itemView.tag = item } } }
workmanager/src/main/java/siarhei/luskanau/example/workmanager/monitor/WorkInfoAdapter.kt
3704851786
package app.cash.sqldelight.integration import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver.Companion.IN_MEMORY import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test class IntegrationTests { private lateinit var queryWrapper: QueryWrapper private lateinit var personQueries: PersonQueries @Before fun before() { val database = JdbcSqliteDriver(IN_MEMORY) QueryWrapper.Schema.create(database) queryWrapper = QueryWrapper(database) personQueries = queryWrapper.personQueries } @Test fun upsertNoConflict() { // ?1 is the only arg personQueries.performUpsert(5, "Bo", "Jangles") assertThat(personQueries.selectAll().executeAsList()) .containsExactly( Person(1, "Alec", "Strong"), Person(2, "Matt", "Precious"), Person(3, "Jake", "Wharton"), Person(4, "Bob", "Bob"), Person(5, "Bo", "Jangles"), ) } @Test fun upsertConflict() { // ?1 is the only arg personQueries.performUpsert(3, "James", "Mosley") assertThat(personQueries.selectAll().executeAsList()) .containsExactly( Person(1, "Alec", "Strong"), Person(2, "Matt", "Precious"), Person(3, "James", "Mosley"), Person(4, "Bob", "Bob"), ) } }
sqldelight-gradle-plugin/src/test/integration-sqlite-3-24/src/test/java/app/cash/sqldelight/integration/IntegrationTests.kt
2991024946
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.builders.tables import i.katydid.vdom.builders.KatydidAttributesContentBuilderImpl import i.katydid.vdom.builders.KatydidContentRestrictions import i.katydid.vdom.builders.KatydidFlowContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import i.katydid.vdom.elements.tabular.* import i.katydid.vdom.elements.text.KatydidComment import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.builders.KatydidFlowContentBuilder import o.katydid.vdom.builders.tables.KatydidColGroupContentBuilder import o.katydid.vdom.builders.tables.KatydidTableBodyContentBuilder import o.katydid.vdom.builders.tables.KatydidTableContentBuilder import o.katydid.vdom.builders.tables.KatydidTableRowContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Builder DSL to create the contents of a table. * * @constructor Constructs a new builder for the contents of a `<table>` element. * @param itsElement the element whose content is being built. * @param itsContentRestrictions restrictions on content enforced at run time. * @param itsDispatchMessages dispatcher of event handling results for when we want event handling to be reactive or Elm-like. */ internal class KatydidTableContentBuilderImpl<Msg>( itsElement: KatydidTable<Msg>, itsContentRestrictions: KatydidContentRestrictions = KatydidContentRestrictions(), itsDispatchMessages: (messages: Iterable<Msg>) -> Unit ) : KatydidAttributesContentBuilderImpl<Msg>(itsElement, itsDispatchMessages), KatydidTableContentBuilder<Msg> { /** Restrictions on content enforced at run time. */ val contentRestrictions = itsContentRestrictions /** Restrictions enforcing the order of sub-elements within the table being built. */ val tableContentRestrictions = KatydidTableContentRestrictions() //// /** * Creates a new attributes content builder for the given child [element]. */ fun attributesContent(element: KatydidColGroup<Msg>): KatydidAttributesContentBuilderImpl<Msg> { return KatydidAttributesContentBuilderImpl(element, dispatchMessages) } override fun caption( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidCaption(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate, defineContent) ) } override fun colgroup( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, span: Int?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidColGroup(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, span, spellcheck, style, tabindex, title, translate, defineAttributes) ) } override fun colgroup( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidColGroupContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidColGroup(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate, defineContent) ) } /** * Creates a new flow content builder for the given child [element] that has the same restrictions * as this builder plus a table is not allowed */ fun colGroupContent(element: KatydidColGroup<Msg>): KatydidColGroupContentBuilderImpl<Msg> { return KatydidColGroupContentBuilderImpl( element, dispatchMessages ) } override fun comment(nodeValue: String, key: Any?) { element.addChildNode(KatydidComment(nodeValue, key)) } /** * Creates a new flow content builder for the given child [element] that has the same restrictions * as this builder plus a table is not allowed */ fun flowContentWithTableNotAllowed(element: KatydidCaption<Msg>): KatydidFlowContentBuilderImpl<Msg> { return KatydidFlowContentBuilderImpl( element, contentRestrictions.withTableNotAllowed(), dispatchMessages ) } /** * Creates a new table row content builder for the given child [element] that has the same restrictions * as this builder. */ fun tableRowContent(element: KatydidTr<Msg>): KatydidTableRowContentBuilderImpl<Msg> { return KatydidTableRowContentBuilderImpl( element, contentRestrictions, dispatchMessages ) } override fun tbody( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidTableBodyContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidTBody(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate, defineContent) ) } override fun tfoot( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidTableBodyContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidTFoot(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate, defineContent) ) } override fun thead( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidTableBodyContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidTHead(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate, defineContent) ) } override fun tr( selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidTableRowContentBuilder<Msg>.() -> Unit ) { element.addChildNode( KatydidTr(this, selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate, defineContent) ) } /** * Creates a new table body content builder for the given child [element] that has the same restrictions * as this builder. */ fun tableBodyContent(element: KatydidHtmlElementImpl<Msg>): KatydidTableBodyContentBuilderImpl<Msg> { return KatydidTableBodyContentBuilderImpl( element, contentRestrictions, dispatchMessages ) } } //---------------------------------------------------------------------------------------------------------------------
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/builders/tables/KatydidTableContentBuilderImpl.kt
459935503
/* * Copyright (C) 2017-2018 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.marklogic.api import java.util.HashMap abstract class EvalRequestBuilder protected constructor() { var contentDatabase: String? = null var transactionID: String? = null private var xquery: String? = null @Suppress("PropertyName") var XQuery: String? get() = xquery set(xquery) { this.xquery = xquery this.javascript = null // There can only be one! } private var javascript: String? = null var javaScript: String? get() = javascript set(javascript) { this.xquery = null // There can only be one! this.javascript = javascript } private val vars = HashMap<QName, Item>() val variableNames get(): Set<QName> = vars.keys fun addVariables(variables: Map<QName, Item>) { for ((key, value) in variables) { vars.put(key, value) } } fun addVariable(name: QName, value: Item) { vars[name] = value } fun getVariable(name: QName): Item { return vars[name]!! } abstract fun build(): Request }
src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/api/EvalRequestBuilder.kt
2055259456
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.css.styles.builders import o.katydid.css.styles.KatydidStyle import o.katydid.css.types.EOverflow import o.katydid.css.types.EOverflowWrap import o.katydid.css.types.EResize //--------------------------------------------------------------------------------------------------------------------- /** * Builder class for setting overflow properties of a given [style] from a nested block. */ @KatydidStyleBuilderDsl class KatydidOverflowStyleBuilder( private val style: KatydidStyle ) { fun x(value: EOverflow) = style.overflowX(value) fun y(value: EOverflow) = style.overflowY(value) fun wrap(value: EOverflowWrap) = style.overflowWrap(value) } //--------------------------------------------------------------------------------------------------------------------- fun KatydidStyle.overflow(build: KatydidOverflowStyleBuilder.() -> Unit) = KatydidOverflowStyleBuilder(this).build() fun KatydidStyle.overflow(x: EOverflow, y: EOverflow = x) = setXyProperty("overflow", x, y) //--------------------------------------------------------------------------------------------------------------------- fun KatydidStyle.overflowX(value: EOverflow) = setProperty("overflow-x", "$value") //--------------------------------------------------------------------------------------------------------------------- fun KatydidStyle.overflowY(value: EOverflow) = setProperty("overflow-y", "$value") //--------------------------------------------------------------------------------------------------------------------- fun KatydidStyle.overflowWrap(value: EOverflowWrap) = setProperty("overflow-wrap", "$value") //--------------------------------------------------------------------------------------------------------------------- fun KatydidStyle.resize(value: EResize) = setProperty("resize", "$value") //---------------------------------------------------------------------------------------------------------------------
Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/builders/KatydidOverflowStyleBuilder.kt
80341319
package net.codechunk.speedofsound.util import android.content.Context import android.content.res.TypedArray import android.preference.DialogPreference import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import net.codechunk.speedofsound.R /** * A preference that is displayed as a seek bar. */ open class SliderPreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs), OnSeekBarChangeListener { /** * Seek bar widget to control preference value. */ protected var seekBar: SeekBar? = null /** * Text view displaying the value of the seek bar. */ private var valueDisplay: TextView? = null /** * Dialog view. */ protected var view: View? = null /** * Minimum value. */ protected val minValue: Int /** * Maximum value. */ protected val maxValue: Int /** * Units of this preference. */ protected var units: String? = null /** * Current value. */ protected var value: Int = 0 init { this.minValue = attrs.getAttributeIntValue(LOCAL_NS, "minValue", 0) this.maxValue = attrs.getAttributeIntValue(LOCAL_NS, "maxValue", 0) this.units = attrs.getAttributeValue(LOCAL_NS, "units") } /** * Set the initial value. * Needed to properly load the default value. */ override fun onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any?) { if (restorePersistedValue) { // Restore existing state this.value = this.getPersistedInt(-1) } else { // Set default state from the XML attribute this.value = defaultValue as Int persistInt(this.value) } } /** * Support loading a default value. */ override fun onGetDefaultValue(a: TypedArray, index: Int): Any { return a.getInteger(index, -1) } /** * Set up the preference display. */ override fun onCreateDialogView(): View { // reload the persisted value since onSetInitialValue is only performed once // for the activity, not each time the preference is opened this.value = getPersistedInt(-1) // load the layout val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater this.view = inflater.inflate(R.layout.slider_preference_dialog, null) // setup the slider this.seekBar = this.view!!.findViewById<View>(R.id.slider_preference_seekbar) as SeekBar this.seekBar!!.max = this.maxValue - this.minValue this.seekBar!!.progress = this.value - this.minValue this.seekBar!!.setOnSeekBarChangeListener(this) this.valueDisplay = this.view!!.findViewById<View>(R.id.slider_preference_value) as TextView this.updateDisplay() return this.view!! } /** * Save on dialog close. */ override fun onDialogClosed(positiveResult: Boolean) { super.onDialogClosed(positiveResult) if (!positiveResult) { return } if (shouldPersist()) { this.persistInt(this.value) } this.notifyChanged() } protected fun updateDisplay() { var text = this.value.toString() if (this.units != null) { text += this.units } this.valueDisplay!!.text = text } /** * Updated the displayed value on change. */ override fun onProgressChanged(seekBar: SeekBar, value: Int, fromTouch: Boolean) { this.value = value + this.minValue this.updateDisplay() } override fun onStartTrackingTouch(sb: SeekBar) {} override fun onStopTrackingTouch(sb: SeekBar) {} companion object { /** * Our custom namespace for this preference. */ protected const val LOCAL_NS = "http://schemas.android.com/apk/res-auto" } }
src/net/codechunk/speedofsound/util/SliderPreference.kt
1311190854
package org.pixelndice.table.pixelclient.connection.main import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.PixelResourceBundle import org.pixelndice.table.pixelprotocol.Protobuf import java.text.MessageFormat private val logger = LogManager.getLogger(State02WaitingProtocolVersion::class.java) class State02WaitingProtocolVersion : State { override fun process(ctx: Context) { val packet = ctx.packet if (packet != null) { if (packet.payloadCase == Protobuf.Packet.PayloadCase.VERSIONOK) { logger.info("Procol check version ok") ctx.state = State03SendingAuthRequest() ctx.process() } else if( packet.payloadCase == Protobuf.Packet.PayloadCase.VERSIONERROR){ logger.fatal("Wrong version, update your client!") ApplicationBus.post(ApplicationBus.SystemFailure()) } else { val message = "Expecting VERSIONOK / VERSIONERROR, instead received: $packet. IP: ${ctx.channel.address}" logger.fatal(message) val resp = Protobuf.Packet.newBuilder() val rend = Protobuf.EndWithError.newBuilder() rend.reason = message resp.setEndWithError(rend) ctx.packet = resp.build() ApplicationBus.post(ApplicationBus.SystemFailure()) } } } }
src/main/kotlin/org/pixelndice/table/pixelclient/connection/main/State02WaitingProtocolVersion.kt
2132079224
package com.benoitquenaudon.tvfoot.red.util import android.graphics.Bitmap import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.Paint import android.graphics.Paint.ANTI_ALIAS_FLAG import android.graphics.Paint.DITHER_FLAG import android.graphics.Paint.FILTER_BITMAP_FLAG import android.graphics.Shader.TileMode.CLAMP import androidx.core.graphics.createBitmap import com.squareup.picasso.Transformation object CircleTransform : Transformation { override fun transform(source: Bitmap): Bitmap { val size = minOf(source.width, source.height) val x = (source.width - size) / 2 val y = (source.height - size) / 2 val squared = Bitmap.createBitmap(source, x, y, size, size) val result = createBitmap(size, size) val canvas = Canvas(result) val paint = Paint(FILTER_BITMAP_FLAG or DITHER_FLAG or ANTI_ALIAS_FLAG) paint.shader = BitmapShader(squared, CLAMP, CLAMP) val r = size / 2f canvas.drawCircle(r, r, r, paint) if (source != result) { source.recycle() } return result } override fun key(): String = javaClass.name }
app/src/main/java/com/benoitquenaudon/tvfoot/red/util/CircleTransform.kt
989513739
/* * Copyright (C) 2022 panpf <[email protected]> * * 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.panpf.sketch import android.widget.ImageView import com.github.panpf.sketch.fetch.newAppIconUri import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.DisplayResult import com.github.panpf.sketch.request.Disposable /** * Load the icon of the installed app and and display it on this [ImageView] * * You can set request params with a trailing lambda function [configBlock] */ fun ImageView.displayAppIconImage( packageName: String, versionCode: Int, configBlock: (DisplayRequest.Builder.() -> Unit)? = null ): Disposable<DisplayResult> = DisplayRequest(this, newAppIconUri(packageName, versionCode), configBlock).enqueue()
sketch-extensions/src/main/java/com/github/panpf/sketch/OtherImageViewExtensions.kt
1348129591
package com.telenav.osv.common.model import android.location.Location data class KVLatLng(var lat: Double = 0.0, var lon: Double = 0.0, var index: Int = 0) { constructor(location: Location, index: Int = 0) : this(location.latitude, location.longitude, index) }
app/src/main/java/com/telenav/osv/common/model/KVLatLng.kt
2994420408
package com.stripe.android.payments.core.injection import com.stripe.android.core.injection.Injectable import com.stripe.android.core.injection.Injector import com.stripe.android.core.injection.WeakMapInjectorRegistry import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull @RunWith(RobolectricTestRunner::class) @ExperimentalCoroutinesApi class WeakMapInjectorRegistryTest { @Before fun clearStaticCache() { WeakMapInjectorRegistry.clear() } @Test fun verifyRegistryRetrievesCorrectObject() { val injector1 = TestInjector() val keyForInjector1 = WeakMapInjectorRegistry.nextKey(requireNotNull(TestInjector::class.simpleName)) val injector2 = TestInjector() val keyForInjector2 = WeakMapInjectorRegistry.nextKey(requireNotNull(TestInjector::class.simpleName)) WeakMapInjectorRegistry.register(injector1, keyForInjector1) WeakMapInjectorRegistry.register(injector2, keyForInjector2) assertEquals(injector1, WeakMapInjectorRegistry.retrieve(keyForInjector1)) assertEquals(injector2, WeakMapInjectorRegistry.retrieve(keyForInjector2)) assertNotEquals( WeakMapInjectorRegistry.retrieve(keyForInjector1), WeakMapInjectorRegistry.retrieve(keyForInjector2) ) } @Suppress("UNUSED_VALUE") @Test fun verifyCacheIsClearedOnceWeakReferenceIsDeReferenced() { var injector1: Injector? = TestInjector() val keyForInjector1 = WeakMapInjectorRegistry.nextKey(requireNotNull(TestInjector::class.simpleName)) WeakMapInjectorRegistry.register(injector1!!, keyForInjector1) assertNotNull(WeakMapInjectorRegistry.retrieve(keyForInjector1)) var retry = 10 // de-reference the injector and hint System.gc to trigger removal injector1 = null while (WeakMapInjectorRegistry.retrieve(keyForInjector1) != null && retry > 0) { System.gc() retry-- } if (retry == 0) { assertNull(WeakMapInjectorRegistry.retrieve(keyForInjector1)) } // otherwise WeakSetInjectorRegistry.retrieve(keyForInjector1) == null, // indicating the entry is already cleared } // calling whenever() on a mock will end up holding the mock instance, therefore a real // Injector instance is needed to ensure System.gc() works correctly. internal class TestInjector : Injector { override fun inject(injectable: Injectable<*>) { // no - op } } }
payments-core/src/test/java/com/stripe/android/payments/core/injection/WeakMapInjectorRegistryTest.kt
1528116223
package mswift42.com.github.wo4 import android.os.Bundle import android.os.Handler import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import kotlinx.android.synthetic.main.fragment_stop_watch.* /** * A simple [Fragment] subclass. */ class StopWatchFragment : Fragment(), View.OnClickListener { private var seconds = 0; private var running = false; private var wasRunning = false; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { seconds = savedInstanceState.getInt("seconds") running = savedInstanceState.getBoolean("running") wasRunning = savedInstanceState.getBoolean("wasRunning") if (wasRunning) { running = true } } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val layout = inflater!!.inflate(R.layout.fragment_stop_watch, container,false) runTimer(layout) val startButton = layout.findViewById(R.id.start_button) as Button startButton.setOnClickListener(this) val stopButton = layout.findViewById(R.id.stop_button) as Button stopButton.setOnClickListener(this) val resetButton = layout.findViewById(R.id.reset_button) as Button resetButton.setOnClickListener(this) return layout } override fun onClick(view: View) { when (view.getId()) { R.id.start_button -> onClickStart(view) R.id.stop_button -> onClickStop(view) R.id.reset_button -> onClickReset(view) } } override public fun onPause() { super.onPause() wasRunning = running running = false } override public fun onResume() { super.onResume(); if (wasRunning) { running = true } } override public fun onSaveInstanceState(savedInstanceState: Bundle?) { savedInstanceState?.putInt("seconds", seconds) savedInstanceState?.putBoolean("running", running) savedInstanceState?.putBoolean("wasRunning", wasRunning) } fun onClickStart(view: View) { running = true } fun onClickStop(view: View) { running = false } fun onClickReset(view: View) { running = false seconds = 0 } private fun runTimer(view: View): Unit { val timeView = view.findViewById(R.id.time_view) as TextView val handler = Handler() val settimer = object : Runnable { override fun run() { val hours = seconds / 3600 val minutes = (seconds % 3600) / 60 val sec = seconds % 60 val time = String.format("%d:%02d:%02d", hours, minutes, sec) timeView.text = time if (running) { seconds++ } handler.postDelayed(this, 1000) } } handler.post(settimer) } }// Required empty public constructor
Wo4/app/src/main/java/mswift42/com/github/wo4/StopWatchFragment.kt
2966465408
/* * 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.camera.camera2.pipe.integration.impl import androidx.annotation.RequiresApi @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java interface UseCaseCameraControl { var useCaseCamera: UseCaseCamera? fun reset() }
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/UseCaseCameraControl.kt
2347986489
/* * 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 com.tealcube.minecraft.bukkit.mythicdrops.errors.MythicLoadingErrorManager import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicItemGroup import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicItemGroupManager import com.tealcube.minecraft.bukkit.mythicdrops.tiers.MythicTier import io.pixeloutlaw.minecraft.spigot.mythicdrops.getMaterials import org.bukkit.Material import org.bukkit.configuration.ConfigurationSection import org.bukkit.configuration.file.YamlConfiguration import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class ItemUtilTest { companion object { private val itemGroupsYaml = YamlConfiguration().apply { loadFromString( ItemUtilTest::class.java.classLoader.getResource("itemGroups_test.yml")!!.readText() ) } private val legendaryTierYaml = YamlConfiguration().apply { loadFromString( ItemUtilTest::class.java.classLoader.getResource("legendary_tier.yml")!!.readText() ) } private val itemGroupManager = MythicItemGroupManager() private val loadingErrorManager = MythicLoadingErrorManager() } @BeforeEach fun setup() { itemGroupManager.clear() loadingErrorManager.clear() itemGroupsYaml.getKeys(false).forEach { key -> if (!itemGroupsYaml.isConfigurationSection(key)) { return@forEach } val itemGroupCs: ConfigurationSection = itemGroupsYaml.getConfigurationSection(key) ?: return@forEach itemGroupManager.add(MythicItemGroup.fromConfigurationSection(itemGroupCs, key)) } } @Test fun `ensure that group doesn't contain wrong material`() { val tier = MythicTier.fromConfigurationSection(legendaryTierYaml, "legendary", itemGroupManager, loadingErrorManager)!! val materials = tier.getMaterials() Assertions.assertFalse(materials.contains(Material.STONE_SHOVEL)) } }
src/test/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/ItemUtilTest.kt
2295881846
package com.exyui.android.debugbottle.components.fragments import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.support.annotation.IdRes import android.text.TextUtils import android.util.Log import android.view.* import android.widget.* import com.exyui.android.debugbottle.components.R import com.exyui.android.debugbottle.components.crash.CrashBlock import com.exyui.android.debugbottle.components.crash.CrashBlockDetailAdapter import com.exyui.android.debugbottle.components.crash.CrashReportFileMgr import java.util.* import java.util.concurrent.Executor import java.util.concurrent.Executors /** * Created by yuriel on 9/13/16. */ class __DisplayCrashBlockFragment: __ContentFragment() { private var rootView: ViewGroup? = null private val mBlockEntries: MutableList<CrashBlock> by lazy { ArrayList<CrashBlock>() } private var mBlockStartTime: String? = null private val mListView by lazy { findViewById(R.id.__dt_canary_display_leak_list) as ListView } private val mFailureView by lazy { findViewById(R.id.__dt_canary_display_leak_failure) as TextView } private val mActionButton by lazy { findViewById(R.id.__dt_canary_action) as Button } private val mMaxStoredBlockCount by lazy { resources.getInteger(R.integer.__block_canary_max_stored_count) } companion object { private val TAG = "__DisplayBlockActivity" private val SHOW_BLOCK_EXTRA = "show_latest" val SHOW_BLOCK_EXTRA_KEY = "BlockStartTime" // @JvmOverloads fun createPendingIntent(context: Context, blockStartTime: String? = null): PendingIntent { // val intent = Intent(context, DisplayHttpBlockActivity::class.java) // intent.putExtra(SHOW_BLOCK_EXTRA, blockStartTime) // intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP // return PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT) // } internal fun classSimpleName(className: String): String { val separator = className.lastIndexOf('.') return if (separator == -1) { className } else { className.substring(separator + 1) } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { if (savedInstanceState != null) { mBlockStartTime = savedInstanceState.getString(SHOW_BLOCK_EXTRA_KEY) } else { val intent = context?.intent if (intent?.hasExtra(SHOW_BLOCK_EXTRA) == true) { mBlockStartTime = intent.getStringExtra(SHOW_BLOCK_EXTRA) } } val rootView = inflater.inflate(R.layout.__dt_canary_display_leak_light, container, false) this.rootView = rootView as ViewGroup setHasOptionsMenu(true) updateUi() return rootView } // No, it's not deprecated. Android lies. // override fun onRetainNonConfigurationInstance(): Any { // return mBlockEntries as Any // } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(SHOW_BLOCK_EXTRA_KEY, mBlockStartTime) } override fun onResume() { super.onResume() LoadBlocks.load(this) } override fun onDestroy() { super.onDestroy() LoadBlocks.forgetActivity() } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { val block = getBlock(mBlockStartTime) if (block != null) { menu.add(R.string.__block_canary_share_leak).setOnMenuItemClickListener { shareBlock(block) true } menu.add(R.string.__block_canary_share_stack_dump).setOnMenuItemClickListener { shareHeapDump(block) true } //return true } //return false } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { mBlockStartTime = null updateUi() } return true } override fun onBackPressed(): Boolean { return if (mBlockStartTime != null) { mBlockStartTime = null updateUi() true } else { super.onBackPressed() } } private fun shareBlock(block: CrashBlock) { val leakInfo = block.toString() val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_TEXT, leakInfo) startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with))) } private fun shareHeapDump(block: CrashBlock) { val heapDumpFile = block.file if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { heapDumpFile?.setReadable(true, false) } val intent = Intent(Intent.ACTION_SEND) intent.type = "application/octet-stream" intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(heapDumpFile)) startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with))) } private fun updateUi() { val block = getBlock(mBlockStartTime) if (block == null) { mBlockStartTime = null } // Reset to defaults mListView.visibility = View.VISIBLE mFailureView.visibility = View.GONE if (block != null) { renderBlockDetail(block) } else { renderBlockList() } } private fun renderBlockList() { val listAdapter = mListView.adapter if (listAdapter is BlockListAdapter) { listAdapter.notifyDataSetChanged() } else { val adapter = BlockListAdapter() mListView.adapter = adapter mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> mBlockStartTime = mBlockEntries[position].time updateUi() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { context?.invalidateOptionsMenu() //val actionBar = actionBar //actionBar?.setDisplayHomeAsUpEnabled(false) } //title = "Http Listener" mActionButton.setText(R.string.__block_canary_delete_all) mActionButton.setOnClickListener { CrashReportFileMgr.deleteLogFiles() mBlockEntries.clear() updateUi() } } mActionButton.visibility = if (mBlockEntries.isEmpty()) View.GONE else View.VISIBLE } private fun renderBlockDetail(block: CrashBlock?) { val listAdapter = mListView.adapter val adapter: CrashBlockDetailAdapter if (listAdapter is CrashBlockDetailAdapter) { adapter = listAdapter } else { adapter = CrashBlockDetailAdapter() mListView.adapter = adapter mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> adapter.toggleRow(position) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { context?.invalidateOptionsMenu() //val actionBar = actionBar //actionBar?.setDisplayHomeAsUpEnabled(true) } mActionButton.visibility = View.VISIBLE mActionButton.setText(R.string.__block_canary_delete) mActionButton.setOnClickListener { if (block != null) { block.file?.delete() mBlockStartTime = null mBlockEntries.remove(block) updateUi() } } } adapter.update(block) //title = "${block?.method}: ${block?.url}" } private fun getBlock(startTime: String?): CrashBlock? { if (TextUtils.isEmpty(startTime)) { return null } return mBlockEntries.firstOrNull { it.time == startTime } } private fun findViewById(@IdRes id: Int): View? = rootView?.findViewById(id) internal inner class BlockListAdapter : BaseAdapter() { override fun getCount(): Int = mBlockEntries.size override fun getItem(position: Int): CrashBlock = mBlockEntries[position] override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.__dt_canary_block_row, parent, false) } val titleView = view!!.findViewById(R.id.__dt_canary_row_text) as TextView @Suppress("UNUSED_VARIABLE") val timeView = view.findViewById(R.id.__dt_canary_row_time) as TextView val block = getItem(position) val index: String = if (position == 0 && mBlockEntries.size == mMaxStoredBlockCount) { "MAX. " } else { "${mBlockEntries.size - position}. " } val title = "$index${block.message}" titleView.text = title //timeView.text = block.time return view } } internal class LoadBlocks(private var fragmentOrNull: __DisplayCrashBlockFragment?) : Runnable { private val mainHandler: Handler = Handler(Looper.getMainLooper()) override fun run() { val blocks = ArrayList<CrashBlock>() val files = CrashReportFileMgr.logFiles if (files != null) { for (blockFile in files) { try { blocks.add(CrashBlock.newInstance(blockFile)) } catch (e: Exception) { // Likely a format change in the blockFile blockFile.delete() Log.e(TAG, "Could not read block log file, deleted :" + blockFile, e) } } Collections.sort(blocks) { lhs, rhs -> rhs.file?.lastModified()?.compareTo((lhs.file?.lastModified())?: 0L)?: 0 } } mainHandler.post { inFlight.remove(this@LoadBlocks) if (fragmentOrNull != null) { fragmentOrNull!!.mBlockEntries.clear() fragmentOrNull!!.mBlockEntries.addAll(blocks) //Log.d("BlockCanary", "load block entries: " + blocks.size()); fragmentOrNull!!.updateUi() } } } companion object { val inFlight: MutableList<LoadBlocks> = ArrayList() private val backgroundExecutor: Executor = Executors.newSingleThreadExecutor() fun load(activity: __DisplayCrashBlockFragment) { val loadBlocks = LoadBlocks(activity) inFlight.add(loadBlocks) backgroundExecutor.execute(loadBlocks) } fun forgetActivity() { for (loadBlocks in inFlight) { loadBlocks.fragmentOrNull = null } inFlight.clear() } } } }
components/src/main/kotlin/com/exyui/android/debugbottle/components/fragments/__DisplayCrashBlockFragment.kt
4075854870
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.docker.build import batect.docker.DockerException import java.nio.file.Files import java.nio.file.Path class DockerIgnoreParser { // Based on https://github.com/docker/cli/blob/master/cli/command/image/build/dockerignore.go and // https://github.com/docker/engine/blob/master/builder/dockerignore/dockerignore.go fun parse(path: Path): DockerImageBuildIgnoreList { if (Files.notExists(path)) { return DockerImageBuildIgnoreList(emptyList()) } val lines = Files.readAllLines(path) val entries = lines .filterNot { it.startsWith('#') } .map { it.trim() } .filterNot { it.isEmpty() } .filterNot { it == "." } .map { if (it == "!") { throw DockerException("The .dockerignore pattern '$it' is invalid.") } if (it.startsWith('!')) { Pair(it.substring(1).trimStart(), true) } else { Pair(it, false) } }.map { (pattern, inverted) -> DockerImageBuildIgnoreEntry(cleanPattern(pattern), inverted) } return DockerImageBuildIgnoreList(entries) } // This needs to match the behaviour of Golang's filepath.Clean() private fun cleanPattern(pattern: String): String { val normalisedPattern = pattern .split("/") .filterNot { it == "" } .filterNot { it == "." } .fold(emptyList<String>()) { soFar, nextSegment -> if (nextSegment != "..") { soFar + nextSegment } else if (soFar.isEmpty()) { if (pattern.startsWith("/")) { emptyList() } else { listOf(nextSegment) } } else if (soFar.last() == "..") { soFar + nextSegment } else { soFar.dropLast(1) } } .joinToString("/") if (normalisedPattern.isEmpty()) { return "." } return normalisedPattern } }
app/src/main/kotlin/batect/docker/build/DockerIgnoreParser.kt
3655074853
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.docker import batect.docker.client.DockerSystemInfoClient import batect.docker.client.DockerVersionInfoRetrievalResult import batect.os.OperatingSystem import batect.os.SystemInfo import batect.utils.Version import batect.utils.VersionComparisonMode class DockerHostNameResolver( private val systemInfo: SystemInfo, private val dockerSystemInfoClient: DockerSystemInfoClient ) { private val dockerVersionInfoRetrievalResult by lazy { dockerSystemInfoClient.getDockerVersionInfo() } fun resolveNameOfDockerHost(): DockerHostNameResolutionResult = when (systemInfo.operatingSystem) { OperatingSystem.Mac -> getDockerHostName("mac") OperatingSystem.Windows -> getDockerHostName("win") OperatingSystem.Linux, OperatingSystem.Other -> DockerHostNameResolutionResult.NotSupported } private fun getDockerHostName(operatingSystemPart: String): DockerHostNameResolutionResult { val version = (dockerVersionInfoRetrievalResult as? DockerVersionInfoRetrievalResult.Succeeded)?.info?.version return when { version == null -> DockerHostNameResolutionResult.NotSupported version.isGreaterThanOrEqualToDockerVersion(Version(18, 3, 0)) -> DockerHostNameResolutionResult.Resolved("host.docker.internal") version.isGreaterThanOrEqualToDockerVersion(Version(17, 12, 0)) -> DockerHostNameResolutionResult.Resolved("docker.for.$operatingSystemPart.host.internal") version.isGreaterThanOrEqualToDockerVersion(Version(17, 6, 0)) -> DockerHostNameResolutionResult.Resolved("docker.for.$operatingSystemPart.localhost") else -> DockerHostNameResolutionResult.NotSupported } } private fun Version.isGreaterThanOrEqualToDockerVersion(dockerVersion: Version): Boolean = this.compareTo(dockerVersion, VersionComparisonMode.DockerStyle) >= 0 } sealed class DockerHostNameResolutionResult { object NotSupported : DockerHostNameResolutionResult() data class Resolved(val hostName: String) : DockerHostNameResolutionResult() }
app/src/main/kotlin/batect/docker/DockerHostNameResolver.kt
4038835811
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.compose import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.layout.FirstBaseline import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.constraintlayout.core.widgets.ConstraintWidget /** * Common scope for [ConstraintLayoutScope] and [ConstraintSetScope], the content being shared * between the inline DSL API and the ConstraintSet-based API. */ abstract class ConstraintLayoutBaseScope { protected val tasks = mutableListOf<(State) -> Unit>() fun applyTo(state: State): Unit = tasks.forEach { it(state) } open fun reset() { tasks.clear() helperId = HelpersStartId helpersHashCode = 0 } @PublishedApi internal var helpersHashCode: Int = 0 private fun updateHelpersHashCode(value: Int) { helpersHashCode = (helpersHashCode * 1009 + value) % 1000000007 } private val HelpersStartId = 1000 private var helperId = HelpersStartId private fun createHelperId() = helperId++ /** * Represents a vertical anchor (e.g. start/end of a layout, guideline) that layouts * can link to in their `Modifier.constrainAs` or `constrain` blocks. * * @param reference The [LayoutReference] that this anchor belongs to. */ @Stable data class VerticalAnchor internal constructor( internal val id: Any, internal val index: Int, val reference: LayoutReference ) /** * Represents a horizontal anchor (e.g. top/bottom of a layout, guideline) that layouts * can link to in their `Modifier.constrainAs` or `constrain` blocks. * * @param reference The [LayoutReference] that this anchor belongs to. */ @Stable data class HorizontalAnchor internal constructor( internal val id: Any, internal val index: Int, val reference: LayoutReference ) /** * Represents a horizontal anchor corresponding to the [FirstBaseline] of a layout that other * layouts can link to in their `Modifier.constrainAs` or `constrain` blocks. * * @param reference The [LayoutReference] that this anchor belongs to. */ // TODO(popam): investigate if this can be just a HorizontalAnchor @Stable data class BaselineAnchor internal constructor( internal val id: Any, val reference: LayoutReference ) /** * Specifies additional constraints associated to the horizontal chain identified with [ref]. */ fun constrain( ref: HorizontalChainReference, constrainBlock: HorizontalChainScope.() -> Unit ): HorizontalChainScope = HorizontalChainScope(ref.id).apply { constrainBlock() [email protected](this.tasks) } /** * Specifies additional constraints associated to the vertical chain identified with [ref]. */ fun constrain( ref: VerticalChainReference, constrainBlock: VerticalChainScope.() -> Unit ): VerticalChainScope = VerticalChainScope(ref.id).apply { constrainBlock() [email protected](this.tasks) } /** * Specifies the constraints associated to the layout identified with [ref]. */ fun constrain( ref: ConstrainedLayoutReference, constrainBlock: ConstrainScope.() -> Unit ): ConstrainScope = ConstrainScope(ref.id).apply { constrainBlock() [email protected](this.tasks) } /** * Creates a guideline at a specific offset from the start of the [ConstraintLayout]. */ fun createGuidelineFromStart(offset: Dp): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.verticalGuideline(id).apply { if (state.layoutDirection == LayoutDirection.Ltr) start(offset) else end(offset) } } updateHelpersHashCode(1) updateHelpersHashCode(offset.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a specific offset from the left of the [ConstraintLayout]. */ fun createGuidelineFromAbsoluteLeft(offset: Dp): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.verticalGuideline(id).apply { start(offset) } } updateHelpersHashCode(2) updateHelpersHashCode(offset.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a specific offset from the start of the [ConstraintLayout]. * A [fraction] of 0f will correspond to the start of the [ConstraintLayout], while 1f will * correspond to the end. */ fun createGuidelineFromStart(fraction: Float): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.verticalGuideline(id).apply { if (state.layoutDirection == LayoutDirection.Ltr) { percent(fraction) } else { percent(1f - fraction) } } } updateHelpersHashCode(3) updateHelpersHashCode(fraction.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a width fraction from the left of the [ConstraintLayout]. * A [fraction] of 0f will correspond to the left of the [ConstraintLayout], while 1f will * correspond to the right. */ // TODO(popam, b/157781990): this is not really percenide fun createGuidelineFromAbsoluteLeft(fraction: Float): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.verticalGuideline(id).apply { percent(fraction) } } updateHelpersHashCode(4) updateHelpersHashCode(fraction.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a specific offset from the end of the [ConstraintLayout]. */ fun createGuidelineFromEnd(offset: Dp): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.verticalGuideline(id).apply { if (state.layoutDirection == LayoutDirection.Ltr) end(offset) else start(offset) } } updateHelpersHashCode(5) updateHelpersHashCode(offset.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a specific offset from the right of the [ConstraintLayout]. */ fun createGuidelineFromAbsoluteRight(offset: Dp): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.verticalGuideline(id).apply { end(offset) } } updateHelpersHashCode(6) updateHelpersHashCode(offset.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a width fraction from the end of the [ConstraintLayout]. * A [fraction] of 0f will correspond to the end of the [ConstraintLayout], while 1f will * correspond to the start. */ fun createGuidelineFromEnd(fraction: Float): VerticalAnchor { return createGuidelineFromStart(1f - fraction) } /** * Creates a guideline at a width fraction from the right of the [ConstraintLayout]. * A [fraction] of 0f will correspond to the right of the [ConstraintLayout], while 1f will * correspond to the left. */ fun createGuidelineFromAbsoluteRight(fraction: Float): VerticalAnchor { return createGuidelineFromAbsoluteLeft(1f - fraction) } /** * Creates a guideline at a specific offset from the top of the [ConstraintLayout]. */ fun createGuidelineFromTop(offset: Dp): HorizontalAnchor { val id = createHelperId() tasks.add { state -> state.horizontalGuideline(id).apply { start(offset) } } updateHelpersHashCode(7) updateHelpersHashCode(offset.hashCode()) return HorizontalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a height percenide from the top of the [ConstraintLayout]. * A [fraction] of 0f will correspond to the top of the [ConstraintLayout], while 1f will * correspond to the bottom. */ fun createGuidelineFromTop(fraction: Float): HorizontalAnchor { val id = createHelperId() tasks.add { state -> state.horizontalGuideline(id).apply { percent(fraction) } } updateHelpersHashCode(8) updateHelpersHashCode(fraction.hashCode()) return HorizontalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a specific offset from the bottom of the [ConstraintLayout]. */ fun createGuidelineFromBottom(offset: Dp): HorizontalAnchor { val id = createHelperId() tasks.add { state -> state.horizontalGuideline(id).apply { end(offset) } } updateHelpersHashCode(9) updateHelpersHashCode(offset.hashCode()) return HorizontalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates a guideline at a height percenide from the bottom of the [ConstraintLayout]. * A [fraction] of 0f will correspond to the bottom of the [ConstraintLayout], while 1f will * correspond to the top. */ fun createGuidelineFromBottom(fraction: Float): HorizontalAnchor { return createGuidelineFromTop(1f - fraction) } /** * Creates and returns a start barrier, containing the specified elements. */ fun createStartBarrier( vararg elements: LayoutReference, margin: Dp = 0.dp ): VerticalAnchor { val id = createHelperId() tasks.add { state -> val direction = if (state.layoutDirection == LayoutDirection.Ltr) { SolverDirection.LEFT } else { SolverDirection.RIGHT } state.barrier(id, direction).apply { add(*(elements.map { it.id }.toTypedArray())) }.margin(state.convertDimension(margin)) } updateHelpersHashCode(10) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(margin.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates and returns a left barrier, containing the specified elements. */ fun createAbsoluteLeftBarrier( vararg elements: LayoutReference, margin: Dp = 0.dp ): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.barrier(id, SolverDirection.LEFT).apply { add(*(elements.map { it.id }.toTypedArray())) }.margin(state.convertDimension(margin)) } updateHelpersHashCode(11) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(margin.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates and returns a top barrier, containing the specified elements. */ fun createTopBarrier( vararg elements: LayoutReference, margin: Dp = 0.dp ): HorizontalAnchor { val id = createHelperId() tasks.add { state -> state.barrier(id, SolverDirection.TOP).apply { add(*(elements.map { it.id }.toTypedArray())) }.margin(state.convertDimension(margin)) } updateHelpersHashCode(12) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(margin.hashCode()) return HorizontalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates and returns an end barrier, containing the specified elements. */ fun createEndBarrier( vararg elements: LayoutReference, margin: Dp = 0.dp ): VerticalAnchor { val id = createHelperId() tasks.add { state -> val direction = if (state.layoutDirection == LayoutDirection.Ltr) { SolverDirection.RIGHT } else { SolverDirection.LEFT } state.barrier(id, direction).apply { add(*(elements.map { it.id }.toTypedArray())) }.margin(state.convertDimension(margin)) } updateHelpersHashCode(13) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(margin.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates and returns a right barrier, containing the specified elements. */ fun createAbsoluteRightBarrier( vararg elements: LayoutReference, margin: Dp = 0.dp ): VerticalAnchor { val id = createHelperId() tasks.add { state -> state.barrier(id, SolverDirection.RIGHT).apply { add(*(elements.map { it.id }.toTypedArray())) }.margin(state.convertDimension(margin)) } updateHelpersHashCode(14) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(margin.hashCode()) return VerticalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * Creates and returns a bottom barrier, containing the specified elements. */ fun createBottomBarrier( vararg elements: LayoutReference, margin: Dp = 0.dp ): HorizontalAnchor { val id = createHelperId() tasks.add { state -> state.barrier(id, SolverDirection.BOTTOM).apply { add(*(elements.map { it.id }.toTypedArray())) }.margin(state.convertDimension(margin)) } updateHelpersHashCode(15) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(margin.hashCode()) return HorizontalAnchor(id, 0, LayoutReferenceImpl(id)) } /** * This creates a flow helper * Flow helpers allows a long sequence of Composable widgets to wrap onto * multiple rows or columns. * [flowVertically] if set to true aranges the Composables from top to bottom. * Normally they are arranged from left to right. * [verticalGap] defines the gap between views in the y axis * [horizontalGap] defines the gap between views in the x axis * [maxElement] defines the maximum element on a row before it if the * [padding] sets padding around the content * [wrapMode] sets the way reach maxElements is handled * Flow.WRAP_NONE (default) -- no wrap behavior, * Flow.WRAP_CHAIN - create additional chains * [verticalAlign] set the way elements are aligned vertically. Center is default * [horizontalAlign] set the way elements are aligned horizontally. Center is default * [horizontalFlowBias] set the way elements are aligned vertically Center is default * [verticalFlowBias] sets the top bottom bias of the vertical chain * [verticalStyle] sets the style of a vertical chain (Spread,Packed, or SpreadInside) * [horizontalStyle] set the style of the horizontal chain (Spread, Packed, or SpreadInside) */ fun createFlow( vararg elements: LayoutReference?, flowVertically: Boolean = false, verticalGap: Dp = 0.dp, horizontalGap: Dp = 0.dp, maxElement: Int = 0, padding: Dp = 0.dp, wrapMode: Wrap = Wrap.None, verticalAlign: VerticalAlign = VerticalAlign.Center, horizontalAlign: HorizontalAlign = HorizontalAlign.Center, horizontalFlowBias: Float = 0.0f, verticalFlowBias: Float = 0.0f, verticalStyle: FlowStyle = FlowStyle.Packed, horizontalStyle: FlowStyle = FlowStyle.Packed, ): ConstrainedLayoutReference { val id = createHelperId() tasks.add { state -> state.getFlow(id, flowVertically).apply { add(*(elements.map { it?.id }.toTypedArray())) horizontalChainStyle = horizontalStyle.style setVerticalChainStyle(verticalStyle.style) verticalBias(verticalFlowBias) horizontalBias(horizontalFlowBias) setHorizontalAlign(horizontalAlign.mode) setVerticalAlign(verticalAlign.mode) setWrapMode(wrapMode.mode) paddingLeft = state.convertDimension(padding) paddingTop = state.convertDimension(padding) paddingRight = state.convertDimension(padding) paddingBottom = state.convertDimension(padding) maxElementsWrap = maxElement setHorizontalGap(state.convertDimension(horizontalGap)) setVerticalGap(state.convertDimension(verticalGap)) } } updateHelpersHashCode(16) elements.forEach { updateHelpersHashCode(it.hashCode()) } return ConstrainedLayoutReference(id) } /** * This creates a flow helper * Flow helpers allows a long sequence of Composable widgets to wrap onto * multiple rows or columns. * [flowVertically] if set to true aranges the Composables from top to bottom. * Normally they are arranged from left to right. * [verticalGap] defines the gap between views in the y axis * [horizontalGap] defines the gap between views in the x axis * [maxElement] defines the maximum element on a row before it if the * [paddingHorizontal] sets paddingLeft and paddingRight of the content * [paddingVertical] sets paddingTop and paddingBottom of the content * [wrapMode] sets the way reach maxElements is handled * Flow.WRAP_NONE (default) -- no wrap behavior, * Flow.WRAP_CHAIN - create additional chains * [verticalAlign] set the way elements are aligned vertically. Center is default * [horizontalAlign] set the way elements are aligned horizontally. Center is default * [horizontalFlowBias] set the way elements are aligned vertically Center is default * [verticalFlowBias] sets the top bottom bias of the vertical chain * [verticalStyle] sets the style of a vertical chain (Spread,Packed, or SpreadInside) * [horizontalStyle] set the style of the horizontal chain (Spread, Packed, or SpreadInside) */ fun createFlow( vararg elements: LayoutReference?, flowVertically: Boolean = false, verticalGap: Dp = 0.dp, horizontalGap: Dp = 0.dp, maxElement: Int = 0, paddingHorizontal: Dp = 0.dp, paddingVertical: Dp = 0.dp, wrapMode: Wrap = Wrap.None, verticalAlign: VerticalAlign = VerticalAlign.Center, horizontalAlign: HorizontalAlign = HorizontalAlign.Center, horizontalFlowBias: Float = 0.0f, verticalFlowBias: Float = 0.0f, verticalStyle: FlowStyle = FlowStyle.Packed, horizontalStyle: FlowStyle = FlowStyle.Packed, ): ConstrainedLayoutReference { val id = createHelperId() tasks.add { state -> state.getFlow(id, flowVertically).apply { add(*(elements.map { it?.id }.toTypedArray())) horizontalChainStyle = horizontalStyle.style setVerticalChainStyle(verticalStyle.style) verticalBias(verticalFlowBias) horizontalBias(horizontalFlowBias) setHorizontalAlign(horizontalAlign.mode) setVerticalAlign(verticalAlign.mode) setWrapMode(wrapMode.mode) paddingLeft = state.convertDimension(paddingHorizontal) paddingTop = state.convertDimension(paddingVertical) paddingRight = state.convertDimension(paddingHorizontal) paddingBottom = state.convertDimension(paddingVertical) maxElementsWrap = maxElement setHorizontalGap(state.convertDimension(horizontalGap)) setVerticalGap(state.convertDimension(verticalGap)) } } updateHelpersHashCode(16) elements.forEach { updateHelpersHashCode(it.hashCode()) } return ConstrainedLayoutReference(id) } /** * This creates a flow helper * Flow helpers allows a long sequence of Composable widgets to wrap onto * multiple rows or columns. * [flowVertically] if set to true aranges the Composables from top to bottom. * Normally they are arranged from left to right. * [verticalGap] defines the gap between views in the y axis * [horizontalGap] defines the gap between views in the x axis * [maxElement] defines the maximum element on a row before it if the * [paddingLeft] sets paddingLeft of the content * [paddingTop] sets paddingTop of the content * [paddingRight] sets paddingRight of the content * [paddingBottom] sets paddingBottom of the content * [wrapMode] sets the way reach maxElements is handled * Flow.WRAP_NONE (default) -- no wrap behavior, * Flow.WRAP_CHAIN - create additional chains * [verticalAlign] set the way elements are aligned vertically. Center is default * [horizontalAlign] set the way elements are aligned horizontally. Center is default * [horizontalFlowBias] set the way elements are aligned vertically Center is default * [verticalFlowBias] sets the top bottom bias of the vertical chain * [verticalStyle] sets the style of a vertical chain (Spread,Packed, or SpreadInside) * [horizontalStyle] set the style of the horizontal chain (Spread, Packed, or SpreadInside) */ fun createFlow( vararg elements: LayoutReference?, flowVertically: Boolean = false, verticalGap: Dp = 0.dp, horizontalGap: Dp = 0.dp, maxElement: Int = 0, paddingLeft: Dp = 0.dp, paddingTop: Dp = 0.dp, paddingRight: Dp = 0.dp, paddingBottom: Dp = 0.dp, wrapMode: Wrap = Wrap.None, verticalAlign: VerticalAlign = VerticalAlign.Center, horizontalAlign: HorizontalAlign = HorizontalAlign.Center, horizontalFlowBias: Float = 0.0f, verticalFlowBias: Float = 0.0f, verticalStyle: FlowStyle = FlowStyle.Packed, horizontalStyle: FlowStyle = FlowStyle.Packed, ): ConstrainedLayoutReference { val id = createHelperId() tasks.add { state -> state.getFlow(id, flowVertically).apply { add(*(elements.map { it?.id }.toTypedArray())) horizontalChainStyle = horizontalStyle.style setVerticalChainStyle(verticalStyle.style) verticalBias(verticalFlowBias) horizontalBias(horizontalFlowBias) setHorizontalAlign(horizontalAlign.mode) setVerticalAlign(verticalAlign.mode) setWrapMode(wrapMode.mode) setPaddingLeft(state.convertDimension(paddingLeft)) setPaddingTop(state.convertDimension(paddingTop)) setPaddingRight(state.convertDimension(paddingRight)) setPaddingBottom(state.convertDimension(paddingBottom)) maxElementsWrap = maxElement setHorizontalGap(state.convertDimension(horizontalGap)) setVerticalGap(state.convertDimension(verticalGap)) } } updateHelpersHashCode(16) elements.forEach { updateHelpersHashCode(it.hashCode()) } return ConstrainedLayoutReference(id) } /** * Creates a horizontal chain including the referenced layouts. * * Use [constrain] with the resulting [HorizontalChainReference] to modify the start/left and * end/right constraints of this chain. */ fun createHorizontalChain( vararg elements: LayoutReference, chainStyle: ChainStyle = ChainStyle.Spread ): HorizontalChainReference { val id = createHelperId() tasks.add { state -> val helper = state.helper( id, androidx.constraintlayout.core.state.State.Helper.HORIZONTAL_CHAIN ) as androidx.constraintlayout.core.state.helpers.HorizontalChainReference elements.forEach { chainElement -> val elementParams = chainElement.getHelperParams() ?: ChainParams.Default helper.addChainElement( chainElement.id, elementParams.weight, state.convertDimension(elementParams.startMargin).toFloat(), state.convertDimension(elementParams.endMargin).toFloat(), state.convertDimension(elementParams.startGoneMargin).toFloat(), state.convertDimension(elementParams.endGoneMargin).toFloat() ) } helper.style(chainStyle.style) helper.apply() if (chainStyle.bias != null) { state.constraints(elements[0].id).horizontalBias(chainStyle.bias) } } updateHelpersHashCode(16) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(chainStyle.hashCode()) return HorizontalChainReference(id) } /** * Creates a vertical chain including the referenced layouts. * * Use [constrain] with the resulting [VerticalChainReference] to modify the top and * bottom constraints of this chain. */ fun createVerticalChain( vararg elements: LayoutReference, chainStyle: ChainStyle = ChainStyle.Spread ): VerticalChainReference { val id = createHelperId() tasks.add { state -> val helper = state.helper( id, androidx.constraintlayout.core.state.State.Helper.VERTICAL_CHAIN ) as androidx.constraintlayout.core.state.helpers.VerticalChainReference elements.forEach { chainElement -> val elementParams = chainElement.getHelperParams() ?: ChainParams.Default helper.addChainElement( chainElement.id, elementParams.weight, state.convertDimension(elementParams.topMargin).toFloat(), state.convertDimension(elementParams.bottomMargin).toFloat(), state.convertDimension(elementParams.topGoneMargin).toFloat(), state.convertDimension(elementParams.bottomGoneMargin).toFloat() ) } helper.style(chainStyle.style) helper.apply() if (chainStyle.bias != null) { state.constraints(elements[0].id).verticalBias(chainStyle.bias) } } updateHelpersHashCode(17) elements.forEach { updateHelpersHashCode(it.hashCode()) } updateHelpersHashCode(chainStyle.hashCode()) return VerticalChainReference(id) } /** * Sets the parameters that are used by chains to customize the resulting layout. * * Use margins to customize the space between widgets in the chain. * * Use weight to distribute available space to each widget when their dimensions are not * fixed. * * &nbsp; * * Similarly named parameters available from [ConstrainScope.linkTo] are ignored in * Chains. * * Since margins are only for widgets within the chain: Top, Start and End, Bottom margins are * ignored when the widget is the first or the last element in the chain, respectively. * * @param startMargin Added space from the start of this widget to the previous widget * @param topMargin Added space from the top of this widget to the previous widget * @param endMargin Added space from the end of this widget to the next widget * @param bottomMargin Added space from the bottom of this widget to the next widget * @param startGoneMargin Added space from the start of this widget when the previous widget has [Visibility.Gone] * @param topGoneMargin Added space from the top of this widget when the previous widget has [Visibility.Gone] * @param endGoneMargin Added space from the end of this widget when the next widget has [Visibility.Gone] * @param bottomGoneMargin Added space from the bottom of this widget when the next widget has [Visibility.Gone] * @param weight Defines the proportion of space (relative to the total weight) occupied by this * layout when the corresponding dimension is not a fixed value. * @return The same [LayoutReference] instance with the applied values */ fun LayoutReference.withChainParams( startMargin: Dp = 0.dp, topMargin: Dp = 0.dp, endMargin: Dp = 0.dp, bottomMargin: Dp = 0.dp, startGoneMargin: Dp = 0.dp, topGoneMargin: Dp = 0.dp, endGoneMargin: Dp = 0.dp, bottomGoneMargin: Dp = 0.dp, weight: Float = Float.NaN, ): LayoutReference = this.apply { setHelperParams( ChainParams( startMargin = startMargin, topMargin = topMargin, endMargin = endMargin, bottomMargin = bottomMargin, startGoneMargin = startGoneMargin, topGoneMargin = topGoneMargin, endGoneMargin = endGoneMargin, bottomGoneMargin = bottomGoneMargin, weight = weight ) ) } /** * Sets the parameters that are used by horizontal chains to customize the resulting layout. * * Use margins to customize the space between widgets in the chain. * * Use weight to distribute available space to each widget when their horizontal dimension is * not fixed. * * &nbsp; * * Similarly named parameters available from [ConstrainScope.linkTo] are ignored in * Chains. * * Since margins are only for widgets within the chain: Start and End margins are * ignored when the widget is the first or the last element in the chain, respectively. * * @param startMargin Added space from the start of this widget to the previous widget * @param endMargin Added space from the end of this widget to the next widget * @param startGoneMargin Added space from the start of this widget when the previous widget has [Visibility.Gone] * @param endGoneMargin Added space from the end of this widget when the next widget has [Visibility.Gone] * @param weight Defines the proportion of space (relative to the total weight) occupied by this * layout when the width is not a fixed dimension. * @return The same [LayoutReference] instance with the applied values */ fun LayoutReference.withHorizontalChainParams( startMargin: Dp = 0.dp, endMargin: Dp = 0.dp, startGoneMargin: Dp = 0.dp, endGoneMargin: Dp = 0.dp, weight: Float = Float.NaN ): LayoutReference = withChainParams( startMargin = startMargin, topMargin = 0.dp, endMargin = endMargin, bottomMargin = 0.dp, startGoneMargin = startGoneMargin, topGoneMargin = 0.dp, endGoneMargin = endGoneMargin, bottomGoneMargin = 0.dp, weight = weight ) /** * Sets the parameters that are used by vertical chains to customize the resulting layout. * * Use margins to customize the space between widgets in the chain. * * Use weight to distribute available space to each widget when their vertical dimension is not * fixed. * * &nbsp; * * Similarly named parameters available from [ConstrainScope.linkTo] are ignored in * Chains. * * Since margins are only for widgets within the chain: Top and Bottom margins are * ignored when the widget is the first or the last element in the chain, respectively. * * @param topMargin Added space from the top of this widget to the previous widget * @param bottomMargin Added space from the bottom of this widget to the next widget * @param topGoneMargin Added space from the top of this widget when the previous widget has [Visibility.Gone] * @param bottomGoneMargin Added space from the bottom of this widget when the next widget has [Visibility.Gone] * @param weight Defines the proportion of space (relative to the total weight) occupied by this * layout when the height is not a fixed dimension. * @return The same [LayoutReference] instance with the applied values */ fun LayoutReference.withVerticalChainParams( topMargin: Dp = 0.dp, bottomMargin: Dp = 0.dp, topGoneMargin: Dp = 0.dp, bottomGoneMargin: Dp = 0.dp, weight: Float = Float.NaN ): LayoutReference = withChainParams( startMargin = 0.dp, topMargin = topMargin, endMargin = 0.dp, bottomMargin = bottomMargin, startGoneMargin = 0.dp, topGoneMargin = topGoneMargin, endGoneMargin = 0.dp, bottomGoneMargin = bottomGoneMargin, weight = weight ) } /** * Represents a [ConstraintLayout] item that requires a unique identifier. Typically a layout or a * helper such as barriers, guidelines or chains. */ @Stable abstract class LayoutReference internal constructor(internal open val id: Any) { /** * This map should be used to store one instance of different implementations of [HelperParams]. */ private val helperParamsMap: MutableMap<String, HelperParams> = mutableMapOf() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as LayoutReference if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } internal fun setHelperParams(helperParams: HelperParams) { // Use the class name to force one instance per implementation helperParamsMap[helperParams.javaClass.simpleName] = helperParams } /** * Returns the [HelperParams] that corresponds to the class type [T]. Null if no instance of * type [T] has been set. */ internal inline fun <reified T> getHelperParams(): T? where T : HelperParams { return helperParamsMap[T::class.java.simpleName] as? T } } /** * Helpers that need parameters on a per-widget basis may implement this interface to store custom * parameters within [LayoutReference]. * * @see [LayoutReference.getHelperParams] * @see [LayoutReference.setHelperParams] */ internal interface HelperParams /** * Parameters that may be defined for each widget within a chain. * * These will always be used instead of similarly named parameters defined with other calls such as * [ConstrainScope.linkTo]. */ internal class ChainParams( val startMargin: Dp, val topMargin: Dp, val endMargin: Dp, val bottomMargin: Dp, val startGoneMargin: Dp, val topGoneMargin: Dp, val endGoneMargin: Dp, val bottomGoneMargin: Dp, val weight: Float, ) : HelperParams { companion object { internal val Default = ChainParams( startMargin = 0.dp, topMargin = 0.dp, endMargin = 0.dp, bottomMargin = 0.dp, startGoneMargin = 0.dp, topGoneMargin = 0.dp, endGoneMargin = 0.dp, bottomGoneMargin = 0.dp, weight = Float.NaN ) } } /** * Basic implementation of [LayoutReference], used as fallback for items that don't fit other * implementations of [LayoutReference], such as [ConstrainedLayoutReference]. */ @Stable internal class LayoutReferenceImpl internal constructor(id: Any) : LayoutReference(id) /** * Represents a layout within a [ConstraintLayout]. * * This is a [LayoutReference] that may be constrained to other elements. */ @Stable class ConstrainedLayoutReference(override val id: Any) : LayoutReference(id) { /** * The start anchor of this layout. Represents left in LTR layout direction, or right in RTL. */ @Stable val start = ConstraintLayoutBaseScope.VerticalAnchor(id, -2, this) /** * The left anchor of this layout. */ @Stable val absoluteLeft = ConstraintLayoutBaseScope.VerticalAnchor(id, 0, this) /** * The top anchor of this layout. */ @Stable val top = ConstraintLayoutBaseScope.HorizontalAnchor(id, 0, this) /** * The end anchor of this layout. Represents right in LTR layout direction, or left in RTL. */ @Stable val end = ConstraintLayoutBaseScope.VerticalAnchor(id, -1, this) /** * The right anchor of this layout. */ @Stable val absoluteRight = ConstraintLayoutBaseScope.VerticalAnchor(id, 1, this) /** * The bottom anchor of this layout. */ @Stable val bottom = ConstraintLayoutBaseScope.HorizontalAnchor(id, 1, this) /** * The baseline anchor of this layout. */ @Stable val baseline = ConstraintLayoutBaseScope.BaselineAnchor(id, this) } /** * Represents a horizontal chain within a [ConstraintLayout]. * * The anchors correspond to the first and last elements in the chain. */ @Stable class HorizontalChainReference internal constructor(id: Any) : LayoutReference(id) { /** * The start anchor of the first element in the chain. * * Represents left in LTR layout direction, or right in RTL. */ @Stable val start = ConstraintLayoutBaseScope.VerticalAnchor(id, -2, this) /** * The left anchor of the first element in the chain. */ @Stable val absoluteLeft = ConstraintLayoutBaseScope.VerticalAnchor(id, 0, this) /** * The end anchor of the last element in the chain. * * Represents right in LTR layout direction, or left in RTL. */ @Stable val end = ConstraintLayoutBaseScope.VerticalAnchor(id, -1, this) /** * The right anchor of the last element in the chain. */ @Stable val absoluteRight = ConstraintLayoutBaseScope.VerticalAnchor(id, 1, this) } /** * Represents a vertical chain within a [ConstraintLayout]. * * The anchors correspond to the first and last elements in the chain. */ @Stable class VerticalChainReference internal constructor(id: Any) : LayoutReference(id) { /** * The top anchor of the first element in the chain. */ @Stable val top = ConstraintLayoutBaseScope.HorizontalAnchor(id, 0, this) /** * The bottom anchor of the last element in the chain. */ @Stable val bottom = ConstraintLayoutBaseScope.HorizontalAnchor(id, 1, this) } /** * The style of a horizontal or vertical chain. */ @Immutable class ChainStyle internal constructor( internal val style: SolverChain, internal val bias: Float? = null ) { companion object { /** * A chain style that evenly distributes the contained layouts. */ @Stable val Spread = ChainStyle(SolverChain.SPREAD) /** * A chain style where the first and last layouts are affixed to the constraints * on each end of the chain and the rest are evenly distributed. */ @Stable val SpreadInside = ChainStyle(SolverChain.SPREAD_INSIDE) /** * A chain style where the contained layouts are packed together and placed to the * center of the available space. */ @Stable val Packed = Packed(0.5f) /** * A chain style where the contained layouts are packed together and placed in * the available space according to a given [bias]. */ @Stable fun Packed(bias: Float) = ChainStyle(SolverChain.PACKED, bias) } } /** * The overall visibility of a widget in a [ConstraintLayout]. */ @Immutable class Visibility internal constructor( internal val solverValue: Int ) { companion object { /** * Indicates that the widget will be painted in the [ConstraintLayout]. All render-time * transforms will apply normally. */ @Stable val Visible = Visibility(ConstraintWidget.VISIBLE) /** * The widget will not be painted in the [ConstraintLayout] but its dimensions and constraints * will still apply. * * Equivalent to forcing the alpha to 0.0. */ @Stable val Invisible = Visibility(ConstraintWidget.INVISIBLE) /** * Like [Invisible], but the dimensions of the widget will collapse to (0,0), the * constraints will still apply. */ @Stable val Gone = Visibility(ConstraintWidget.GONE) } } /** * Wrap defines the type of chain */ @Immutable class Wrap internal constructor( internal val mode: Int ) { companion object { val None = Wrap(androidx.constraintlayout.core.widgets.Flow.WRAP_NONE) val Chain = Wrap(androidx.constraintlayout.core.widgets.Flow.WRAP_CHAIN) val Aligned = Wrap(androidx.constraintlayout.core.widgets.Flow.WRAP_ALIGNED) } } /** * Defines how objects align vertically within the chain */ @Immutable class VerticalAlign internal constructor( internal val mode: Int ) { companion object { val Top = VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_TOP) val Bottom = VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_BOTTOM) val Center = VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_CENTER) val Baseline = VerticalAlign(androidx.constraintlayout.core.widgets.Flow.VERTICAL_ALIGN_BASELINE) } } /** * Defines how objects align horizontally in the chain */ @Immutable class HorizontalAlign internal constructor( internal val mode: Int ) { companion object { val Start = HorizontalAlign(androidx.constraintlayout.core.widgets.Flow.HORIZONTAL_ALIGN_START) val End = HorizontalAlign(androidx.constraintlayout.core.widgets.Flow.HORIZONTAL_ALIGN_END) val Center = HorizontalAlign(androidx.constraintlayout.core.widgets.Flow.HORIZONTAL_ALIGN_CENTER) } } /** * Defines how widgets are spaced in a chain */ @Immutable class FlowStyle internal constructor( internal val style: Int ) { companion object { val Spread = FlowStyle(0) val SpreadInside = FlowStyle(1) val Packed = FlowStyle(2) } }
constraintlayout/constraintlayout-compose/src/androidMain/kotlin/androidx/constraintlayout/compose/ConstraintLayoutBaseScope.kt
1566487265
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.input import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.os.Build import android.util.Log import android.view.View import android.view.Window import android.view.inputmethod.ExtractedText import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.compose.ui.window.DialogWindowProvider import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat internal interface InputMethodManager { fun restartInput() fun showSoftInput() fun hideSoftInput() fun updateExtractedText( token: Int, extractedText: ExtractedText ) fun updateSelection( selectionStart: Int, selectionEnd: Int, compositionStart: Int, compositionEnd: Int ) } /** * Wrapper class to prevent depending on getSystemService and final InputMethodManager. * Let's us test TextInputServiceAndroid class. */ internal class InputMethodManagerImpl(private val view: View) : InputMethodManager { private val imm by lazy(LazyThreadSafetyMode.NONE) { view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager } private val helper = if (Build.VERSION.SDK_INT < 30) { ImmHelper21(view) } else { ImmHelper30(view) } override fun restartInput() { imm.restartInput(view) } override fun showSoftInput() { if (DEBUG && !view.hasWindowFocus()) { Log.d(TAG, "InputMethodManagerImpl: requesting soft input on non focused field") } helper.showSoftInput(imm) } override fun hideSoftInput() { helper.hideSoftInput(imm) } override fun updateExtractedText( token: Int, extractedText: ExtractedText ) { imm.updateExtractedText(view, token, extractedText) } override fun updateSelection( selectionStart: Int, selectionEnd: Int, compositionStart: Int, compositionEnd: Int ) { imm.updateSelection(view, selectionStart, selectionEnd, compositionStart, compositionEnd) } } private interface ImmHelper { fun showSoftInput(imm: android.view.inputmethod.InputMethodManager) fun hideSoftInput(imm: android.view.inputmethod.InputMethodManager) } private class ImmHelper21(private val view: View) : ImmHelper { @DoNotInline override fun showSoftInput(imm: android.view.inputmethod.InputMethodManager) { view.post { imm.showSoftInput(view, 0) } } @DoNotInline override fun hideSoftInput(imm: android.view.inputmethod.InputMethodManager) { imm.hideSoftInputFromWindow(view.windowToken, 0) } } @RequiresApi(30) private class ImmHelper30(private val view: View) : ImmHelper { /** * Get a [WindowInsetsControllerCompat] for the view. This returns a new instance every time, * since the view may return null or not null at different times depending on window attach * state. */ private val insetsControllerCompat // This can return null when, for example, the view is not attached to a window. get() = view.findWindow()?.let { WindowInsetsControllerCompat(it, view) } /** * This class falls back to the legacy implementation when the window insets controller isn't * available. */ private val immHelper21: ImmHelper21 get() = _immHelper21 ?: ImmHelper21(view).also { _immHelper21 = it } private var _immHelper21: ImmHelper21? = null @DoNotInline override fun showSoftInput(imm: android.view.inputmethod.InputMethodManager) { insetsControllerCompat?.apply { show(WindowInsetsCompat.Type.ime()) } ?: immHelper21.showSoftInput(imm) } @DoNotInline override fun hideSoftInput(imm: android.view.inputmethod.InputMethodManager) { insetsControllerCompat?.apply { hide(WindowInsetsCompat.Type.ime()) } ?: immHelper21.hideSoftInput(imm) } // TODO(b/221889664) Replace with composition local when available. private fun View.findWindow(): Window? = (parent as? DialogWindowProvider)?.window ?: context.findWindow() private tailrec fun Context.findWindow(): Window? = when (this) { is Activity -> window is ContextWrapper -> baseContext.findWindow() else -> null } }
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/text/input/InputMethodManager.kt
2912499092
import testpackage.SimpleClass val x: <caret>SimpleClass? = null // SRC: testpackage/testfile.kt // TARGET: (testpackage).SimpleClass
kotlin-eclipse-ui-test/testData/navigation/lib/class.kt
2388875479
package me.proxer.app.ui.view.bbcode import me.proxer.app.ui.view.bbcode.prototype.BBPrototype import me.proxer.app.ui.view.bbcode.prototype.ConditionalTextMutatorPrototype import me.proxer.app.ui.view.bbcode.prototype.TextMutatorPrototype import me.proxer.app.ui.view.bbcode.prototype.TextPrototype import me.proxer.app.util.extension.unsafeLazy /** * @author Ruben Gees */ class BBTree( val prototype: BBPrototype, val parent: BBTree?, val children: MutableList<BBTree> = mutableListOf(), val args: BBArgs = BBArgs() ) { fun endsWith(code: String) = prototype.endRegex.matches(code) fun makeViews(parent: BBCodeView, args: BBArgs) = prototype.makeViews(parent, children, args + this.args) fun optimize(args: BBArgs = BBArgs()) = recursiveOptimize(args).first() private fun recursiveOptimize(args: BBArgs): List<BBTree> { val recursiveNewChildren by unsafeLazy { getRecursiveChildren(children) } val canOptimize = prototype !is ConditionalTextMutatorPrototype || prototype.canOptimize(recursiveNewChildren) if (prototype is TextMutatorPrototype && canOptimize) { recursiveNewChildren.forEach { if (it.prototype == TextPrototype) { val mergedArgs = args + this.args + it.args it.args.text = prototype.mutate(it.args.safeText.toSpannableStringBuilder(), mergedArgs) } } } val newChildren = mergeChildren(children.flatMap { it.recursiveOptimize(args) }) return when { canOptimize && prototype is TextMutatorPrototype -> newChildren.map { BBTree(it.prototype, parent, it.children, it.args) } else -> { children.clear() children.addAll(newChildren) listOf(this) } } } private fun mergeChildren(newChildren: List<BBTree>): List<BBTree> { val result = mutableListOf<BBTree>() if (newChildren.isNotEmpty()) { var current = newChildren.first() newChildren.drop(1).forEach { next -> if (current.prototype == TextPrototype && next.prototype == TextPrototype) { current.args.text = current.args.safeText.toSpannableStringBuilder().append(next.args.safeText) } else { result += current current = next } } result += current } return result } private fun getRecursiveChildren(current: List<BBTree>): List<BBTree> = current .plus(current.flatMap { getRecursiveChildren(it.children) }) @Suppress("EqualsAlwaysReturnsTrueOrFalse") // False positive override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BBTree if (prototype != other.prototype) return false if (children != other.children) return false if (args != other.args) return false return true } override fun hashCode(): Int { var result = prototype.hashCode() result = 31 * result + children.hashCode() result = 31 * result + args.hashCode() return result } }
src/main/kotlin/me/proxer/app/ui/view/bbcode/BBTree.kt
1854620658
package com.tomclaw.drawa.share import java.io.File data class ShareResult( val file: File, val mime: String )
app/src/main/java/com/tomclaw/drawa/share/ShareResult.kt
1855756307
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.service import org.andstatus.app.context.MyContextHolder import org.andstatus.app.timeline.ViewItem /** * @author [email protected] */ class QueueData protected constructor(val queueType: QueueType, val commandData: CommandData) : ViewItem<QueueData>(false, commandData.getCreatedDate()), Comparable<QueueData> { override fun getId(): Long { return commandData.hashCode().toLong() } override fun getDate(): Long { return commandData.getCreatedDate() } fun toSharedSubject(): String { return (queueType.acronym + "; " + commandData.toCommandSummary( MyContextHolder.myContextHolder.getNow())) } fun toSharedText(): String { return (queueType.acronym + "; " + commandData.share( MyContextHolder.myContextHolder.getNow())) } override operator fun compareTo(other: QueueData): Int { return -longCompare(getDate(), other.getDate()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val queueData = other as QueueData return if (queueType != queueData.queueType) false else commandData.getCreatedDate() == queueData.commandData.getCreatedDate() } override fun hashCode(): Int { var result = queueType.hashCode() result = 31 * result + (commandData.getCreatedDate() xor (commandData.getCreatedDate() ushr 32)).toInt() return result } companion object { val EMPTY: QueueData = QueueData(QueueType.UNKNOWN, CommandData.EMPTY) fun getNew(queueType: QueueType, commandData: CommandData): QueueData { return QueueData(queueType, commandData) } // TODO: Replace with Long.compare for API >= 19 private fun longCompare(lhs: Long, rhs: Long): Int { return if (lhs < rhs) -1 else if (lhs == rhs) 0 else 1 } } }
app/src/main/kotlin/org/andstatus/app/service/QueueData.kt
807736515
package ru.fantlab.android.ui.modules.classificator.age import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Classificator import ru.fantlab.android.data.dao.model.ClassificatorModel import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.viewholder.ClassificatorViewHolder import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.classificator.ClassificatorPagerMvp import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import java.util.* class ClassificationAgeFragment : BaseFragment<ClassificationAgeMvp.View, ClassificationAgePresenter>(), ClassificationAgeMvp.View { private var pagerCallback: ClassificatorPagerMvp.View? = null var selectedItems = 0 override fun fragmentLayout() = R.layout.micro_grid_refresh_list override fun providePresenter() = ClassificationAgePresenter() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { presenter.onFragmentCreated(arguments!!) } override fun onInitViews(classificators: ArrayList<ClassificatorModel>) { hideProgress() fastScroller.attachRecyclerView(recycler) refresh.setOnRefreshListener(this) val nodes = arrayListOf<TreeNode<*>>() classificators.forEach { val root = TreeNode(Classificator(it.name, it.descr, it.id)) nodes.add(root) work(it, root, false) } val adapter = TreeViewAdapter(nodes, Arrays.asList(ClassificatorViewHolder())) recycler.adapter = adapter adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener { override fun onSelected(extra: Int, add: Boolean) { if (add) selectedItems++ else selectedItems-- onSetTabCount(selectedItems) pagerCallback?.onSelected(extra, add) } override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean { val viewHolder = holder as ClassificatorViewHolder.ViewHolder val state = viewHolder.checkbox.isChecked if (!node.isLeaf) { onToggle(!node.isExpand, holder) if (!state && !node.isExpand) { viewHolder.checkbox.isChecked = true } } else { viewHolder.checkbox.isChecked = !state } return false } override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) { val viewHolder = holder as ClassificatorViewHolder.ViewHolder val ivArrow = viewHolder.arrow val rotateDegree = if (isExpand) 90.0f else -90.0f ivArrow.animate().rotationBy(rotateDegree) .start() } }) } private fun work(it: ClassificatorModel, root: TreeNode<Classificator>, lastLevel: Boolean) { if (it.childs != null) { val counter = root.childList.size - 1 it.childs.forEach { val child = TreeNode(Classificator(it.name, it.descr, it.id)) if (lastLevel) { val childB = TreeNode(Classificator(it.name, it.descr, it.id)) root.childList[counter].addChild(childB) } else root.addChild(child) work(it, root, true) } } } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showErrorMessage(msgRes: String?) { hideProgress() super.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun onClick(v: View?) { onRefresh() } override fun onRefresh() { hideProgress() } fun onSetTabCount(count: Int) { pagerCallback?.onSetBadge(6, count) } override fun onAttach(context: Context) { super.onAttach(context) if (context is ClassificatorPagerMvp.View) { pagerCallback = context } } override fun onDetach() { pagerCallback = null super.onDetach() } companion object { fun newInstance(workId: Int): ClassificationAgeFragment { val view = ClassificationAgeFragment() view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end() return view } } }
app/src/main/kotlin/ru/fantlab/android/ui/modules/classificator/age/ClassificationAgeFragment.kt
767553445
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.common.certificates.testing import java.security.PrivateKey import java.security.cert.X509Certificate import org.wfanet.panelmatch.common.certificates.CertificateAuthority object TestCertificateAuthority : CertificateAuthority { override suspend fun generateX509CertificateAndPrivateKey(): Pair<X509Certificate, PrivateKey> { return TestCertificateManager.CERTIFICATE to TestCertificateManager.PRIVATE_KEY } }
src/main/kotlin/org/wfanet/panelmatch/common/certificates/testing/TestCertificateAuthority.kt
1130249193
/** * Copyright © MyCollab * * 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.mycollab.module.user.accountsettings.view.parameters import com.mycollab.vaadin.mvp.ScreenData /** * @author MyCollab Ltd * @since 6.0.0 */ object AccountModuleScreenData { class GotoModule(source: Array<String>?) : ScreenData<Array<String>>(source) }
mycollab-web/src/main/java/com/mycollab/module/user/accountsettings/view/parameters/AccountModuleScreenData.kt
1108462319
package gl3 import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.KeyListener import com.jogamp.newt.event.WindowAdapter import com.jogamp.newt.event.WindowEvent import com.jogamp.newt.opengl.GLWindow import com.jogamp.opengl.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.util.Animator import com.jogamp.opengl.util.GLBuffers import glm.set import uno.buffer.toFloatBuffer /** * Created by GBarbieri on 27.03.2017. */ fun main(args: Array<String>) { GL_injection_().setup() } class GL_injection_ : GLEventListener, KeyListener { lateinit var window: GLWindow lateinit var animator:Animator val clearColor = floatArrayOf(0f, 0f, 0f, 0f).toFloatBuffer() fun setup() { val glProfile = GLProfile.get(GLProfile.GL3) val glCapabilities = GLCapabilities(glProfile) window = GLWindow.create(glCapabilities) window.title = "gl injection" window.setSize(1024, 768) window.addGLEventListener(this) window.addKeyListener(this) window.autoSwapBufferMode = false window.isVisible = true animator = Animator(window) animator.start() window.addWindowListener(object : WindowAdapter() { override fun windowDestroyed(e: WindowEvent?) { animator.stop() System.exit(1) } }) } override fun init(drawable: GLAutoDrawable) {} override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) {} override fun display(drawable: GLAutoDrawable) {} override fun dispose(drawable: GLAutoDrawable) {} override fun keyPressed(e: KeyEvent) { if (e.keyCode == KeyEvent.VK_ESCAPE) Thread { window.destroy() }.start() when (e.keyCode) { KeyEvent.VK_R -> modified(0) KeyEvent.VK_G -> modified(1) KeyEvent.VK_B -> modified(2) KeyEvent.VK_A -> modified(3) } } fun modified(index: Int) { clearColor[index] = if (clearColor[index] == 0f) 1f else 0f println("clear color: (" + clearColor[0] + ", " + clearColor[1] + ", " + clearColor[2] + ", " + clearColor[3] + ")") window.invoke(false) { drawable -> drawable.gl.gL3.glClearBufferfv(GL_COLOR, 0, clearColor) drawable.swapBuffers() true } } override fun keyReleased(e: KeyEvent) {} }
src/main/kotlin/gl3/gl_injection.kt
3837626603
package de.pbauerochse.worklogviewer.plugins.actions /** * Represents an menu item in the plugins menu of the main * application. When the user clicks on the specific menu * item, the actionHandler will be invoked by the main application */ interface PluginMenuItem { /** * The name / label of the menu item */ val name: String /** * The actionHandler that will be invoked when the menu item is clicked */ val actionHandler: PluginActionHandler }
plugin-api/src/main/java/de/pbauerochse/worklogviewer/plugins/actions/PluginMenuItem.kt
3491187829
package lt.neworld.spanner import android.text.style.StyleSpan import java.util.* internal class StyleSpanBuilder(private val style: Int) : SpanBuilder { override fun build(): Any = StyleSpan(style) }
lib/src/main/java/lt/neworld/spanner/StyleSpanBuilder.kt
192412107
package com.polidea.rxandroidble2.samplekotlin.util import android.bluetooth.BluetoothGattCharacteristic fun BluetoothGattCharacteristic.hasProperty(property: Int): Boolean = (properties and property) > 0
sample-kotlin/src/main/kotlin/com/polidea/rxandroidble2/samplekotlin/util/BluetoothGatt.kt
3417493435
package de.westnordost.streetcomplete.user import android.os.Bundle import android.view.View import android.view.ViewGroup import android.view.ViewPropertyAnimator import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.view.animation.OvershootInterpolator import androidx.fragment.app.Fragment import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.util.Transforms import de.westnordost.streetcomplete.util.animateFrom import de.westnordost.streetcomplete.util.animateTo import de.westnordost.streetcomplete.util.applyTransforms /** It is not a real dialog because a real dialog has its own window, or in other words, has a * different root view than the rest of the UI. However, for the calculation to animate the icon * from another view to the position in the "dialog", there must be a common root view.*/ abstract class AbstractInfoFakeDialogFragment(layoutId: Int) : Fragment(layoutId) { /** View from which the title image view is animated from (and back on dismissal)*/ private var sharedTitleView: View? = null var isShowing: Boolean = false private set // need to keep the animators here to be able to clear them on cancel private val currentAnimators: MutableList<ViewPropertyAnimator> = mutableListOf() private lateinit var dialogAndBackgroundContainer: ViewGroup private lateinit var dialogBackground: View private lateinit var dialogContentContainer: ViewGroup private lateinit var dialogBubbleBackground: View private lateinit var titleView: View /* ---------------------------------------- Lifecycle --------------------------------------- */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dialogAndBackgroundContainer = view.findViewById(R.id.dialogAndBackgroundContainer) dialogBackground = view.findViewById(R.id.dialogBackground) titleView = view.findViewById(R.id.titleView) dialogContentContainer = view.findViewById(R.id.dialogContentContainer) dialogBubbleBackground = view.findViewById(R.id.dialogBubbleBackground) dialogAndBackgroundContainer.setOnClickListener { dismiss() } } override fun onDestroy() { super.onDestroy() sharedTitleView = null clearAnimators() } /* ---------------------------------------- Interface --------------------------------------- */ open fun dismiss(): Boolean { if (currentAnimators.isNotEmpty()) return false isShowing = false animateOut(sharedTitleView) return true } protected fun show(sharedView: View): Boolean { if (currentAnimators.isNotEmpty()) return false isShowing = true this.sharedTitleView = sharedView animateIn(sharedView) return true } /* ----------------------------------- Animating in and out --------------------------------- */ private fun animateIn(sharedView: View) { dialogAndBackgroundContainer.visibility = View.VISIBLE currentAnimators.addAll( createDialogPopInAnimations() + listOf( createTitleImageFlingInAnimation(sharedView), createFadeInBackgroundAnimation() ) ) currentAnimators.forEach { it.start() } } private fun animateOut(sharedView: View?) { currentAnimators.addAll(createDialogPopOutAnimations()) if (sharedView != null) currentAnimators.add(createTitleImageFlingOutAnimation(sharedView)) currentAnimators.add(createFadeOutBackgroundAnimation()) currentAnimators.forEach { it.start() } } private fun createFadeInBackgroundAnimation(): ViewPropertyAnimator { dialogBackground.alpha = 0f return dialogBackground.animate() .alpha(1f) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(DecelerateInterpolator()) .withEndAction { currentAnimators.clear() } } private fun createFadeOutBackgroundAnimation(): ViewPropertyAnimator { return dialogBackground.animate() .alpha(0f) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateInterpolator()) .withEndAction { dialogAndBackgroundContainer.visibility = View.INVISIBLE currentAnimators.clear() } } private fun createTitleImageFlingInAnimation(sourceView: View): ViewPropertyAnimator { sourceView.visibility = View.INVISIBLE val root = sourceView.rootView as ViewGroup titleView.applyTransforms(Transforms.IDENTITY) return titleView.animateFrom(sourceView, root) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(OvershootInterpolator()) } private fun createTitleImageFlingOutAnimation(targetView: View): ViewPropertyAnimator { val root = targetView.rootView as ViewGroup return titleView.animateTo(targetView, root) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateDecelerateInterpolator()) .withEndAction { targetView.visibility = View.VISIBLE sharedTitleView = null } } private fun createDialogPopInAnimations(): List<ViewPropertyAnimator> { return listOf(dialogContentContainer, dialogBubbleBackground).map { it.alpha = 0f it.scaleX = 0.5f it.scaleY = 0.5f it.translationY = 0f it.animate() .alpha(1f) .scaleX(1f).scaleY(1f) .setDuration(ANIMATION_TIME_IN_MS) .setInterpolator(OvershootInterpolator()) } } private fun createDialogPopOutAnimations(): List<ViewPropertyAnimator> { return listOf(dialogContentContainer, dialogBubbleBackground).map { it.animate() .alpha(0f) .scaleX(0.5f).scaleY(0.5f) .translationYBy(it.height * 0.2f) .setDuration(ANIMATION_TIME_OUT_MS) .setInterpolator(AccelerateInterpolator()) } } private fun clearAnimators() { for (anim in currentAnimators) { anim.cancel() } currentAnimators.clear() } companion object { const val ANIMATION_TIME_IN_MS = 600L const val ANIMATION_TIME_OUT_MS = 300L } }
app/src/main/java/de/westnordost/streetcomplete/user/AbstractInfoFakeDialogFragment.kt
1240558855
package de.westnordost.streetcomplete.data.osmnotes.notequests import de.westnordost.osmapi.notes.Note import org.junit.Before import de.westnordost.streetcomplete.data.quest.QuestStatus import de.westnordost.streetcomplete.data.osm.upload.ConflictException import de.westnordost.streetcomplete.on import de.westnordost.streetcomplete.any import org.junit.Test import org.mockito.Mockito.* import de.westnordost.osmapi.map.data.OsmLatLon import de.westnordost.streetcomplete.data.osmnotes.ImageUploadException import de.westnordost.streetcomplete.data.osmnotes.OsmNoteWithPhotosUploader import de.westnordost.streetcomplete.mock import org.junit.Assert.assertEquals import java.util.concurrent.atomic.AtomicBoolean class OsmNoteQuestsChangesUploaderTest { private lateinit var osmNoteQuestController: OsmNoteQuestController private lateinit var singleNoteUploader: OsmNoteWithPhotosUploader private lateinit var uploader: OsmNoteQuestsChangesUploader @Before fun setUp() { osmNoteQuestController = mock() singleNoteUploader = mock() uploader = OsmNoteQuestsChangesUploader(osmNoteQuestController, singleNoteUploader) } @Test fun `cancel upload works`() { uploader.upload(AtomicBoolean(true)) verifyZeroInteractions(singleNoteUploader, osmNoteQuestController) } @Test fun `catches conflict exception`() { on(osmNoteQuestController.getAllAnswered()).thenReturn(listOf(createQuest())) on(singleNoteUploader.comment(anyLong(),any(),any())).thenThrow(ConflictException()) uploader.upload(AtomicBoolean(false)) // will not throw ElementConflictException } @Test fun `close each uploaded quest in local DB and call listener`() { val quests = listOf(createQuest(), createQuest()) on(osmNoteQuestController.getAllAnswered()).thenReturn(quests) on(singleNoteUploader.comment(anyLong(),any(),any())).thenReturn(createNote()) uploader.uploadedChangeListener = mock() uploader.upload(AtomicBoolean(false)) for (quest in quests) { verify(osmNoteQuestController).success(quest) } verify(uploader.uploadedChangeListener, times(quests.size))?.onUploaded(any(), any()) } @Test fun `delete each unsuccessfully uploaded quest in local DB and call listener`() { val quests = listOf(createQuest(), createQuest()) on(osmNoteQuestController.getAllAnswered()).thenReturn(quests) on(singleNoteUploader.comment(anyLong(),any(),any())).thenThrow(ConflictException()) uploader.uploadedChangeListener = mock() uploader.upload(AtomicBoolean(false)) verify(osmNoteQuestController, times(quests.size)).fail(any()) verify(uploader.uploadedChangeListener, times(2))?.onDiscarded(any(), any()) } @Test fun `catches image upload exception`() { val quest = createQuest() quest.imagePaths = listOf("hello") on(osmNoteQuestController.getAllAnswered()).thenReturn(listOf(quest)) on(singleNoteUploader.comment(anyLong(),any(),any())).thenThrow(ImageUploadException()) uploader.upload(AtomicBoolean(false)) // will not throw ElementConflictException, nor delete the note from db, nor update it verify(osmNoteQuestController, never()).fail(any()) verify(osmNoteQuestController, never()).success(any()) } } private fun createNote(): Note { val note = Note() note.id = 1 note.position = OsmLatLon(1.0, 2.0) return note } private fun createQuest(): OsmNoteQuest { val quest = OsmNoteQuest(createNote(), OsmNoteQuestType()) quest.id = 3 quest.status = QuestStatus.NEW quest.comment = "blablub" return quest }
app/src/test/java/de/westnordost/streetcomplete/data/osmnotes/notequests/OsmNoteQuestsChangesUploaderTest.kt
1131854350
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.adapters import android.graphics.Color import android.support.v7.widget.RecyclerView import android.text.Spannable import android.text.SpannableString import android.text.Spanned import android.text.style.BackgroundColorSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import giuliolodi.gitnav.R import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.row_commit_file.view.* import org.eclipse.egit.github.core.CommitFile import android.text.style.ForegroundColorSpan /** * Created by giulio on 06/01/2018. */ class CommitFileAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var mCommitFileList: MutableList<CommitFile?> = arrayListOf() private val onFileClick: PublishSubject<CommitFile> = PublishSubject.create() fun getPositionClicks(): Observable<CommitFile> { return onFileClick } class CommitFileHolder(root: View) : RecyclerView.ViewHolder(root) { fun bind (file: CommitFile) = with(itemView) { row_commit_file_filename.text = file.filename.substring(file.filename.lastIndexOf("/") + 1, file.filename.length) if (file.patch != null && !file.patch.isEmpty()) { val raw = file.patch val cleaned = raw.substring(raw.lastIndexOf("@@") + 3, raw.length) val spannable = SpannableString(cleaned) val c = cleaned.toCharArray() val backslash: MutableList<String> = mutableListOf() val piu: MutableList<String> = mutableListOf() val meno: MutableList<String> = mutableListOf() for (i in 0 until c.size - 1) { if (c[i] == '\n') { backslash.add(i.toString()) } if (c[i] == '\n' && c[i + 1] == '+') { piu.add(i.toString()) } if (c[i] == '\n' && c[i + 1] == '-') { meno.add(i.toString()) } } for (i in 0 until piu.size) { for (j in 0 until backslash.size) { if (Integer.valueOf(piu[i]) < Integer.valueOf(backslash[j])) { spannable.setSpan(BackgroundColorSpan(Color.parseColor("#cff7cf")), Integer.valueOf(piu[i]), Integer.valueOf(backslash[j]), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) break } } } for (i in 0 until meno.size) { for (j in 0 until backslash.size) { if (Integer.valueOf(meno[i]) < Integer.valueOf(backslash[j])) { spannable.setSpan(BackgroundColorSpan(Color.parseColor("#f7cdcd")), Integer.valueOf(meno[i]), Integer.valueOf(backslash[j]), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) break } } } row_commit_file_cv.setOnClickListener { if (row_commit_file_content.text == "...") row_commit_file_content.text = spannable else row_commit_file_content.text = "..." } } val changed = "+ " + file.additions.toString() + " - " + file.deletions.toString() val changedString = SpannableString(changed) changedString.setSpan(ForegroundColorSpan(Color.parseColor("#099901")), 0, changed.indexOf("-"), Spanned.SPAN_INCLUSIVE_INCLUSIVE) changedString.setSpan(ForegroundColorSpan(Color.parseColor("#c4071a")), changed.indexOf("-"), changedString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE) row_commit_file_changes.text = changedString } } class LoadingHolder(root: View) : RecyclerView.ViewHolder(root) override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val root: RecyclerView.ViewHolder if (viewType == 1) { val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_commit_file, parent, false)) root = CommitFileHolder(view) } else { val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_loading, parent, false)) root = LoadingHolder(view) } return root } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is CommitFileHolder) { val file = mCommitFileList[position]!! holder.bind(file) holder.itemView.setOnClickListener { onFileClick.onNext(file) } } } override fun getItemViewType(position: Int): Int { return if (mCommitFileList[position] != null) 1 else 0 } override fun getItemCount(): Int { return mCommitFileList.size } override fun getItemId(position: Int): Long { return position.toLong() } fun addCommitFileList(commitFileList: List<CommitFile>) { if (mCommitFileList.isEmpty()) { mCommitFileList.addAll(commitFileList) notifyDataSetChanged() } else if (!commitFileList.isEmpty()) { val lastItemIndex = if (mCommitFileList.size > 0) mCommitFileList.size else 0 mCommitFileList.addAll(commitFileList) notifyItemRangeInserted(lastItemIndex, mCommitFileList.size) } } fun addCommitFile(commitFile: CommitFile) { mCommitFileList.add(commitFile) notifyItemInserted(mCommitFileList.size - 1) } fun addLoading() { mCommitFileList.add(null) notifyItemInserted(mCommitFileList.size - 1) } fun clear() { mCommitFileList.clear() notifyDataSetChanged() } }
app/src/main/java/giuliolodi/gitnav/ui/adapters/CommitFileAdapter.kt
109737717
package org.stepik.android.presentation.comment.model import org.stepik.android.domain.latex.model.LatexData import org.stepik.android.model.Submission import org.stepik.android.model.attempts.Attempt import org.stepik.android.model.comments.Comment import org.stepik.android.model.comments.Vote import org.stepik.android.model.user.User import ru.nobird.android.core.model.Identifiable sealed class CommentItem { data class Data( val comment: Comment, val textData: LatexData, val user: User, val voteStatus: VoteStatus, val isFocused: Boolean, val solution: Solution? ) : CommentItem(), Identifiable<Long> { override val id: Long = comment.id sealed class VoteStatus { data class Resolved(val vote: Vote) : VoteStatus() object Pending : VoteStatus() } data class Solution( val attempt: Attempt, val submission: Submission ) } data class LoadMoreReplies( val parentComment: Comment, val lastCommentId: Long, val count: Int ) : CommentItem(), Identifiable<Long> { override val id: Long = parentComment.id } object Placeholder : CommentItem() data class ReplyPlaceholder( val parentComment: Comment ) : CommentItem(), Identifiable<Long> { override val id: Long = parentComment.id } data class RemovePlaceholder( override val id: Long, val isReply: Boolean ) : CommentItem(), Identifiable<Long> }
app/src/main/java/org/stepik/android/presentation/comment/model/CommentItem.kt
3139319616
package org.stepik.android.presentation.profile_courses import android.os.Bundle import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import ru.nobird.android.domain.rx.emptyOnErrorStub import ru.nobird.android.core.model.mapPaged import ru.nobird.android.core.model.mapToLongArray import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_list.interactor.CourseListInteractor import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.course_list.model.CourseListQuery import org.stepik.android.domain.profile.model.ProfileData import org.stepik.android.model.Course import org.stepik.android.presentation.course_continue.delegate.CourseContinuePresenterDelegate import org.stepik.android.presentation.course_continue.delegate.CourseContinuePresenterDelegateImpl import org.stepik.android.view.injection.course.EnrollmentCourseUpdates import org.stepik.android.view.injection.profile.UserId import ru.nobird.android.presentation.base.PresenterBase import ru.nobird.android.presentation.base.PresenterViewContainer import ru.nobird.android.presentation.base.delegate.PresenterDelegate import javax.inject.Inject class ProfileCoursesPresenter @Inject constructor( @UserId private val userId: Long, private val profileDataObservable: Observable<ProfileData>, private val courseListInteractor: CourseListInteractor, @EnrollmentCourseUpdates private val enrollmentUpdatesObservable: Observable<Course>, viewContainer: PresenterViewContainer<ProfileCoursesView>, continueCoursePresenterDelegate: CourseContinuePresenterDelegateImpl, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<ProfileCoursesView>(viewContainer), CourseContinuePresenterDelegate by continueCoursePresenterDelegate { companion object { private const val KEY_COURSES = "courses" } override val delegates: List<PresenterDelegate<in ProfileCoursesView>> = listOf(continueCoursePresenterDelegate) private var state: ProfileCoursesView.State = ProfileCoursesView.State.Idle set(value) { field = value view?.setState(value) } private var isBlockingLoading: Boolean = false set(value) { field = value view?.setBlockingLoading(value) } init { subscriberForEnrollmentUpdates() } override fun attachView(view: ProfileCoursesView) { super.attachView(view) view.setBlockingLoading(isBlockingLoading) view.setState(state) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) val courseIds = savedInstanceState.getLongArray(KEY_COURSES) if (courseIds != null) { if (state == ProfileCoursesView.State.Idle) { state = ProfileCoursesView.State.Loading compositeDisposable += courseListInteractor // TODO Cache data source? .getCourseListItems(courseIds.toList(), courseViewSource = CourseViewSource.Query(CourseListQuery(teacher = userId, order = CourseListQuery.Order.POPULARITY_DESC))) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { state = ProfileCoursesView.State.Content(it) }, onError = { state = ProfileCoursesView.State.Idle; fetchCourses() } ) } } } fun fetchCourses(forceUpdate: Boolean = false) { if (state == ProfileCoursesView.State.Idle || (forceUpdate && state is ProfileCoursesView.State.Error)) { state = ProfileCoursesView.State.Loading compositeDisposable += profileDataObservable .firstElement() .flatMapSingleElement { profileData -> // TODO Pagination courseListInteractor .getCourseListItems( CourseListQuery( teacher = profileData.user.id, order = CourseListQuery.Order.POPULARITY_DESC ) ) } .filter { it.isNotEmpty() } .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { state = ProfileCoursesView.State.Content(it) }, onComplete = { state = ProfileCoursesView.State.Empty }, onError = { state = ProfileCoursesView.State.Error } ) } } private fun subscriberForEnrollmentUpdates() { compositeDisposable += enrollmentUpdatesObservable .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onNext = { enrolledCourse -> val oldState = state if (oldState is ProfileCoursesView.State.Content) { state = ProfileCoursesView.State.Content( oldState.courseListDataItems.mapPaged { if (it.course.id == enrolledCourse.id) it.copy(course = enrolledCourse) else it } ) } }, onError = emptyOnErrorStub ) } override fun onSaveInstanceState(outState: Bundle) { val courseListDataItems = (state as? ProfileCoursesView.State.Content) ?.courseListDataItems ?: return outState.putLongArray(KEY_COURSES, courseListDataItems.mapToLongArray(CourseListItem.Data::id)) super.onSaveInstanceState(outState) } }
app/src/main/java/org/stepik/android/presentation/profile_courses/ProfileCoursesPresenter.kt
716564446
package lt.markmerkk.app import com.badlogic.gdx.Game import com.badlogic.gdx.Gdx import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.World import lt.markmerkk.app.box2d.WorldProviderImpl import lt.markmerkk.app.entities.PlayerServer import lt.markmerkk.app.factory.PhysicsComponentFactory import lt.markmerkk.app.mvp.* import lt.markmerkk.app.screens.GameScreen /** * @author mariusmerkevicius * @since 2016-06-04 */ class RacerGame( private val isHost: Boolean, private val serverIp: String = Const.DEFAULT_SERVER_IP ) : Game() { lateinit var camera: CameraHelper lateinit var world: World lateinit var componentFactory: PhysicsComponentFactory lateinit var worldPresenter: WorldPresenter lateinit var debugPresenter: DebugPresenter lateinit var serverPresenter: ServerPresenter lateinit var playerPresenterServer: PlayerPresenterServer private val players = mutableListOf<PlayerServer>() override fun create() { camera = CameraHelper(GameScreen.VIRTUAL_WIDTH, GameScreen.VIRTUAL_HEIGHT) world = World(Vector2(0.0f, 0.0f), true) componentFactory = PhysicsComponentFactory(world, camera) worldPresenter = WorldPresenterImpl(WorldInteractorImpl(world)) debugPresenter = DebugPresenterImpl(world, camera) worldPresenter.onAttach() debugPresenter.onAttach() componentFactory.createBoundWalls() componentFactory.createPen() if (isHost) { playerPresenterServer = PlayerPresenterServerImpl( WorldProviderImpl(world), players ) serverPresenter = ServerPresenterImpl( serverInteractor = ServerInteractorImpl(), playerPresenterServer = playerPresenterServer ) serverPresenter.onAttach() } setScreen(GameScreen(camera)) } override fun render() { super.render() val deltaTime = Gdx.graphics.deltaTime worldPresenter.render(deltaTime) debugPresenter.render() if (isHost) { serverPresenter.update() playerPresenterServer.render(deltaTime) } } override fun dispose() { debugPresenter.onDetach() worldPresenter.onDetach() if (isHost) { serverPresenter.onDetach() } super.dispose() } }
core/src/main/java/lt/markmerkk/app/RacerGame.kt
1564109554
package com.marknjunge.core.data.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class UpdateUserDto( @SerialName("firstName") val firstName: String, @SerialName("lastName") val lastName: String, @SerialName("mobileNumber") val mobileNumber: String, @SerialName("email") val email: String )
core/src/main/java/com/marknjunge/core/data/model/UpdateUserDto.kt
1446830142
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.element.tools.model import com.savvasdalkitsis.gameframe.feature.workspace.element.grid.model.ColorGrid import com.savvasdalkitsis.gameframe.feature.workspace.element.grid.model.Grid /** * Modified from http://stackoverflow.com/questions/15474122/is-there-a-midpoint-ellipse-algorithm */ open class OvalTool : ScratchTool() { override fun drawOnScratch(scratch: Grid, startColumn: Int, startRow: Int, column: Int, row: Int, color: Int) { val rx = Math.abs(startColumn - column) / 2f val ry = Math.abs(startRow - row) / 2f val cx = Math.min(startColumn, column) + rx val cy = Math.min(startRow, row) + ry val a2 = rx * rx val b2 = ry * ry val twoA2 = 2 * a2 val twoB2 = 2 * b2 var p: Float var x = 0f var y = ry var px = 0f var py = twoA2 * y plot(cx, cy, x, y, scratch, color) p = Math.round(b2 - a2 * ry + 0.25 * a2).toFloat() while (px < py) { x++ px += twoB2 if (p < 0) p += b2 + px else { y-- py -= twoA2 p += b2 + px - py } plot(cx, cy, x, y, scratch, color) } p = Math.round(b2.toDouble() * (x + 0.5) * (x + 0.5) + a2 * (y - 1) * (y - 1) - a2 * b2).toFloat() while (y > 0) { y-- py -= twoA2 if (p > 0) p += a2 - py else { x++ px += twoB2 p += a2 - py + px } plot(cx, cy, x, y, scratch, color) } } private fun plot(xc: Float, yc: Float, x: Float, y: Float, scratch: Grid, color: Int) { draw(xc + x, yc + y, scratch, color) draw(xc - x, yc + y, scratch, color) draw(xc + x, yc - y, scratch, color) draw(xc - x, yc - y, scratch, color) } private fun draw(x: Float, y: Float, scratch: Grid, color: Int) { val c = x.toInt() val r = y.toInt() if (!ColorGrid.isOutOfBounds(c, r)) { scratch.setColor(color, c, r) } } }
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/tools/model/OvalTool.kt
908986224
package eu.kanade.tachiyomi.ui.reader.model import com.jakewharton.rxrelay.BehaviorRelay import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.ui.reader.loader.PageLoader import eu.kanade.tachiyomi.util.system.logcat data class ReaderChapter(val chapter: Chapter) { var state: State = State.Wait set(value) { field = value stateRelay.call(value) } private val stateRelay by lazy { BehaviorRelay.create(state) } val stateObserver by lazy { stateRelay.asObservable() } val pages: List<ReaderPage>? get() = (state as? State.Loaded)?.pages var pageLoader: PageLoader? = null var requestedPage: Int = 0 var references = 0 private set fun ref() { references++ } fun unref() { references-- if (references == 0) { if (pageLoader != null) { logcat { "Recycling chapter ${chapter.name}" } } pageLoader?.recycle() pageLoader = null state = State.Wait } } sealed class State { object Wait : State() object Loading : State() class Error(val error: Throwable) : State() class Loaded(val pages: List<ReaderPage>) : State() } }
app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderChapter.kt
2129567265
package info.nightscout.androidaps.diaconn.pumplog import okhttp3.internal.and import java.nio.ByteBuffer import java.nio.ByteOrder /* * 스퀘어주입 설정(시작) */ class LOG_SET_SQUARE_INJECTION private constructor( val data: String, val dttm: String, typeAndKind: Byte, // 47.5=4750 val setAmount: Short, // 1~30(10분 단위 값 의미) private val injectTime: Byte, val batteryRemain: Byte ) { val type: Byte = PumplogUtil.getType(typeAndKind) val kind: Byte = PumplogUtil.getKind(typeAndKind) fun getInjectTime(): Int { return injectTime and 0xff } override fun toString(): String { val sb = StringBuilder("LOG_SET_SQUARE_INJECTION{") sb.append("LOG_KIND=").append(LOG_KIND.toInt()) sb.append(", data='").append(data).append('\'') sb.append(", dttm='").append(dttm).append('\'') sb.append(", type=").append(type.toInt()) sb.append(", kind=").append(kind.toInt()) sb.append(", setAmount=").append(setAmount.toInt()) sb.append(", injectTime=").append(injectTime and 0xff) sb.append(", batteryRemain=").append(batteryRemain.toInt()) sb.append('}') return sb.toString() } companion object { const val LOG_KIND: Byte = 0x0C fun parse(data: String): LOG_SET_SQUARE_INJECTION { val bytes = PumplogUtil.hexStringToByteArray(data) val buffer = ByteBuffer.wrap(bytes) buffer.order(ByteOrder.LITTLE_ENDIAN) return LOG_SET_SQUARE_INJECTION( data, PumplogUtil.getDttm(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getShort(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer) ) } } }
diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_SQUARE_INJECTION.kt
4033992578
/* * Copyright © 2020 Paul Ambrose ([email protected]) * * 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. */ @file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction") package io.prometheus.proxy import com.github.pambrose.common.delegate.AtomicDelegates.atomicBoolean import com.github.pambrose.common.delegate.AtomicDelegates.nonNullableReference import com.github.pambrose.common.dsl.GuavaDsl.toStringElements import io.prometheus.grpc.RegisterAgentRequest import kotlinx.coroutines.channels.Channel import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import kotlin.time.TimeMark import kotlin.time.TimeSource.Monotonic internal class AgentContext(private val remoteAddr: String) { val agentId = AGENT_ID_GENERATOR.incrementAndGet().toString() private val scrapeRequestChannel = Channel<ScrapeRequestWrapper>(Channel.UNLIMITED) private val channelBacklogSize = AtomicInteger(0) private val clock = Monotonic private var lastActivityTimeMark: TimeMark by nonNullableReference(clock.markNow()) private var lastRequestTimeMark: TimeMark by nonNullableReference(clock.markNow()) private var valid by atomicBoolean(true) private var launchId: String by nonNullableReference("Unassigned") var hostName: String by nonNullableReference("Unassigned") private set var agentName: String by nonNullableReference("Unassigned") private set var consolidated: Boolean by nonNullableReference(false) private set internal val desc: String get() = if (consolidated) "consolidated " else "" private val lastRequestDuration get() = lastRequestTimeMark.elapsedNow() val inactivityDuration get() = lastActivityTimeMark.elapsedNow() val scrapeRequestBacklogSize: Int get() = channelBacklogSize.get() init { markActivityTime(true) } fun assignProperties(request: RegisterAgentRequest) { launchId = request.launchId agentName = request.agentName hostName = request.hostName consolidated = request.consolidated } suspend fun writeScrapeRequest(scrapeRequest: ScrapeRequestWrapper) { scrapeRequestChannel.send(scrapeRequest) channelBacklogSize.incrementAndGet() } suspend fun readScrapeRequest(): ScrapeRequestWrapper? = scrapeRequestChannel.receiveCatching().getOrNull() ?.apply { channelBacklogSize.decrementAndGet() } fun isValid() = valid && !scrapeRequestChannel.isClosedForReceive fun isNotValid() = !isValid() fun invalidate() { valid = false scrapeRequestChannel.close() } fun markActivityTime(isRequest: Boolean) { lastActivityTimeMark = clock.markNow() if (isRequest) lastRequestTimeMark = clock.markNow() } override fun toString() = toStringElements { add("agentId", agentId) add("launchId", launchId) add("consolidated", consolidated) add("valid", valid) add("agentName", agentName) add("hostName", hostName) add("remoteAddr", remoteAddr) add("lastRequestDuration", lastRequestDuration) //add("inactivityDuration", inactivityDuration) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AgentContext return agentId == other.agentId } override fun hashCode() = agentId.hashCode() companion object { private val AGENT_ID_GENERATOR = AtomicLong(0L) } }
src/main/kotlin/io/prometheus/proxy/AgentContext.kt
3190481908
package com.prateekj.snooper.formatter import org.junit.Test import com.prateekj.snooper.utils.TestUtilities.readFrom import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.assertThat class XmlFormatterTest { @Test @Throws(Exception::class) fun shouldReturnFormattedXmlObject() { val formatter = XmlFormatter() val formattedResponse = formatter.format(readFrom("person_details_raw_response.xml")) val expectedResponse = readFrom("person_details_formatted_response.xml") assertThat(formattedResponse, `is`<String>(expectedResponse)) } @Test @Throws(Exception::class) fun shouldReturnSameXmlWhenExceptionOccurs() { val formatter = XmlFormatter() val xml = "<invalid>1</tags>" val formattedResponse = formatter.format(xml) assertThat(formattedResponse, `is`(xml)) } }
Snooper/src/androidTest/java/com/prateekj/snooper/formatter/XmlFormatterTest.kt
2944564176
package net.dean.jraw.references import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Types import net.dean.jraw.* import net.dean.jraw.JrawUtils.urlEncode import net.dean.jraw.databind.Enveloped import net.dean.jraw.http.NetworkException import net.dean.jraw.models.* import net.dean.jraw.models.internal.GenericJsonResponse import net.dean.jraw.models.internal.RedditModelEnvelope import net.dean.jraw.models.internal.TrophyList import net.dean.jraw.pagination.BarebonesPaginator import net.dean.jraw.pagination.DefaultPaginator import okhttp3.MediaType import okhttp3.RequestBody /** * A user reference is exactly what you think it is, a reference to a user. * * @property username The name of the users account (note: not the ID or the full name) */ sealed class UserReference<out T : UserFlairReference>(reddit: RedditClient, val username: String) : AbstractReference(reddit) { /** True if and only if this UserReference is a [SelfUserReference] */ abstract val isSelf: Boolean /** * Fetches basic information about this user. */ @Throws(SuspendedAccountException::class) @Deprecated("Prefer query() for better handling of non-existent/suspended accounts", ReplaceWith("query()")) fun about(): Account { val body = reddit.request { it.path(if (isSelf) "/api/v1/me" else "/user/$username/about") }.body // /api/v1/me returns an Account that isn't wrapped with the data/kind nodes if (isSelf) return JrawUtils.adapter<Account>().fromJson(body)!! try { return JrawUtils.adapter<Account>(Enveloped::class.java).fromJson(body)!! } catch (npe: NullPointerException) { throw SuspendedAccountException(username) } } /** * Gets information about this account. */ @EndpointImplementation(Endpoint.GET_ME, Endpoint.GET_USER_USERNAME_ABOUT) fun query(): AccountQuery { return try { AccountQuery.create(username, AccountStatus.EXISTS, about()) } catch (e: ApiException) { if (e.cause is NetworkException && e.cause.res.code != 404) throw e else AccountQuery.create(username, AccountStatus.NON_EXISTENT) } catch (e: SuspendedAccountException) { AccountQuery.create(username, AccountStatus.SUSPENDED) } } /** Fetches any trophies the user has achieved */ @EndpointImplementation(Endpoint.GET_ME_TROPHIES, Endpoint.GET_USER_USERNAME_TROPHIES) fun trophies(): List<Trophy> { return reddit.request { if (isSelf) it.endpoint(Endpoint.GET_ME_TROPHIES) else it.endpoint(Endpoint.GET_USER_USERNAME_TROPHIES, username) }.deserializeEnveloped<TrophyList>().trophies } /** * Creates a new [net.dean.jraw.pagination.Paginator.Builder] which can iterate over a user's public history. * * Possible `where` values: * * - `overview` — submissions and comments * - `submitted` — only submissions * - `comments` — only comments * - `gilded` — submissions and comments which have received reddit Gold * * If this user reference is for the currently logged-in user, these `where` values can be used: * * - `upvoted` * - `downvoted` * - `hidden` * - `saved` * * Only `overview`, `submitted`, and `comments` are sortable. */ @EndpointImplementation(Endpoint.GET_USER_USERNAME_WHERE, type = MethodType.NON_BLOCKING_CALL) fun history(where: String): DefaultPaginator.Builder<PublicContribution<*>, UserHistorySort> { // Encode URLs to prevent accidental malformed URLs return DefaultPaginator.Builder.create(reddit, "/user/${urlEncode(username)}/${urlEncode(where)}", sortingAlsoInPath = false) } /** * Creates a [MultiredditReference] for a multireddit that belongs to this user. */ fun multi(name: String) = MultiredditReference(reddit, username, name) /** * Lists the multireddits this client is able to view. * * If this UserReference is for the logged-in user, all multireddits will be returned. Otherwise, only public * multireddits will be returned. */ @EndpointImplementation(Endpoint.GET_MULTI_MINE, Endpoint.GET_MULTI_USER_USERNAME) fun listMultis(): List<Multireddit> { val res = reddit.request { if (isSelf) { it.endpoint(Endpoint.GET_MULTI_MINE) } else { it.endpoint(Endpoint.GET_MULTI_USER_USERNAME, username) } } val type = Types.newParameterizedType(List::class.java, Multireddit::class.java) val adapter = JrawUtils.moshi.adapter<List<Multireddit>>(type, Enveloped::class.java) return res.deserializeWith(adapter) } /** * Returns a [UserFlairReference] for this user for the given subreddit. If this user is not the authenticated user, * the authenticated must be a moderator of the given subreddit to access anything specific to this user. */ abstract fun flairOn(subreddit: String): T } /** A reference to the currently authenticated user */ class SelfUserReference(reddit: RedditClient) : UserReference<SelfUserFlairReference>(reddit, reddit.requireAuthenticatedUser()) { override val isSelf = true private val prefsAdapter: JsonAdapter<Map<String, Any>> by lazy { val type = Types.newParameterizedType(Map::class.java, String::class.java, Object::class.java) JrawUtils.moshi.adapter<Map<String, Any>>(type) } /** Creates an InboxReference */ fun inbox() = InboxReference(reddit) /** * Creates a Multireddit (or updates it if it already exists). * * This method is equivalent to * * ```kotlin * userReference.multi(name).createOrUpdate(patch) * ``` * * and provided for semantics. */ fun createMulti(name: String, patch: MultiredditPatch) = multi(name).createOrUpdate(patch) /** * Creates a live thread. The only property that's required to be non-null in the LiveThreadPatch is * [title][LiveThreadPatch.title]. * * @see LiveThreadReference.edit */ @EndpointImplementation(Endpoint.POST_LIVE_CREATE) fun createLiveThread(data: LiveThreadPatch): LiveThreadReference { val res = reddit.request { it.endpoint(Endpoint.POST_LIVE_CREATE) .post(data.toRequestMap()) }.deserialize<GenericJsonResponse>() val id = res.json?.data?.get("id") as? String ?: throw IllegalArgumentException("Could not find ID") return LiveThreadReference(reddit, id) } /** * Gets a Map of preferences set at [https://www.reddit.com/prefs]. * * Likely to throw an [ApiException] if authenticated via application-only credentials */ @EndpointImplementation(Endpoint.GET_ME_PREFS) @Throws(ApiException::class) fun prefs(): Map<String, Any> { return reddit.request { it.endpoint(Endpoint.GET_ME_PREFS) }.deserializeWith(prefsAdapter) } /** * Patches over certain user preferences and returns all preferences. * * Although technically you can send any value as a preference value, generally only strings and booleans are used. * See [here](https://www.reddit.com/dev/api/oauth#GET_api_v1_me_prefs) for a list of all available preferences. * * Likely to throw an [ApiException] if authenticated via application-only credentials */ @EndpointImplementation(Endpoint.PATCH_ME_PREFS) @Throws(ApiException::class) fun patchPrefs(newPrefs: Map<String, Any>): Map<String, Any> { val body = RequestBody.create(MediaType.parse("application/json"), prefsAdapter.toJson(newPrefs)) return reddit.request { it.endpoint(Endpoint.PATCH_ME_PREFS).patch(body) }.deserialize() } /** * Returns a Paginator builder for subreddits the user is associated with * * Possible `where` values: * * - `contributor` * - `moderator` * - `subscriber` */ @EndpointImplementation(Endpoint.GET_SUBREDDITS_MINE_WHERE, type = MethodType.NON_BLOCKING_CALL) fun subreddits(where: String): BarebonesPaginator.Builder<Subreddit> { return BarebonesPaginator.Builder.create(reddit, "/subreddits/mine/${JrawUtils.urlEncode(where)}") } /** * Fetches a breakdown of comment and link karma by subreddit for the user */ @EndpointImplementation(Endpoint.GET_ME_KARMA) fun karma(): List<KarmaBySubreddit> { val json = reddit.request { it.endpoint(Endpoint.GET_ME_KARMA) } // Our data is represented by RedditModelEnvelope<List<KarmaBySubreddit>> so we need to create a Type instance // that reflects that val listType = Types.newParameterizedType(List::class.java, KarmaBySubreddit::class.java) val type = Types.newParameterizedType(RedditModelEnvelope::class.java, listType) // Parse the envelope and return its data val adapter = JrawUtils.moshi.adapter<RedditModelEnvelope<List<KarmaBySubreddit>>>(type) val parsed = adapter.fromJson(json.body)!! return parsed.data } override fun flairOn(subreddit: String): SelfUserFlairReference = SelfUserFlairReference(reddit, subreddit) } /** * A reference to user that is not the currently authenticated user. Note that it's still technically possible to create * an OtherUserReference for the currently authenticated user, but it won't be nearly as useful as creating a * [SelfUserReference] instead. */ class OtherUserReference(reddit: RedditClient, username: String) : UserReference<OtherUserFlairReference>(reddit, username) { override val isSelf = false override fun flairOn(subreddit: String): OtherUserFlairReference = OtherUserFlairReference(reddit, subreddit, username) }
lib/src/main/kotlin/net/dean/jraw/references/UserReferences.kt
3580244235
// 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.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtWhenConditionWithExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset class AddIsToWhenConditionFix( expression: KtWhenConditionWithExpression, private val referenceText: String ) : KotlinQuickFixAction<KtWhenConditionWithExpression>(expression) { override fun getText(): String = KotlinBundle.message("fix.add.is.to.when", referenceText) override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expression = element ?: return val replaced = expression.replaced(KtPsiFactory(expression).createWhenCondition("is ${expression.text}")) editor?.caretModel?.moveToOffset(replaced.endOffset) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtWhenConditionWithExpression>? { val element = diagnostic.psiElement.parent as? KtWhenConditionWithExpression ?: return null return AddIsToWhenConditionFix(element, element.text) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddIsToWhenConditionFix.kt
3712376932
package just4fun.holomorph.types import just4fun.holomorph.* import just4fun.holomorph.forms.RawCollectionConsumer import just4fun.holomorph.forms.RawMapConsumer import kotlin.reflect.KClass import kotlin.reflect.full.starProjectedType abstract class PrimType<T: Any>(override final val typeKlas: KClass<T>): Type<T> { override fun toString() = typeName override fun hashCode(): Int = typeKlas.hashCode() } object AnyType: PrimType<Any>(Any::class) { override fun newInstance() = Any() override fun isInstance(v: Any): Boolean = true override fun asInstance(v: Any): Any? = v override fun fromEntry(value: String) = value override fun fromEntry(value: Long) = value override fun fromEntry(value: Int) = value override fun fromEntry(value: Short) = value override fun fromEntry(value: Byte) = value override fun fromEntry(value: Char) = value override fun fromEntry(value: Double) = value override fun fromEntry(value: Float) = value override fun fromEntry(value: Boolean) = value override fun fromEntry(value: ByteArray) = value override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = subEntries.intercept(if (expectNames) RawMapConsumer(false) else RawCollectionConsumer(false)) override fun toEntry(value: Any, name: String?, entryBuilder: EntryBuilder): Entry = detectType(value)?.toEntry(value, name, entryBuilder) ?: entryBuilder.Entry(name, value.toString()) override fun copy(v: Any?, deep: Boolean): Any? = if (v == null) null else detectType(v)?.copy(v, deep) ?: v override fun toString(v: Any?, sequenceSizeLimit: Int): String = if (v == null) "null" else detectType(v)?.toString(v, sequenceSizeLimit) ?: v.toString() override fun equal(v1: Any?, v2: Any?): Boolean = when { v1 == null -> v2 == null v2 == null -> false else -> { val type = detectType(v1) when (type) { null -> v1 == v2 else -> type.equal(type.asInstance(v1), type.asInstance(v2)) } } } fun <T: Any> detectType(v: T): Type<T>? { var typ: Type<*>? = when (v) { is String -> StringType is Int -> IntType is Long -> LongType is Double -> DoubleType is Float -> FloatType is Short -> ShortType is Byte -> ByteType is Boolean -> BooleanType is Char -> CharType else -> { val klas = v::class Types.resolve(klas.starProjectedType, klas) ?: logError("Can not detect Type of $v") } } @Suppress("UNCHECKED_CAST") return typ as Type<T>? } } object LongType: PrimType<Long>(Long::class) { override fun newInstance() = 0L override val default get() = 0L override fun isInstance(v: Any): Boolean = v is Long override fun asInstance(v: Any): Long? = when (v) { is Long -> v is Number -> v.toLong() is String -> v.toNumber(String::toLong, Double::toLong) is Boolean -> if (v) 1L else 0L is Char -> v.toLong() else -> evalError(v, this) } override fun fromEntry(value: String) = value.toNumber(String::toLong, Double::toLong) override fun fromEntry(value: Long) = value override fun fromEntry(value: Int) = value.toLong() override fun fromEntry(value: Short) = value.toLong() override fun fromEntry(value: Byte) = value.toLong() override fun fromEntry(value: Char) = value.toLong() override fun fromEntry(value: Double) = value.toLong() override fun fromEntry(value: Float) = value.toLong() override fun fromEntry(value: Boolean) = if (value) 1L else 0L override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Long, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object IntType: PrimType<Int>(Int::class) { override fun newInstance() = 0 override val default: Int get() = 0 override fun isInstance(v: Any): Boolean = v is Int override fun asInstance(v: Any): Int? = when (v) { is Int -> v is Number -> v.toInt() is String -> v.toNumber(String::toInt, Double::toInt) is Boolean -> if (v) 1 else 0 is Char -> v.toInt() else -> evalError(v, this) } override fun fromEntry(value: String) = value.toNumber(String::toInt, Double::toInt) override fun fromEntry(value: Long) = value.toInt() override fun fromEntry(value: Int) = value override fun fromEntry(value: Short) = value.toInt() override fun fromEntry(value: Byte) = value.toInt() override fun fromEntry(value: Char) = value.toInt() override fun fromEntry(value: Double) = value.toInt() override fun fromEntry(value: Float) = value.toInt() override fun fromEntry(value: Boolean) = if (value) 1 else 0 override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Int, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object ShortType: PrimType<Short>(Short::class) { override fun newInstance(): Short = 0 override val default: Short get() = 0 override fun isInstance(v: Any): Boolean = v is Short override fun asInstance(v: Any): Short? = when (v) { is Short -> v is Number -> v.toShort() is String -> v.toNumber(String::toShort, Double::toShort) is Boolean -> if (v) 1 else 0 is Char -> v.toShort() else -> evalError(v, this) } override fun fromEntry(value: String) = value.toNumber(String::toShort, Double::toShort) override fun fromEntry(value: Long) = value.toShort() override fun fromEntry(value: Int) = value.toShort() override fun fromEntry(value: Short) = value override fun fromEntry(value: Byte) = value.toShort() override fun fromEntry(value: Char) = value.toShort() override fun fromEntry(value: Double) = value.toShort() override fun fromEntry(value: Float) = value.toShort() override fun fromEntry(value: Boolean) = if (value) 1.toShort() else 0.toShort() override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Short, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object ByteType: PrimType<Byte>(Byte::class) { override fun newInstance(): Byte = 0 override val default: Byte get() = 0 override fun isInstance(v: Any): Boolean = v is Byte override fun asInstance(v: Any): Byte? = when (v) { is Byte -> v is Number -> v.toByte() is String -> v.toNumber(String::toByte, Double::toByte) is Boolean -> if (v) 1 else 0 is Char -> v.toByte() else -> evalError(v, this) } override fun fromEntry(value: String) = value.toNumber(String::toByte, Double::toByte) override fun fromEntry(value: Long) = value.toByte() override fun fromEntry(value: Int) = value.toByte() override fun fromEntry(value: Short) = value.toByte() override fun fromEntry(value: Byte) = value override fun fromEntry(value: Char) = value.toByte() override fun fromEntry(value: Double) = value.toByte() override fun fromEntry(value: Float) = value.toByte() override fun fromEntry(value: Boolean) = if (value) 1.toByte() else 0.toByte() override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Byte, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object DoubleType: PrimType<Double>(Double::class) { override fun newInstance(): Double = 0.0 override val default: Double get() = 0.0 override fun isInstance(v: Any): Boolean = v is Double override fun asInstance(v: Any): Double? = when (v) { is Double -> v is Number -> v.toDouble() is String -> v.toNumber(String::toDouble, Double::toDouble) is Boolean -> if (v) 1.0 else 0.0 is Char -> v.toDouble() else -> evalError(v, this) } override fun fromEntry(value: String) = value.toNumber(String::toDouble, Double::toDouble) override fun fromEntry(value: Long) = value.toDouble() override fun fromEntry(value: Int) = value.toDouble() override fun fromEntry(value: Short) = value.toDouble() override fun fromEntry(value: Byte) = value.toDouble() override fun fromEntry(value: Char) = value.toDouble() override fun fromEntry(value: Double) = value override fun fromEntry(value: Float) = value.toDouble() override fun fromEntry(value: Boolean) = if (value) 1.0 else 0.0 override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Double, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object FloatType: PrimType<Float>(Float::class) { override fun newInstance(): Float = 0f override val default: Float get() = 0f override fun isInstance(v: Any): Boolean = v is Float override fun asInstance(v: Any): Float? = when (v) { is Float -> v is Number -> v.toFloat() is String -> v.toNumber(String::toFloat, Double::toFloat) is Boolean -> if (v) 1.0f else 0.0f is Char -> v.toFloat() else -> evalError(v, this) } override fun fromEntry(value: String) = value.toNumber(String::toFloat, Double::toFloat) override fun fromEntry(value: Long) = value.toFloat() override fun fromEntry(value: Int) = value.toFloat() override fun fromEntry(value: Short) = value.toFloat() override fun fromEntry(value: Byte) = value.toFloat() override fun fromEntry(value: Char) = value.toFloat() override fun fromEntry(value: Double) = value.toFloat() override fun fromEntry(value: Float) = value override fun fromEntry(value: Boolean) = if (value) 1.0f else 0.0f override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Float, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object CharType: PrimType<Char>(Char::class) { override fun newInstance(): Char = '\u0000' override val default: Char get() = '\u0000' override fun isInstance(v: Any): Boolean = v is Char override fun asInstance(v: Any): Char? = when (v) { is Char -> v is Int -> v.toChar()// glitch : is Number fails is String -> if (v.isEmpty()) '\u0000' else try { Integer.parseInt(v).toChar() } catch (e: Throwable) { v[0] } is Long -> v.toChar() is Double -> v.toChar() is Boolean -> if (v) '1' else '0' is Float -> v.toChar() is Short -> v.toChar() is Byte -> v.toChar() else -> evalError(v, this) } override fun fromEntry(value: String) = if (value.isEmpty()) '\u0000' else if (value.length == 1) value[0] else if (value.all { Character.isDigit(it) }) Integer.parseInt(value).toChar() else evalError(value, this) override fun fromEntry(value: Long) = value.toChar() override fun fromEntry(value: Int) = value.toChar() override fun fromEntry(value: Short) = value.toChar() override fun fromEntry(value: Byte) = value.toChar() override fun fromEntry(value: Char) = value override fun fromEntry(value: Double) = value.toChar() override fun fromEntry(value: Float) = value.toChar() override fun fromEntry(value: Boolean) = if (value) '1' else '0' override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Char, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object BooleanType: PrimType<Boolean>(Boolean::class) { var falseLike = listOf("", "0", "null", "0.0", "0,0") override fun newInstance(): Boolean = false override val default: Boolean get() = false override fun isInstance(v: Any): Boolean = v is Boolean override fun asInstance(v: Any): Boolean? = when (v) { is Boolean -> v is Number -> v.toInt() != 0 "false" -> false "true" -> true is String -> v !in falseLike is Char -> v != '0' else -> evalError(v, this) } override fun fromEntry(value: String) = value.toLowerCase().let { if (it == "false") false else if (it == "true") true else it !in falseLike } override fun fromEntry(value: Long) = value.toInt() != 0 override fun fromEntry(value: Int) = value != 0 override fun fromEntry(value: Short) = value.toInt() != 0 override fun fromEntry(value: Byte) = value.toInt() != 0 override fun fromEntry(value: Char) = value.toInt() != 0 override fun fromEntry(value: Double) = value.toInt() != 0 override fun fromEntry(value: Float) = value.toInt() != 0 override fun fromEntry(value: Boolean) = value override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: Boolean, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } object StringType: PrimType<String>(String::class) { override fun newInstance(): String = "" override fun isInstance(v: Any): Boolean = v is String override fun asInstance(v: Any): String? = when (v) { is String -> v is Number -> v.toString() is Boolean -> v.toString() is Char -> v.toString() else -> evalError(v, this) } override fun fromEntry(value: String) = value override fun fromEntry(value: Long) = value.toString() override fun fromEntry(value: Int) = value.toString() override fun fromEntry(value: Short) = value.toString() override fun fromEntry(value: Byte) = value.toString() override fun fromEntry(value: Char) = value.toString() override fun fromEntry(value: Double) = value.toString() override fun fromEntry(value: Float) = value.toString() override fun fromEntry(value: Boolean) = value.toString() override fun fromEntry(value: ByteArray) = evalError(value, this) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this) override fun toEntry(value: String, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.Entry(name, value) } //todo reasoning for that Unit values object UnitType: PrimType<Unit>(Unit::class) { override fun newInstance(): Unit = Unit override val default: Unit get() = Unit override fun asInstance(v: Any): Unit? = Unit override fun copy(v: Unit?, deep: Boolean): Unit? = Unit override fun equal(v1: Unit?, v2: Unit?): Boolean = true override fun isInstance(v: Any): Boolean = v == Unit override fun fromEntry(value: String) = Unit override fun fromEntry(value: Long) = Unit override fun fromEntry(value: Int) = Unit override fun fromEntry(value: Short) = Unit override fun fromEntry(value: Byte) = Unit override fun fromEntry(value: Char) = Unit override fun fromEntry(value: Double) = Unit override fun fromEntry(value: Float) = Unit override fun fromEntry(value: Boolean) = Unit override fun fromEntry(value: ByteArray) = Unit override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = Unit override fun toEntry(value: Unit, name: String?, entryBuilder: EntryBuilder): Entry = entryBuilder.NullEntry(name) } internal val NumPattern = """[\D&&[^.,\-]]*(-?[\D&&[^.,]]*)(\d*)([.,]*)(\d*).*""".toRegex() internal inline fun <T: Any> String.toNumber(fromString: String.() -> T, fromDouble: Double.() -> T): T { return try { fromString() } catch (e: NumberFormatException) { // call cost 30000 ns NumPattern.matchEntire(this)?.run { var (sig, r, pt, f) = destructured var mult = if (sig.endsWith("-")) -1 else 1 if (r.isEmpty()) r = "0" if (f.isEmpty()) f = "0" if (pt.length > 1) { if (r != "0") f = "0" else mult = 1 } val n = "$r.$f".toDouble() * mult // println("string2double: $v VS $sig$r $pt $f > $n") n.fromDouble() } ?: 0.0.fromDouble() } }
src/main/kotlin/just4fun/holomorph/types/prims.kt
414825042
package org.example import org.gradle.testkit.runner.GradleRunner import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File class BuildLogicFunctionalTest { @Rule @JvmField val testProjectDir: TemporaryFolder = TemporaryFolder() lateinit var buildFile: File @Before fun setup() { testProjectDir.newFile("settings.gradle").writeText("") buildFile = testProjectDir.newFile("build.gradle") } // tag::functional-test-configuration-cache[] @Test fun `my task can be loaded from the configuration cache`() { buildFile.writeText(""" plugins { id 'org.example.my-plugin' } """) runner() .withArguments("--configuration-cache", "myTask") // <1> .build() val result = runner() .withArguments("--configuration-cache", "myTask") // <2> .build() require(result.output.contains("Reusing configuration cache.")) // <3> // ... more assertions on your task behavior } // end::functional-test-configuration-cache[] private fun runner() = GradleRunner.create() .withProjectDir(testProjectDir.root) .withPluginClasspath() }
subprojects/docs/src/snippets/configurationCache/testKit/kotlin/src/test/kotlin/org/example/BuildLogicFunctionalTest.kt
3948924945
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import io.reactivex.Maybe import io.reactivex.Single @Dao abstract class CharactersDao { @Query( """ SELECT * FROM character, thumbnail, comic_list, story_list, event_list, series_list WHERE id = :id AND thumbnail.thumbnail_character_id = character.id AND comic_list.comic_list_character_id = character.id AND story_list.story_list_character_id = character.id AND event_list.event_list_character_id = character.id AND series_list.series_list_character_id = character.id LIMIT 1 """ ) abstract fun findById(id: Long): Maybe<CharacterRelations> @Query( """ SELECT * FROM character, thumbnail, comic_list, story_list, event_list, series_list WHERE thumbnail.thumbnail_character_id = character.id AND comic_list.comic_list_character_id = character.id AND story_list.story_list_character_id = character.id AND event_list.event_list_character_id = character.id AND series_list.series_list_character_id = character.id """ ) abstract fun all(): Single<List<CharacterRelations>> @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(characterEntity: CharacterEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(urlEntity: UrlEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(thumbnailEntity: ThumbnailEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(comicListEntity: ComicListEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(storyListEntity: StoryListEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(eventListEntity: EventListEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(seriesListEntity: SeriesListEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) internal abstract fun insert(summaryEntity: SummaryEntity): Long fun insert(characterRelations: CharacterRelations) { val characterId = insert(characterRelations.character) characterRelations.urls.forEach { it.characterId = characterRelations.character.id it.id = insert(it) } characterRelations.thumbnail.characterId = characterId characterRelations.thumbnail.id = insert(characterRelations.thumbnail) characterRelations.comicListRelations.apply { comicList.characterId = characterId comicList.id = insert(comicList) comicListSummary.forEach { it.comicListId = comicList.id it.id = insert(it) } } characterRelations.storyListRelations.apply { storyListEntity.characterId = characterId storyListEntity.id = insert(storyListEntity) storyListSummary.forEach { it.storyListId = storyListEntity.id it.id = insert(it) } } characterRelations.eventListRelations.apply { eventListEntity.characterId = characterId eventListEntity.id = insert(eventListEntity) eventListSummary.forEach { it.eventListId = eventListEntity.id it.id = insert(it) } } characterRelations.seriesListRelations.apply { seriesListEntity.characterId = characterId seriesListEntity.id = insert(seriesListEntity) seriesListSummary.forEach { it.seriesListId = seriesListEntity.id it.id = insert(it) } } } }
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/CharactersDao.kt
1151178741
package com.timepath.vgui import com.timepath.Logger import com.timepath.io.utils.ViewableData import com.timepath.steam.io.VDFNode import java.awt.Color import java.awt.Font import java.awt.Image import java.beans.PropertyVetoException import java.io.IOException import java.io.InputStream import java.nio.charset.Charset import java.util.LinkedHashMap import java.util.LinkedList import java.util.logging.Level import javax.swing.Icon import javax.swing.UIManager /** * Conditional handling: * <br/> * If there are multiple values with supported conditionals, the last one specified wins. * <br/> * Some tags: * <table> * <tr> * <th>Conditional</th> * <th>Meaning</th> * </tr> * <tr> * <td>$WIN32</td> * <td>Not a console</td> * </tr> * <tr> * <td>$WINDOWS</td> * <td>Windows</td> * </tr> * <tr> * <td>$POSIX</td> * <td>OSX or Linux</td> * </tr> * <tr> * <td>$OSX</td> * <td>Mac OSX</td> * </tr> * <tr> * <td>$LINUX</td> * <td>Linux</td> * </tr> * <tr> * <td>$X360</td> * <td>Xbox360</td> * </tr> * </table> */ throws(IOException::class) public fun Element(`is`: InputStream, c: Charset): Element { val __ = Element(null) __.vdf = VDFNode(`is`, c) Element.parseScheme(__.vdf!!) return __ } public fun Element(): Element { return Element(null) } private fun Element(name: String): Element { val __ = Element(null) __.name = name return __ } private fun Element(name: String, info: String): Element { val __ = Element(info) __.name = name return __ } public class Element(private val info: String?) : ViewableData { public fun addNode(e: Element) { vdf!!.addNode(e.vdf) } private fun trim(s: String?) = when { s != null && "\"" in s -> { var tmp: String = s // assumes one set of quotes tmp = tmp.substring(1, tmp.length() - 1) tmp = tmp.replace("\"", "") tmp.trim() } else -> s } private fun parseInt(v: String): Int? { var vint: Int? = null try { vint = Integer.parseInt(v) } catch (ignored: NumberFormatException) { } if (vint == null) try { vint = java.lang.Float.parseFloat(v).toInt() } catch (ignored: NumberFormatException) { } return vint } public fun load() { for (entry in props) { val k = trim(entry.getKey()) var v = trim(java.lang.String.valueOf(entry.getValue()))!! var vint = parseInt(v) val vbool = vint != null && vint == 1 val switchArg = k!!.toLowerCase() if ("enabled" == switchArg) { if (vbool) enabled = vbool } else if ("visible" == switchArg) { if (vbool) enabled = vbool } else if ("xpos" == switchArg) { if (v.startsWith("c")) { XAlignment = Alignment.Center v = v.substring(1) } else if (v.startsWith("r")) { XAlignment = Alignment.Right v = v.substring(1) } else { XAlignment = Alignment.Left } vint = parseInt(v) if (vint != null) localX = vint.toDouble() } else if ("ypos" == switchArg) { if (v.startsWith("c")) { YAlignment = VAlignment.Center v = v.substring(1) } else if (v.startsWith("r")) { YAlignment = VAlignment.Bottom v = v.substring(1) } else { YAlignment = VAlignment.Top } vint = parseInt(v) if (vint != null) localY = vint.toDouble() } else if ("zpos" == switchArg) { if (vint != null) layer = vint } else if ("wide" == switchArg) { if (v.startsWith("f")) { v = v.substring(1) wideMode = DimensionMode.Mode2 } vint = parseInt(v) if (vint != null) wide = vint } else if ("tall" == switchArg) { if (v.startsWith("f")) { v = v.substring(1) tallMode = DimensionMode.Mode2 } vint = parseInt(v) if (vint != null) tall = vint } else if ("labeltext" == switchArg) { labelText = v } else if ("textalignment" == switchArg) { if ("center".equals(v, ignoreCase = true)) { textAlignment = Alignment.Center } else { textAlignment = if ("right".equals(v, ignoreCase = true)) Alignment.Right else Alignment.Left } } else if ("controlname" == switchArg) { controlName = v } else if ("fgcolor" == switchArg) { val c = v.splitBy(" ") try { fgColor = Color(Integer.parseInt(c[0]), Integer.parseInt(c[1]), Integer.parseInt(c[2]), Integer.parseInt(c[3])) } catch (ignored: NumberFormatException) { // It's a variable } } else if ("font" == switchArg) { if (!fonts.containsKey(v)) continue val f = fonts[v]?.font if (f != null) font = f } else if ("image" == switchArg || "icon" == switchArg) { image = VGUIRenderer.locateImage(v) } else { LOG.log(Level.WARNING, { "Unknown property: ${k}" }) } } if (controlName != null) { val control = Controls[controlName!!] } else { if ("hudlayout".equals(file ?: "", ignoreCase = true)) { areas.put(name!!, this) } } } public fun save(): String { val sb = StringBuilder() // preceding header for (p in props) { if (java.lang.String.valueOf(p.getValue()).isEmpty()) { if ("\\n" == p.getKey()) { sb.append("\n") } if ("//" == p.getKey()) { sb.append("//").append(p.info).append("\n") } } } sb.append(name).append("\n") sb.append("{\n") for (p in props) { if (!java.lang.String.valueOf(p.getValue()).isEmpty()) { sb.append(if ("\\n" == p.getKey()) "\t \n" else { "\t ${p.getKey()}\t ${p.getValue()}${' ' + p.info}\n" }) } } sb.append("}\n") return sb.toString() } public val size: Int get() = wide * tall override fun toString(): String { return name + (when { info != null -> " ~ $info" else -> "" }) // elements cannot have a value, only info } public fun validateDisplay() { for (entry in props) { val k = entry.getKey() if (k == null) continue try { if ("enabled".equals(k, ignoreCase = true)) { entry.setValue(if (enabled) 1 else 0) } else if ("visible".equals(k, ignoreCase = true)) { entry.setValue(if (visible) 1 else 0) } else if ("xpos".equals(k, ignoreCase = true)) { val e = XAlignment entry.setValue("${e.name().substring(0, 1).toLowerCase().replaceFirstLiteral("l", "")}$localX") } else if ("ypos".equals(k, ignoreCase = true)) { val e = Alignment.values()[YAlignment.ordinal()] entry.setValue("${e.name().substring(0, 1).toLowerCase().replaceFirstLiteral("l", "")}$localY") } else if ("zpos".equals(k, ignoreCase = true)) { entry.setValue(layer) } else if ("wide".equals(k, ignoreCase = true)) { entry.setValue("${if ((wideMode == DimensionMode.Mode2)) "f" else ""}$wide") } else if ("tall".equals(k, ignoreCase = true)) { entry.setValue("${if ((tallMode == DimensionMode.Mode2)) "f" else ""}$tall") } else if ("labelText".equals(k, ignoreCase = true)) { entry.setValue(labelText) } else if ("ControlName".equals(k, ignoreCase = true)) { entry.setValue(controlName) } // else if("font".equalsIgnoreCase(k)) { // entry.setValue(this.getFont()) // TODO // } } catch (e: PropertyVetoException) { LOG.log(Level.SEVERE, { null }, e) } } } public val localXi: Int get() = Math.round(localX).toInt() public val localYi: Int get() = Math.round(localY).toInt() override fun getIcon(): Icon? { return UIManager.getIcon("FileChooser.listViewIcon") } public fun isVisible(): Boolean = visible public fun isEnabled(): Boolean = enabled public val properties: List<VDFNode.VDFProperty> get() = props public fun setProperties(properties: List<VDFNode.VDFProperty>) { this.props = properties } public var name: String? = null public var parent: Element? = null public var localX: Double = 0.toDouble() public var localY: Double = 0.toDouble() /** * > 0 = out of screen */ public var layer: Int = 0 public var wide: Int = 0 public var wideMode: DimensionMode = DimensionMode.Mode1 public var tall: Int = 0 public var tallMode: DimensionMode = DimensionMode.Mode1 public var visible: Boolean = false public var enabled: Boolean = false public var font: Font? = null public var fgColor: Color? = null public var props: List<VDFNode.VDFProperty> = LinkedList() private set public var controlName: String? = null public var XAlignment: Alignment = Alignment.Left public var YAlignment: VAlignment = VAlignment.Top public var labelText: String? = null public var textAlignment: Alignment = Alignment.Left public var image: Image? = null var vdf: VDFNode? = null public var file: String? = null public enum class Alignment { Left, Center, Right } public enum class VAlignment { Top, Center, Bottom } public enum class DimensionMode { Mode1, Mode2 } companion object { private val LOG = Logger() /** * TODO */ fun parseScheme(props: VDFNode) { val root = props["Scheme", "Fonts"] ?: return LOG.info { "Found scheme" } for (fontNode in root.getNodes()) { for (detailNode in fontNode.getNodes()) { // val fontKey = fontNode.getCustom().toString() val fontName = detailNode.getValue("name").toString() fonts.put(fontName, HudFont(fontName, detailNode)) LOG.info({ "TODO: Load font ${fontName}" }) break// XXX: hardcoded detail level (the first one) } LOG.info { "Loaded scheme" } } } public fun importVdf(vdf: VDFNode): Element { val e = Element() e.vdf = vdf e.setProperties(vdf.getProperties()) //, file: vdf.file) e.load() return e } public val fonts: MutableMap<String, HudFont> = LinkedHashMap() public val areas: MutableMap<String, Element> = LinkedHashMap() } }
src/main/kotlin/com/timepath/vgui/Element.kt
4106480550
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.commands import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCommandGroup.Companion.BLACKLISTED_ALIASES import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.common.CommandAlias import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.helper.VimNlsSafe import com.maddyhome.idea.vim.vimscript.model.ExecutionResult /** * @author Elliot Courant * see "h :command" */ data class CmdCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges) { override val argFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY) private val unsupportedArgs = listOf( Regex("-range(=[^ ])?") to "-range", Regex("-complete=[^ ]*") to "-complete", Regex("-count=[^ ]*") to "-count", Regex("-addr=[^ ]*") to "-addr", Regex("-bang") to "-bang", Regex("-bar") to "-bar", Regex("-register") to "-register", Regex("-buffer") to "-buffer", Regex("-keepscript") to "-keepscript", ) // Static definitions needed for aliases. private companion object { const val overridePrefix = "!" @VimNlsSafe const val argsPrefix = "-nargs" const val anyNumberOfArguments = "*" const val zeroOrOneArguments = "?" const val moreThanZeroArguments = "+" } override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { val result: Boolean = if (argument.trim().isEmpty()) { this.listAlias(editor, "") } else { this.addAlias(editor) } return if (result) ExecutionResult.Success else ExecutionResult.Error } private fun listAlias(editor: VimEditor, filter: String): Boolean { val lineSeparator = "\n" val allAliases = injector.commandGroup.listAliases() val aliases = allAliases.filter { (filter.isEmpty() || it.key.startsWith(filter)) }.map { "${it.key.padEnd(12)}${it.value.numberOfArguments.padEnd(11)}${it.value.printValue()}" }.sortedWith(String.CASE_INSENSITIVE_ORDER).joinToString(lineSeparator) injector.exOutputPanel.getPanel(editor).output("Name Args Definition$lineSeparator$aliases") return true } private fun addAlias(editor: VimEditor?): Boolean { var argument = argument.trim() // Handle overwriting of aliases val overrideAlias = argument.startsWith(overridePrefix) if (overrideAlias) { argument = argument.removePrefix(overridePrefix).trim() } for ((arg, message) in unsupportedArgs) { val match = arg.find(argument) match?.range?.let { argument = argument.removeRange(it) injector.messages.showStatusBarMessage("'$message' is not supported by `command`") } } // Handle alias arguments val hasArguments = argument.startsWith(argsPrefix) var minNumberOfArgs = 0 var maxNumberOfArgs = 0 if (hasArguments) { // Extract the -nargs that's part of this execution, it's possible that -nargs is // in the actual alias being created, and we don't want to parse that one. val trimmedInput = argument.takeWhile { it != ' ' } val pattern = Regex("(?>-nargs=((|[-])\\d+|[?]|[+]|[*]))").find(trimmedInput) ?: run { injector.messages.showStatusBarMessage(injector.messages.message("e176.invalid.number.of.arguments")) return false } val nargForTrim = pattern.groupValues[0] val argumentValue = pattern.groups[1]!!.value val argNum = argumentValue.toIntOrNull() if (argNum == null) { // If the argument number is null then it is not a number. // Make sure the argument value is a valid symbol that we can handle. when (argumentValue) { anyNumberOfArguments -> { minNumberOfArgs = 0 maxNumberOfArgs = -1 } zeroOrOneArguments -> maxNumberOfArgs = 1 moreThanZeroArguments -> { minNumberOfArgs = 1 maxNumberOfArgs = -1 } else -> { // Technically this should never be reached, but is here just in case // I missed something, since the regex limits the value to be ? + * or // a valid number, its not possible (as far as I know) to have another value // that regex would accept that is not valid. injector.messages.showStatusBarMessage(injector.messages.message("e176.invalid.number.of.arguments")) return false } } } else { // Not sure why this isn't documented, but if you try to create a command in vim // with an explicit number of arguments greater than 1 it returns this error. if (argNum > 1 || argNum < 0) { injector.messages.showStatusBarMessage(injector.messages.message("e176.invalid.number.of.arguments")) return false } minNumberOfArgs = argNum maxNumberOfArgs = argNum } argument = argument.removePrefix(nargForTrim).trim() } // We want to trim off any "!" at the beginning of the arguments. // This will also remove any extra spaces. argument = argument.trim() // We want to get the first character sequence in the arguments. // eg. command! Wq wq // We want to extract the Wq only, and then just use the rest of // the argument as the alias result. val alias = argument.split(" ")[0] argument = argument.removePrefix(alias).trim() // User-aliases need to begin with an uppercase character. if (!alias[0].isUpperCase()) { injector.messages.showStatusBarMessage(injector.messages.message("e183.user.defined.commands.must.start.with.an.uppercase.letter")) return false } if (alias in BLACKLISTED_ALIASES) { injector.messages.showStatusBarMessage(injector.messages.message("e841.reserved.name.cannot.be.used.for.user.defined.command")) return false } if (argument.isEmpty()) { if (editor == null) { // If there is no editor then we can't list aliases, just return false. // No message should be shown either, since there is no editor. return false } return this.listAlias(editor, alias) } // If we are not over-writing existing aliases, and an alias with the same command // already exists then we want to do nothing. if (!overrideAlias && injector.commandGroup.hasAlias(alias)) { injector.messages.showStatusBarMessage(injector.messages.message("e174.command.already.exists.add.to.replace.it")) return false } // Store the alias and the command. We don't need to parse the argument // at this time, if the syntax is wrong an error will be returned when // the alias is executed. injector.commandGroup.setAlias(alias, CommandAlias.Ex(minNumberOfArgs, maxNumberOfArgs, alias, argument)) return true } }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/CmdCommand.kt
2460768844
/* * Copyright 2019 Poly Forest, 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. */ @file:Suppress("EXPERIMENTAL_API_USAGE") package com.acornui.async import com.acornui.time.schedule import com.acornui.time.toDelayMillis import kotlinx.coroutines.* import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.js.Promise import kotlin.properties.ObservableProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.time.Duration @Deprecated("No longer used", ReplaceWith("suspend () -> R")) typealias Work<R> = suspend () -> R /** * Suspends the coroutine until this job is complete, then returns the result if the job has completed, or null if * the job was cancelled. */ suspend fun <T> Deferred<T>.awaitOrNull(): T? { join() return getCompletedOrNull() } /** * If this deferred object [Deferred.isCompleted] and has not completed exceptionally, the [Deferred.getCompleted] value * will be returned. Otherwise, null. */ fun <T> Deferred<T>.getCompletedOrNull(): T? = if (isComplete && getCompletionExceptionOrNull() == null) getCompleted() else null suspend fun <K, V> Map<K, Deferred<V>>.awaitAll(): Map<K, V> { values.awaitAll() return mapValues { it.value.getCompleted() } } /** * @see kotlinx.coroutines.delay */ suspend fun delay(time: Duration) { delay(time.toLongMilliseconds()) } /** * If the given [timeout] is null, runs the block without a timeout, otherwise uses [kotlinx.coroutines.withTimeout]. */ suspend fun <T> withTimeout(timeout: Duration?, block: suspend CoroutineScope.() -> T): T { return if (timeout == null) coroutineScope(block) else withTimeout(timeout.toDelayMillis(), block) } /** * Launches a coroutine inside a supervisor scope. * * - Exceptions thrown in this supervised job will not cancel the parent job. * - Cancellations in the parent job will cancel this supervised job. */ fun CoroutineScope.launchSupervised( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { return launch(context, start) { try { supervisorScope { block() } } catch (ignore: Throwable) {} } } /** * Returns a property for type Job, where upon setting will cancel the previously set job. */ fun <T : Job> cancellingJobProp(): ReadWriteProperty<Any?, T?> { return object : ObservableProperty<T?>(null) { override fun afterChange(property: KProperty<*>, oldValue: T?, newValue: T?) { oldValue?.cancel() } } } /** * Creates a [Promise.race] with `this` promise and a window timeout. */ fun <T> Promise<T>.withTimeout(timeout: Duration): Promise<T> { val timeoutPromise = Promise<T> { _, reject -> val timeoutHandle = schedule(timeout) { reject(TimeoutException(timeout)) } [email protected] { timeoutHandle.dispose() } } return Promise.race(arrayOf(this, timeoutPromise)) } class TimeoutException(val timeout: Duration) : Exception("Promise timed out after $timeout") /** * An alias for [Job.isCompleted]. A minor annoyance, but complete is a transitive verb, therefore "isCompleted" should * be either "hasCompleted" or "isComplete". * @see Job.isCompleted */ val Job.isComplete: Boolean get() = isCompleted
acornui-core/src/main/kotlin/com/acornui/async/asyncUtils.kt
3054771059
package forpdateam.ru.forpda.model.interactors.other import android.content.SharedPreferences import android.util.Log import com.f2prateek.rx.preferences2.RxSharedPreferences import com.jakewharton.rxrelay2.BehaviorRelay import forpdateam.ru.forpda.common.Preferences import forpdateam.ru.forpda.entity.app.other.AppMenuItem import forpdateam.ru.forpda.entity.common.AuthState import forpdateam.ru.forpda.entity.common.MessageCounters import forpdateam.ru.forpda.model.AuthHolder import forpdateam.ru.forpda.model.CountersHolder import forpdateam.ru.forpda.presentation.Screen import io.reactivex.Observable class MenuRepository( private val preferences: SharedPreferences, private val authHolder: AuthHolder, private val countersHolder: CountersHolder ) { companion object { const val group_main = 10 const val group_system = 20 const val group_link = 30 const val item_auth = 110 const val item_article_list = 120 const val item_favorites = 130 const val item_qms_contacts = 140 const val item_mentions = 150 const val item_dev_db = 160 const val item_forum = 170 const val item_search = 180 const val item_history = 190 const val item_notes = 200 const val item_forum_rules = 210 const val item_settings = 220 const val item_other_menu = 230 const val item_link_forum_author = 240 const val item_link_chat_telegram = 250 const val item_link_forum_topic = 260 const val item_link_forum_faq = 270 const val item_link_play_market = 280 const val item_link_github = 290 const val item_link_bitbucket = 300 val GROUP_MAIN = arrayOf( item_auth, item_article_list, item_favorites, item_qms_contacts, item_search, item_mentions, item_forum, item_dev_db, item_history, item_notes, item_forum_rules ) val GROUP_SYSTEM = arrayOf( item_settings ) val GROUP_LINK = arrayOf<Int>( item_link_forum_author, item_link_forum_topic, item_link_forum_faq, item_link_chat_telegram, item_link_play_market, item_link_github, item_link_bitbucket ) } private val allItems = listOf( //AppMenuItem(item_auth, Screen.Auth()), AppMenuItem(item_article_list, Screen.ArticleList()), AppMenuItem(item_favorites, Screen.Favorites()), AppMenuItem(item_qms_contacts, Screen.QmsContacts()), AppMenuItem(item_mentions, Screen.Mentions()), AppMenuItem(item_dev_db, Screen.DevDbBrands()), AppMenuItem(item_forum, Screen.Forum()), AppMenuItem(item_search, Screen.Search()), AppMenuItem(item_history, Screen.History()), AppMenuItem(item_notes, Screen.Notes()), AppMenuItem(item_forum_rules, Screen.ForumRules()), AppMenuItem(item_settings, Screen.Settings()), AppMenuItem(item_link_forum_author), AppMenuItem(item_link_chat_telegram), AppMenuItem(item_link_forum_topic), AppMenuItem(item_link_forum_faq), AppMenuItem(item_link_play_market), AppMenuItem(item_link_github), AppMenuItem(item_link_bitbucket) ) private val mainGroupSequence = mutableListOf<Int>() private val blockedMenu = mutableListOf<Int>() private val blockUnAuth = listOf( item_favorites, item_qms_contacts, item_mentions ) private val blockAuth = listOf( item_auth ) private val mainMenu = mutableListOf<AppMenuItem>() private val systemMenu = mutableListOf<AppMenuItem>() private val linkMenu = mutableListOf<AppMenuItem>() private val menuRelay = BehaviorRelay.create<Map<Int, List<AppMenuItem>>>() private var localCounters = MessageCounters() private val rxPreferences = RxSharedPreferences.create(preferences) private val menuSequence by lazy { rxPreferences.getString("menu_items_sequence") } init { allItems.forEach { it.screen?.fromMenu = true } loadMainMenuGroup() menuSequence .asObservable() .subscribe { Log.e("kulolo", "menuSequence pref change") loadMainMenuGroup() updateMenuItems() } authHolder .observe() .subscribe { loadMainMenuGroup() Log.e("lplplp", "MenuRepository observe auth ${it.state.toString()}") updateMenuItems() } countersHolder .observe() .subscribe { counters -> localCounters = counters updateMenuItems() } updateMenuItems() } private fun loadMainMenuGroup() { mainGroupSequence.clear() mainGroupSequence.addAll(GROUP_MAIN) menuSequence.get().also { savedArray -> if(savedArray.isNotEmpty()){ val array = savedArray.split(',').map { it.toInt() }.filter { GROUP_MAIN.contains(it) } val newItems = GROUP_MAIN.filterNot { array.contains(it) } val finalArray = newItems.plus(array) Log.e("lplplp", "MainRepository init saved ${newItems.size}=${newItems.joinToString { it.toString() }}") mainGroupSequence.clear() mainGroupSequence.addAll(finalArray) } } } fun observerMenu(): Observable<Map<Int, List<AppMenuItem>>> = menuRelay.hide() fun setMainMenuSequence(items: List<AppMenuItem>) { mainGroupSequence.clear() mainGroupSequence.addAll(items.map { it.id }) menuSequence.set(mainGroupSequence.joinToString(",") { it.toString() }) updateMenuItems() } fun setLastOpened(id: Int) { if (GROUP_MAIN.indexOfFirst { it == id } >= 0) { preferences.edit().putInt("app_menu_last_id", id).apply() } } fun getLastOpened(): Int { val menuId = preferences.getInt("app_menu_last_id", -1) return if (GROUP_MAIN.indexOfFirst { it == menuId } >= 0) { menuId } else { -1 } } fun getMenuItem(id: Int): AppMenuItem = allItems.first { it.id == id } fun menuItemContains(id: Int): Boolean = allItems.indexOfFirst { it.id == id } >= 0 fun updateMenuItems() { mainMenu.clear() systemMenu.clear() linkMenu.clear() allItems.firstOrNull { it.id == item_qms_contacts }?.count = localCounters.qms allItems.firstOrNull { it.id == item_mentions }?.count = localCounters.mentions allItems.firstOrNull { it.id == item_favorites }?.count = localCounters.favorites if (authHolder.get().isAuth()) { blockedMenu.addAll(blockAuth) blockedMenu.removeAll(blockUnAuth) } else { blockedMenu.addAll(blockUnAuth) blockedMenu.removeAll(blockAuth) } mainGroupSequence.forEach { if (!blockedMenu.contains(it) && menuItemContains(it)) { mainMenu.add(getMenuItem(it)) } } GROUP_SYSTEM.forEach { if (!blockedMenu.contains(it) && menuItemContains(it)) { systemMenu.add(getMenuItem(it)) } } GROUP_LINK.forEach { if (!blockedMenu.contains(it) && menuItemContains(it)) { linkMenu.add(getMenuItem(it)) } } menuRelay.accept(mapOf( group_main to mainMenu, group_system to systemMenu, group_link to linkMenu )) } }
app/src/main/java/forpdateam/ru/forpda/model/interactors/other/MenuRepository.kt
3837075192
package au.com.dius.pact.provider.junit.descriptions import au.com.dius.pact.core.model.BrokerUrlSource import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Pact import au.com.dius.pact.core.support.isNotEmpty import org.junit.runner.Description import org.junit.runners.model.TestClass /** * Class responsible for building junit tests Description. */ class DescriptionGenerator<I : Interaction>( private val testClass: TestClass, private val pact: Pact<I> ) { /** * Builds an instance of junit Description adhering with this logic for building the name: * If the PactSource is of type <code>BrokerUrlSource</code> and its tag is not empty then * the test name will be "#consumername [tag:#tagname] - Upon #interaction". * For all the other cases "#consumername - Upon #interaction" * @param interaction the Interaction under test */ fun generate(interaction: Interaction): Description { return Description.createTestDescription(testClass.javaClass, "${consumerName()} ${this.getTagDescription()}- Upon ${interaction.description}${this.pending()}") } private fun consumerName(): String { return if (pact.source is BrokerUrlSource) { val source = pact.source as BrokerUrlSource source.result?.name ?: pact.consumer.name } else { pact.consumer.name } } private fun pending(): String { return if (pact.source is BrokerUrlSource) { val source = pact.source as BrokerUrlSource if (source.result != null && source.result!!.pending) { " <PENDING>" } else { "" } } else { "" } } private fun getTagDescription(): String { if (pact.source is BrokerUrlSource) { val tag = (pact.source as BrokerUrlSource).tag return if (tag.isNotEmpty()) "[tag:${(pact.source as BrokerUrlSource).tag}] " else "" } return "" } }
provider/junit/src/main/kotlin/au/com/dius/pact/provider/junit/descriptions/DescriptionGenerator.kt
3243589709
package org.wordpress.android.ui.mysite.jetpackbadge sealed class JetpackPoweredDialogAction { object OpenPlayStore : JetpackPoweredDialogAction() object DismissDialog : JetpackPoweredDialogAction() }
WordPress/src/main/java/org/wordpress/android/ui/mysite/jetpackbadge/JetpackPoweredDialogAction.kt
623221832
// 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.caches.resolve import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.PackageOracle import org.jetbrains.kotlin.analyzer.PackageOracleFactory import org.jetbrains.kotlin.idea.caches.PerModulePackageCacheService import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleOrigin import org.jetbrains.kotlin.idea.caches.project.projectSourceModules import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.isSubpackageOf import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade import org.jetbrains.kotlin.platform.jvm.isJvm class IdePackageOracleFactory(val project: Project) : PackageOracleFactory { override fun createOracle(moduleInfo: ModuleInfo): PackageOracle { if (moduleInfo !is IdeaModuleInfo) return PackageOracle.Optimistic return when { moduleInfo.platform.isJvm() -> when (moduleInfo.moduleOrigin) { ModuleOrigin.LIBRARY -> JavaPackagesOracle(moduleInfo, project) ModuleOrigin.MODULE -> JvmSourceOracle(moduleInfo, project) ModuleOrigin.OTHER -> PackageOracle.Optimistic } else -> when (moduleInfo.moduleOrigin) { ModuleOrigin.MODULE -> KotlinSourceFilesOracle(moduleInfo, project) else -> PackageOracle.Optimistic // binaries for non-jvm platform need some oracles based on their structure } } } private class JavaPackagesOracle(moduleInfo: IdeaModuleInfo, project: Project) : PackageOracle { private val scope = moduleInfo.contentScope private val facade: KotlinJavaPsiFacade = project.service() override fun packageExists(fqName: FqName) = facade.findPackage(fqName.asString(), scope) != null } private class KotlinSourceFilesOracle(moduleInfo: IdeaModuleInfo, private val project: Project) : PackageOracle { private val cacheService: PerModulePackageCacheService = project.service() private val sourceModules = moduleInfo.projectSourceModules() override fun packageExists(fqName: FqName): Boolean { return sourceModules?.any { cacheService.packageExists(fqName, it) } ?: false } } private class JvmSourceOracle(moduleInfo: IdeaModuleInfo, project: Project) : PackageOracle { private val javaPackagesOracle = JavaPackagesOracle(moduleInfo, project) private val kotlinSourceOracle = KotlinSourceFilesOracle(moduleInfo, project) override fun packageExists(fqName: FqName) = javaPackagesOracle.packageExists(fqName) || kotlinSourceOracle.packageExists(fqName) || fqName.isSubpackageOf(ANDROID_SYNTHETIC_PACKAGE_PREFIX) } } private val ANDROID_SYNTHETIC_PACKAGE_PREFIX = FqName("kotlinx.android.synthetic")
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/packageOracles.kt
694376785
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleJava.scripting import com.intellij.icons.AllIcons import com.intellij.ide.actions.ImportModuleAction import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportProvider import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.projectImport.ProjectImportProvider import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import com.intellij.ui.EditorNotificationProvider.CONST_NULL import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleJavaBundle import org.jetbrains.kotlin.idea.gradleJava.scripting.legacy.GradleStandaloneScriptActionsManager import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsLocator import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsLocator.NotificationKind.* import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.Imported import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File import java.util.function.Function import javax.swing.JComponent internal class GradleScriptNotificationProvider : EditorNotificationProvider { override fun collectNotificationData( project: Project, file: VirtualFile, ): Function<in FileEditor, out JComponent?> { if (!isGradleKotlinScript(file) || !file.isKotlinFileType()) { return CONST_NULL } val standaloneScriptActions = GradleStandaloneScriptActionsManager.getInstance(project) val rootsManager = GradleBuildRootsManager.getInstance(project) val scriptUnderRoot = rootsManager?.findScriptBuildRoot(file) ?: return CONST_NULL // todo: this actions will be usefull only when gradle fix https://github.com/gradle/gradle/issues/12640 fun EditorNotificationPanel.showActionsToFixNotEvaluated() { // suggest to reimport project if something changed after import val build: Imported = scriptUnderRoot.nearest as? Imported ?: return val importTs = build.data.importTs if (!build.areRelatedFilesChangedBefore(file, importTs)) { createActionLabel(getConfigurationsActionText()) { rootsManager.updateStandaloneScripts { runPartialGradleImport(project, build) } } } // suggest to choose new gradle project createActionLabel(KotlinIdeaGradleBundle.message("notification.outsideAnything.linkAction")) { linkProject(project, scriptUnderRoot) } } return Function { fileEditor -> when (scriptUnderRoot.notificationKind) { dontCare -> null legacy -> { val actions = standaloneScriptActions[file] if (actions == null) null else { object : EditorNotificationPanel(fileEditor) { val contextHelp = KotlinIdeaGradleBundle.message("notification.gradle.legacy.firstLoad.info") init { if (actions.isFirstLoad) { text(KotlinIdeaGradleBundle.message("notification.gradle.legacy.firstLoad")) toolTipText = contextHelp } else { text(KotlinIdeaGradleBundle.message("notification.text.script.configuration.has.been.changed")) } createActionLabel(KotlinGradleJavaBundle.message("notification.action.text.load.script.configuration")) { actions.reload() } createActionLabel(KotlinBaseScriptingBundle.message("notification.action.text.enable.auto.reload")) { actions.enableAutoReload() } if (actions.isFirstLoad) { contextHelp(contextHelp) } } } } } legacyOutside -> EditorNotificationPanel(fileEditor).apply { text(KotlinIdeaGradleBundle.message("notification.gradle.legacy.outsideProject")) createActionLabel(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.addAsStandaloneAction")) { rootsManager.updateStandaloneScripts { addStandaloneScript(file.path) } } contextHelp(KotlinIdeaGradleBundle.message("notification.gradle.legacy.outsideProject.addToStandaloneHelp")) } outsideAnything -> EditorNotificationPanel(fileEditor).apply { text(KotlinIdeaGradleBundle.message("notification.outsideAnything.text")) createActionLabel(KotlinIdeaGradleBundle.message("notification.outsideAnything.linkAction")) { linkProject(project, scriptUnderRoot) } } wasNotImportedAfterCreation -> EditorNotificationPanel(fileEditor).apply { text(configurationsAreMissingRequestNeeded()) createActionLabel(getConfigurationsActionText()) { val root = scriptUnderRoot.nearest if (root != null) { runPartialGradleImport(project, root) } } val help = configurationsAreMissingRequestNeededHelp() contextHelp(help) } notEvaluatedInLastImport -> EditorNotificationPanel(fileEditor).apply { text(configurationsAreMissingAfterRequest()) // todo: this actions will be usefull only when gradle fix https://github.com/gradle/gradle/issues/12640 // showActionsToFixNotEvaluated() createActionLabel(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.addAsStandaloneAction")) { rootsManager.updateStandaloneScripts { addStandaloneScript(file.path) } } contextHelp(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.info")) } standalone, standaloneLegacy -> EditorNotificationPanel(fileEditor).apply { val actions = standaloneScriptActions[file] if (actions != null) { text( KotlinIdeaGradleBundle.message("notification.standalone.text") + ". " + KotlinIdeaGradleBundle.message("notification.text.script.configuration.has.been.changed") ) createActionLabel(KotlinGradleJavaBundle.message("notification.action.text.load.script.configuration")) { actions.reload() } createActionLabel(KotlinBaseScriptingBundle.message("notification.action.text.enable.auto.reload")) { actions.enableAutoReload() } } else { text(KotlinIdeaGradleBundle.message("notification.standalone.text")) } createActionLabel(KotlinIdeaGradleBundle.message("notification.standalone.disableScriptAction")) { rootsManager.updateStandaloneScripts { removeStandaloneScript(file.path) } } if (scriptUnderRoot.notificationKind == standaloneLegacy) { contextHelp(KotlinIdeaGradleBundle.message("notification.gradle.legacy.standalone.info")) } else { contextHelp(KotlinIdeaGradleBundle.message("notification.standalone.info")) } } } } } private fun linkProject( project: Project, scriptUnderRoot: GradleBuildRootsLocator.ScriptUnderRoot, ) { val settingsFile: File? = tryFindGradleSettings(scriptUnderRoot) // from AttachExternalProjectAction val manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID) ?: return val provider = ProjectImportProvider.PROJECT_IMPORT_PROVIDER.extensions.find { it is AbstractExternalProjectImportProvider && GradleConstants.SYSTEM_ID == it.externalSystemId } ?: return val projectImportProviders = arrayOf(provider) if (settingsFile != null) { PropertiesComponent.getInstance().setValue( "last.imported.location", settingsFile.canonicalPath ) } val wizard = ImportModuleAction.selectFileAndCreateWizard( project, null, manager.externalProjectDescriptor, projectImportProviders ) ?: return if (wizard.stepCount <= 0 || wizard.showAndGet()) { ImportModuleAction.createFromWizard(project, wizard) } } private fun tryFindGradleSettings(scriptUnderRoot: GradleBuildRootsLocator.ScriptUnderRoot): File? { try { var parent = File(scriptUnderRoot.filePath).canonicalFile.parentFile while (parent.isDirectory) { listOf("settings.gradle", "settings.gradle.kts").forEach { val settings = parent.resolve(it) if (settings.isFile) { return settings } } parent = parent.parentFile } } catch (t: Throwable) { // ignore } return null } private fun EditorNotificationPanel.contextHelp(@Nls text: String) { val helpIcon = createActionLabel("") {} helpIcon.icon = AllIcons.General.ContextHelp helpIcon.setUseIconAsLink(true) helpIcon.toolTipText = text } }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/GradleScriptNotificationProvider.kt
988331429
package com.kelsos.mbrc.repository.data import com.kelsos.mbrc.data.RadioStation import com.kelsos.mbrc.data.RadioStation_Table import com.kelsos.mbrc.data.db.RemoteDatabase import com.kelsos.mbrc.di.modules.AppDispatchers import com.kelsos.mbrc.extensions.escapeLike import com.raizlabs.android.dbflow.kotlinextensions.database import com.raizlabs.android.dbflow.kotlinextensions.delete import com.raizlabs.android.dbflow.kotlinextensions.from import com.raizlabs.android.dbflow.kotlinextensions.modelAdapter import com.raizlabs.android.dbflow.kotlinextensions.select import com.raizlabs.android.dbflow.kotlinextensions.where import com.raizlabs.android.dbflow.list.FlowCursorList import com.raizlabs.android.dbflow.sql.language.OperatorGroup.clause import com.raizlabs.android.dbflow.sql.language.SQLite import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction import kotlinx.coroutines.withContext import javax.inject.Inject class LocalRadioDataSource @Inject constructor(val dispatchers: AppDispatchers) : LocalDataSource<RadioStation> { override suspend fun deleteAll() = withContext(dispatchers.db) { delete(RadioStation::class).execute() } override suspend fun saveAll(list: List<RadioStation>) = withContext(dispatchers.db) { val adapter = modelAdapter<RadioStation>() val transaction = FastStoreModelTransaction.insertBuilder(adapter) .addAll(list) .build() database<RemoteDatabase>().executeTransaction(transaction) } override suspend fun loadAllCursor(): FlowCursorList<RadioStation> = withContext(dispatchers.db) { val modelQueriable = (select from RadioStation::class) return@withContext FlowCursorList.Builder(RadioStation::class.java) .modelQueriable(modelQueriable).build() } override suspend fun search(term: String): FlowCursorList<RadioStation> = withContext(dispatchers.db) { val modelQueriable = (select from RadioStation::class where RadioStation_Table.name.like("%${term.escapeLike()}%")) return@withContext FlowCursorList.Builder(RadioStation::class.java) .modelQueriable(modelQueriable).build() } override suspend fun isEmpty(): Boolean = withContext(dispatchers.db){ return@withContext SQLite.selectCountOf().from(RadioStation::class.java).longValue() == 0L } override suspend fun count(): Long = withContext(dispatchers.db){ return@withContext SQLite.selectCountOf().from(RadioStation::class.java).longValue() } override suspend fun removePreviousEntries(epoch: Long) { withContext(dispatchers.db) { SQLite.delete() .from(RadioStation::class.java) .where( clause(RadioStation_Table.date_added.lessThan(epoch)).or( RadioStation_Table.date_added.isNull)) .execute() } } }
app/src/main/kotlin/com/kelsos/mbrc/repository/data/LocalRadioDataSource.kt
3241776355
// 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.images import com.intellij.lang.html.HTMLLanguage import com.intellij.psi.XmlElementFactory import com.intellij.psi.html.HtmlTag import com.intellij.psi.util.PsiTreeUtil import com.intellij.testFramework.LightPlatformCodeInsightTestCase import org.intellij.plugins.markdown.lang.psi.impl.MarkdownImage import java.io.File class MarkdownLineMarkerApplyChangesTest: LightPlatformCodeInsightTestCase() { fun `test markdown image simple changes`() { configureFromFileText("some.md", "![some](image.png)") val markerProvider = ConfigureMarkdownImageLineMarkerProvider() // file > root > paragraph > image > exclamation mark val imageElement = file.firstChild.firstChild.firstChild val data = MarkdownImageData( path = "myImage.png", width = "", height = "", title = "", description = "changed description", shouldConvertToHtml = false ) markerProvider.applyChanges(imageElement, data) val image = file.firstChild.firstChild.firstChild as MarkdownImage assertEquals(data.path, image.linkDestination?.text) assertEquals(data.title, image.collectLinkTitleText() ?: "") assertEquals(data.description, image.collectLinkDescriptionText() ?: "") } fun `test markdown image change to html image`() { configureFromFileText("some.md", "![some](image.png)") val markerProvider = ConfigureMarkdownImageLineMarkerProvider() // file > root > paragraph > image > exclamation mark val imageElement = file.firstChild.firstChild.firstChild val data = MarkdownImageData( path = "image.png", width = "200", height = "300", title = "", description = "some", shouldConvertToHtml = true ) markerProvider.applyChanges(imageElement, data) val image = XmlElementFactory.getInstance(project).createTagFromText(file.text, HTMLLanguage.INSTANCE) val srcAttribute = image.getAttributeValue("src")!! assertEquals(data.path, File(srcAttribute).name) assertEquals(data.width, image.getAttributeValue("width")) assertEquals(data.height, image.getAttributeValue("height")) assertEquals(data.description, image.getAttributeValue("alt")) } fun `test html image simple change`() { configureFromFileText("some.md", "<img src=\"image.png\" alt=\"description\">") val markerProvider = ConfigureHtmlImageLineMarkerProvider() val tag = PsiTreeUtil.findChildOfType(file.viewProvider.getPsi(HTMLLanguage.INSTANCE), HtmlTag::class.java)!! val data = MarkdownImageData( path = "myImage.png", width = "", height = "", title = "my added title", description = "changed description", shouldConvertToHtml = false ) markerProvider.applyChanges(tag, data) val image = file.firstChild.firstChild.firstChild as MarkdownImage assertEquals(data.path, image.linkDestination?.text) assertEquals(data.description, image.collectLinkDescriptionText()) assertEquals(data.title, image.collectLinkTitleText()) } fun `test html image change to markdown image`() { configureFromFileText("some.md", "<img src=\"image.png\" alt=\"description\">") val markerProvider = ConfigureHtmlImageLineMarkerProvider() val tag = PsiTreeUtil.findChildOfType(file.viewProvider.getPsi(HTMLLanguage.INSTANCE), HtmlTag::class.java)!! val data = MarkdownImageData( path = "image.png", width = "", height = "", title = "", description = "changed description", shouldConvertToHtml = false ) markerProvider.applyChanges(tag, data) val image = file.firstChild.firstChild.firstChild as MarkdownImage assertEquals(data.path, image.linkDestination?.text) assertEquals(data.description, image.collectLinkDescriptionText()) } }
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/images/MarkdownLineMarkerApplyChangesTest.kt
79106642
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.caches.resolve import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.SmartList import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory.getLightClassForDecompiledClassOrObject import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport import org.jetbrains.kotlin.asJava.classes.KotlinLightClassFactory import org.jetbrains.kotlin.asJava.classes.KtDescriptorBasedFakeLightClass import org.jetbrains.kotlin.asJava.classes.KtFakeLightClass import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode import org.jetbrains.kotlin.idea.caches.lightClasses.platformMutabilityWrapper import org.jetbrains.kotlin.idea.caches.project.getPlatformModuleInfo import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtScript import org.jetbrains.kotlin.psi.analysisContext import org.jetbrains.kotlin.resolve.scopes.MemberScope open class IDEKotlinAsJavaSupport(private val project: Project) : KotlinAsJavaSupport() { override fun getFacadeNames(packageFqName: FqName, scope: GlobalSearchScope): Collection<String> { val facadeFilesInPackage = project.runReadActionInSmartMode { KotlinFileFacadeClassByPackageIndex.get(packageFqName.asString(), project, scope) } return facadeFilesInPackage.map { it.javaFileFacadeFqName.shortName().asString() }.toSet() } override fun getFacadeClassesInPackage(packageFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> { val facadeFilesInPackage = runReadAction { KotlinFileFacadeClassByPackageIndex.get(packageFqName.asString(), project, scope).platformSourcesFirst() } val groupedByFqNameAndModuleInfo = facadeFilesInPackage.groupBy { Pair(it.javaFileFacadeFqName, it.getModuleInfoPreferringJvmPlatform()) } return groupedByFqNameAndModuleInfo.flatMap { val (key, files) = it val (fqName, moduleInfo) = key createLightClassForFileFacade(fqName, files, moduleInfo) } } override fun findClassOrObjectDeclarations(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtClassOrObject> { return project.runReadActionInSmartMode { KotlinFullClassNameIndex.get( fqName.asString(), project, KotlinSourceFilterScope.projectSourcesAndLibraryClasses(searchScope, project) ) } } override fun findFilesForPackage(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtFile> { return project.runReadActionInSmartMode { KotlinPackageIndexUtils.findFilesWithExactPackage( fqName, KotlinSourceFilterScope.projectSourcesAndLibraryClasses( searchScope, project ), project ) } } override fun findClassOrObjectDeclarationsInPackage( packageFqName: FqName, searchScope: GlobalSearchScope ): Collection<KtClassOrObject> { return KotlinTopLevelClassByPackageIndex.get( packageFqName.asString(), project, KotlinSourceFilterScope.projectSourcesAndLibraryClasses(searchScope, project) ) } override fun packageExists(fqName: FqName, scope: GlobalSearchScope): Boolean { return KotlinPackageIndexUtils.packageExists( fqName, KotlinSourceFilterScope.projectSourcesAndLibraryClasses( scope, project ) ) } override fun getSubPackages(fqn: FqName, scope: GlobalSearchScope): Collection<FqName> { return KotlinPackageIndexUtils.getSubPackageFqNames( fqn, KotlinSourceFilterScope.projectSourcesAndLibraryClasses( scope, project ), MemberScope.ALL_NAME_FILTER, ) } private val recursiveGuard = ThreadLocal<Boolean>() private inline fun <T> guardedRun(body: () -> T): T? { if (recursiveGuard.get() == true) return null return try { recursiveGuard.set(true) body() } finally { recursiveGuard.set(false) } } override fun getLightClass(classOrObject: KtClassOrObject): KtLightClass? { if (!classOrObject.isValid) { return null } val virtualFile = classOrObject.containingFile.virtualFile if (virtualFile != null) { when { RootKindFilter.projectSources.matches(project, virtualFile) -> { return KotlinLightClassFactory.createClass(classOrObject) } RootKindFilter.libraryClasses.matches(project, virtualFile) -> { return getLightClassForDecompiledClassOrObject(classOrObject, project) } RootKindFilter.librarySources.matches(project, virtualFile) -> { return guardedRun { SourceNavigationHelper.getOriginalClass(classOrObject) as? KtLightClass } } } } if ((classOrObject.containingFile as? KtFile)?.analysisContext != null || classOrObject.containingFile.originalFile.virtualFile != null ) { return KotlinLightClassFactory.createClass(classOrObject) } return null } override fun getLightClassForScript(script: KtScript): KtLightClass? { if (!script.isValid) { return null } return KotlinLightClassFactory.createScript(script) } override fun getFacadeClasses(facadeFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> { val filesByModule = findFilesForFacade(facadeFqName, scope).groupBy { it.getModuleInfoPreferringJvmPlatform() } return filesByModule.flatMap { createLightClassForFileFacade(facadeFqName, it.value, it.key) } } override fun getScriptClasses(scriptFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> { return KotlinScriptFqnIndex.get(scriptFqName.asString(), project, scope).mapNotNull { getLightClassForScript(it) } } override fun getKotlinInternalClasses(fqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> { if (fqName.isRoot) return emptyList() val packageParts = findPackageParts(fqName, scope) val platformWrapper = findPlatformWrapper(fqName, scope) return if (platformWrapper != null) packageParts + platformWrapper else packageParts } private fun findPackageParts(fqName: FqName, scope: GlobalSearchScope): List<KtLightClassForDecompiledDeclaration> { val facadeKtFiles = runReadAction { KotlinMultiFileClassPartIndex.get(fqName.asString(), project, scope) } val partShortName = fqName.shortName().asString() val partClassFileShortName = "$partShortName.class" return facadeKtFiles.mapNotNull { facadeKtFile -> if (facadeKtFile is KtClsFile) { val partClassFile = facadeKtFile.virtualFile.parent.findChild(partClassFileShortName) ?: return@mapNotNull null val javaClsClass = DecompiledLightClassesFactory.createClsJavaClassFromVirtualFile(facadeKtFile, partClassFile, null, project) ?: return@mapNotNull null KtLightClassForDecompiledDeclaration(javaClsClass, javaClsClass.parent, facadeKtFile, null) } else { // TODO should we build light classes for parts from source? null } } } private fun findPlatformWrapper(fqName: FqName, scope: GlobalSearchScope): PsiClass? { return platformMutabilityWrapper(fqName) { JavaPsiFacade.getInstance( project ).findClass(it, scope) } } private fun createLightClassForFileFacade( facadeFqName: FqName, facadeFiles: List<KtFile>, moduleInfo: IdeaModuleInfo ): List<PsiClass> = SmartList<PsiClass>().apply { tryCreateFacadesForSourceFiles(moduleInfo, facadeFqName)?.let { sourcesFacade -> add(sourcesFacade) } facadeFiles.filterIsInstance<KtClsFile>().mapNotNullTo(this) { DecompiledLightClassesFactory.createLightClassForDecompiledKotlinFile(it, project) } } private fun tryCreateFacadesForSourceFiles(moduleInfo: IdeaModuleInfo, facadeFqName: FqName): PsiClass? { if (moduleInfo !is ModuleSourceInfo && moduleInfo !is PlatformModuleInfo) return null return KotlinLightClassFactory.createFacade(project, facadeFqName, moduleInfo.contentScope) } override fun findFilesForFacade(facadeFqName: FqName, scope: GlobalSearchScope): Collection<KtFile> { return runReadAction { KotlinFileFacadeFqNameIndex.get(facadeFqName.asString(), project, scope).platformSourcesFirst() } } override fun getFakeLightClass(classOrObject: KtClassOrObject): KtFakeLightClass = KtDescriptorBasedFakeLightClass(classOrObject) override fun createFacadeForSyntheticFile(facadeClassFqName: FqName, file: KtFile): PsiClass = KotlinLightClassFactory.createFacadeForSyntheticFile(facadeClassFqName, file) // NOTE: this is a hacky solution to the following problem: // when building this light class resolver will be built by the first file in the list // (we could assume that files are in the same module before) // thus we need to ensure that resolver will be built by the file from platform part of the module // (resolver built by a file from the common part will have no knowledge of the platform part) // the actual of order of files that resolver receives is controlled by *findFilesForFacade* method private fun Collection<KtFile>.platformSourcesFirst() = sortedByDescending { it.platform.isJvm() } private fun PsiElement.getModuleInfoPreferringJvmPlatform(): IdeaModuleInfo = getPlatformModuleInfo(JvmPlatforms.unspecifiedJvmPlatform) ?: this.moduleInfo }
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IDEKotlinAsJavaSupport.kt
1621136529
// 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.uast.test.kotlin import com.intellij.mock.MockComponentManager import com.intellij.mock.MockProject import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.testFramework.LightProjectDescriptor import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.idea.checkers.CompilerTestLanguageVersionSettings import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoot import org.jetbrains.kotlin.cli.common.messages.MessageRenderer import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM import org.jetbrains.kotlin.cli.jvm.plugins.PluginCliParser import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts import org.jetbrains.kotlin.parsing.KotlinParserDefinition import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension import org.jetbrains.kotlin.idea.test.ConfigurationKind import org.jetbrains.kotlin.test.KotlinRoot import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestJdkKind import org.jetbrains.kotlin.idea.test.testFramework.resetApplicationToNull import org.jetbrains.uast.UastLanguagePlugin import org.jetbrains.uast.evaluation.UEvaluatorExtension import org.jetbrains.uast.kotlin.BaseKotlinUastResolveProviderService import org.jetbrains.uast.kotlin.KotlinUastLanguagePlugin import org.jetbrains.uast.kotlin.KotlinUastResolveProviderService import org.jetbrains.uast.kotlin.evaluation.KotlinEvaluatorExtension import org.jetbrains.uast.kotlin.internal.CliKotlinUastResolveProviderService import org.jetbrains.uast.kotlin.internal.UastAnalysisHandlerExtension import org.jetbrains.uast.test.env.AbstractCoreEnvironment import org.jetbrains.uast.test.kotlin.env.AbstractUastTest import java.io.File abstract class AbstractKotlinUastTest : AbstractUastTest() { private lateinit var compilerConfiguration: CompilerConfiguration private var kotlinCoreEnvironment: KotlinCoreEnvironment? = null open var testDataDir: File = KotlinRoot.DIR.resolve("uast/uast-kotlin/tests/testData") override fun getVirtualFile(testName: String): VirtualFile { val testFile = testDataDir.listFiles { pathname -> pathname.nameWithoutExtension == testName }.first() super.initializeEnvironment(testFile) initializeKotlinEnvironment() enableNewTypeInferenceIfNeeded() val trace = NoScopeRecordCliBindingTrace() val environment = kotlinCoreEnvironment!! TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( project, environment.getSourceFiles(), trace, compilerConfiguration, environment::createPackagePartProvider ) val vfs = VirtualFileManager.getInstance().getFileSystem(URLUtil.FILE_PROTOCOL) val ideaProject = project ideaProject.baseDir = vfs.findFileByPath(TEST_KOTLIN_MODEL_DIR.canonicalPath) return vfs.findFileByPath(testFile.canonicalPath)!! } private fun enableNewTypeInferenceIfNeeded() { val currentLanguageVersionSettings = compilerConfiguration.languageVersionSettings if (currentLanguageVersionSettings.supportsFeature(LanguageFeature.NewInference)) return val extraLanguageFeatures = mutableMapOf<LanguageFeature, LanguageFeature.State>() val extraAnalysisFlags = mutableMapOf<AnalysisFlag<*>, Any?>() if (currentLanguageVersionSettings is CompilerTestLanguageVersionSettings) { extraLanguageFeatures += currentLanguageVersionSettings.extraLanguageFeatures extraAnalysisFlags += currentLanguageVersionSettings.analysisFlags } compilerConfiguration.languageVersionSettings = CompilerTestLanguageVersionSettings( extraLanguageFeatures + (LanguageFeature.NewInference to LanguageFeature.State.ENABLED), currentLanguageVersionSettings.apiVersion, currentLanguageVersionSettings.languageVersion, extraAnalysisFlags ) } private fun initializeKotlinEnvironment() { val area = Extensions.getRootArea() area.getExtensionPoint(UastLanguagePlugin.extensionPointName).registerExtension(KotlinUastLanguagePlugin(), project) area.getExtensionPoint(UEvaluatorExtension.EXTENSION_POINT_NAME).registerExtension(KotlinEvaluatorExtension(), project) val application = ApplicationManager.getApplication() as MockComponentManager application.registerService( BaseKotlinUastResolveProviderService::class.java, CliKotlinUastResolveProviderService::class.java ) project.registerService( KotlinUastResolveProviderService::class.java, CliKotlinUastResolveProviderService::class.java ) } override fun createEnvironment(source: File): AbstractCoreEnvironment { val appWasNull = ApplicationManager.getApplication() == null compilerConfiguration = createKotlinCompilerConfiguration(source) compilerConfiguration.put(JVMConfigurationKeys.USE_PSI_CLASS_FILES_READING, true) compilerConfiguration.put(CLIConfigurationKeys.PATH_TO_KOTLIN_COMPILER_JAR, TestKotlinArtifacts.kotlinCompiler) val parentDisposable = Disposer.newDisposable() val kotlinCoreEnvironment = KotlinCoreEnvironment.createForTests(parentDisposable, compilerConfiguration, EnvironmentConfigFiles.JVM_CONFIG_FILES) this.kotlinCoreEnvironment = kotlinCoreEnvironment AnalysisHandlerExtension.registerExtension( kotlinCoreEnvironment.project, UastAnalysisHandlerExtension() ) return KotlinCoreEnvironmentWrapper(kotlinCoreEnvironment, parentDisposable, appWasNull) } override fun tearDown() { kotlinCoreEnvironment = null super.tearDown() } private fun createKotlinCompilerConfiguration(sourceFile: File): CompilerConfiguration { return KotlinTestUtils.newConfiguration(ConfigurationKind.STDLIB_REFLECT, TestJdkKind.FULL_JDK).apply { addKotlinSourceRoot(sourceFile.canonicalPath) val messageCollector = PrintingMessageCollector(System.err, MessageRenderer.PLAIN_RELATIVE_PATHS, true) put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector) put(CommonConfigurationKeys.MODULE_NAME, LightProjectDescriptor.TEST_MODULE_NAME) if (sourceFile.extension == KotlinParserDefinition.STD_SCRIPT_SUFFIX) { loadScriptingPlugin(this) } } } private class KotlinCoreEnvironmentWrapper( val environment: KotlinCoreEnvironment, val parentDisposable: Disposable, val appWasNull: Boolean ) : AbstractCoreEnvironment() { override fun addJavaSourceRoot(root: File) { TODO("not implemented") } override fun addJar(root: File) { TODO("not implemented") } override val project: MockProject get() = environment.project as MockProject override fun dispose() { Disposer.dispose(parentDisposable) if (appWasNull) { resetApplicationToNull() } } } } val TEST_KOTLIN_MODEL_DIR = KotlinRoot.DIR.resolve("uast/uast-kotlin/tests/testData") private fun loadScriptingPlugin(configuration: CompilerConfiguration) { val pluginClasspath = listOf( TestKotlinArtifacts.kotlinScriptingCompiler, TestKotlinArtifacts.kotlinScriptingCompilerImpl, TestKotlinArtifacts.kotlinScriptingCommon, TestKotlinArtifacts.kotlinScriptingJvm ) PluginCliParser.loadPluginsSafe(pluginClasspath.map { it.absolutePath }, emptyList(), emptyList(), configuration) }
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/AbstractKotlinUastTest.kt
2866857363
package robots import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters @RunWith(Parameterized::class) class CompactSyntaxTest(val what: String, val syntax: String, val ast: Seq) { companion object { private val a = Action("a") private val b = Action("b") private val c = Action("c") private val d = Action("d") private val e = Action("e") private val examples: Map<String, Pair<String, Seq>> = mapOf( "empty program" to Pair("", nop), "sequence of single action" to Pair("a", Seq(a)), "sequence of actions" to Pair("a, b, c", Seq(a, b, c)), "nested program" to Pair("a, [b, c], 4•[d, e]", Seq(a, Seq(b, c), Repeat(4, d, e))), "funky identifiers" to Pair("3•[⬆], 💩", Seq(Repeat(3, Action("⬆")), Action("💩"))) ) @JvmStatic @Parameters(name = "{0}: {1}") fun params() = examples.map { (name, value) -> arrayOf(name, value.first, value.second) } } @Test fun `parses`() { assertThat(what, syntax.toSeq().ok(), equalTo(ast)) } @Test fun `formats`() { assertThat(what, ast.toCompactString(), equalTo(syntax)) } }
jvm/src/test/kotlin/robots/CompactSyntaxTest.kt
1935253458
// MOVE: down class A { fun <caret>foo() { } class B { } }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/classBodyDeclarations/functionAnchors/name.kt
1584118704
package edu.byu.suite.features.testingCenter.service import com.google.gson.GsonBuilder import edu.byu.suite.features.testingCenter.model.scores.ScoresResponseWrapper import edu.byu.support.gson.JsonDateDeserializer import edu.byu.support.retrofit.ByuClient import edu.byu.support.utils.DateUtil import retrofit2.Call import retrofit2.Converter import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query import java.text.SimpleDateFormat import java.util.* /** * Created by cwoodfie on 8/2/16 */ class TestingCenterScoresClient: ByuClient<TestingCenterScoresClient.Api>() { override val baseUrl = "https://api.byu.edu/domains/testingcenter/studenttest/" override fun getConverter(): Converter.Factory = GsonConverterFactory.create(GsonBuilder().registerTypeAdapter(Date::class.java, JsonDateDeserializer(listOf<SimpleDateFormat>(DateUtil.DATE_TIME_TIMEZONE_FORMAT))).create()) override fun getApiInterface() = Api::class.java interface Api { @GET("v1/") @Headers("Accept: application/json") // A null yearTerm returns a list of semesters as well as a list of tests for the current semester fun getScores(@Query("yearTerm") yearTerm: String? = null): Call<ScoresResponseWrapper> } }
app/src/main/java/edu/byu/suite/features/testingCenter/service/TestingCenterScoresClient.kt
980532781
package io.ipoli.android.common.view import android.annotation.SuppressLint import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.support.annotation.DrawableRes import android.support.annotation.StringRes import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.ImageView import android.widget.TextView import com.bluelinelabs.conductor.RestoreViewOnCreateController import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler import io.ipoli.android.R import io.ipoli.android.common.AppState import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.ViewState import io.ipoli.android.common.redux.ViewStateReducer import io.ipoli.android.common.redux.android.ReduxViewController /** * A controller that displays a dialog window, floating on top of its activity's window. * This is a wrapper over [Dialog] object like [android.app.DialogFragment]. * * * Implementations should override this class and implement [.onCreateDialog] to create a custom dialog, such as an [android.app.AlertDialog] */ abstract class BaseDialogController : RestoreViewOnCreateController { protected lateinit var dialog: Dialog private var dismissed: Boolean = false /** * Convenience constructor for use when no arguments are needed. */ protected constructor() : super() /** * Constructor that takes arguments that need to be retained across restarts. * * @param args Any arguments that need to be retained. */ protected constructor(args: Bundle?) : super(args) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val headerView = createHeaderView(inflater) onHeaderViewCreated(headerView) val contentView = onCreateContentView(inflater, savedViewState) val dialogBuilder = AlertDialog.Builder(activity!!) .setView(contentView) headerView?.let { dialogBuilder.setCustomTitle(headerView) } dialog = onCreateDialog(dialogBuilder, contentView, savedViewState) dialog.window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) dialog.ownerActivity = activity!! dialog.setOnDismissListener { dismiss() onDismiss() } if (savedViewState != null) { val dialogState = savedViewState.getBundle(SAVED_DIALOG_STATE_TAG) if (dialogState != null) { dialog.onRestoreInstanceState(dialogState) } } return View(activity) } @SuppressLint("InflateParams") protected open fun createHeaderView(inflater: LayoutInflater): View? { return inflater.inflate(R.layout.view_dialog_header, null) } protected open fun onHeaderViewCreated(headerView: View?) { } protected abstract fun onCreateContentView( inflater: LayoutInflater, savedViewState: Bundle? ): View protected abstract fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog override fun onSaveViewState(view: View, outState: Bundle) { super.onSaveViewState(view, outState) val dialogState = dialog.onSaveInstanceState() outState.putBundle(SAVED_DIALOG_STATE_TAG, dialogState) } override fun onAttach(view: View) { super.onAttach(view) dialog.show() dialog.window.decorView.systemUiVisibility = dialog.ownerActivity.window.decorView.systemUiVisibility dialog.window.clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ) onShow(dialog.window.decorView) } protected open fun onShow(contentView: View) {} override fun onDetach(view: View) { onHide(dialog.window.decorView) dialog.hide() super.onDetach(view) } protected open fun onHide(contentView: View) {} override fun onDestroyView(view: View) { super.onDestroyView(view) dialog.setOnDismissListener(null) dialog.dismiss() } /** * Display the dialog, create a transaction and pushing the controller. * @param router The router on which the transaction will be applied * @param tag The tag for this controller */ fun show(router: Router, tag: String? = null) { dismissed = false router.pushController( RouterTransaction.with(this) .pushChangeHandler(SimpleSwapChangeHandler(false)) .popChangeHandler(SimpleSwapChangeHandler(false)) .tag(tag) ) } /** * Dismiss the dialog and pop this controller */ fun dismiss() { if (dismissed) { return } router.popController(this) dismissed = true } protected open fun onDismiss() { } companion object { private val SAVED_DIALOG_STATE_TAG = "android:savedDialogState" } } abstract class ReduxDialogController<A : Action, VS : ViewState, out R : ViewStateReducer<AppState, VS>>( args: Bundle? = null ) : ReduxViewController<A, VS, R>(args) { protected lateinit var dialog: AlertDialog private lateinit var contentView: View private var dismissed: Boolean = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val headerView = createHeaderView(inflater) onHeaderViewCreated(headerView) contentView = onCreateContentView(inflater, savedViewState) val dialogBuilder = AlertDialog.Builder(contentView.context) .setView(contentView) .setCustomTitle(headerView) dialog = onCreateDialog(dialogBuilder, contentView, savedViewState) dialog.window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) onDialogCreated(dialog, contentView) dialog.setCanceledOnTouchOutside(false) dialog.ownerActivity = activity!! dialog.setOnDismissListener { dismiss() } if (savedViewState != null) { val dialogState = savedViewState.getBundle(SAVED_DIALOG_STATE_TAG) if (dialogState != null) { dialog.onRestoreInstanceState(dialogState) } } return View(activity) } protected open fun createHeaderView(inflater: LayoutInflater): View = inflater.inflate(io.ipoli.android.R.layout.view_dialog_header, null) protected open fun onHeaderViewCreated(headerView: View) { } protected abstract fun onCreateContentView( inflater: LayoutInflater, savedViewState: Bundle? ): View protected abstract fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog protected open fun onDialogCreated(dialog: AlertDialog, contentView: View) { } override fun onSaveViewState(view: View, outState: Bundle) { super.onSaveViewState(view, outState) val dialogState = dialog.onSaveInstanceState() outState.putBundle(SAVED_DIALOG_STATE_TAG, dialogState) } override fun onAttach(view: View) { super.onAttach(view) dialog.show() dialog.window.decorView.systemUiVisibility = dialog.ownerActivity.window.decorView.systemUiVisibility dialog.window.clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ) onShow(dialog.window.decorView) } protected open fun onShow(contentView: View) {} override fun onDetach(view: View) { onHide(dialog.window.decorView) dialog.hide() super.onDetach(view) } protected open fun onHide(contentView: View) {} override fun onDestroyView(view: View) { super.onDestroyView(view) dialog.setOnDismissListener(null) dialog.dismiss() } override fun colorStatusBars() { } /** * Display the dialog, create a transaction and pushing the controller. * @param router The router on which the transaction will be applied * @param tag The tag for this controller */ fun show(router: Router, tag: String? = null) { dismissed = false router.pushController( RouterTransaction.with(this) .pushChangeHandler(SimpleSwapChangeHandler(false)) .popChangeHandler(SimpleSwapChangeHandler(false)) .tag(tag) ) } /** * Dismiss the dialog and pop this controller */ fun dismiss() { if (dismissed) { return } router.popController(this) dismissed = true } override fun onRenderViewState(state: VS) { render(state, contentView) } protected fun changeIcon(@DrawableRes icon: Int) { val headerIcon = dialog.findViewById<ImageView>(io.ipoli.android.R.id.dialogHeaderIcon) headerIcon?.setImageResource(icon) } protected fun changeTitle(@StringRes title: Int) { val headerTitle = dialog.findViewById<TextView>(io.ipoli.android.R.id.dialogHeaderTitle) headerTitle?.setText(title) } protected fun changeLifeCoins(lifeCoins: Int) { val headerLifeCoins = dialog.findViewById<TextView>(io.ipoli.android.R.id.dialogHeaderLifeCoins) headerLifeCoins?.visible() headerLifeCoins?.text = lifeCoins.toString() } protected fun changeNeutralButtonText(@StringRes text: Int) { dialog.getButton(DialogInterface.BUTTON_NEUTRAL).setText(text) } protected fun changePositiveButtonText(@StringRes text: Int) { dialog.getButton(DialogInterface.BUTTON_POSITIVE).setText(text) } protected fun changeNegativeButtonText(@StringRes text: Int) { dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setText(text) } protected fun setNeutralButtonListener(listener: (() -> Unit)?) { dialog.getButton(DialogInterface.BUTTON_NEUTRAL).onDebounceClick { if (listener != null) listener() else dismiss() } } protected fun setPositiveButtonListener(listener: (() -> Unit)?) { dialog.getButton(DialogInterface.BUTTON_POSITIVE).onDebounceClick { if (listener != null) listener() else dismiss() } } protected fun setNegativeButtonListener(listener: (() -> Unit)?) { dialog.getButton(DialogInterface.BUTTON_NEGATIVE).onDebounceClick { if (listener != null) listener() else dismiss() } } companion object { private const val SAVED_DIALOG_STATE_TAG = "android:savedDialogState" } }
app/src/main/java/io/ipoli/android/common/view/BaseDialogController.kt
782703724
package org.akvo.rsr.up.worker import android.content.Context import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import org.akvo.rsr.up.R import org.akvo.rsr.up.dao.RsrDbAdapter import org.akvo.rsr.up.util.ConstantUtil import org.akvo.rsr.up.util.Downloader import org.akvo.rsr.up.util.FileUtil import org.akvo.rsr.up.util.SettingsUtil import java.net.MalformedURLException import java.net.URL class GetOrgDataWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) { override fun doWork(): Result { val appContext = applicationContext val ad = RsrDbAdapter(appContext) val dl = Downloader() var errMsg: String? = null val fetchImages = !SettingsUtil.ReadBoolean(appContext, "setting_delay_image_fetch", false) val host = SettingsUtil.host(appContext) val start = System.currentTimeMillis() ad.open() try { if (FETCH_ORGS) { // Fetch org data. try { if (BRIEF) { dl.fetchTypeaheadOrgList( appContext, ad, URL(host + ConstantUtil.FETCH_ORGS_TYPEAHEAD_URL) ) { sofar, total -> updateProgress(0, sofar, total) } } else { dl.fetchOrgListRestApiPaged( appContext, ad, URL(host + ConstantUtil.FETCH_ORGS_URL) ) { sofar, total -> updateProgress(0, sofar, total) } } // TODO need a way to get this called by the paged fetch: broadcastProgress(0, j, dl.???); } catch (e: Exception) { // probably network reasons Log.e(TAG, "Bad organisation fetch:", e) errMsg = appContext.resources.getString(R.string.errmsg_org_fetch_failed) + e.message } } if (FETCH_EMPLOYMENTS) { // Fetch emp data. try { dl.fetchEmploymentListPaged( appContext, ad, URL( host + String.format( ConstantUtil.FETCH_EMPLOYMENTS_URL_PATTERN, SettingsUtil.getAuthUser(appContext).id ) ) ) { sofar, total -> updateProgress(0, sofar, total) } // TODO need a way to get this called by the paged fetch: broadcastProgress(0, j, dl.???); } catch (e: Exception) { // probably network reasons Log.e(TAG, "Bad employment fetch:", e) errMsg = appContext.resources.getString(R.string.errmsg_emp_fetch_failed) + e.message } } updateProgress(0, 100, 100) try { if (FETCH_COUNTRIES && ad.getCountryCount() == 0) { // rarely changes, so only fetch countries if we never did that dl.fetchCountryListRestApiPaged( appContext, ad, URL(SettingsUtil.host(appContext) + String.format(ConstantUtil.FETCH_COUNTRIES_URL)) ) } } catch (e: Exception) { // probably network reasons Log.e(TAG, "Bad organisation fetch:", e) errMsg = appContext.resources.getString(R.string.errmsg_org_fetch_failed) + e.message } updateProgress(1, 100, 100) // logos? if (fetchImages) { try { dl.fetchMissingThumbnails( appContext, host, FileUtil.getExternalCacheDir(appContext).toString() ) { sofar, total -> updateProgress(2, sofar, total) } } catch (e: MalformedURLException) { Log.e(TAG, "Bad thumbnail URL:", e) errMsg = "Thumbnail url problem: $e" } } } finally { ad.close() } val end = System.currentTimeMillis() Log.i(TAG, "Fetch complete in: " + (end - start) / 1000.0) // broadcast completion return if (errMsg != null) { Result.failure(workDataOf(ConstantUtil.SERVICE_ERRMSG_KEY to errMsg)) } else { Result.success() } } private fun updateProgress(phase: Int, sofar: Int, total: Int) { setProgressAsync( workDataOf( ConstantUtil.PHASE_KEY to phase, ConstantUtil.SOFAR_KEY to sofar, ConstantUtil.TOTAL_KEY to total ) ) } companion object { const val TAG = "GetOrgDataWorker" private const val FETCH_EMPLOYMENTS = true private const val FETCH_ORGS = true private const val FETCH_COUNTRIES = true private const val BRIEF = false // TODO put the brief/full flag in the intent } }
android/AkvoRSR/app/src/main/java/org/akvo/rsr/up/worker/GetOrgDataWorker.kt
4047099449
// WITH_STDLIB fun test(list: List<Int>) { val single: Int = list.<caret>filter { it > 1 }.single() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/single.kt
520250189
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.openapi.application.runReadAction import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileDocumentManagerListener import com.intellij.openapi.fileEditor.FileDocumentSynchronizationVetoer import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Messages.getQuestionIcon import com.intellij.openapi.ui.Messages.showOkCancelDialog import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolderEx import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangesUtil private sealed class SaveState private object SaveDenied : SaveState() private class ConfirmSave(val project: Project) : SaveState() private val SAVE_STATE_KEY = Key<SaveState>("Vcs.Commit.SaveState") private fun getSaveState(document: Document): SaveState? = document.getUserData(SAVE_STATE_KEY) private fun setSaveState(documents: Collection<Document>, state: SaveState?) = documents.forEach { it.putUserData(SAVE_STATE_KEY, state) } private fun replaceSaveState(documents: Map<Document, SaveState?>, newState: SaveState?) = documents.forEach { (document, oldState) -> (document as UserDataHolderEx).replace(SAVE_STATE_KEY, oldState, newState) } internal class SaveCommittingDocumentsVetoer : FileDocumentSynchronizationVetoer(), FileDocumentManagerListener { override fun beforeAllDocumentsSaving() { val confirmSaveDocuments = FileDocumentManager.getInstance().unsavedDocuments .associateBy({ it }, { getSaveState(it) }) .filterValues { it is ConfirmSave } .mapValues { it.value as ConfirmSave } if (confirmSaveDocuments.isEmpty()) return val project = confirmSaveDocuments.values.first().project val newSaveState = if (confirmSave(project, confirmSaveDocuments.keys)) null else SaveDenied replaceSaveState(confirmSaveDocuments, newSaveState) // use `replace` as commit could already be completed } override fun maySaveDocument(document: Document, isSaveExplicit: Boolean): Boolean = when (val saveState = getSaveState(document)) { SaveDenied -> false is ConfirmSave -> confirmSave(saveState.project, listOf(document)) null -> true } } fun vetoDocumentSaving(project: Project, changes: Collection<Change>, block: () -> Unit) { vetoDocumentSavingForPaths(project, ChangesUtil.getPaths(changes), block) } fun vetoDocumentSavingForPaths(project: Project, filePaths: Collection<FilePath>, block: () -> Unit) { val confirmSaveState = ConfirmSave(project) val documents = runReadAction { getDocuments(filePaths).also { setSaveState(it, confirmSaveState) } } try { block() } finally { runReadAction { setSaveState(documents, null) } } } private fun getDocuments(filePaths: Iterable<FilePath>): List<Document> = filePaths .mapNotNull { it.virtualFile } .filterNot { it.fileType.isBinary } .mapNotNull { FileDocumentManager.getInstance().getDocument(it) } .toList() private fun confirmSave(project: Project, documents: Collection<Document>): Boolean { val files = documents.mapNotNull { FileDocumentManager.getInstance().getFile(it) } val text = message("save.committing.files.confirmation.text", documents.size, files.joinToString("\n") { it.presentableUrl }) return Messages.OK == showOkCancelDialog( project, text, message("save.committing.files.confirmation.title"), message("save.committing.files.confirmation.ok"), message("save.committing.files.confirmation.cancel"), getQuestionIcon() ) }
platform/vcs-impl/src/com/intellij/vcs/commit/SaveCommittingDocumentsVetoer.kt
3542442859
// 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 training.learn import com.intellij.DynamicBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey @NonNls private const val BUNDLE = "messages.LessonsBundle" object LessonsBundle : DynamicBundle(BUNDLE) { @Nls fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params) }
plugins/ide-features-trainer/src/training/learn/LessonsBundle.kt
2703650486
package pack import pack.A.* internal class A @JvmOverloads constructor(nested: Nested = Nested(Nested.FIELD)) { internal class Nested(p: Int) { companion object { val FIELD = 0 } } } internal class B { var nested: Nested? = null }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/constructors/nestedClassNameInParameterDefaults4.kt
1457138679
package com.eldersoss.identitykit.errors class OAuth2InvalidScopeError : OAuth2Error() { override val errorType: OAuth2ErrorType = OAuth2ErrorType.INVALID_SCOPE }
identitykit/src/main/java/com/eldersoss/identitykit/errors/OAuth2InvalidScopeError.kt
3832547108
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn.mergeinfo import org.jetbrains.idea.svn.api.ErrorCode.MERGE_INFO_PARSE_ERROR import org.jetbrains.idea.svn.commandLine.SvnBindException data class MergeRangeList(val ranges: Set<MergeRange>) { companion object { @JvmStatic @Throws(SvnBindException::class) fun parseMergeInfo(value: String): Map<String, MergeRangeList> = value.lineSequence().map { parseLine(it) }.toMap() @Throws(SvnBindException::class) fun parseRange(value: String): MergeRange { val revisions = value.removeSuffix("*").split('-') if (revisions.isEmpty() || revisions.size > 2) throwParseFailed(value) val start = parseRevision(revisions[0]) val end = if (revisions.size == 2) parseRevision(revisions[1]) else start return MergeRange(start, end, value.lastOrNull() != '*') } private fun parseLine(value: String): Pair<String, MergeRangeList> { val parts = value.split(':') if (parts.size != 2) throwParseFailed(value) return Pair(parts[0], MergeRangeList(parts[1].splitToSequence(',').map { parseRange(it) }.toSet())) } private fun parseRevision(value: String) = try { value.toLong() } catch (e: NumberFormatException) { throwParseFailed(value) } private fun throwParseFailed(value: String): Nothing = throw SvnBindException(MERGE_INFO_PARSE_ERROR, "Could not parse $value") } }
plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeRangeList.kt
440230301
/* * Copyright (c) 2016. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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 pdvrieze on 04/04/16. */ package kotlinsql.builder import java.io.Writer @Suppress("unused") class GenerateDatabaseBaseKt { fun doGenerate(output: Writer, input: Any) { val count = input as Int output.apply { appendCopyright() appendLine() appendLine("package io.github.pdvrieze.kotlinsql.dml") appendLine() appendLine("import io.github.pdvrieze.kotlinsql.ddl.Column") appendLine("import io.github.pdvrieze.kotlinsql.ddl.IColumnType") appendLine("import io.github.pdvrieze.kotlinsql.ddl.Table") appendLine("import io.github.pdvrieze.kotlinsql.ddl.TableRef") appendLine("import io.github.pdvrieze.kotlinsql.dml.impl.*") appendLine("import io.github.pdvrieze.kotlinsql.dml.impl.DatabaseMethodsBase") appendLine() appendLine("interface DatabaseMethods : DatabaseMethodsBase {") // appendln(" companion object {") appendLine(" operator fun get(key:TableRef):Table") appendFunctionGroup("SELECT", "_Select", count, "_Select") appendFunctionGroup("INSERT", "_Insert", count) appendFunctionGroup("INSERT_OR_UPDATE", "_Insert", count) // appendLine(" }") appendLine("}") } } private fun Writer.appendFunctionGroup(funName: String, className: String, count: Int, interfaceName: String = className) { for (n in 1..count) { appendLine() // appendln(" @JvmStatic") append(" fun <") run { val indent = " ".repeat(if (n < 9) 9 else 10) (1..n).joinToString(",\n$indent") { m -> "T$m:Any, S$m:IColumnType<T$m,S$m,C$m>, C$m: Column<T$m, S$m, C$m>" } .apply { append(this) } } append(">\n $funName(") (1..n).joinToString { m -> "col$m: C$m" }.apply { append(this) } append("): ") if (n == 1 && funName == "SELECT") { append("$interfaceName$n<T1, S1, C1>") } else { (1..n).joinTo(this, prefix = "$interfaceName$n<", postfix = ">") { m -> "T$m, S$m, C$m" } } appendLine(" =") if (className == "_Insert") { val update = funName == "INSERT_OR_UPDATE" append(" $className$n(get(col1.table), $update, ") } else if (n == 1 && funName == "SELECT") { append(" $className$n(") } else { append(" $className$n(") } (1..n).joinToString { m -> "col$m" }.apply { append(this) } appendLine(")") } } }
sql/src/generators/kotlin/kotlinsql/builder/generate_database_statics.kt
1669313729
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.http.cio.websocket import io.ktor.websocket.* import kotlin.test.* class WebSocketExtensionHeaderTest { @Test fun testParseExtensions() { val result = parseWebSocketExtensions("superspeed, colormode; depth=16") assertEquals(2, result.size) assertEquals("superspeed", result[0].name) assertEquals("colormode", result[1].name) assertEquals(0, result[0].parameters.size) assertEquals(1, result[1].parameters.size) assertEquals("depth=16", result[1].parameters[0]) } }
ktor-shared/ktor-websockets/common/test/io/ktor/tests/http/cio/websocket/WebSocketExtensionHeaderTest.kt
482439654
package lt.markmerkk.migration import org.apache.commons.io.FileUtils import org.slf4j.Logger import java.io.File /** * Migration that would move configuration by the app flavor. * This is needed, as both flavors normally "inherit" its configuration and its changes * thus resulting in incorrect application when both applications are launched. * * For instance, when both apps are launched and are using different jiras at the same time */ class ConfigMigration1( private val versionCode: Int, private val configDirLegacy: File, private val configDirFull: File, private val l: Logger ) : ConfigPathMigrator.ConfigMigration { override fun isMigrationNeeded(): Boolean { val configCountInFull = ConfigUtils.listConfigs(configDirFull) .count() // Only one version would trigger migration + full path should be empty l.info("Checking if configs need migration1: [configCountInFull <= 1($configCountInFull)] " + "/ [versionCode <= 67($versionCode)]") return configCountInFull <= 1 && versionCode <= 67 } override fun doMigration() { l.info("Triggering migration1...") ConfigUtils.listConfigs(configDirLegacy) .filter { it != configDirFull } .filterNot { it.isDirectory && it.name == "logs" } // ignore log directory .forEach { try { FileUtils.copyToDirectory(it, configDirFull) } catch (e: Exception) { l.warn("Error doing migration1", e) } } l.info("Migration complete!") } }
components/src/main/java/lt/markmerkk/migration/ConfigMigration1.kt
1242915422
package xyz.javecs.tools.text2expr.test.kotlin import org.junit.Test import xyz.javecs.tools.text2expr.rules.RuleRenderer import xyz.javecs.tools.text2expr.rules.Variable import xyz.javecs.tools.text2expr.templates.TemplateLoader import xyz.javecs.tools.text2expr.utils.read import kotlin.test.assertEquals class RuleRendererTest { @Test fun renderer1() { val expected = """ |x = 1.0 |y = 1.0 | |こうだから、 |x+y | |答えは、 |2 | """.trimMargin("|") val template = read("test-templates/template1.st") val renderer = RuleRenderer(template) renderer.add("variables", listOf(Variable("x", 1.0), Variable("y", 1.0))) renderer.add("expr", listOf("x+y")) renderer.add("value", 2) assertEquals(expected, renderer.render()) assertEquals(3, renderer.attributes().size) renderer.clear() assertEquals(3, renderer.attributes().size) renderer.add("variables", listOf(Variable("x", 1.0), Variable("y", 1.0))) renderer.add("expr", listOf("x+y")) renderer.add("value", 2) assertEquals(expected, renderer.render()) renderer.add("variables", listOf(Variable("x", 1.0), Variable("y", 1.0)), overwrite = true) renderer.add("expr", listOf("x+y"), overwrite = true) renderer.add("value", 2, overwrite = true) assertEquals(expected, renderer.render()) assertEquals(3, renderer.attributes().size) } @Test fun renderer2() { val template = TemplateLoader().defaultTemplate val renderer = RuleRenderer(template) renderer.add("value1", "Hello") assertEquals("", renderer.render()) renderer.add("value", "Hello") assertEquals("Hello", renderer.render()) renderer.add("value", 5, overwrite = true) assertEquals("5", renderer.render()) } @Test fun render3() { val template = TemplateLoader().defaultTemplate val rendered = RuleRenderer(template).apply { add("value", "1") add("value", "2") add("value", "3") add("value", "4") add("value", "5") }.render() assertEquals("12345", rendered) } }
src/test/kotlin/xyz/javecs/tools/text2expr/test/kotlin/RuleRendererTest.kt
3299888413
package fr.tikione.c2e.core.service.home import fr.tikione.c2e.core.model.home.MagazineSummary import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File class LocalReaderServiceImpl : LocalReaderService { private val log: Logger = LoggerFactory.getLogger(this.javaClass) override fun listDownloadedMagazines(folder: File): List<MagazineSummary> { log.info("analyse du repertoire $folder") return folder .listFiles { _, name -> name.endsWith(".html") } .filter { file -> !file.name.startsWith("CPC-") } .map { file -> val filename = file.name val mag = MagazineSummary() val size = file.length() if (size > 4 * 1024 * 1014) mag.humanSize = ((size / (1024 * 1014)).toString() + " Mo") else mag.humanSize = ((size / 1024).toString() + " Ko") if (filename.contains("-")) { mag.number = filename.substring("CPC".length, filename.indexOf("-")) mag.file = file when { filename.contains("-nopic") -> mag.options = "sans images" filename.contains("-resize") -> { val picRatio = filename.substring(filename.indexOf("-resize") + "-resize".length, filename.indexOf(".")) mag.options = "images ratio $picRatio%" } else -> mag.options = "images ratio 100%" } } else { mag.number = filename.substring("CPC".length, filename.indexOf(".")) mag.file = file mag.options = "images ratio 100%" } val coverImgTag = "<img class='edito-cover-img' src='" val coverLine = file.readLines().firstOrNull { s -> s.contains(coverImgTag) } if (coverLine == null) { mag.coverAsBase64 = "" } else { mag.coverAsBase64 = coverLine.substring(coverLine.indexOf(coverImgTag) + coverImgTag.length, coverLine.indexOf("'>")) } log.info("magazine trouve : $mag") mag } .toList() } }
src/main/kotlin/fr/tikione/c2e/core/service/home/LocalReaderServiceImpl.kt
1479637626
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.kayenta.pipeline import com.fasterxml.jackson.module.kotlin.convertValue import com.netflix.spinnaker.moniker.Moniker import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.DisableClusterStage import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.ShrinkClusterStage import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper import com.netflix.spinnaker.orca.pipeline.WaitStage import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import java.time.Duration internal object CleanupCanaryClustersStageTest : Spek({ val subject = CleanupCanaryClustersStage() val mapper = OrcaObjectMapper.newInstance() given("a canary deployment pipeline") { val baseline = mapOf( "application" to "spindemo", "account" to "prod", "cluster" to "spindemo-prestaging-prestaging" ) val controlCluster = mapOf( "account" to "prod", "application" to "spindemo", "availabilityZones" to mapOf( "us-west-1" to listOf("us-west-1a", "us-west-1c") ), "capacity" to mapOf("desired" to 1, "max" to 1, "min" to 1), "cloudProvider" to "aws", "cooldown" to 10, "copySourceCustomBlockDeviceMappings" to true, "ebsOptimized" to false, "enabledMetrics" to listOf<Any>(), "freeFormDetails" to "prestaging-baseline", "healthCheckGracePeriod" to 600, "healthCheckType" to "EC2", "iamRole" to "spindemoInstanceProfile", "instanceMonitoring" to true, "instanceType" to "m3.large", "interestingHealthProviderNames" to listOf("Amazon"), "keyPair" to "nf-prod-keypair-a", "loadBalancers" to listOf<Any>(), "moniker" to mapOf( "app" to "spindemo", "cluster" to "spindemo-prestaging-prestaging-baseline", "detail" to "prestaging-baseline", "stack" to "prestaging" ), "provider" to "aws", "securityGroups" to listOf("sg-b575ded0", "sg-b775ded2", "sg-dbe43abf"), "spotPrice" to "", "stack" to "prestaging", "subnetType" to "internal (vpc0)", "suspendedProcesses" to listOf<Any>(), "tags" to mapOf<String, Any>(), "targetGroups" to listOf<Any>(), "targetHealthyDeployPercentage" to 100, "terminationPolicies" to listOf("Default"), "useAmiBlockDeviceMappings" to false, "useSourceCapacity" to false ) val experimentCluster = mapOf( "account" to "prod", "application" to "spindemo", "availabilityZones" to mapOf( "us-west-1" to listOf("us-west-1a", "us-west-1c") ), "capacity" to mapOf("desired" to 1, "max" to 1, "min" to 1), "cloudProvider" to "aws", "cooldown" to 10, "copySourceCustomBlockDeviceMappings" to true, "ebsOptimized" to false, "enabledMetrics" to listOf<Any>(), "freeFormDetails" to "prestaging-canary", "healthCheckGracePeriod" to 600, "healthCheckType" to "EC2", "iamRole" to "spindemoInstanceProfile", "instanceMonitoring" to true, "instanceType" to "m3.large", "interestingHealthProviderNames" to listOf("Amazon"), "keyPair" to "nf-prod-keypair-a", "loadBalancers" to listOf<Any>(), "moniker" to mapOf( "app" to "spindemo", "cluster" to "spindemo-prestaging-prestaging-canary", "detail" to "prestaging-canary", "stack" to "prestaging" ), "provider" to "aws", "securityGroups" to listOf("sg-b575ded0", "sg-b775ded2", "sg-dbe43abf"), "spotPrice" to "", "stack" to "prestaging", "subnetType" to "internal (vpc0)", "suspendedProcesses" to listOf<Any>(), "tags" to mapOf<String, Any>(), "targetGroups" to listOf<Any>(), "targetHealthyDeployPercentage" to 100, "terminationPolicies" to listOf("Default"), "useAmiBlockDeviceMappings" to false, "useSourceCapacity" to false ) val delayBeforeCleanup = Duration.ofHours(3) val pipeline = pipeline { stage { refId = "1" type = KayentaCanaryStage.STAGE_TYPE context["deployments"] = mapOf( "baseline" to baseline, "control" to controlCluster, "experiment" to experimentCluster, "delayBeforeCleanup" to delayBeforeCleanup.toString() ) stage { refId = "1<1" type = DeployCanaryClustersStage.STAGE_TYPE } stage { refId = "1>1" type = CleanupCanaryClustersStage.STAGE_TYPE syntheticStageOwner = STAGE_AFTER } } } val canaryCleanupStage = pipeline.stageByRef("1>1") val beforeStages = subject.beforeStages(canaryCleanupStage) it("first disables the control and experiment clusters") { beforeStages.named("Disable control cluster") { assertThat(type).isEqualTo(DisableClusterStage.STAGE_TYPE) assertThat(requisiteStageRefIds).isEmpty() assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(controlCluster["account"]) assertThat(context["cluster"]).isEqualTo((controlCluster["moniker"] as Map<String, Any>)["cluster"]) assertThat(context["moniker"]).isEqualTo(mapper.convertValue<Moniker>(controlCluster["moniker"]!!)) assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["remainingEnabledServerGroups"]).isEqualTo(0) } beforeStages.named("Disable experiment cluster") { assertThat(type).isEqualTo(DisableClusterStage.STAGE_TYPE) assertThat(requisiteStageRefIds).isEmpty() assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(experimentCluster["account"]) assertThat(context["cluster"]).isEqualTo((experimentCluster["moniker"] as Map<String, Any>)["cluster"]) assertThat(context["moniker"]).isEqualTo(mapper.convertValue<Moniker>(experimentCluster["moniker"]!!)) assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["remainingEnabledServerGroups"]).isEqualTo(0) } } it("waits after disabling the clusters") { beforeStages.named("Wait before cleanup") { assertThat(type).isEqualTo(WaitStage.STAGE_TYPE) assertThat( requisiteStageRefIds .map(pipeline::stageByRef) .map(Stage::getName) ).containsExactlyInAnyOrder( "Disable control cluster", "Disable experiment cluster" ) assertThat(context["waitTime"]).isEqualTo(delayBeforeCleanup.seconds) } } it("finally destroys the clusters") { beforeStages.named("Cleanup control cluster") { assertThat(type).isEqualTo(ShrinkClusterStage.STAGE_TYPE) assertThat( requisiteStageRefIds .map(pipeline::stageByRef) .map(Stage::getName) ).containsExactly("Wait before cleanup") assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(controlCluster["account"]) assertThat(context["cluster"]).isEqualTo((controlCluster["moniker"] as Map<String, Any>)["cluster"]) assertThat(context["moniker"]).isEqualTo(mapper.convertValue<Moniker>(controlCluster["moniker"]!!)) assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["allowDeleteActive"]).isEqualTo(true) assertThat(context["shrinkToSize"]).isEqualTo(0) } beforeStages.named("Cleanup experiment cluster") { assertThat(type).isEqualTo(ShrinkClusterStage.STAGE_TYPE) assertThat( requisiteStageRefIds .map(pipeline::stageByRef) .map(Stage::getName) ).containsExactly("Wait before cleanup") assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(experimentCluster["account"]) assertThat(context["cluster"]).isEqualTo((experimentCluster["moniker"] as Map<String, Any>)["cluster"]) assertThat(context["moniker"]).isEqualTo(mapper.convertValue<Moniker>(experimentCluster["moniker"]!!)) assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["allowDeleteActive"]).isEqualTo(true) assertThat(context["shrinkToSize"]).isEqualTo(0) } } } })
orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/CleanupCanaryClustersStageTest.kt
1018343665
/* * Copyright 2022 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. */ import org.gradle.api.Project import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.configure fun Project.configureLicensee() { apply(plugin = "app.cash.licensee") configure<app.cash.licensee.LicenseeExtension> { allow("Apache-2.0") allow("MIT") // Occasionally, dependencies may add their licenses via a direct URL instead of an SPDX id. nonStandardLicenseUrls.forEach { allowUrl(it) } ignoreDependencies("junit", "junit") { because("JUnit is used in tests only, so it is not distributed with our library") } ignoreDependencies("org.jacoco", "org.jacoco.agent") { because("JaCoCo is used in tests only, so it is not distributed with our library") } allowDependency("org.javassist", "javassist", "3.20.0-GA") { because("Multi-licensed under Apache. https://github.com/jboss-javassist/javassist") } // xpp3 (HAPI FHIR transitive dep) allowDependency("xpp3", "xpp3_xpath", "1.1.4c") { because("Custom license, essentially BSD-5. https://fedoraproject.org/wiki/Licensing/xpp") } // json-patch and its transitive deps allowDependency("com.github.java-json-tools", "btf", "1.3") { because("Dual-licensed under Apache. https://github.com/java-json-tools/btf") } allowDependency("com.github.java-json-tools", "jackson-coreutils", "2.0") { because("Dual-licensed under Apache. https://github.com/java-json-tools/jackson-coreutils") } allowDependency("com.github.java-json-tools", "json-patch", "1.13") { because("Dual-licensed under Apache. https://github.com/java-json-tools/json-patch") } allowDependency("com.github.java-json-tools", "msg-simple", "1.2") { because("Dual-licensed under Apache. https://github.com/java-json-tools/msg-simple") } // SQLCipher allowDependency("net.zetetic", "android-database-sqlcipher", "4.5.0") { because("Custom license, essentially BSD-3. https://www.zetetic.net/sqlcipher/license/") } // Jakarta XML Binding API allowDependency("jakarta.xml.bind", "jakarta.xml.bind-api", "2.3.3") { because("BSD 3-clause.") } // Jakarta Activation API 2.1 Specification allowDependency("jakarta.activation", "jakarta.activation-api", "1.2.2") { because( "Licensed under Eclipse Distribution License 1.0. http://www.eclipse.org/org/documents/edl-v10.php" ) } // Javax Annotation API allowDependency("javax.annotation", "javax.annotation-api", "1.3.2") { because("Dual-licensed under CDDL 1.1 and GPL v2 with classpath exception.") } // Streaming API for XML (StAX) allowDependency("javax.xml.stream", "stax-api", "1.0-2") { because("Dual-licensed under CDDL 1.0 and GPL v3.") } // xml-commons allowDependency("xml-apis", "xml-apis", "1.4.01") { because("Licensed under Mozilla Public License Version 2.0. http://www.mozilla.org/MPL/2.0/") } // The XSLT and XQuery Processor allowDependency("net.sf.saxon", "Saxon-HE", "9.8.0-15") { because("BSD 3-clause. http://www.antlr.org/license.html") } // ANTLR 4 allowDependency("org.antlr", "antlr-runtime", "3.5.3") { because("BSD 3-clause. http://www.antlr.org/license.html") } // ANTLR 4 allowDependency("org.antlr", "antlr4-runtime", "4.10.1") { because("BSD 3-clause. http://www.antlr.org/license.html") } // ANTLR 4 allowDependency("org.antlr", "antlr4", "4.10.1") { because("BSD 3-clause. http://www.antlr.org/license.html") } // Utilities // https://developers.google.com/android/reference/com/google/android/gms/common/package-summary allowDependency("com.google.android.gms", "play-services-base", "17.4.0") { because("") } // More utility classes // https://developers.google.com/android/reference/com/google/android/gms/common/package-summary allowDependency("com.google.android.gms", "play-services-basement", "17.4.0") { because("") } // https://developers.google.com/android/reference/com/google/android/gms/common/package-summary allowDependency("com.google.android.gms", "play-services-clearcut", "17.0.0") { because("") } // ML Kit barcode scanning https://developers.google.com/ml-kit/vision/barcode-scanning/android allowDependency("com.google.android.gms", "play-services-mlkit-barcode-scanning", "16.1.4") { because("") } // Play Services Phenotype allowDependency("com.google.android.gms", "play-services-phenotype", "17.0.0") { because("") } // Tasks API Android https://developers.google.com/android/guides/tasks allowDependency("com.google.android.gms", "play-services-tasks", "17.2.0") { because("") } // Barcode Scanning https://developers.google.com/ml-kit/vision/barcode-scanning allowDependency("com.google.mlkit", "barcode-scanning", "16.1.1") { because("") } // MLKit Common https://developers.google.com/ml-kit/vision/barcode-scanning allowDependency("com.google.mlkit", "common", "17.1.1") { because("") } // Object Detection https://developers.google.com/ml-kit/vision/object-detection allowDependency("com.google.mlkit", "object-detection", "16.2.3") { because("") } // Object Detection https://developers.google.com/ml-kit/vision/object-detection allowDependency("com.google.mlkit", "object-detection-common", "17.0.0") { because("") } // Object Detection https://developers.google.com/ml-kit/vision/object-detection allowDependency("com.google.mlkit", "object-detection-custom", "16.3.1") { because("") } // Vision Common // https://developers.google.com/android/reference/com/google/mlkit/vision/common/package-summary allowDependency("com.google.mlkit", "vision-common", "16.3.0") { because("") } // Vision Common // https://developers.google.com/android/reference/com/google/mlkit/vision/common/package-summary allowDependency("com.google.mlkit", "vision-internal-vkp", "18.0.0") { because("") } } } private val nonStandardLicenseUrls = listOf( // BSD-3 "http://opensource.org/licenses/BSD-3-Clause", "http://www.opensource.org/licenses/bsd-license.php", )
buildSrc/src/main/kotlin/LicenseeConfig.kt
3094315096
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.visualization import java.util.* import org.hisp.dhis.android.core.common.AggregationType import org.hisp.dhis.android.core.common.ObjectWithUid import org.hisp.dhis.android.core.common.RelativePeriod internal data class VisualizationAPI36( val id: String, val code: String?, val name: String?, val displayName: String?, val created: Date?, val lastUpdated: Date?, val deleted: Boolean?, val description: String?, val displayDescription: String?, val displayFormName: String?, val title: String?, val displayTitle: String?, val subtitle: String?, val displaySubtitle: String?, val type: VisualizationType?, val hideTitle: Boolean?, val hideSubtitle: Boolean?, val hideEmptyColumns: Boolean?, val hideEmptyRows: Boolean?, val hideEmptyRowItems: HideEmptyItemStrategy?, val hideLegend: Boolean?, val showHierarchy: Boolean?, val rowTotals: Boolean?, val rowSubTotals: Boolean?, val colTotals: Boolean?, val colSubTotals: Boolean?, val showDimensionLabels: Boolean?, val percentStackedValues: Boolean?, val noSpaceBetweenColumns: Boolean?, val skipRounding: Boolean?, val displayDensity: DisplayDensity?, val digitGroupSeparator: DigitGroupSeparator?, val relativePeriods: Map<RelativePeriod, Boolean>?, val categoryDimensions: List<CategoryDimension>?, val filterDimensions: List<String>?, val rowDimensions: List<String>?, val columnDimensions: List<String>?, val dataDimensionItems: List<DataDimensionItem>?, val organisationUnitLevels: List<Int>?, val userOrganisationUnit: Boolean?, val userOrganisationUnitChildren: Boolean?, val userOrganisationUnitGrandChildren: Boolean?, val organisationUnits: List<ObjectWithUid>?, val periods: List<ObjectWithUid>?, val legendSet: ObjectWithUid?, val legendDisplayStyle: LegendStyle?, val legendDisplayStrategy: LegendStrategy?, val aggregationType: AggregationType? ) { fun toVisualization(): Visualization = Visualization.builder() .uid(id) .code(code) .name(name) .displayName(displayName) .created(created) .lastUpdated(lastUpdated) .deleted(deleted) .description(description) .displayDescription(displayDescription) .displayFormName(displayFormName) .title(title) .displayTitle(displayTitle) .subtitle(subtitle) .displaySubtitle(displaySubtitle) .type(type) .hideTitle(hideTitle) .hideSubtitle(hideSubtitle) .hideEmptyColumns(hideEmptyColumns) .hideEmptyRows(hideEmptyRows) .hideEmptyRowItems(hideEmptyRowItems) .hideLegend(hideLegend) .showHierarchy(showHierarchy) .rowTotals(rowTotals) .rowSubTotals(rowSubTotals) .colTotals(colTotals) .colSubTotals(colSubTotals) .showDimensionLabels(showDimensionLabels) .percentStackedValues(percentStackedValues) .noSpaceBetweenColumns(noSpaceBetweenColumns) .skipRounding(skipRounding) .displayDensity(displayDensity) .digitGroupSeparator(digitGroupSeparator) .relativePeriods(relativePeriods) .categoryDimensions(categoryDimensions) .filterDimensions(filterDimensions) .rowDimensions(rowDimensions) .columnDimensions(columnDimensions) .dataDimensionItems(dataDimensionItems) .organisationUnitLevels(organisationUnitLevels) .userOrganisationUnit(userOrganisationUnit) .userOrganisationUnitChildren(userOrganisationUnitChildren) .userOrganisationUnitGrandChildren(userOrganisationUnitGrandChildren) .organisationUnits(organisationUnits) .periods(periods) .aggregationType(aggregationType) .legend( VisualizationLegend.builder() .set(legendSet) .style(legendDisplayStyle) .strategy(legendDisplayStrategy) .showKey(false) .build() ) .build() }
core/src/main/java/org/hisp/dhis/android/core/visualization/VisualizationAPI36.kt
1129447082
package com.stanfy.helium.handler.codegen.swift.entity.filegenerator /** * Generic interface for all swift files */ interface SwiftFile { /** * file name */ fun name(): String /** * File contents */ fun contents(): String }
codegen/swift/swift-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/swift/entity/filegenerator/SwiftFile.kt
1542637717
package com.nice.balafm.util import android.content.Context import android.util.Log import android.widget.Toast import okhttp3.* private val client = OkHttpClient() private val JSON = MediaType.parse("application/json; charset=utf-8") internal val HOST_ADDRESS = "http://115.159.67.95" @JvmOverloads fun Context.postJsonRequest(url: String, json: String, callback: Callback, okHttpClient: OkHttpClient = client) { fun isNetworkAvailable() = true if (!isNetworkAvailable()) { Toast.makeText(this, "网络连接不可用, 请连接网络后重试", Toast.LENGTH_SHORT).show() return } val body = RequestBody.create(JSON, json) val request = Request.Builder() .url(url) .post(body) .build() Log.d("request_to_server", "URL: $url, JSON: $json") okHttpClient.newCall(request).enqueue(callback) }
app/src/main/java/com/nice/balafm/util/HttpUtil.kt
3141653517