repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AndroidX/androidx
|
lifecycle/lifecycle-reactivestreams-ktx/src/test/java/androidx/lifecycle/LiveDataReactiveStreamsTest.kt
|
3
|
2233
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.lifecycle
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.testing.TestLifecycleOwner
import com.google.common.truth.Truth.assertThat
import io.reactivex.processors.PublishProcessor
import io.reactivex.processors.ReplayProcessor
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class LiveDataReactiveStreamsTest {
@get:Rule val rule = InstantTaskExecutorRule()
private lateinit var lifecycleOwner: LifecycleOwner
@Before fun init() {
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
lifecycleOwner = TestLifecycleOwner(coroutineDispatcher = UnconfinedTestDispatcher())
}
@Test fun convertsFromPublisher() {
val processor = PublishProcessor.create<String>()
val liveData = processor.toLiveData()
val output = mutableListOf<String?>()
liveData.observe(lifecycleOwner, Observer { output.add(it) })
processor.onNext("foo")
processor.onNext("bar")
processor.onNext("baz")
assertThat(output).containsExactly("foo", "bar", "baz")
}
@Test fun convertsToPublisherWithSyncData() {
val liveData = MutableLiveData<String>()
liveData.value = "foo"
val outputProcessor = ReplayProcessor.create<String>()
liveData.toPublisher(lifecycleOwner).subscribe(outputProcessor)
liveData.value = "bar"
liveData.value = "baz"
assertThat(outputProcessor.values).asList().containsExactly("foo", "bar", "baz")
}
}
|
apache-2.0
|
ea6cb5c2001b049eaa9566d887b69d47
| 33.353846 | 93 | 0.728168 | 4.701053 | false | true | false | false |
JoachimR/Bible2net
|
app/src/main/java/de/reiss/bible2net/theword/note/export/FileProvider.kt
|
1
|
1255
|
package de.reiss.bible2net.theword.note.export
import android.content.Context
import android.os.Environment
import de.reiss.bible2net.theword.logger.logWarn
import de.reiss.bible2net.theword.util.extensions.asDateString
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Date
open class FileProvider(private val context: Context) {
val fileName = "${Date().asDateString()}_wordnotes.xml"
open fun isExternalStorageWritable() =
Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
open fun createBufferedOutputStream(): BufferedOutputStream? {
try {
return BufferedOutputStream(FileOutputStream(createFile()))
} catch (e: IOException) {
logWarn(e) { "error when creating file" }
} catch (e: SecurityException) {
logWarn(e) { "security error when creating file" }
}
return null
}
private fun createFile(): File {
val absoluteDir = context.getExternalFilesDir(null)!!.absoluteFile.toString()
val dir = File(absoluteDir)
dir.mkdirs()
val file = File(dir, fileName)
file.createNewFile()
return file
}
}
|
gpl-3.0
|
974c7cf2292a4f27d18bebca4e880a76
| 31.179487 | 85 | 0.694024 | 4.59707 | false | true | false | false |
kohesive/kohesive-iac
|
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/AutoScaling.kt
|
1
|
4962
|
package uy.kohesive.iac.model.aws.cloudformation.resources
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationType
import uy.kohesive.iac.model.aws.cloudformation.CloudFormationTypes
import uy.kohesive.iac.model.aws.cloudformation.ResourceProperties
@CloudFormationTypes
object AutoScaling {
@CloudFormationType("AWS::AutoScaling::AutoScalingGroup")
data class AutoScalingGroup(
val AvailabilityZones: List<String>? = null,
val Cooldown: String? = null,
val DesiredCapacity: String? = null,
val HealthCheckGracePeriod: String? = null,
val HealthCheckType: String? = null,
val InstanceId: String? = null,
val LaunchConfigurationName: String? = null,
val LoadBalancerNames: List<String>? = null,
val MaxSize: String,
val MetricsCollection: List<AutoScaling.AutoScalingGroup.MetricsCollectionProperty>? = null,
val MinSize: String,
val NotificationConfigurations: List<AutoScaling.AutoScalingGroup.NotificationConfigurationProperty>? = null,
val PlacementGroup: String? = null,
val Tags: List<AutoScaling.AutoScalingGroup.TagProperty>? = null,
val TargetGroupARNs: List<String>? = null,
val TerminationPolicies: List<String>? = null,
val VPCZoneIdentifier: List<String>? = null
) : ResourceProperties {
data class MetricsCollectionProperty(
val Granularity: String,
val Metrics: List<String>? = null
)
data class NotificationConfigurationProperty(
val NotificationTypes: List<String>,
val TopicARN: String
)
data class TagProperty(
val Key: String,
val Value: String,
val PropagateAtLaunch: String
)
}
@CloudFormationType("AWS::AutoScaling::LaunchConfiguration")
data class LaunchConfiguration(
val AssociatePublicIpAddress: String? = null,
val BlockDeviceMappings: List<AutoScaling.LaunchConfiguration.MappingProperty>? = null,
val ClassicLinkVPCId: String? = null,
val ClassicLinkVPCSecurityGroups: List<String>? = null,
val EbsOptimized: String? = null,
val IamInstanceProfile: String? = null,
val ImageId: String,
val InstanceId: String? = null,
val InstanceMonitoring: String? = null,
val InstanceType: String,
val KernelId: String? = null,
val KeyName: String? = null,
val PlacementTenancy: String? = null,
val RamDiskId: String? = null,
val SecurityGroups: List<String>? = null,
val SpotPrice: String? = null,
val UserData: String? = null
) : ResourceProperties {
data class MappingProperty(
val DeviceName: String,
val Ebs: LaunchConfiguration.MappingProperty.AutoScalingEBSBlockDevice? = null,
val NoDevice: String? = null,
val VirtualName: String? = null
) {
data class AutoScalingEBSBlockDevice(
val DeleteOnTermination: String? = null,
val Encrypted: String? = null,
val Iops: String? = null,
val SnapshotId: String? = null,
val VolumeSize: String? = null,
val VolumeType: String? = null
)
}
}
@CloudFormationType("AWS::AutoScaling::LifecycleHook")
data class LifecycleHook(
val AutoScalingGroupName: String,
val DefaultResult: String? = null,
val HeartbeatTimeout: String? = null,
val LifecycleTransition: String,
val NotificationMetadata: String? = null,
val NotificationTargetARN: String,
val RoleARN: String
) : ResourceProperties
@CloudFormationType("AWS::AutoScaling::ScalingPolicy")
data class ScalingPolicy(
val AdjustmentType: String,
val AutoScalingGroupName: String,
val Cooldown: String? = null,
val EstimatedInstanceWarmup: String? = null,
val MetricAggregationType: String? = null,
val MinAdjustmentMagnitude: String? = null,
val PolicyType: String? = null,
val ScalingAdjustment: String? = null,
val StepAdjustments: List<AutoScaling.ScalingPolicy.StepAdjustmentProperty>? = null
) : ResourceProperties {
data class StepAdjustmentProperty(
val MetricIntervalLowerBound: String? = null,
val MetricIntervalUpperBound: String? = null,
val ScalingAdjustment: String
)
}
@CloudFormationType("AWS::AutoScaling::ScheduledAction")
data class ScheduledAction(
val AutoScalingGroupName: String,
val DesiredCapacity: String? = null,
val EndTime: String? = null,
val MaxSize: String? = null,
val MinSize: String? = null,
val Recurrence: String? = null,
val StartTime: String? = null
) : ResourceProperties
}
|
mit
|
29998726abaa01b73dac644256c06f94
| 35.492647 | 117 | 0.644498 | 4.725714 | false | true | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt
|
1
|
9478
|
package info.nightscout.androidaps.plugins.general.maintenance
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.io.*
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MaintenancePlugin @Inject constructor(
injector: HasAndroidInjector,
private val context: Context,
resourceHelper: ResourceHelper,
private val sp: SP,
private val nsSettingsStatus: NSSettingsStatus,
aapsLogger: AAPSLogger,
private val buildHelper: BuildHelper,
private val config: Config
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(MaintenanceFragment::class.java.name)
.alwaysVisible(false)
.alwaysEnabled(true)
.pluginIcon(R.drawable.ic_maintenance)
.pluginName(R.string.maintenance)
.shortName(R.string.maintenance_shortname)
.preferencesId(R.xml.pref_maintenance)
.description(R.string.description_maintenance),
aapsLogger, resourceHelper, injector
) {
fun sendLogs() {
val recipient = sp.getString(R.string.key_maintenance_logs_email, "[email protected]")
val amount = sp.getInt(R.string.key_maintenance_logs_amount, 2)
val logDirectory = LoggerUtils.getLogDirectory()
val logs = getLogFiles(logDirectory, amount)
val zipDir = context.getExternalFilesDir("exports")
val zipFile = File(zipDir, constructName())
aapsLogger.debug("zipFile: ${zipFile.absolutePath}")
val zip = zipLogs(zipFile, logs)
val attachmentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", zip)
val emailIntent: Intent = this.sendMail(attachmentUri, recipient, "Log Export")
aapsLogger.debug("sending emailIntent")
context.startActivity(emailIntent)
}
//todo replace this with a call on startup of the application, specifically to remove
// unnecessary garbage from the log exports
fun deleteLogs() {
LoggerUtils.getLogDirectory()?.let { logDirectory ->
val logDir = File(logDirectory)
val files = logDir.listFiles { _: File?, name: String ->
(name.startsWith("AndroidAPS") && name.endsWith(".zip"))
}
Arrays.sort(files) { f1: File, f2: File -> f1.name.compareTo(f2.name) }
var delFiles = listOf(*files)
val amount = sp.getInt(R.string.key_logshipper_amount, 2)
val keepIndex = amount - 1
if (keepIndex < delFiles.size) {
delFiles = delFiles.subList(keepIndex, delFiles.size)
for (file in delFiles) {
file.delete()
}
}
val exportDir = File(logDirectory, "exports")
if (exportDir.exists()) {
val expFiles = exportDir.listFiles()
for (file in expFiles) {
file.delete()
}
exportDir.delete()
}
}
}
/**
* returns a list of log files. The number of returned logs is given via the amount
* parameter.
*
* The log files are sorted by the name descending.
*
* @param directory
* @param amount
* @return
*/
fun getLogFiles(directory: String, amount: Int): List<File> {
aapsLogger.debug("getting $amount logs from directory $directory")
val logDir = File(directory)
val files = logDir.listFiles { _: File?, name: String ->
(name.startsWith("AndroidAPS")
&& (name.endsWith(".log")
|| name.endsWith(".zip") && !name.endsWith(LoggerUtils.SUFFIX)))
}
Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) }
val result = listOf(*files)
var toIndex = amount
if (toIndex > result.size) {
toIndex = result.size
}
aapsLogger.debug("returning sublist 0 to $toIndex")
return result.subList(0, toIndex)
}
fun zipLogs(zipFile: File, files: List<File>): File {
aapsLogger.debug("creating zip ${zipFile.absolutePath}")
try {
zip(zipFile, files)
} catch (e: IOException) {
aapsLogger.error("Cannot retrieve zip", e)
}
return zipFile
}
/**
* construct the name of zip file which is used to export logs.
*
* The name is constructed using the following scheme:
* AndroidAPS_LOG_ + Long Time + .log.zip
*
* @return
*/
private fun constructName(): String {
return "AndroidAPS_LOG_" + Date().time + LoggerUtils.SUFFIX
}
private fun zip(zipFile: File?, files: List<File>) {
val bufferSize = 2048
val out = ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile)))
for (file in files) {
val data = ByteArray(bufferSize)
FileInputStream(file).use { fileInputStream ->
BufferedInputStream(fileInputStream, bufferSize).use { origin ->
val entry = ZipEntry(file.name)
out.putNextEntry(entry)
var count: Int
while (origin.read(data, 0, bufferSize).also { count = it } != -1) {
out.write(data, 0, count)
}
}
}
}
out.close()
}
@Suppress("SameParameterValue")
private fun sendMail(attachmentUri: Uri, recipient: String, subject: String): Intent {
val builder = StringBuilder()
builder.append("ADD TIME OF EVENT HERE: " + System.lineSeparator())
builder.append("ADD ISSUE DESCRIPTION OR GITHUB ISSUE REFERENCE NUMBER: " + System.lineSeparator())
builder.append("-------------------------------------------------------" + System.lineSeparator())
builder.append("(Please remember this will send only very recent logs." + System.lineSeparator())
builder.append("If you want to provide logs for event older than a few hours," + System.lineSeparator())
builder.append("you have to do it manually)" + System.lineSeparator())
builder.append("-------------------------------------------------------" + System.lineSeparator())
builder.append(resourceHelper.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator())
if (config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator())
builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator())
builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator())
builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator())
builder.append(resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.nightscoutVersionName + System.lineSeparator())
if (buildHelper.isEngineeringMode()) builder.append(resourceHelper.gs(R.string.engineering_mode_enabled))
return sendMail(attachmentUri, recipient, subject, builder.toString())
}
/**
* send a mail with the given file to the recipients with the given subject.
*
* the returned intent should be used to really send the mail using
*
* startActivity(Intent.createChooser(emailIntent , "Send email..."));
*
* @param attachmentUri
* @param recipient
* @param subject
* @param body
*
* @return
*/
private fun sendMail(attachmentUri: Uri, recipient: String, subject: String, body: String): Intent {
aapsLogger.debug("sending email to $recipient with subject $subject")
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "text/plain"
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_TEXT, body)
aapsLogger.debug("put path $attachmentUri")
emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri)
emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return emailIntent
}
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)
val encryptSwitch = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_maintenance_encrypt_exported_prefs)) as SwitchPreference?
?: return
encryptSwitch.isVisible = buildHelper.isEngineeringMode()
encryptSwitch.isEnabled = buildHelper.isEngineeringMode()
}
}
|
agpl-3.0
|
c5826b3a00c7ca6d9ff2cacf3ecfd9fd
| 42.283105 | 161 | 0.653935 | 4.680494 | false | true | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/libs/preferences/BooleanDataStore.kt
|
1
|
2546
|
package com.kickstarter.libs.preferences
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import java.io.IOException
import kotlin.jvm.JvmOverloads
class BooleanDataStore @JvmOverloads constructor(
private val context: Context,
private val key: String,
private val defaultValue: Boolean = false
) : BooleanDataStoreType {
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
private val prefKey = booleanPreferencesKey(this.key)
override fun get(): Boolean {
val flow: Flow<Boolean> = context.dataStore.data.map {
it[prefKey] ?: defaultValue
}
return unwrapFlowValue(flow) as Boolean
}
// - Blocking current thread here, we should return FLOW to be consumed by a coroutine,
// for now as we slowly adopt Coroutines we do not want to change the nomenclature
// for BooleanPreferenceType, reason why we "force" the value extraction.
private fun unwrapFlowValue(flow: Flow<Any>): Any {
var flowValue: Any
runBlocking(Dispatchers.IO) {
flowValue = flow.first()
}
return flowValue
}
override val isSet: Boolean
get(): Boolean {
val flow: Flow<Boolean> = context.dataStore.data.catch { exception ->
// dataStore.data throws an IOException if it can't read the data
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}.map { it.contains(prefKey) }
return unwrapFlowValue(flow) as Boolean
}
override fun set(value: Boolean) {
runBlocking {
context.dataStore.edit {
it[prefKey] = value
}
}
}
override fun delete() {
runBlocking {
context.dataStore.edit {
if (it.contains(prefKey))
it.remove(prefKey)
}
}
}
}
|
apache-2.0
|
9383156c556c3d1d3422753e15da7e07
| 31.641026 | 92 | 0.660644 | 4.83112 | false | false | false | false |
NativeScript/android-runtime
|
test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/kotlin/metadata/bytecode/BytecodeClassMetadataParser.kt
|
1
|
2745
|
package com.telerik.metadata.parsing.kotlin.metadata.bytecode
import com.telerik.metadata.parsing.NativeClassDescriptor
import com.telerik.metadata.parsing.kotlin.classes.KotlinClassDescriptor
import com.telerik.metadata.parsing.kotlin.metadata.ClassMetadataParser
import kotlinx.metadata.Flag
import kotlinx.metadata.KmFunction
import kotlinx.metadata.KmProperty
import kotlinx.metadata.jvm.KotlinClassMetadata
import java.lang.reflect.Modifier
import java.util.stream.Stream
class BytecodeClassMetadataParser : ClassMetadataParser {
override fun wasKotlinCompanionObject(clazz: NativeClassDescriptor, possibleCompanion: NativeClassDescriptor): Boolean {
if (clazz !is KotlinClassDescriptor) {
return false
}
val kotlinMetadata = clazz.kotlinMetadata
if (kotlinMetadata is KotlinClassMetadata.Class) {
val kmClass = kotlinMetadata.toKmClass()
kmClass.companionObject
val companion = kmClass.companionObject
val fullCompanionName = clazz.className + "$" + companion
return possibleCompanion.className == fullCompanionName
}
return false
}
override fun getKotlinProperties(kotlinMetadata: KotlinClassMetadata): Stream<KmProperty> {
if (kotlinMetadata is KotlinClassMetadata.Class) {
val kmClass = kotlinMetadata.toKmClass()
return kmClass.properties
.stream()
.filter {
Flag.IS_PUBLIC(it.flags) || Flag.IS_PROTECTED(it.flags)
}
.filter { p ->
((Modifier.isPublic(p.getterFlags) || Modifier.isProtected(p.getterFlags))
&& (Modifier.isPublic(p.setterFlags) || Modifier.isProtected(p.setterFlags))
&& !p.name.startsWith("is"))
}
}
return Stream.empty()
}
override fun getKotlinExtensionFunctions(kotlinMetadata: KotlinClassMetadata): Stream<KmFunction> {
if (kotlinMetadata is KotlinClassMetadata.Class) {
val kmClass = kotlinMetadata.toKmClass()
return kmClass.functions
.stream()
.filter { isVisibleExtensionFunction(it) }
} else if (kotlinMetadata is KotlinClassMetadata.FileFacade) {
val kmClass = kotlinMetadata.toKmPackage()
return kmClass.functions
.stream()
.filter { isVisibleExtensionFunction(it) }
}
return Stream.empty()
}
private fun isVisibleExtensionFunction(function: KmFunction): Boolean {
return function.receiverParameterType != null
}
}
|
apache-2.0
|
81b0594717488021fcdf691ae90a995f
| 37.661972 | 124 | 0.643352 | 5.289017 | false | false | false | false |
zdary/intellij-community
|
plugins/ml-local-models/src/com/intellij/ml/local/models/frequency/methods/MethodsFrequencyStorage.kt
|
1
|
3417
|
package com.intellij.ml.local.models.frequency.methods
import com.intellij.ml.local.models.api.LocalModelStorage
import com.intellij.ml.local.util.StorageUtil
import com.intellij.ml.local.util.StorageUtil.isEmpty
import com.intellij.util.Processor
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.PersistentMapBuilder
import java.io.DataInput
import java.io.DataOutput
import java.nio.file.Path
class MethodsFrequencyStorage internal constructor(private val storageDirectory: Path,
private var isValid: Boolean) : LocalModelStorage {
companion object {
private const val STORAGE_NAME = "methods_frequency"
private const val VERSION = 1
fun getStorage(baseDirectory: Path): MethodsFrequencyStorage? {
val storageDirectory = baseDirectory.resolve(STORAGE_NAME)
return StorageUtil.getStorage(storageDirectory, VERSION) { path, isValid -> MethodsFrequencyStorage(path, isValid) }
}
}
private val storage = PersistentMapBuilder.newBuilder(storageDirectory.resolve(STORAGE_NAME),
EnumeratorStringDescriptor(),
MyDataExternalizer()).compactOnClose().build()
@Volatile var totalMethods = 0
private set
@Volatile var totalMethodsUsages = 0
private set
init {
if (isValid) {
getTotalCounts()
}
}
override fun name(): String = STORAGE_NAME
override fun version(): Int = VERSION
override fun isValid(): Boolean = isValid
override fun isEmpty(): Boolean = storage.isEmpty()
override fun setValid(isValid: Boolean) {
if (isValid) {
getTotalCounts()
} else {
storage.closeAndClean()
}
this.isValid = isValid
StorageUtil.saveInfo(VERSION, isValid, storageDirectory)
}
@Synchronized
fun addMethodUsage(className: String, methodName: String) {
val existingFrequencies = storage.get(className)
if (existingFrequencies == null) {
storage.put(className, MethodsFrequencies.withUsage(methodName))
} else {
existingFrequencies.addUsage(methodName)
storage.put(className, existingFrequencies)
}
}
fun get(className: String): MethodsFrequencies? = storage.get(className)
private fun getTotalCounts() {
totalMethods = 0
totalMethodsUsages = 0
storage.processKeys(Processor {
val frequencies = storage.get(it) ?: return@Processor true
totalMethods++
totalMethodsUsages += frequencies.getTotalFrequency()
return@Processor true
})
storage.force()
}
private class MyDataExternalizer : DataExternalizer<MethodsFrequencies> {
override fun save(out: DataOutput, value: MethodsFrequencies) {
out.writeInt(value.getTotalFrequency())
val methods = value.getMethods()
out.writeInt(methods.size)
for (method in methods) {
out.writeInt(method.key)
out.writeInt(method.value)
}
}
override fun read(input: DataInput): MethodsFrequencies {
val totalFrequency = input.readInt()
val count = input.readInt()
val methods = mutableMapOf<Int, Int>()
for (i in 1..count) {
val index = input.readInt()
methods[index] = input.readInt()
}
return MethodsFrequencies(totalFrequency, methods)
}
}
}
|
apache-2.0
|
72e3bc81c0ce22a25c03d12d94f45eed
| 31.245283 | 122 | 0.685397 | 4.661664 | false | false | false | false |
JetBrains/kotlin-native
|
runtime/src/main/kotlin/kotlin/Throwable.kt
|
1
|
7026
|
/*
* Copyright 2010-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 kotlin
import kotlin.native.concurrent.freeze
import kotlin.native.concurrent.isFrozen
import kotlin.native.internal.ExportForCppRuntime
import kotlin.native.internal.ExportTypeInfo
import kotlin.native.internal.NativePtrArray
/**
* The base class for all errors and exceptions. Only instances of this class can be thrown or caught.
*
* @param message the detail message string.
* @param cause the cause of this throwable.
*/
@ExportTypeInfo("theThrowableTypeInfo")
public open class Throwable(open val message: String?, open val cause: Throwable?) {
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(cause?.toString(), cause)
constructor() : this(null, null)
@get:ExportForCppRuntime("Kotlin_Throwable_getStackTrace")
private val stackTrace: NativePtrArray = getCurrentStackTrace()
private val stackTraceStrings: Array<String> by lazy {
getStackTraceStrings(stackTrace).freeze()
}
/**
* Returns an array of stack trace strings representing the stack trace
* pertaining to this throwable.
*/
public fun getStackTrace(): Array<String> = stackTraceStrings
internal fun getStackTraceAddressesInternal(): List<Long> =
(0 until stackTrace.size).map { index -> stackTrace[index].toLong() }
/**
* Prints the [detailed description][Throwable.stackTraceToString] of this throwable to the standard output.
*/
public fun printStackTrace(): Unit = ExceptionTraceBuilder(this).print()
internal fun dumpStackTrace(): String = ExceptionTraceBuilder(this).build()
private class ExceptionTraceBuilder(private val top: Throwable) {
private val target = StringBuilder()
private var printOut = false
private val visited = mutableSetOf<Throwable>()
fun build(): String {
top.dumpFullTrace("", "")
return target.toString()
}
fun print() {
printOut = true
top.dumpFullTrace("", "")
}
private fun StringBuilder.endln() {
if (printOut) {
println(this)
clear()
} else {
appendLine()
}
}
private fun Throwable.dumpFullTrace(indent: String, qualifier: String) {
this.dumpSelfTrace(indent, qualifier) || return
var cause = this.cause
while (cause != null) {
cause.dumpSelfTrace(indent, "Caused by: ")
cause = cause.cause
}
}
private fun Throwable.dumpSelfTrace(indent: String, qualifier: String): Boolean {
if (!visited.add(this)) {
target.append(indent).append(qualifier).append("[CIRCULAR REFERENCE, SEE ABOVE: ").append(this).append("]").endln()
return false
}
target.append(indent).append(qualifier).append(this).endln()
// leave 1 common frame to ease matching with the top exception stack
val commonFrames = (commonStackFrames() - 1).coerceAtLeast(0)
for (frameIndex in 0 until stackTraceStrings.size - commonFrames) {
val element = stackTraceStrings[frameIndex]
target.append(indent).append(" at ").append(element).endln()
}
if (commonFrames > 0) {
target.append(indent).append(" ... and ").append(commonFrames).append(" more common stack frames skipped").endln()
}
val suppressed = suppressedExceptionsList
if (!suppressed.isNullOrEmpty()) {
val suppressedIndent = indent + " "
for (s in suppressed) {
s.dumpFullTrace(suppressedIndent, "Suppressed: ")
}
}
return true
}
private fun Throwable.commonStackFrames(): Int {
if (top === this) return 0
val topStack = top.stackTrace
val topSize = topStack.size
val thisStack = this.stackTrace
val thisSize = thisStack.size
val maxSize = minOf(topSize, thisSize)
var frame = 0
while (frame < maxSize) {
if (thisStack[thisSize - 1 - frame] != topStack[topSize - 1 - frame]) break
frame++
}
return frame
}
}
/**
* Returns the short description of this throwable consisting of
* the exception class name (fully qualified if possible)
* followed by the exception message if it is not null.
*/
public override fun toString(): String {
val kClass = this::class
val s = kClass.qualifiedName ?: kClass.simpleName ?: "Throwable"
return if (message != null) s + ": " + message.toString() else s
}
internal var suppressedExceptionsList: MutableList<Throwable>? = null
}
@SymbolName("Kotlin_getCurrentStackTrace")
private external fun getCurrentStackTrace(): NativePtrArray
@SymbolName("Kotlin_getStackTraceStrings")
private external fun getStackTraceStrings(stackTrace: NativePtrArray): Array<String>
/**
* Returns the detailed description of this throwable with its stack trace.
*
* The detailed description includes:
* - the short description (see [Throwable.toString]) of this throwable;
* - the complete stack trace;
* - detailed descriptions of the exceptions that were [suppressed][suppressedExceptions] in order to deliver this exception;
* - the detailed description of each throwable in the [Throwable.cause] chain.
*/
@SinceKotlin("1.4")
public actual fun Throwable.stackTraceToString(): String = dumpStackTrace()
/**
* Prints the [detailed description][Throwable.stackTraceToString] of this throwable to the standard output.
*/
@SinceKotlin("1.4")
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
@kotlin.internal.InlineOnly
public actual inline fun Throwable.printStackTrace(): Unit = printStackTrace()
/**
* Adds the specified exception to the list of exceptions that were
* suppressed in order to deliver this exception.
*
* Does nothing if this [Throwable] is frozen.
*/
@SinceKotlin("1.4")
public actual fun Throwable.addSuppressed(exception: Throwable) {
if (this !== exception && !this.isFrozen) {
val suppressed = suppressedExceptionsList
when {
suppressed == null -> suppressedExceptionsList = mutableListOf<Throwable>(exception)
suppressed.isFrozen -> suppressedExceptionsList = suppressed.toMutableList().apply { add(exception) }
else -> suppressed.add(exception)
}
}
}
/**
* Returns a list of all exceptions that were suppressed in order to deliver this exception.
*/
@SinceKotlin("1.4")
public actual val Throwable.suppressedExceptions: List<Throwable> get() {
return this.suppressedExceptionsList ?: emptyList()
}
|
apache-2.0
|
c03e92b73e642931aecb15fb9aa321eb
| 35.59375 | 133 | 0.647168 | 4.786104 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/asJava/classes/AbstractUltraLightFacadeClassLoadingTest.kt
|
4
|
2041
|
// 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.asJava.classes
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.idea.perf.UltraLightChecker
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
abstract class AbstractUltraLightFacadeClassTest15 : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
open fun doTest(testDataPath: String) {
val testDataFile = File(testDataPath)
val sourceText = testDataFile.readText()
myFixture.addFileToProject(testDataFile.name, sourceText) as KtFile
UltraLightChecker.checkForReleaseCoroutine(sourceText, module)
val additionalFile = File("$testDataPath.1")
if (additionalFile.exists()) {
myFixture.addFileToProject(additionalFile.name.replaceFirst(".kt.1", "1.kt"), additionalFile.readText())
}
val scope = GlobalSearchScope.allScope(project)
val facades = KotlinAsJavaSupport.getInstance(project).getFacadeNames(FqName.ROOT, scope)
checkLightFacades(testDataPath, facades, scope)
}
protected open fun checkLightFacades(testDataPath: String, facades: Collection<String>, scope: GlobalSearchScope) {
for (facadeName in facades) {
val ultraLightClass = UltraLightChecker.checkFacadeEquivalence(FqName(facadeName), scope, project)
if (ultraLightClass != null) {
UltraLightChecker.checkDescriptorsLeak(ultraLightClass)
}
}
}
}
|
apache-2.0
|
e3f303886a705487445f990d2c74b7c0
| 45.386364 | 158 | 0.762861 | 5.064516 | false | true | false | false |
dahlstrom-g/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/GrUnnecessarySemicolonInspection.kt
|
3
|
3429
|
// 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.plugins.groovy.codeInspection.style
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.fixes.RemoveElementWithoutFormatterFix
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets.WHITE_SPACES_OR_COMMENTS
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.*
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstantList
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipSet
import org.jetbrains.plugins.groovy.util.TokenSet
import org.jetbrains.plugins.groovy.util.minus
import org.jetbrains.plugins.groovy.util.plus
class GrUnnecessarySemicolonInspection : LocalInspectionTool(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element.node.elementType !== T_SEMI || isSemicolonNecessary(element)) return
holder.registerProblem(
element,
GroovyBundle.message("unnecessary.semicolon.description"),
fix
)
}
}
companion object {
private val fix = RemoveElementWithoutFormatterFix(GroovyBundle.message("unnecessary.semicolon.fix"))
private val nlSet = TokenSet(NL)
private val forwardSet = WHITE_SPACES_OR_COMMENTS + TokenSet(T_SEMI) - nlSet
private val backwardSet = WHITE_SPACES_OR_COMMENTS - nlSet
private val separators = TokenSet(NL, T_SEMI)
private val previousSet = TokenSet(T_LBRACE, T_ARROW)
private fun isSemicolonNecessary(semicolon: PsiElement): Boolean {
if (semicolon.parent is GrTraditionalForClause) return true
val prevSibling = skipSet(semicolon, false, backwardSet) ?: return false
val nextSibling = skipSet(semicolon, true, forwardSet) ?: return false
val prevType = prevSibling.node.elementType
return when {
prevType in separators -> {
prevSibling.prevSibling is GrEnumConstantList
}
prevType in previousSet -> {
false
}
prevSibling is GrStatement -> {
nextSibling is GrStatement || nextSibling.nextSibling is GrClosableBlock
}
prevSibling is GrPackageDefinition || prevSibling is GrImportStatement -> {
nextSibling.node.elementType !in separators
}
prevSibling is GrParameterList && prevSibling.parent is GrClosableBlock -> {
false // beginning of a closure
}
else -> true
}
}
}
}
|
apache-2.0
|
0d594545894a91c5a522188cc7f370cd
| 44.72 | 124 | 0.764363 | 4.608871 | false | false | false | false |
allotria/intellij-community
|
plugins/git4idea/src/git4idea/log/GitLogTerminalCustomCommandHandler.kt
|
2
|
5439
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.log
import com.intellij.execution.Executor
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.terminal.TerminalShellCommandHandler
import com.intellij.util.execution.ParametersListUtil
import com.intellij.vcs.log.VcsLogBranchFilter
import com.intellij.vcs.log.VcsLogUserFilter
import com.intellij.vcs.log.VcsUserRegistry
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitBranch
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
class GitLogTerminalCustomCommandHandler : TerminalShellCommandHandler {
override fun matches(project: Project, workingDirectory: String?, localSession: Boolean, command: String): Boolean =
parse(project, workingDirectory, command) != null
override fun execute(project: Project, workingDirectory: String?, localSession: Boolean, command: String, executor: Executor): Boolean {
if (workingDirectory == null) {
LOG.warn("Cannot open git log for unknown root.")
return false
}
val repository = GitRepositoryManager.getInstance(project).getRepositoryForFileQuick(VcsUtil.getFilePath(workingDirectory))
if (repository == null) {
LOG.warn("Cannot find repository for working directory: $workingDirectory")
return false
}
val parameters = parse(project, workingDirectory, command)
val branch = parameters?.branch
val branchesPatterns = parameters?.branchesPatterns
val users = parameters?.users
val projectLog = VcsProjectLog.getInstance(project)
projectLog.openLogTab(VcsLogFilterObject.collection(
VcsLogFilterObject.fromRoot(repository.root),
getBranchPatternsFilter(branchesPatterns, repository),
getBranchFilter(branch),
getUsersFilter(users, projectLog)))
return true
}
private fun getBranchFilter(branch: String?): VcsLogBranchFilter? {
if (branch == null) return null
return VcsLogFilterObject.fromBranch(branch)
}
private fun getBranchPatternsFilter(branchesPatterns: String?, repository: GitRepository): VcsLogBranchFilter? {
if (branchesPatterns == null) return null
val allBranches = sequenceOf<GitBranch>()
.plus(repository.branches.localBranches)
.plus(repository.branches.remoteBranches)
.mapTo(mutableSetOf()) { it.name }
return VcsLogFilterObject.fromBranchPatterns(listOf(branchesPatterns), allBranches)
}
private fun getUsersFilter(users: List<String>?, projectLog: VcsProjectLog): VcsLogUserFilter? {
if (users.isNullOrEmpty()) return null
return VcsLogFilterObject.fromUserNames(users, projectLog.dataManager!!)
}
private fun parse(project: Project, workingDirectory: String?, command: String): Parameters? {
if (command != GIT_LOG_COMMAND && !command.startsWith("${GIT_LOG_COMMAND} ")) {
return null
}
if (workingDirectory == null
|| GitRepositoryManager.getInstance(project).getRepositoryForFileQuick(VcsUtil.getFilePath(workingDirectory)) == null) {
return null
}
val commands = ParametersListUtil.parse(command)
assert(commands.size >= 2)
commands.removeAt(0)
commands.removeAt(0)
val userRegexps = mutableListOf<String>()
val iterator = commands.listIterator()
iterator.forEach { currentCommand ->
when {
currentCommand == AUTHOR_PARAMETER -> {
if (iterator.hasNext()) {
iterator.remove()
userRegexps.add(iterator.next())
iterator.remove()
}
}
currentCommand.startsWith(AUTHOR_PARAMETER_WITH_SUFFIX) -> {
val parameter = currentCommand.substringAfter(AUTHOR_PARAMETER_WITH_SUFFIX)
if (parameter.isNotBlank()) {
userRegexps.add(parameter)
iterator.remove()
}
}
}
}
val userNames = userRegexps.map { regexp ->
val regex = ".*$regexp.*".toRegex()
project.service<VcsUserRegistry>().users.filter { user ->
regex.matches(user.name.toLowerCase())
}
}
.flatten()
.distinct()
.map { it.name }
val branchesParameter = commands.find { it.startsWith(BRANCHES_PARAMETER) }
var branchesPatterns: String? = null
if (branchesParameter != null) {
branchesPatterns = branchesParameter.substringAfter(BRANCHES_PARAMETER)
commands.remove(branchesParameter)
}
var branch: String? = null
if (commands.isNotEmpty()) {
branch = commands[0]
if (branch.startsWith('-')) return null
commands.remove(branch)
}
if (commands.isEmpty()) {
return Parameters(branch, branchesPatterns, userNames)
}
return null
}
companion object {
data class Parameters(val branch: String? = null, val branchesPatterns: String? = null, val users: List<String>)
private val LOG = Logger.getInstance(GitLogTerminalCustomCommandHandler::class.java)
private const val GIT_LOG_COMMAND = "git log"
private const val AUTHOR_PARAMETER = "--author"
private const val AUTHOR_PARAMETER_WITH_SUFFIX = "$AUTHOR_PARAMETER="
private const val BRANCHES_PARAMETER = "--branches="
}
}
|
apache-2.0
|
d9cfd867ab8a1aa1a807126310efac21
| 35.756757 | 140 | 0.716492 | 4.713172 | false | false | false | false |
androidx/androidx
|
compose/material/material/samples/src/main/java/androidx/compose/material/samples/ThemeSamples.kt
|
3
|
2645
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.ExtendedFloatingActionButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.Typography
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
@Sampled
@Composable
fun MaterialThemeSample() {
val lightColors = lightColors(
primary = Color(0xFF1EB980)
)
val darkColors = darkColors(
primary = Color(0xFF66ffc7)
)
val colors = if (isSystemInDarkTheme()) darkColors else lightColors
val typography = Typography(
h1 = TextStyle(
fontWeight = FontWeight.W100,
fontSize = 96.sp
),
button = TextStyle(
fontWeight = FontWeight.W600,
fontSize = 14.sp
)
)
MaterialTheme(colors = colors, typography = typography) {
val currentTheme = if (MaterialTheme.colors.isLight) "light" else "dark"
ExtendedFloatingActionButton(
text = { Text("FAB with text style and color from $currentTheme theme") },
onClick = {}
)
}
}
@Sampled
@Composable
fun ThemeColorSample() {
val colors = MaterialTheme.colors
Box(Modifier.aspectRatio(1f).fillMaxSize().background(color = colors.primary))
}
@Sampled
@Composable
fun ThemeTextStyleSample() {
val typography = MaterialTheme.typography
Text(text = "H4 styled text", style = typography.h4)
}
|
apache-2.0
|
48f74f61c598d6ee8ae3481196e4f13b
| 30.86747 | 86 | 0.736484 | 4.475465 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantUnitReturnTypeInspection.kt
|
5
|
1969
|
// 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.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeIntention
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.namedFunctionVisitor
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class RedundantUnitReturnTypeInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return namedFunctionVisitor(fun(function) {
if (function.containingFile is KtCodeFragment) return
val typeElement = function.typeReference?.typeElement ?: return
if (hasRedundantUnitReturnType(function)) {
holder.registerProblem(
typeElement,
KotlinBundle.message("redundant.unit.return.type"),
IntentionWrapper(RemoveExplicitTypeIntention())
)
}
})
}
companion object {
fun hasRedundantUnitReturnType(function: KtNamedFunction): Boolean {
if (!function.hasBlockBody()) return false
if (function.typeReference?.typeElement == null) return false
val descriptor = function.resolveToDescriptorIfAny() ?: return false
return descriptor.returnType?.isUnit() == true
}
}
}
|
apache-2.0
|
0b3ae3a47f9e13a87b7b6ae50d749d26
| 45.904762 | 120 | 0.741493 | 5.469444 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/StripTrailingSpacesTest.kt
|
4
|
1729
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.editor
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.EditorTestUtil
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.util.slashedPath
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class StripTrailingSpacesTest : LightJavaCodeInsightFixtureTestCase() {
override fun getTestDataPath() = IDEA_TEST_DATA_DIR.resolve("editor/stripTrailingSpaces").slashedPath
fun testKeepTrailingSpacesInRawString() {
doTest()
}
fun doTest() {
myFixture.configureByFile("${getTestName(true)}.kt")
val editorSettings = EditorSettingsExternalizable.getInstance()
val stripSpaces = editorSettings.stripTrailingSpaces
try {
editorSettings.stripTrailingSpaces = EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE
val doc = myFixture.editor.document
EditorTestUtil.performTypingAction(editor, ' ')
PsiDocumentManager.getInstance(project).commitDocument(doc)
FileDocumentManager.getInstance().saveDocument(doc)
} finally {
editorSettings.stripTrailingSpaces = stripSpaces
}
myFixture.checkResultByFile("${getTestName(true)}.kt.after")
}
}
|
apache-2.0
|
b01d8a7660911840cb085f4cf21c4f00
| 42.225 | 158 | 0.762869 | 5.130564 | false | true | false | false |
GunoH/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/completion/CompletionMemory.kt
|
2
|
2982
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Segment
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import java.util.*
object CompletionMemory {
private val LAST_CHOSEN_METHODS = Key.create<LinkedList<RangeMarker>>("COMPLETED_METHODS")
private val CHOSEN_METHODS = Key.create<SmartPsiElementPointer<PsiMethod>>("CHOSEN_METHODS")
@JvmStatic
fun registerChosenMethod(method: PsiMethod, call: PsiCall) {
val nameRange = getAnchorRange(call) ?: return
val document = call.containingFile.viewProvider.document ?: return
addToMemory(document, createChosenMethodMarker(document, CompletionUtil.getOriginalOrSelf(method), nameRange))
}
private fun getAnchorRange(call: PsiCall) = when (call) {
is PsiMethodCallExpression -> call.methodExpression.referenceNameElement?.textRange
is PsiNewExpression -> call.classOrAnonymousClassReference?.referenceNameElement?.textRange
else -> null
}
private fun addToMemory(document: Document, marker: RangeMarker) {
val completedMethods = LinkedList<RangeMarker>()
document.getUserData(LAST_CHOSEN_METHODS)?.let { completedMethods.addAll(it.filter { it.isValid && !haveSameRange(it, marker) }) }
while (completedMethods.size > 10) {
completedMethods.removeAt(0)
}
document.putUserData(LAST_CHOSEN_METHODS, completedMethods)
completedMethods.add(marker)
}
private fun createChosenMethodMarker(document: Document, method: PsiMethod, nameRange: TextRange): RangeMarker {
val marker = document.createRangeMarker(nameRange.startOffset, nameRange.endOffset)
marker.putUserData(CHOSEN_METHODS, SmartPointerManager.getInstance(method.project).createSmartPsiElementPointer(method))
return marker
}
@JvmStatic
fun getChosenMethod(call: PsiCall): PsiMethod? {
val range = getAnchorRange(call) ?: return null
val completedMethods = call.containingFile.viewProvider.document?.getUserData(LAST_CHOSEN_METHODS)
val marker = completedMethods?.let { it.find { m -> haveSameRange(m, range) } }
return marker?.getUserData(CHOSEN_METHODS)?.element
}
private fun haveSameRange(s1: Segment, s2: Segment) = s1.startOffset == s2.startOffset && s1.endOffset == s2.endOffset
}
|
apache-2.0
|
2181ebe40f0aab45d67ce04d384d077a
| 42.231884 | 134 | 0.765929 | 4.378855 | false | false | false | false |
shogo4405/HaishinKit.java
|
haishinkit/src/main/java/com/haishinkit/view/HkSurfaceView.kt
|
1
|
2899
|
package com.haishinkit.view
import android.content.Context
import android.util.AttributeSet
import android.util.Size
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.WindowManager
import com.haishinkit.graphics.ImageOrientation
import com.haishinkit.graphics.PixelTransform
import com.haishinkit.graphics.PixelTransformFactory
import com.haishinkit.graphics.VideoGravity
import com.haishinkit.net.NetStream
import java.util.concurrent.atomic.AtomicBoolean
@Suppress("unused")
class HkSurfaceView(context: Context, attributes: AttributeSet) :
SurfaceView(context, attributes),
HkView {
var videoOrientation: ImageOrientation = ImageOrientation.UP
set(value) {
field = value
pixelTransform.imageOrientation = field
stream?.videoCodec?.pixelTransform?.imageOrientation = field
}
override val isRunning: AtomicBoolean = AtomicBoolean(false)
override var videoGravity: VideoGravity = VideoGravity.RESIZE_ASPECT_FILL
set(value) {
field = value
pixelTransform.videoGravity = field
}
override var stream: NetStream? = null
set(value) {
field?.renderer = null
field = value
field?.renderer = this
}
override val pixelTransform: PixelTransform by lazy {
PixelTransformFactory().create()
}
init {
pixelTransform.assetManager = context.assets
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
pixelTransform.extent = Size(width, height)
pixelTransform.surface = holder.surface
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int
) {
(context.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.defaultDisplay?.orientation?.let {
pixelTransform.surfaceRotation = it
}
pixelTransform.extent = Size(width, height)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
pixelTransform.surface = null
}
})
}
override fun attachStream(stream: NetStream?) {
this.stream = stream
if (stream != null) {
startRunning()
} else {
stopRunning()
}
}
override fun startRunning() {
if (isRunning.get()) return
stream?.video?.startRunning()
isRunning.set(true)
}
override fun stopRunning() {
if (!isRunning.get()) return
stream?.video?.stopRunning()
isRunning.set(false)
}
companion object {
private var TAG = HkSurfaceView::class.java.simpleName
}
}
|
bsd-3-clause
|
ee9341cea21841013511bb40eaf42002
| 30.172043 | 120 | 0.627458 | 5.068182 | false | false | false | false |
GunoH/intellij-community
|
platform/collaboration-tools/src/com/intellij/collaboration/ui/SimpleComboboxWithActionsFactory.kt
|
2
|
2626
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.collaboration.ui
import com.intellij.collaboration.ui.util.bind
import com.intellij.collaboration.ui.util.getName
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.annotations.Nls
import javax.swing.Action
import javax.swing.JList
class SimpleComboboxWithActionsFactory<T : Any>(
private val mappingsState: StateFlow<Collection<T>>,
private val selectionState: MutableStateFlow<T?>
) {
fun create(scope: CoroutineScope,
presenter: (T) -> Presentation,
actions: StateFlow<List<Action>> = MutableStateFlow(emptyList()),
sortComparator: Comparator<T> = Comparator.comparing { presenter(it).name }): ComboBox<*> {
val comboModel = ComboBoxWithActionsModel<T>().apply {
bind(scope, mappingsState, selectionState, actions, sortComparator)
selectFirst()
}
return ComboBox(comboModel).apply {
renderer = object : ColoredListCellRenderer<ComboBoxWithActionsModel.Item<T>>() {
override fun customizeCellRenderer(list: JList<out ComboBoxWithActionsModel.Item<T>>,
value: ComboBoxWithActionsModel.Item<T>?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
if (value is ComboBoxWithActionsModel.Item.Wrapper) {
val presentations = presenter(value.wrappee)
append(presentations.name)
presentations.secondaryName?.let {
append(" ").append(it, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
}
if (value is ComboBoxWithActionsModel.Item.Action) {
if (model.size == index) border = IdeBorderFactory.createBorder(SideBorder.TOP)
append(value.action.getName())
}
}
}
isUsePreferredSizeAsMinimum = false
isOpaque = false
isSwingPopup = true
}.also { combo ->
ComboboxSpeedSearch.installSpeedSearch(combo) {
when (it) {
is ComboBoxWithActionsModel.Item.Wrapper -> presenter(it.wrappee).name
is ComboBoxWithActionsModel.Item.Action -> it.action.getName()
}
}
}
}
data class Presentation(val name: @Nls String, val secondaryName: @Nls String?)
}
|
apache-2.0
|
48ef1f1910ecf49d4caa0282568ae002
| 40.046875 | 140 | 0.653085 | 4.992395 | false | false | false | false |
JetBrains/xodus
|
environment/src/main/kotlin/jetbrains/exodus/env/BitmapImpl.kt
|
1
|
7146
|
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.env
import jetbrains.exodus.ArrayByteIterable
import jetbrains.exodus.ByteIterable
import jetbrains.exodus.bindings.LongBinding
import jetbrains.exodus.bindings.LongBinding.compressedEntryToLong
import jetbrains.exodus.core.dataStructures.hash.LongHashMap
private typealias Bit = Long
open class BitmapImpl(open val store: StoreImpl) : Bitmap {
override fun getEnvironment() = store.environment
override fun get(txn: Transaction, bit: Bit): Boolean {
val key = bit.ensureNonNegative().key
val bitmapEntry = store.get(txn, LongBinding.longToCompressedEntry(key)) ?: return false
val mask = 1L shl bit.index
return bitmapEntry.asLong and mask != 0L
}
override fun set(txn: Transaction, bit: Bit, value: Boolean): Boolean {
val key = bit.ensureNonNegative().key
val keyEntry = LongBinding.longToCompressedEntry(key)
val mask = 1L shl bit.index
val bitmap = store.get(txn, keyEntry)?.asLong ?: 0L
val prevValue = bitmap and mask != 0L
if (prevValue == value) return false
(bitmap xor mask).let {
if (it == 0L) {
store.delete(txn, keyEntry)
} else {
store.put(txn, keyEntry, it.asEntry)
}
}
return true
}
override fun clear(txn: Transaction, bit: Bit): Boolean = this.set(txn, bit, false)
override fun iterator(txn: Transaction): BitmapIterator = BitmapIterator(txn, store)
override fun reverseIterator(txn: Transaction): BitmapIterator = BitmapIterator(txn, store, -1)
override fun getFirst(txn: Transaction): Long {
return iterator(txn).use {
if (it.hasNext()) it.next() else -1L
}
}
override fun getLast(txn: Transaction): Long {
return reverseIterator(txn).use {
if (it.hasNext()) it.next() else -1L
}
}
override fun count(txn: Transaction): Long {
store.openCursor(txn).use { cursor ->
var count = 0L
cursor.forEach {
count += value.countBits
}
return count
}
}
override fun count(txn: Transaction, firstBit: Bit, lastBit: Bit): Long {
if (firstBit > lastBit) throw IllegalArgumentException("firstBit > lastBit")
if (firstBit == lastBit) {
return if (get(txn, firstBit)) 1L else 0L
}
store.openCursor(txn).use { cursor ->
val firstKey = firstBit.ensureNonNegative().key
val lastKey = lastBit.ensureNonNegative().key
val keyEntry = LongBinding.longToCompressedEntry(firstKey)
val valueEntry = cursor.getSearchKeyRange(keyEntry) ?: return 0L
var count = 0L
val key = compressedEntryToLong(cursor.key)
if (key in (firstKey + 1) until lastKey) {
count += valueEntry.countBits
} else {
val bits = valueEntry.asLong
val lowBit = if (key == firstKey) firstBit.index else 0
val highBit = if (key == lastKey) lastBit.index else Long.SIZE_BITS - 1
for (i in lowBit..highBit) {
if (bits and (1L shl i) != 0L) {
++count
}
}
}
cursor.forEach {
val currentKey = compressedEntryToLong(this.key)
if (currentKey < lastKey) {
count += value.countBits
} else {
if (currentKey == lastKey) {
val bits = value.asLong
for (i in 0..lastBit.index) {
if (bits and (1L shl i) != 0L) {
++count
}
}
}
return count
}
}
return count
}
}
companion object {
private const val ALL_ONES = -1L
private val SINGLE_ZEROS = LongHashMap<Int>()
private val SINGLE_ONES = LongHashMap<Int>()
init {
var bit = 1L
for (i in 0..63) {
SINGLE_ONES[bit] = i
SINGLE_ZEROS[ALL_ONES xor bit] = i
bit = bit shl 1
}
}
internal val Long.asEntry: ByteIterable
get() {
if (this == ALL_ONES) {
return ArrayByteIterable(byteArrayOf(0))
}
SINGLE_ONES[this]?.let { bit ->
return ArrayByteIterable(byteArrayOf((bit + 1).toByte()))
}
SINGLE_ZEROS[this]?.let { bit ->
return ArrayByteIterable(byteArrayOf((bit + Long.SIZE_BITS + 1).toByte()))
}
return LongBinding.longToEntry(this)
}
internal val ByteIterable.asLong: Long
get() {
if (this.length != 1) {
return LongBinding.entryToLong(this)
}
this.iterator().next().unsigned.let { tag ->
return when {
tag == 0 -> ALL_ONES
tag < Long.SIZE_BITS + 1 -> 1L shl (tag - 1)
else -> ALL_ONES xor (1L shl (tag - Long.SIZE_BITS - 1))
}
}
}
private val ByteIterable.countBits: Int
get() {
this.iterator().let {
if (length == 1) {
return it.next().unsigned.let { tag ->
when {
tag == 0 -> 64
tag < Long.SIZE_BITS + 1 -> 1
else -> 63
}
}
}
var size = 0
size += (it.next().unsigned xor 0x80).countOneBits()
while (it.hasNext()) {
size += it.next().unsigned.countOneBits()
}
return size
}
}
}
}
internal val Bit.key: Bit get() = this shr 6
internal val Bit.index: Int get() = (this and 63).toInt()
private val Byte.unsigned: Int get() = this.toInt() and 0xff
private fun Bit.ensureNonNegative() =
this.also { if (it < 0L) throw IllegalArgumentException("Bit number should be non-negative") }
|
apache-2.0
|
0f7172bee0a4b8d5dd5981eb1d3a996f
| 34.909548 | 99 | 0.517072 | 4.64026 | false | false | false | false |
jwren/intellij-community
|
platform/lang-impl/src/com/intellij/util/indexing/roots/builders/ModuleRootsIndexableIteratorHandler.kt
|
1
|
3239
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots.builders
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PlatformUtils
import com.intellij.util.indexing.roots.IndexableEntityProvider
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods
import com.intellij.util.indexing.roots.IndexableFilesIterator
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.moduleMap
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
class ModuleRootsIndexableIteratorHandler : IndexableIteratorBuilderHandler {
override fun accepts(builder: IndexableEntityProvider.IndexableIteratorBuilder): Boolean =
builder is ModuleRootsIteratorBuilder || builder is FullModuleContentIteratorBuilder
override fun instantiate(builders: Collection<IndexableEntityProvider.IndexableIteratorBuilder>,
project: Project,
entityStorage: WorkspaceEntityStorage): List<IndexableFilesIterator> {
val fullIndexedModules: Set<ModuleId> = builders.mapNotNull { (it as? FullModuleContentIteratorBuilder)?.moduleId }.toSet()
@Suppress("UNCHECKED_CAST")
val partialIterators = builders.filter {
it is ModuleRootsIteratorBuilder && !fullIndexedModules.contains(it.moduleId)
} as List<ModuleRootsIteratorBuilder>
val partialIteratorsMap = partialIterators.groupBy { builder -> builder.moduleId }
val result = mutableListOf<IndexableFilesIterator>()
fullIndexedModules.forEach { moduleId ->
entityStorage.resolve(moduleId)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, entityStorage, project))
}
}
val moduleMap = entityStorage.moduleMap
partialIteratorsMap.forEach { pair ->
entityStorage.resolve(pair.key)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, resolveRoots(pair.value), moduleMap, project))
}
}
return result
}
private fun resolveRoots(builders: List<ModuleRootsIteratorBuilder>): List<VirtualFile> {
if (PlatformUtils.isRider() || PlatformUtils.isCLion()) {
return builders.flatMap { builder -> builder.urls }.mapNotNull { url -> url.virtualFile }
}
val roots = mutableListOf<VirtualFileUrl>()
for (builder in builders) {
for (root in builder.urls) {
var isChild = false
val it = roots.iterator()
while (it.hasNext()) {
val next = it.next()
if (next.isEqualOrParentOf(root)) {
isChild = true
break
}
if (root.isEqualOrParentOf(next)) {
it.remove()
}
}
if (!isChild) {
roots.add(root)
}
}
}
return roots.mapNotNull { url -> url.virtualFile }
}
}
|
apache-2.0
|
aabe5951dbb1ad37dfde0008a12970b1
| 42.783784 | 127 | 0.730781 | 5.006182 | false | false | false | false |
hotchemi/PermissionsDispatcher
|
test/src/test/java/permissions/dispatcher/test/Extensions.kt
|
1
|
4589
|
package permissions.dispatcher.test
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.PermissionChecker
import androidx.fragment.app.Fragment
import org.mockito.Matchers.any
import org.mockito.Matchers.anyString
import org.powermock.api.mockito.PowerMockito
import java.lang.reflect.Field
import java.lang.reflect.Modifier
import kotlin.jvm.internal.CallableReference
import kotlin.reflect.KFunction
fun mockShouldShowRequestPermissionRationaleActivity(result: Boolean) {
PowerMockito.`when`(ActivityCompat.shouldShowRequestPermissionRationale(any(Activity::class.java), anyString())).thenReturn(result)
}
@SuppressLint("NewApi")
fun mockShouldShowRequestPermissionRationaleFragment(fragment: Fragment, result: Boolean) {
PowerMockito.`when`(fragment.shouldShowRequestPermissionRationale(anyString())).thenReturn(result)
}
fun mockActivityCompatShouldShowRequestPermissionRationale(result: Boolean) {
PowerMockito.`when`(ActivityCompat.shouldShowRequestPermissionRationale(any(Activity::class.java), anyString())).thenReturn(result)
}
fun mockCheckSelfPermission(result: Boolean) {
val value = if (result) PackageManager.PERMISSION_GRANTED else PackageManager.PERMISSION_DENIED
PowerMockito.`when`(PermissionChecker.checkSelfPermission(any(Context::class.java), anyString())).thenReturn(value)
}
fun mockCanDrawOverlays(result: Boolean) {
PowerMockito.`when`(Settings.canDrawOverlays(any(Context::class.java))).thenReturn(result)
}
fun mockCanWrite(result: Boolean) {
PowerMockito.`when`(Settings.System.canWrite(any(Context::class.java))).thenReturn(result)
}
private fun getPrivateField(clazz: Class<*>, fieldName: String): Field {
val field = clazz.getDeclaredField(fieldName)
field.isAccessible = true
return field
}
private fun getPrivateIntField(clazz: Class<*>, fieldName: String): Int = getPrivateField(clazz, fieldName).getInt(null)
fun getRequestWriteSetting(clazz: Class<*>) = getPrivateIntField(clazz, "REQUEST_WRITESETTING")
fun getRequestSystemAlertWindow(clazz: Class<*>) = getPrivateIntField(clazz, "REQUEST_SYSTEMALERTWINDOW")
fun getRequestCameraConstant(clazz: Class<*>) = getPrivateIntField(clazz, "REQUEST_SHOWCAMERA")
fun getPermissionRequestConstant(clazz: Class<*>) = getPrivateField(clazz, "PERMISSION_SHOWCAMERA").get(null) as Array<String>
fun overwriteCustomSdkInt(sdkInt: Int = 23) {
val modifiersField = Field::class.java.getDeclaredField("modifiers")
modifiersField.isAccessible = true
val field = Build.VERSION::class.java.getDeclaredField("SDK_INT")
field.isAccessible = true
modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv())
field.set(null, sdkInt)
}
fun clearCustomSdkInt() {
overwriteCustomSdkInt()
}
fun mockUriParse(result: Uri? = null) {
PowerMockito.`when`(Uri.parse(anyString())).thenReturn(result)
}
/**
* get other package level property value by other package level function name which is in the same kotlin file
*/
fun <R> KFunction<R>.packageLevelGetPropertyValueByName(otherPropertyName: String): Any? {
return getTopPropertyValueByName(this as CallableReference, otherPropertyName)
}
fun getTopPropertyValueByName(otherCallableReference: CallableReference, propertyName: String): Any? {
val owner = otherCallableReference.owner ?: return null
val containerClass: Class<*>
try {
containerClass = owner::class.members.firstOrNull { it.name == "jClass" }?.call(owner) as Class<*>
} catch (e: Exception) {
throw IllegalArgumentException("No such property 'jClass'")
}
var tobeSearchMethodClass: Class<*>? = containerClass
while (tobeSearchMethodClass != null) {
tobeSearchMethodClass.declaredFields.forEach {
if (it.name == propertyName) {
it.isAccessible = true
// top property(package property) should be static in java level
if (Modifier.isStatic(it.modifiers)) {
return it.get(null)
} else {
throw IllegalStateException("It is not a top property : $propertyName")
}
}
}
tobeSearchMethodClass = tobeSearchMethodClass.superclass
}
throw IllegalArgumentException("Can't find the property named :$propertyName in the same file with ${otherCallableReference.name}")
}
|
apache-2.0
|
dffaba602ed920ab3e38bf1074989784
| 39.254386 | 135 | 0.754849 | 4.6167 | false | false | false | false |
jwren/intellij-community
|
plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/AbstractFeatureSuggester.kt
|
1
|
2973
|
@file:Suppress("UnstableApiUsage")
package training.featuresSuggester.suggesters
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.local.ActionsLocalSummary
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.keymap.KeymapUtil
import org.jetbrains.annotations.Nls
import training.featuresSuggester.*
import training.featuresSuggester.settings.FeatureSuggesterSettings
import java.util.concurrent.TimeUnit
abstract class AbstractFeatureSuggester : FeatureSuggester {
protected open val suggestingTipFileName: String? = null
protected open val suggestingDocUrl: String? = null
protected abstract val message: String
protected abstract val suggestingActionId: String
/**
* There are following conditions that must be met to show suggestion:
* 1. The suggesting action must not have been used during the last [minSuggestingIntervalDays] working days
* 2. This suggestion must not have been shown during the last 24 hours
*/
override fun isSuggestionNeeded() = !isSuggestingActionUsedRecently() && !isSuggestionShownRecently()
private fun isSuggestingActionUsedRecently(): Boolean {
val summary = service<ActionsLocalSummary>().getActionStatsById(suggestingActionId) ?: return false
val lastTimeUsed = summary.lastUsedTimestamp
val oldestWorkingDayStart = FeatureSuggesterSettings.instance().getOldestWorkingDayStartMillis(minSuggestingIntervalDays)
return lastTimeUsed > oldestWorkingDayStart
}
private fun isSuggestionShownRecently(): Boolean {
val lastTimeShown = FeatureSuggesterSettings.instance().getSuggestionLastShownTime(id)
val delta = System.currentTimeMillis() - lastTimeShown
return delta < TimeUnit.DAYS.toMillis(1L)
}
protected fun createSuggestion(): Suggestion {
if (isRedoOrUndoRunning()) return NoSuggestion
val fullMessage = "$message ${getShortcutText(suggestingActionId)}"
return if (suggestingTipFileName != null) {
TipSuggestion(fullMessage, id, suggestingTipFileName!!)
}
else if (suggestingDocUrl != null) {
DocumentationSuggestion(fullMessage, id, suggestingDocUrl!!)
}
else error("Suggester must implement 'suggestingTipFileName' or 'suggestingDocLink' property.")
}
private fun isRedoOrUndoRunning(): Boolean {
val commandName = CommandProcessor.getInstance().currentCommandName
return commandName != null && (commandName.startsWith(ActionsBundle.message("action.redo.description", ""))
|| commandName.startsWith(ActionsBundle.message("action.undo.description", "")))
}
@Nls
fun getShortcutText(actionId: String): String {
val shortcut = KeymapUtil.getShortcutText(actionId)
return if (shortcut == "<no shortcut>") {
FeatureSuggesterBundle.message("shortcut.not.found.message")
}
else {
FeatureSuggesterBundle.message("shortcut", shortcut)
}
}
}
|
apache-2.0
|
df4d96fb5074f2d6cf3eb19da9cec778
| 41.471429 | 125 | 0.768248 | 5.005051 | false | false | false | false |
vovagrechka/fucking-everything
|
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/declaration/EnumTranslator.kt
|
1
|
3707
|
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.declaration
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.translate.context.Namer
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.general.AbstractTranslator
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
class EnumTranslator(
context: TranslationContext,
val descriptor: ClassDescriptor,
val entries: List<ClassDescriptor>
) : AbstractTranslator(context) {
fun generateStandardMethods() {
generateValuesFunction()
generateValueOfFunction()
}
private fun generateValuesFunction() {
val function = createFunction(DescriptorUtils.getFunctionByName(descriptor.staticScope, DescriptorUtils.ENUM_VALUES))
val values = entries.map { JsInvocation(JsAstUtils.pureFqn(context().getNameForObjectInstance(it), null)) }
function.body.statements += JsReturn(JsArrayLiteral(values))
}
private fun generateValueOfFunction() {
val function = createFunction(DescriptorUtils.getFunctionByName(descriptor.staticScope, DescriptorUtils.ENUM_VALUE_OF))
val nameParam = function.scope.declareTemporaryName("name")
function.parameters += JsParameter(nameParam)
val clauses = entries.map { entry ->
JsCase().apply {
caseExpression = context().program().getStringLiteral(entry.name.asString())
statements += JsReturn(JsInvocation(JsAstUtils.pureFqn(context().getNameForObjectInstance(entry), null)))
}
}
val message = JsBinaryOperation(JsBinaryOperator.ADD,
context().program().getStringLiteral("No enum constant ${descriptor.fqNameSafe}."),
nameParam.makeRef())
val throwStatement = JsExpressionStatement(JsInvocation(Namer.throwIllegalStateExceptionFunRef(), message))
if (clauses.isNotEmpty()) {
val defaultCase = JsDefault().apply { statements += throwStatement }
function.body.statements += JsSwitch(nameParam.makeRef(), clauses + defaultCase)
}
else {
function.body.statements += throwStatement
}
}
private fun createFunction(functionDescriptor: FunctionDescriptor): JsFunction {
val function = context().getFunctionObject(functionDescriptor)
function.name = context().getInnerNameForDescriptor(functionDescriptor)
context().addDeclarationStatement(function.makeStmt())
val classRef = context().getInnerReference(descriptor)
val functionRef = function.name.makeRef()
val assignment = JsAstUtils.assignment(JsNameRef(context().getNameForDescriptor(functionDescriptor), classRef), functionRef)
context().addDeclarationStatement(assignment.makeStmt())
return function
}
}
|
apache-2.0
|
8a168a722ba18b2e7cd41a800ec8990b
| 42.116279 | 132 | 0.727273 | 4.909934 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/DeprecatedCallableAddReplaceWithInspection.kt
|
1
|
10254
|
// 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.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.core.unblockDocument
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isUnit
class DeprecatedCallableAddReplaceWithInspection : AbstractApplicabilityBasedInspection<KtCallableDeclaration>(
KtCallableDeclaration::class.java
) {
override fun inspectionText(element: KtCallableDeclaration) = KotlinBundle.message("deprecated.annotation.without.replacewith.argument")
override fun inspectionHighlightRangeInElement(element: KtCallableDeclaration) = element.annotationEntries.first {
it.shortName == DEPRECATED_NAME
}.textRangeIn(element)
override val defaultFixText get() = KotlinBundle.message("add.replacewith.argument.to.specify.replacement.pattern")
private class ReplaceWith(val expression: String, vararg val imports: String)
override fun isApplicable(element: KtCallableDeclaration): Boolean {
element.deprecatedAnnotationWithNoReplaceWith() ?: return false
return element.suggestReplaceWith() != null
}
override fun applyTo(element: KtCallableDeclaration, project: Project, editor: Editor?) {
val replaceWith = element.suggestReplaceWith() ?: return
assert('\n' !in replaceWith.expression && '\r' !in replaceWith.expression) { "Formatted expression text should not contain \\n or \\r" }
val annotationEntry = element.deprecatedAnnotationWithNoReplaceWith()!!
val psiFactory = KtPsiFactory(element)
var escapedText = replaceWith.expression.replace("\\", "\\\\").replace("\"", "\\\"")
// escape '$' if it's followed by a letter or '{'
if (escapedText.contains('$')) {
escapedText = StringBuilder().apply {
var i = 0
val length = escapedText.length
while (i < length) {
val c = escapedText[i++]
if (c == '$' && i < length) {
val c1 = escapedText[i]
if (c1.isJavaIdentifierStart() || c1 == '{') {
append('\\')
}
}
append(c)
}
}.toString()
}
val argumentText = StringBuilder().apply {
if (annotationEntry.valueArguments.any { it.isNamed() }) append("replaceWith = ")
append("kotlin.ReplaceWith(\"")
append(escapedText)
append("\"")
//TODO: who should escape keywords here?
replaceWith.imports.forEach { append(",\"").append(it).append("\"") }
append(")")
}.toString()
var argument = psiFactory.createArgument(psiFactory.createExpression(argumentText))
argument = annotationEntry.valueArgumentList!!.addArgument(argument)
argument = ShortenReferences.DEFAULT.process(argument) as KtValueArgument
editor?.apply {
unblockDocument()
moveCaret(argument.textOffset)
}
}
private fun KtCallableDeclaration.deprecatedAnnotationWithNoReplaceWith(): KtAnnotationEntry? {
for (entry in annotationEntries) {
if (entry.shortName != DEPRECATED_NAME) continue
val bindingContext = entry.analyze()
val resolvedCall = entry.calleeExpression.getResolvedCall(bindingContext) ?: continue
if (!resolvedCall.isReallySuccess()) continue
val descriptor = resolvedCall.resultingDescriptor.containingDeclaration
val descriptorFqName = DescriptorUtils.getFqName(descriptor).toSafe()
if (descriptorFqName != StandardNames.FqNames.deprecated) continue
val args = resolvedCall.valueArguments.mapKeys { it.key.name.asString() }
val replaceWithArguments = args["replaceWith"] /*TODO: kotlin.deprecated::replaceWith.name*/
val level = args["level"]
if (replaceWithArguments?.arguments?.isNotEmpty() == true) return null
if (level != null && level.arguments.isNotEmpty()) {
val levelDescriptor = level.arguments[0].getArgumentExpression().getResolvedCall(bindingContext)?.candidateDescriptor
if (levelDescriptor?.name?.asString() == "HIDDEN") return null
}
return entry
}
return null
}
private fun KtCallableDeclaration.suggestReplaceWith(): ReplaceWith? {
val replacementExpression = when (this) {
is KtNamedFunction -> replacementExpressionFromBody()
is KtProperty -> {
if (isVar) return null //TODO
getter?.replacementExpressionFromBody()
}
else -> null
} ?: return null
var isGood = true
replacementExpression.accept(object : KtVisitorVoid() {
override fun visitReturnExpression(expression: KtReturnExpression) {
isGood = false
}
override fun visitDeclaration(dcl: KtDeclaration) {
isGood = false
}
override fun visitBlockExpression(expression: KtBlockExpression) {
if (expression.statements.size > 1) {
isGood = false
return
}
super.visitBlockExpression(expression)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val target = expression.resolveToCall()?.resultingDescriptor as? DeclarationDescriptorWithVisibility ?: return
if (DescriptorVisibilities.isPrivate((target.visibility))) {
isGood = false
}
}
override fun visitKtElement(element: KtElement) {
element.acceptChildren(this)
}
})
if (!isGood) return null
//TODO: check that no receivers that cannot be referenced from outside involved
val text = replacementExpression.text
var expression = try {
KtPsiFactory(this).createExpression(text.replace('\n', ' '))
} catch (e: Throwable) { // does not parse in one line
return null
}
expression = expression.reformatted(true) as KtExpression
return ReplaceWith(
expression.text.trim(),
*extractImports(
replacementExpression
).toTypedArray()
)
}
private fun KtDeclarationWithBody.replacementExpressionFromBody(): KtExpression? {
val body = bodyExpression ?: return null
if (!hasBlockBody()) return body
val block = body as? KtBlockExpression ?: return null
val statement = block.statements.singleOrNull() ?: return null
val returnsUnit = (resolveToDescriptorIfAny(BodyResolveMode.FULL) as? FunctionDescriptor)?.returnType?.isUnit() ?: return null
return when (statement) {
is KtReturnExpression -> statement.returnedExpression
else -> if (returnsUnit) statement else null
}
}
private fun extractImports(expression: KtExpression): Collection<String> {
val file = expression.containingKtFile
val currentPackageFqName = file.packageFqName
val importHelper = ImportInsertHelper.getInstance(expression.project)
val result = ArrayList<String>()
expression.accept(object : KtVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val bindingContext = expression.analyze()
val target = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, expression]
?: bindingContext[BindingContext.REFERENCE_TARGET, expression]
?: return
if (target.isExtension || expression.getReceiverExpression() == null) {
val fqName = target.importableFqName ?: return
if (!importHelper.isImportedWithDefault(ImportPath(fqName, false), file)
&& (target.containingDeclaration as? PackageFragmentDescriptor)?.fqName != currentPackageFqName
) {
result.add(fqName.asString())
}
}
}
override fun visitKtElement(element: KtElement) {
element.acceptChildren(this)
}
})
return result
}
companion object {
val DEPRECATED_NAME = StandardNames.FqNames.deprecated.shortName()
}
}
|
apache-2.0
|
f2c387ab7a5ffa05fbd5f0df610dd683
| 43.008584 | 144 | 0.6575 | 5.649587 | false | false | false | false |
GunoH/intellij-community
|
plugins/ide-features-trainer/src/training/dsl/TaskTestContext.kt
|
9
|
14795
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.dsl
import com.intellij.ide.util.treeView.NodeRenderer
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.ui.MultilineTreeCellRenderer
import com.intellij.ui.SimpleColoredComponent
import com.intellij.util.ui.tree.TreeUtil
import org.assertj.swing.core.GenericTypeMatcher
import org.assertj.swing.core.Robot
import org.assertj.swing.driver.BasicJListCellReader
import org.assertj.swing.driver.ComponentDriver
import org.assertj.swing.exception.ComponentLookupException
import org.assertj.swing.exception.WaitTimedOutError
import org.assertj.swing.fixture.*
import org.assertj.swing.timing.Condition
import org.assertj.swing.timing.Pause
import org.assertj.swing.timing.Timeout
import training.ui.IftTestContainerFixture
import training.ui.LearningUiUtil
import training.ui.LearningUiUtil.findComponentWithTimeout
import training.util.getActionById
import training.util.invokeActionForFocusContext
import java.awt.Component
import java.awt.Container
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.*
import javax.swing.tree.TreePath
@LearningDsl
class TaskTestContext(rt: TaskRuntimeContext) : TaskRuntimeContext(rt) {
val defaultTimeout = Timeout.timeout(3, TimeUnit.SECONDS)
val robot: Robot get() = LearningUiUtil.robot
data class TestScriptProperties(
val duration: Int = 15, //seconds
val skipTesting: Boolean = false
)
fun type(text: String) {
robot.waitForIdle()
for (element in text) {
robot.type(element)
Pause.pause(10, TimeUnit.MILLISECONDS)
}
Pause.pause(300, TimeUnit.MILLISECONDS)
}
fun actions(vararg actionIds: String) {
for (actionId in actionIds) {
val action = getActionById(actionId)
invokeActionForFocusContext(action)
}
}
fun ideFrame(action: IftTestContainerFixture<IdeFrameImpl>.() -> Unit) {
with(findIdeFrame(project, robot, defaultTimeout)) {
action()
}
}
fun <ComponentType : Component> waitComponent(componentClass: Class<ComponentType>, partOfName: String? = null) {
LearningUiUtil.waitUntilFound(robot, typeMatcher(componentClass) {
(if (partOfName != null) it.javaClass.name.contains(partOfName)
else true) && it.isShowing
}, defaultTimeout) { LearningUiUtil.getUiRootsForProject(project) }
}
/**
* Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture.
*
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <C : Container> IftTestContainerFixture<C>.jList(containingItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture {
return generalListFinder(timeout, containingItem) { element, p -> element == p }
}
/**
* Finds a JTree component in hierarchy of context component with a path satisfies the [checkPath] predicate and returns JTreeFixture
*
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
inline fun <C : Container> IftTestContainerFixture<C>.jTree(timeout: Timeout = defaultTimeout,
crossinline checkPath: (TreePath) -> Boolean): JTreeFixture {
val tree = findComponentWithTimeout(timeout) { ui: JTree ->
ui.isShowing && TreeUtil.treePathTraverser(ui).any { path -> checkPath(path) }
}
return JTreeFixture(robot(), tree)
}
/**
* Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture.
*
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <C : Container> IftTestContainerFixture<C>.button(name: String, timeout: Timeout = defaultTimeout): JButtonFixture {
return button(timeout) { b: JButton -> b.text == name }
}
inline fun <C : Container, reified ButtonType : JButton> IftTestContainerFixture<C>.button(
timeout: Timeout = defaultTimeout,
crossinline finderFunction: (ButtonType) -> Boolean
): JButtonFixture {
val button = findComponentWithTimeout(timeout) { b: ButtonType -> b.isShowing && b.isEnabled && finderFunction(b) }
return JButtonFixture(robot(), button)
}
fun <C : Container> IftTestContainerFixture<C>.actionButton(actionName: String, timeout: Timeout = defaultTimeout)
: AbstractComponentFixture<*, ActionButton, ComponentDriver> {
val actionButton: ActionButton = findComponentWithTimeout(timeout) {
it.isShowing && it.isEnabled && actionName == it.action.templatePresentation.text
}
return ActionButtonFixture(robot(), actionButton)
}
inline fun <C : Container, reified MenuItemType : JMenuItem> IftTestContainerFixture<C>.jMenuItem(timeout: Timeout = defaultTimeout,
crossinline finderFunction: (MenuItemType) -> Boolean
): JMenuItemFixture {
val item = findComponentWithTimeout(timeout) { item: MenuItemType -> item.isShowing && finderFunction(item) }
return JMenuItemFixture(robot(), item)
}
// Modified copy-paste
fun <C : Container> IftTestContainerFixture<C>.jListContains(partOfItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture {
return generalListFinder(timeout, partOfItem) { element, p -> element.contains(p) }
}
fun <C : Container> IftTestContainerFixture<C>.jListFixture(target: JList<*>): JListFixture {
return JListFixture(robot(), target)
}
/**
* Finds JDialog with a specific title (if title is null showing dialog should be only one) and returns created JDialogFixture
*/
fun dialog(title: String? = null,
ignoreCaseTitle: Boolean = false,
predicate: (String, String) -> Boolean = { found: String, wanted: String -> found == wanted },
timeout: Timeout = defaultTimeout,
func: IftTestContainerFixture<JDialog>.() -> Unit = {})
: AbstractComponentFixture<*, JDialog, ComponentDriver> {
val jDialogFixture = if (title == null) {
val jDialog = LearningUiUtil.waitUntilFound(robot, typeMatcher(JDialog::class.java) { true }, timeout) {
LearningUiUtil.getUiRootsForProject(project)
}
JDialogFixture(robot, jDialog)
}
else {
try {
val dialog = withPauseWhenNull(timeout = timeout) {
val allMatchedDialogs = robot.finder().findAll(typeMatcher(JDialog::class.java) {
it.isFocused &&
if (ignoreCaseTitle) predicate(it.title.toLowerCase(), title.toLowerCase()) else predicate(it.title, title)
}).filter { it.isShowing && it.isEnabled && it.isVisible }
if (allMatchedDialogs.size > 1) throw Exception(
"Found more than one (${allMatchedDialogs.size}) dialogs matched title \"$title\"")
allMatchedDialogs.firstOrNull()
}
JDialogFixture(robot, dialog)
}
catch (timeoutError: WaitTimedOutError) {
throw ComponentLookupException("Timeout error for finding JDialog by title \"$title\" for ${timeout.duration()}")
}
}
func(jDialogFixture)
return jDialogFixture
}
fun IftTestContainerFixture<*>.jComponent(target: Component): AbstractComponentFixture<*, Component, ComponentDriver> {
return SimpleComponentFixture(robot(), target)
}
fun invokeActionViaShortcut(shortcut: String) {
val keyStroke = KeyStrokeAdapter.getKeyStroke(shortcut)
robot.pressAndReleaseKey(keyStroke.keyCode, keyStroke.modifiers)
}
companion object {
@Volatile
var inTestMode: Boolean = false
}
////////////------------------------------
private fun <C : Container> IftTestContainerFixture<C>.generalListFinder(timeout: Timeout,
containingItem: String?,
predicate: (String, String) -> Boolean): JListFixture {
val extCellReader = ExtendedJListCellReader()
val myJList: JList<*> = findComponentWithTimeout(timeout) { jList: JList<*> ->
if (containingItem == null) true //if were searching for any jList()
else {
val elements = (0 until jList.model.size).mapNotNull { extCellReader.valueAt(jList, it) }
elements.any { predicate(it, containingItem) } && jList.isShowing
}
}
val jListFixture = JListFixture(robot(), myJList)
jListFixture.replaceCellReader(extCellReader)
return jListFixture
}
/**
* waits for [timeout] when functionProbeToNull() not return null
*
* @throws WaitTimedOutError with the text: "Timed out waiting for $timeout second(s) until {@code conditionText} will be not null"
*/
private fun <ReturnType> withPauseWhenNull(conditionText: String = "function to probe",
timeout: Timeout = defaultTimeout,
functionProbeToNull: () -> ReturnType?): ReturnType {
var result: ReturnType? = null
waitUntil("$conditionText will be not null", timeout) {
result = functionProbeToNull()
result != null
}
return result!!
}
private fun waitUntil(condition: String, timeout: Timeout = defaultTimeout, conditionalFunction: () -> Boolean) {
Pause.pause(object : Condition("${timeout.duration()} until $condition") {
override fun test() = conditionalFunction()
}, timeout)
}
private class SimpleComponentFixture(robot: Robot, target: Component) :
ComponentFixture<SimpleComponentFixture, Component>(SimpleComponentFixture::class.java, robot, target)
private fun <ComponentType : Component> typeMatcher(componentTypeClass: Class<ComponentType>,
matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> {
return object : GenericTypeMatcher<ComponentType>(componentTypeClass) {
// Do not check for isValid because for some reason needed dialogs are invalids!
override fun isMatching(component: ComponentType): Boolean = component.isShowing && matcher(component)
}
}
}
private fun getValueWithCellRenderer(cellRendererComponent: Component, isExtended: Boolean = true): String? {
val result = when (cellRendererComponent) {
is JLabel -> cellRendererComponent.text
is NodeRenderer -> {
if (isExtended) cellRendererComponent.getFullText()
else cellRendererComponent.getFirstText()
} //should stand before SimpleColoredComponent because it is more specific
is SimpleColoredComponent -> cellRendererComponent.getFullText()
is MultilineTreeCellRenderer -> cellRendererComponent.text
else -> cellRendererComponent.findText()
}
return result?.trimEnd()
}
private class ExtendedJListCellReader : BasicJListCellReader() {
override fun valueAt(list: JList<*>, index: Int): String? {
val element = list.model.getElementAt(index) ?: return null
@Suppress("UNCHECKED_CAST")
val cellRendererComponent = (list as JList<Any>).cellRenderer
.getListCellRendererComponent(list, element, index, true, true)
return getValueWithCellRenderer(cellRendererComponent)
}
}
private fun SimpleColoredComponent.getFullText(): String {
return invokeAndWaitIfNeeded {
this.getCharSequence(false).toString()
}
}
private fun SimpleColoredComponent.getFirstText(): String {
return invokeAndWaitIfNeeded {
this.getCharSequence(true).toString()
}
}
private fun Component.findText(): String? {
try {
assert(this is Container)
val container = this as Container
val resultList = ArrayList<String>()
resultList.addAll(
findAllWithBFS(container, JLabel::class.java)
.asSequence()
.filter { !it.text.isNullOrEmpty() }
.map { it.text }
.toList()
)
resultList.addAll(
findAllWithBFS(container, SimpleColoredComponent::class.java)
.asSequence()
.filter {
it.getFullText().isNotEmpty()
}
.map {
it.getFullText()
}
.toList()
)
return resultList.firstOrNull { it.isNotEmpty() }
}
catch (ignored: ComponentLookupException) {
return null
}
}
private fun <ComponentType : Component> findAllWithBFS(container: Container, clazz: Class<ComponentType>): List<ComponentType> {
val result = LinkedList<ComponentType>()
val queue: Queue<Component> = LinkedList()
@Suppress("UNCHECKED_CAST")
fun check(container: Component) {
if (clazz.isInstance(container)) result.add(container as ComponentType)
}
queue.add(container)
while (queue.isNotEmpty()) {
val polled = queue.poll()
check(polled)
if (polled is Container)
queue.addAll(polled.components)
}
return result
}
private open class ComponentFixture<S, C : Component>(selfType: Class<S>, robot: Robot, target: C)
: AbstractComponentFixture<S, C, ComponentDriver>(selfType, robot, target) {
override fun createDriver(robot: Robot): ComponentDriver {
return ComponentDriver(robot)
}
}
private class ActionButtonFixture(robot: Robot, target: ActionButton) :
ComponentFixture<ActionButtonFixture, ActionButton>(ActionButtonFixture::class.java, robot, target), IftTestContainerFixture<ActionButton>
private class IdeFrameFixture(robot: Robot, target: IdeFrameImpl)
: ComponentFixture<IdeFrameFixture, IdeFrameImpl>(IdeFrameFixture::class.java, robot, target), IftTestContainerFixture<IdeFrameImpl>
private class JDialogFixture(robot: Robot, jDialog: JDialog) :
ComponentFixture<JDialogFixture, JDialog>(JDialogFixture::class.java, robot, jDialog), IftTestContainerFixture<JDialog>
private fun findIdeFrame(project: Project, robot: Robot, timeout: Timeout): IdeFrameFixture {
val matcher: GenericTypeMatcher<IdeFrameImpl> = object : GenericTypeMatcher<IdeFrameImpl>(
IdeFrameImpl::class.java) {
override fun isMatching(frame: IdeFrameImpl): Boolean {
return frame.isShowing && ProjectFrameHelper.getFrameHelper(frame)?.project == project
}
}
return try {
Pause.pause(object : Condition("IdeFrame to show up") {
override fun test(): Boolean {
return !robot.finder().findAll(matcher).isEmpty()
}
}, timeout)
val ideFrame = robot.finder().find(matcher)
IdeFrameFixture(robot, ideFrame)
}
catch (timedOutError: WaitTimedOutError) {
throw ComponentLookupException("Unable to find IdeFrame in " + timeout.duration())
}
}
|
apache-2.0
|
6028e64363360819b4f4cad66b1eed74
| 39.094851 | 141 | 0.705779 | 4.805132 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/compiler-reference-index/src/org/jetbrains/kotlin/idea/search/refIndex/ClassOneToManyStorage.kt
|
4
|
1985
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.refIndex
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.util.containers.generateRecursiveSequence
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.PersistentMapBuilder
import com.intellij.util.io.externalizer.StringCollectionExternalizer
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import java.nio.file.Path
import kotlin.io.path.deleteIfExists
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.name
@IntellijInternalApi
class ClassOneToManyStorage(storagePath: Path) {
init {
val storageName = storagePath.name
storagePath.parent.listDirectoryEntries("$storageName*").ifNotEmpty {
forEach { it.deleteIfExists() }
LOG.warn("'$storageName' was deleted")
}
}
private val storage = PersistentMapBuilder.newBuilder(
storagePath,
EnumeratorStringDescriptor.INSTANCE,
externalizer,
).build()
fun closeAndClean(): Unit = storage.closeAndClean()
fun put(key: String, values: Collection<String>) {
storage.put(key, values)
}
operator fun get(key: FqName, deep: Boolean): Sequence<FqName> = get(key.asString(), deep).map(::FqName)
operator fun get(key: String, deep: Boolean): Sequence<String> {
val values = storage[key]?.asSequence() ?: emptySequence()
if (!deep) return values
return generateRecursiveSequence(values) {
storage[it]?.asSequence() ?: emptySequence()
}
}
companion object {
private val externalizer = StringCollectionExternalizer<Collection<String>>(::ArrayList)
private val LOG = logger<ClassOneToManyStorage>()
}
}
|
apache-2.0
|
482e182eee77ff040fc5ccc27e65a153
| 36.471698 | 158 | 0.730479 | 4.460674 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/LetImplementInterfaceFix.kt
|
1
|
3957
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isInterface
class LetImplementInterfaceFix(
element: KtClassOrObject,
expectedType: KotlinType,
expressionType: KotlinType
) : KotlinQuickFixAction<KtClassOrObject>(element), LowPriorityAction {
private fun KotlinType.renderShort() = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(this)
private val expectedTypeName: String
private val expectedTypeNameSourceCode: String
private val prefix: String
private val validExpectedType = with(expectedType) {
isInterface() &&
!containsStarProjections() &&
constructor !in TypeUtils.getAllSupertypes(expressionType).map(KotlinType::constructor)
}
init {
val expectedTypeNotNullable = TypeUtils.makeNotNullable(expectedType)
expectedTypeName = expectedTypeNotNullable.renderShort()
expectedTypeNameSourceCode = IdeDescriptorRenderers.SOURCE_CODE.renderType(expectedTypeNotNullable)
val verb = if (expressionType.isInterface()) KotlinBundle.message("text.extend") else KotlinBundle.message("text.implement")
val typeDescription = if (element.isObjectLiteral())
KotlinBundle.message("the.anonymous.object")
else
"'${expressionType.renderShort()}'"
prefix = KotlinBundle.message("let.0.1", typeDescription, verb)
}
override fun getFamilyName() = KotlinBundle.message("let.type.implement.interface")
override fun getText() = KotlinBundle.message("0.interface.1", prefix, expectedTypeName)
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = validExpectedType
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val point = element.createSmartPointer()
val superTypeEntry = KtPsiFactory(element).createSuperTypeEntry(expectedTypeNameSourceCode)
runWriteAction {
val entryElement = element.addSuperTypeListEntry(superTypeEntry)
ShortenReferences.DEFAULT.process(entryElement)
}
val newElement = point.element ?: return
val implementMembersHandler = ImplementMembersHandler()
if (implementMembersHandler.collectMembersToGenerate(newElement).isEmpty()) return
if (editor != null) {
editor.caretModel.moveToOffset(element.textRange.startOffset)
val containingFile = element.containingFile
FileEditorManager.getInstance(project).openFile(containingFile.virtualFile, true)
implementMembersHandler.invoke(project, editor, containingFile)
}
}
}
|
apache-2.0
|
8a00712b0505afa9cabf0377c451c895
| 44.482759 | 158 | 0.765479 | 5.165796 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/api/query/language/SampleQueryLanguage.kt
|
5
|
2252
|
package com.jetbrains.packagesearch.intellij.plugin.api.query.language
import com.intellij.util.io.URLUtil
import com.jetbrains.packagesearch.intellij.plugin.api.query.SearchQueryCompletionProvider
import com.jetbrains.packagesearch.intellij.plugin.api.query.SearchQueryParser
// NOTE: This file contains a *sample* implementation for a query parser and completion provider.
// Since we do not have any server-side options for handling special queries, the IntelliJ plugin
// uses a no-op provider. However for future reference and/or testing, this sample is a useful
// artifact. Keep it around until we start using something else than the no-op version.
class SampleQueryCompletionProvider : SearchQueryCompletionProvider(true) {
override fun getAttributes(): List<String> {
return listOf("/onlyMpp", "/onlyStable", "/tag")
}
override fun getValuesFor(attribute: String): List<String> {
if (attribute.startsWith("/onlyStable:", true)) {
return listOf("true", "false")
}
if (attribute.startsWith("/onlyMpp:", true)) {
return listOf("true", "false")
}
return emptyList()
}
}
class SampleQuery(query: String) : SearchQueryParser() {
private val tags = mutableSetOf<String>()
private var onlyStable = true
private var onlyMpp = false
init {
parse(query)
}
override fun handleAttribute(name: String, value: String, invert: Boolean) {
when {
name.equals("/tag", true) -> {
tags.add(value)
}
name.equals("/onlyStable", true) -> {
onlyStable = value.toBoolean()
}
name.equals("/onlyMpp", true) -> {
onlyMpp = value.toBoolean()
}
}
}
fun buildQueryString(): String {
val url = StringBuilder()
url.append("q=")
if (!searchQuery.isNullOrEmpty()) {
url.append(URLUtil.encodeURIComponent(searchQuery!!))
}
url.append("&onlyStable=$onlyStable")
url.append("&onlyMpp=$onlyMpp")
for (tag in tags) {
url.append("&tags=").append(URLUtil.encodeURIComponent(tag))
}
return url.toString()
}
}
|
apache-2.0
|
b7ef8291d1daeb89737ab13cae55415c
| 31.171429 | 97 | 0.629218 | 4.643299 | false | false | false | false |
smmribeiro/intellij-community
|
platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/RuntimeChooserJbr.kt
|
12
|
1915
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.projectRoots.impl.jdkDownloader
import com.intellij.lang.LangBundle
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.registry.Registry
data class RuntimeChooserDownloadableItem(val item: JdkItem) : RuntimeChooserItem() {
override fun toString() = item.fullPresentationText
}
fun RuntimeChooserModel.fetchAvailableJbrs() {
object : Task.Backgroundable(null, LangBundle.message("progress.title.choose.ide.runtime.downloading.jetbrains.runtime.list")) {
override fun run(indicator: ProgressIndicator) {
val builds = service<RuntimeChooserJbrListDownloader>()
.downloadForUI(indicator)
.filter { RuntimeChooserJreValidator.isSupportedSdkItem(it) }
invokeLater(modalityState = ModalityState.any()) {
updateDownloadJbrList(builds)
}
}
}.queue()
}
@Service(Service.Level.APP)
private class RuntimeChooserJbrListDownloader : JdkListDownloaderBase() {
override val feedUrl: String
get() {
val registry = runCatching { Registry.get("runtime.chooser.url").asString() }.getOrNull()
if (!registry.isNullOrBlank()) return registry
val majorVersion = runCatching { Registry.get("runtime.chooser.pretend.major").asInteger() }.getOrNull()
?: ApplicationInfo.getInstance().build.components.firstOrNull()
return "https://download.jetbrains.com/jdk/feed/v1/jbr-choose-runtime-${majorVersion}.json.xz"
}
}
|
apache-2.0
|
1ad3f13efee8c9cf450194c0338a59c9
| 41.555556 | 140 | 0.764491 | 4.382151 | false | false | false | false |
paul58914080/ff4j-spring-boot-starter-parent
|
ff4j-spring-boot-web-api/src/main/kotlin/org/ff4j/spring/boot/web/api/exceptions/FF4jExceptionHandler.kt
|
1
|
5370
|
/*-
* #%L
* ff4j-spring-boot-web-api
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* 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.
* #L%
*/
package org.ff4j.spring.boot.web.api.exceptions
import org.ff4j.exception.InvalidPropertyTypeException
import org.ff4j.services.exceptions.*
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
/**
* Created by Paul
*
* @author [Paul Williams](mailto:[email protected])
*/
@ControllerAdvice(basePackages = ["org.ff4j.spring.boot.web.api.resources"])
class FF4jExceptionHandler {
@ExceptionHandler(value = [(IllegalArgumentException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "bad request")
fun badRequestHandler() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(FeatureNotFoundException::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "feature not found")
fun featureNotFoundException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(FeatureIdBlankException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "feature uid cannot be blank")
fun featureIdBlankException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(FeatureIdNotMatchException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "feature uid did not match with the requested feature uid to be created or updated")
fun featureIdNotMatchException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(FlippingStrategyBadRequestException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "flipping strategy specified wrongly")
fun flippingStrategyBadRequestException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(PropertiesBadRequestException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "properties specified wrongly")
fun propertiesBadRequestException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(RoleExistsException::class)])
@ResponseStatus(value = HttpStatus.NOT_MODIFIED, reason = "role already exists")
fun roleExistsException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(RoleNotExistsException::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "role does not exist")
fun roleNotExistsException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(GroupExistsException::class)])
@ResponseStatus(value = HttpStatus.NOT_MODIFIED, reason = "group already exists")
fun groupExistsException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(GroupNotExistsException::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "group does not exist")
fun groupNotExistsException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(FeatureStoreNotCached::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "feature store is not cached")
fun featureStoreNotCached() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(AuthorizationNotExistsException::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "no security has been defined")
fun authorizationNotExistsException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(PropertyNotFoundException::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "property not found")
fun propertyNotFoundException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(PropertyNameBlankException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "property name cannot be blank")
fun propertyNameBlankException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(InvalidPropertyTypeException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "bad request")
fun propertyValueInvalidException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(PropertyNameNotMatchException::class)])
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "property name did not match with the requested property name to be created or updated")
fun propertyNameNotMatchException() {
// no-op comment, do nothing
}
@ExceptionHandler(value = [(PropertyStoreNotCached::class)])
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "property store is not cached")
fun propertyStoreNotCached() {
// no-op comment, do nothing
}
}
|
apache-2.0
|
5385c2e0546da37591428127ea7a2018
| 37.913043 | 149 | 0.707263 | 4.41249 | false | false | false | false |
webianks/BlueChat
|
app/src/main/java/com/webianks/bluechat/ChatAdapter.kt
|
1
|
2915
|
package com.webianks.bluechat
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by ramankit on 25/7/17.
*/
class ChatAdapter(val chatData: List<Message>, val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val SENT = 0
val RECEIVED = 1
var df: SimpleDateFormat = SimpleDateFormat("hh:mm a",Locale.getDefault())
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
when(holder?.itemViewType){
SENT -> {
val holder: SentHolder = holder as SentHolder
holder.sentTV.text = chatData[position].message
val timeMilliSeconds = chatData[position].time
val resultdate = Date(timeMilliSeconds)
holder.timeStamp.text = df.format(resultdate)
}
RECEIVED -> {
val holder: ReceivedHolder = holder as ReceivedHolder
holder.receivedTV.text = chatData[position].message
val timeMilliSeconds = chatData[position].time
val resultdate = Date(timeMilliSeconds)
holder.timeStamp.text = df.format(resultdate)
}
}
}
override fun getItemViewType(position: Int): Int {
when(chatData[position].type){
Constants.MESSAGE_TYPE_SENT -> return SENT
Constants.MESSAGE_TYPE_RECEIVED -> return RECEIVED
}
return -1
}
override fun getItemCount(): Int {
return chatData.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
when(viewType){
SENT -> {
val view = LayoutInflater.from(context).inflate(R.layout.sent_layout,parent,false)
return SentHolder(view)
}
RECEIVED -> {
val view = LayoutInflater.from(context).inflate(R.layout.received_layout,parent,false)
return ReceivedHolder(view)
}
else -> {
val view = LayoutInflater.from(context).inflate(R.layout.sent_layout,parent,false)
return SentHolder(view)
}
}
}
inner class SentHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var sentTV = itemView.findViewById<TextView>(R.id.sentMessage)
var timeStamp = itemView.findViewById<TextView>(R.id.timeStamp)
}
inner class ReceivedHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var receivedTV = itemView.findViewById<TextView>(R.id.receivedMessage)
var timeStamp = itemView.findViewById<TextView>(R.id.timeStamp)
}
}
|
mit
|
1786b5b1bdcd4cfdf3c561ff9dba9aca
| 31.764045 | 120 | 0.635678 | 4.664 | false | false | false | false |
ThiagoGarciaAlves/intellij-community
|
plugins/git4idea/tests/git4idea/rebase/GitMultiRepoRebaseTest.kt
|
2
|
9164
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.rebase
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vcs.Executor
import com.intellij.openapi.vcs.Executor.mkdir
import com.intellij.openapi.vcs.Executor.touch
import com.intellij.vcs.test.cleanupForAssertion
import git4idea.branch.GitBranchUiHandler
import git4idea.branch.GitBranchWorker
import git4idea.branch.GitRebaseParams
import git4idea.repo.GitRepository
import git4idea.test.UNKNOWN_ERROR_TEXT
import git4idea.test.git
import git4idea.test.resolveConflicts
import org.mockito.Mockito
import kotlin.properties.Delegates
class GitMultiRepoRebaseTest : GitRebaseBaseTest() {
private var ultimate: GitRepository by Delegates.notNull()
private var community: GitRepository by Delegates.notNull()
private var contrib: GitRepository by Delegates.notNull()
private var allRepositories: List<GitRepository> by Delegates.notNull()
override fun setUp() {
super.setUp()
Executor.cd(projectRoot)
val community = mkdir("community")
val contrib = mkdir("contrib")
ultimate = createRepository(projectPath)
this.community = createRepository(community.path)
this.contrib = createRepository(contrib.path)
allRepositories = listOf(ultimate, this.community, this.contrib)
Executor.cd(projectRoot)
touch(".gitignore", "community\ncontrib")
git("add .gitignore")
git("commit -m gitignore")
}
fun `test all successful`() {
ultimate.`place feature above master`()
community.`diverge feature and master`()
contrib.`place feature on master`()
rebase("master")
assertSuccessfulRebaseNotification("Rebased feature on master")
assertAllRebased()
assertNoRebaseInProgress(allRepositories)
}
fun `test abort from critical error during rebasing 2nd root, before any commits were applied`() {
val localChange = LocalChange(community, "new.txt", "Some content")
`fail with critical error while rebasing 2nd root`(localChange)
assertErrorNotification("Rebase Failed",
"""
contrib: $UNKNOWN_ERROR_TEXT <br/>
$LOCAL_CHANGES_WARNING
""")
community.`assert feature rebased on master`()
contrib.`assert feature not rebased on master`()
ultimate.`assert feature not rebased on master`()
assertNoRebaseInProgress(allRepositories)
ultimate.assertNoLocalChanges()
var confirmation: String? = null
dialogManager.onMessage {
confirmation = it
Messages.YES
}
abortOngoingRebase()
assertNotNull(confirmation, "Abort confirmation message was not shown")
assertEquals("Incorrect confirmation message text",
cleanupForAssertion("Do you want to rollback the successful rebase in community?"),
cleanupForAssertion(confirmation!!))
assertNoRebaseInProgress(allRepositories)
allRepositories.forEach { it.`assert feature not rebased on master`() }
localChange.verify()
}
fun `test abort from critical error while rebasing 2nd root, after some commits were applied`() {
val localChange = LocalChange(community, "new.txt", "Some content")
`fail with critical error while rebasing 2nd root after some commits are applied`(localChange)
vcsNotifier.lastNotification
var confirmation: String? = null
dialogManager.onMessage {
confirmation = it
Messages.YES
}
abortOngoingRebase()
assertNotNull(confirmation, "Abort confirmation message was not shown")
assertEquals("Incorrect confirmation message text",
cleanupForAssertion("Do you want just to abort rebase in contrib, or also rollback the successful rebase in community?"),
cleanupForAssertion(confirmation!!))
assertNoRebaseInProgress(allRepositories)
allRepositories.forEach { it.`assert feature not rebased on master`() }
localChange.verify()
}
fun `test conflicts in multiple repositories are resolved separately`() {
ultimate.`prepare simple conflict`()
community.`prepare simple conflict`()
contrib.`diverge feature and master`()
var facedConflictInUltimate = false
var facedConflictInCommunity = false
vcsHelper.onMerge({
assertFalse(facedConflictInCommunity && facedConflictInUltimate)
if (ultimate.hasConflict("c.txt")) {
assertFalse(facedConflictInUltimate)
facedConflictInUltimate = true
assertNoRebaseInProgress(community)
ultimate.resolveConflicts()
}
else if (community.hasConflict("c.txt")) {
assertFalse(facedConflictInCommunity)
facedConflictInCommunity = true
assertNoRebaseInProgress(ultimate)
community.resolveConflicts()
}
})
rebase("master")
assertTrue(facedConflictInUltimate)
assertTrue(facedConflictInCommunity)
allRepositories.forEach {
it.`assert feature rebased on master`()
assertNoRebaseInProgress(it)
it.assertNoLocalChanges()
}
}
fun `test retry doesn't touch successful repositories`() {
`fail with critical error while rebasing 2nd root`()
GitRebaseUtils.continueRebase(project)
assertSuccessfulRebaseNotification("Rebased feature on master")
assertAllRebased()
assertNoRebaseInProgress(allRepositories)
}
fun `test continue rebase shouldn't attempt to stash`() {
ultimate.`diverge feature and master`()
community.`prepare simple conflict`()
contrib.`diverge feature and master`()
`do nothing on merge`()
rebase("master")
GitRebaseUtils.continueRebase(project)
`assert conflict not resolved notification`()
assertNotRebased("feature", "master", community)
}
fun `test continue rebase with unresolved conflicts should show merge dialog`() {
ultimate.`diverge feature and master`()
community.`prepare simple conflict`()
contrib.`diverge feature and master`()
`do nothing on merge`()
rebase("master")
var mergeDialogShown = false
vcsHelper.onMerge {
mergeDialogShown = true
community.resolveConflicts()
}
GitRebaseUtils.continueRebase(project)
assertTrue("Merge dialog was not shown", mergeDialogShown)
assertAllRebased()
}
fun `test rollback if checkout with rebase fails on 2nd root`() {
allRepositories.forEach {
it.`diverge feature and master`()
it.git("checkout master")
}
git.setShouldRebaseFail { it == contrib }
val uiHandler = Mockito.mock(GitBranchUiHandler::class.java)
Mockito.`when`(uiHandler.progressIndicator).thenReturn(EmptyProgressIndicator())
try {
GitBranchWorker(project, git, uiHandler).rebaseOnCurrent(allRepositories, "feature")
}
finally {
git.setShouldRebaseFail { false }
}
var confirmation: String? = null
dialogManager.onMessage {
confirmation = it
Messages.YES
}
abortOngoingRebase()
assertNotNull(confirmation, "Abort confirmation message was not shown")
assertEquals("Incorrect confirmation message text",
cleanupForAssertion("Do you want to rollback the successful rebase in community?"),
cleanupForAssertion(confirmation!!))
assertNoRebaseInProgress(allRepositories)
allRepositories.forEach {
it.`assert feature not rebased on master`()
assertEquals("Incorrect current branch", "master", it.currentBranchName) }
}
private fun `fail with critical error while rebasing 2nd root`(localChange: LocalChange? = null) {
allRepositories.forEach { it.`diverge feature and master`() }
localChange?.generate()
git.setShouldRebaseFail { it == contrib }
try {
rebase("master")
}
finally {
git.setShouldRebaseFail { false }
}
}
private fun `fail with critical error while rebasing 2nd root after some commits are applied`(localChange: LocalChange? = null) {
community.`diverge feature and master`()
contrib.`make rebase fail on 2nd commit`()
ultimate.`diverge feature and master`()
localChange?.generate()
try {
rebase("master")
}
finally {
git.setShouldRebaseFail { false }
}
}
private fun rebase(onto: String) {
GitTestingRebaseProcess(project, GitRebaseParams(onto), allRepositories).rebase()
}
private fun abortOngoingRebase() {
GitRebaseUtils.abort(project, EmptyProgressIndicator())
}
private fun assertAllRebased() {
assertRebased(ultimate, "feature", "master")
assertRebased(community, "feature", "master")
assertRebased(contrib, "feature", "master")
}
}
|
apache-2.0
|
371a0a6b8773ff0bb00dcf4f9ea8d6f3
| 31.845878 | 138 | 0.717372 | 4.942826 | false | true | false | false |
leesocrates/remind
|
lib/src/main/java/com/lee/library/network/RetrofitConfig.kt
|
1
|
1741
|
package com.lee.library.network
import com.lee.library.network.SpecialConverterFactory
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by lee on 2015/11/12.
*/
object RetrofitConfig {
val DEFAULT_TIMEOUT = 30//默认超时时间(秒)
// public static final String BASE_URL = "http://101.37.39.146:8080/";
val BASE_URL = "http://172.30.66.77:8080/"
private val httpClient = generatorHttpClient()
//这里不加@JvmField注解,在java中调用的时候只能通过getRetrofit()调用,加了注解后可以直接通过属性名引用
@JvmField
val retrofit = generatorRetrofit()
private fun generatorHttpClient(): OkHttpClient {
val logLevel = HttpLoggingInterceptor.Level.BODY
val interceptor = HttpLoggingInterceptor()
interceptor.level = logLevel
return OkHttpClient.Builder().addInterceptor(interceptor)
.connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS).build()
}
private fun generatorRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(SpecialConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
}
|
gpl-3.0
|
703c5598cd63a9c7a40a4a95937c13f0
| 35.644444 | 80 | 0.698605 | 4.671388 | false | false | false | false |
MyCollab/mycollab
|
mycollab-servlet/src/main/java/com/mycollab/module/file/servlet/UserAvatarHttpServletRequestHandler.kt
|
3
|
3219
|
/**
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.file.servlet
import com.mycollab.configuration.ServerConfiguration
import com.mycollab.configuration.SiteConfiguration
import com.mycollab.core.MyCollabException
import com.mycollab.core.ResourceNotFoundException
import com.mycollab.core.utils.FileUtils
import com.mycollab.servlet.GenericHttpServlet
import org.apache.commons.io.FilenameUtils
import org.springframework.beans.factory.annotation.Autowired
import java.io.*
import javax.servlet.ServletException
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @author MyCollab Ltd.
* @since 1.0
*/
@WebServlet(urlPatterns = ["/file/avatar/*"], name = "userAvatarFSServlet")
class UserAvatarHttpServletRequestHandler : GenericHttpServlet() {
@Autowired
private lateinit var serverConfiguration: ServerConfiguration
@Throws(ServletException::class, IOException::class)
override fun onHandleRequest(request: HttpServletRequest, response: HttpServletResponse) {
if (SiteConfiguration.isDemandEdition()) {
throw MyCollabException("This servlet support file system setting only")
}
var path: String? = request.pathInfo
if (path != null) {
path = FilenameUtils.getBaseName(path)
val lastIndex = path!!.lastIndexOf("_")
if (lastIndex > 0) {
val username = path.substring(0, lastIndex)
val size = Integer.valueOf(path.substring(lastIndex + 1, path.length))!!
val userAvatarFile = File(serverConfiguration.getHomeDir(), "/avatar/${username}_$size.png")
val avatarInputStream = FileInputStream(userAvatarFile)
response.setHeader("Content-Type", "image/png")
response.setHeader("Content-Length", avatarInputStream.available().toString())
BufferedInputStream(avatarInputStream).use { input ->
BufferedOutputStream(response.outputStream).use { output ->
val buffer = ByteArray(8192)
var length = input.read(buffer)
while (length > 0) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
}
}
} else {
throw ResourceNotFoundException("Invalid path $path")
}
}
}
}
|
agpl-3.0
|
92f09af3b6c2826256c70d7ab1a10aff
| 40.25641 | 108 | 0.669049 | 4.981424 | false | true | false | false |
MyCollab/mycollab
|
mycollab-web/src/main/java/com/mycollab/vaadin/mvp/service/ComponentScannerService.kt
|
3
|
3804
|
/**
* 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.vaadin.mvp.service
import com.mycollab.vaadin.mvp.IPresenter
import com.mycollab.vaadin.mvp.PageView
import com.mycollab.vaadin.mvp.ViewComponent
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.InitializingBean
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
import org.springframework.core.type.filter.AnnotationTypeFilter
import org.springframework.core.type.filter.AssignableTypeFilter
import org.springframework.stereotype.Component
import org.springframework.util.ClassUtils
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
class ComponentScannerService : InitializingBean {
companion object {
val LOG: Logger = LoggerFactory.getLogger(ComponentScannerService::class.java)
}
private val viewClasses = mutableSetOf<Class<*>> ()
private val presenterClasses = mutableSetOf<Class<IPresenter<PageView>>>()
private val cacheViewClasses = mutableMapOf<Class<*>, Class<*>>()
private val cachePresenterClasses = mutableMapOf<Class<*>, Class<*>>()
override fun afterPropertiesSet() {
val provider = ClassPathScanningCandidateComponentProvider(false)
provider.addIncludeFilter(AnnotationTypeFilter(ViewComponent::class.java))
provider.addIncludeFilter(AssignableTypeFilter(IPresenter::class.java))
LOG.info("Started resolving view and presenter classes")
val candidateComponents = provider.findCandidateComponents("com.mycollab.**.view")
candidateComponents.forEach {
val cls = ClassUtils.resolveClassName(it.beanClassName!!, ClassUtils.getDefaultClassLoader())
when {
cls.getAnnotation(ViewComponent::class.java) != null -> viewClasses.add(cls)
IPresenter::class.java.isAssignableFrom(cls) -> presenterClasses.add(cls as Class<IPresenter<PageView>>)
}
}
LOG.info("Resolved view and presenter classes $this that has ${viewClasses.size} view classes and ${presenterClasses.size} presenter classes")
}
fun getViewImplCls(viewClass: Class<*>): Class<*>? {
val aClass = cacheViewClasses[viewClass]
return when (aClass) {
null -> {
viewClasses.forEach {
if (viewClass.isAssignableFrom(it)) {
cacheViewClasses += (viewClass to it)
return it
}
}
null
}
else -> aClass
}
}
fun getPresenterImplCls(presenterClass: Class<*>): Class<*>? {
val aClass = cachePresenterClasses[presenterClass]
return when (aClass) {
null -> {
presenterClasses.forEach {
if (presenterClass.isAssignableFrom(it) && !it.isInterface) {
cachePresenterClasses += (presenterClass to it)
return it
}
}
return null
}
else -> aClass
}
}
}
|
agpl-3.0
|
94244b6fd7ac614e33c63e52e09f34dc
| 39.042105 | 150 | 0.666579 | 4.945384 | false | false | false | false |
ylimit/PrivacyStreams
|
privacystreams-app/src/main/java/io/github/privacystreams/app/db/PStreamDBHelper.kt
|
2
|
2926
|
package io.github.privacystreams.app.db
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import io.github.privacystreams.core.UQI
import io.github.privacystreams.core.purposes.Purpose
import java.util.*
class PStreamDBHelper private constructor(var context: Context)
: SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
companion object {
val DB_VERSION = 2
val DB_NAME = "privacystreams.db"
@SuppressLint("StaticFieldLeak")
private var instance: PStreamDBHelper? = null
fun getInstance(context: Context): PStreamDBHelper {
if (instance == null) {
instance = PStreamDBHelper(context.applicationContext)
}
else {
instance!!.context = context.applicationContext
}
return instance!!
}
}
val tables: List<PStreamTable> = this.getAllTables()
private fun getAllTables(): List<PStreamTable> {
val tables: MutableList<PStreamTable> = ArrayList<PStreamTable>()
tables.add(TableGeolocation(this))
tables.add(TableNotification(this))
tables.add(TableUIEvent(this))
tables.add(TableDeviceEvent(this))
tables.add(TableDeviceState(this))
tables.add(TableBgPhoto(this))
tables.add(TableBgAudio(this))
return tables
}
override fun onCreate(db: SQLiteDatabase) {
tables.map { it.sqlCreateEntries.map{db.execSQL(it)} }
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
tables.map { it.sqlDeleteEntries.map{db.execSQL(it)} }
onCreate(db)
}
override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
this.onUpgrade(db, oldVersion, newVersion)
}
fun startCollectServiceAll() = PStreamCollectService.startAllTables(context)
fun stopCollectServiceAll() = PStreamCollectService.stopAllTables(context)
fun test() {
UQI(context).getData(TableGeolocation.PROVIDER(), Purpose.TEST("Test"))
.limit(10)
.debug();
UQI(context).getData(TableNotification.PROVIDER(), Purpose.TEST("Test"))
.limit(10)
.debug();
}
fun getDBSize(): Long {
return context.getDatabasePath(DB_NAME).absoluteFile.length()
}
fun backupData() {
// TODO backup the database
}
fun restoreData() {
// TODO restore the database
}
fun clearData() {
stopCollectServiceAll()
onUpgrade(writableDatabase, DB_VERSION, DB_VERSION)
tables.forEach { it.initStatus() }
}
}
|
apache-2.0
|
0d1f7d604f726b23fd69d79c2bf8d36f
| 30.804348 | 84 | 0.65311 | 4.341246 | false | true | false | false |
ilya-g/kotlinx.collections.immutable
|
benchmarks/commonMain/src/benchmarks/immutableMap/Canonicalization.kt
|
1
|
4685
|
/*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package benchmarks.immutableMap
import benchmarks.*
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.benchmark.*
/**
* Benchmarks below measure how the trie canonicalization affects performance of the persistent map.
*
* Benchmark methods firstly remove some entries of the [persistentMap].
* The expected height of the resulting map is half of the [persistentMap]'s expected height.
* Then another operation is applied on the resulting map.
*
* If the [persistentMap] does not maintain its canonical form,
* after removing some entries its actual average height will become bigger then its expected height.
* Thus, many operations on the resulting map will be slower.
*/
@State(Scope.Benchmark)
open class Canonicalization {
@Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000)
var size: Int = 0
@Param(HASH_IMPL, ORDERED_IMPL)
var implementation = ""
@Param(ASCENDING_HASH_CODE, RANDOM_HASH_CODE, COLLISION_HASH_CODE)
var hashCodeType = ""
private var keys = listOf<IntWrapper>()
private var keysToRemove = listOf<IntWrapper>()
private var persistentMap = persistentMapOf<IntWrapper, String>()
/**
* Expected height of this persistent map is equal to the [persistentMap]'s expected height divided by 2.
* Obtained by removing some entries of the [persistentMap].
*/
private var halfHeightPersistentMap = persistentMapOf<IntWrapper, String>()
@Setup
fun prepare() {
keys = generateKeys(hashCodeType, size)
persistentMap = persistentMapPut(implementation, keys)
val entriesToLeave = sizeForHalfHeight(persistentMap)
keysToRemove = keys.shuffled().subList(fromIndex = entriesToLeave, toIndex = size)
halfHeightPersistentMap = persistentMapRemove(persistentMap, keysToRemove)
}
/**
* Removes `keysToRemove.size` entries of the [persistentMap] and
* then puts `keysToRemove.size` new entries.
*
* Measures mean time and memory spent per (roughly one) `remove` and `put` operations.
*
* Expected time: [Remove.remove] + [putAfterRemove]
* Expected memory: [Remove.remove] + [putAfterRemove]
*/
@Benchmark
fun removeAndPut(): PersistentMap<IntWrapper, String> {
var map = persistentMapRemove(persistentMap, keysToRemove)
for (key in keysToRemove) {
map = map.put(key, "new value")
}
return map
}
/**
* Removes `keysToRemove.size` entries of the [persistentMap] and
* then iterates keys of the resulting map several times until iterating [size] elements.
*
* Measures mean time and memory spent per (roughly one) `remove` and `next` operations.
*
* Expected time: [Remove.remove] + [iterateKeysAfterRemove]
* Expected memory: [Remove.remove] + [iterateKeysAfterRemove]
*/
@Benchmark
fun removeAndIterateKeys(bh: Blackhole) {
val map = persistentMapRemove(persistentMap, keysToRemove)
var count = 0
while (count < size) {
for (e in map) {
bh.consume(e)
if (++count == size)
break
}
}
}
/**
* Puts `size - halfHeightPersistentMap.size` new entries to the [Canonicalization.halfHeightPersistentMap].
*
* Measures mean time and memory spent per (roughly one) `put` operation.
*
* Expected time: [Put.put]
* Expected memory: [Put.put]
*/
@Benchmark
fun putAfterRemove(): PersistentMap<IntWrapper, String> {
var map = halfHeightPersistentMap
repeat(size - halfHeightPersistentMap.size) { index ->
map = map.put(keys[index], "new value")
}
return map
}
/**
* Iterates keys of the [Canonicalization.halfHeightPersistentMap] several times until iterating [size] elements.
*
* Measures mean time and memory spent per `iterate` operation.
*
* Expected time: [Iterate.iterateKeys] with [Iterate.size] = `halfHeightPersistentMap.size`
* Expected memory: [Iterate.iterateKeys] with [Iterate.size] = `halfHeightPersistentMap.size`
*/
@Benchmark
fun iterateKeysAfterRemove(bh: Blackhole) {
var count = 0
while (count < size) {
for (e in halfHeightPersistentMap) {
bh.consume(e)
if (++count == size)
break
}
}
}
}
|
apache-2.0
|
801de1144b28539cc5b16765b1da8a0c
| 32.471429 | 117 | 0.657417 | 4.350046 | false | false | false | false |
OpenConference/OpenConference-android
|
app/src/main/java/com/openconference/search/SessionItemAdapterDelegate.kt
|
1
|
2830
|
package com.openconference.search
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.bindView
import com.hannesdorfmann.adapterdelegates2.AbsListItemAdapterDelegate
import com.openconference.R
import com.openconference.model.Session
import com.openconference.model.search.SearchableItem
import com.openconference.sessions.presentationmodel.SessionPresentationModel
/**
* Represents a Session item in a RecyclerView
*
* @author Hannes Dorfmann
*/
class SessionItemAdapterDelegate(protected val layoutInflater: LayoutInflater, private val clickListener: (Session) -> Unit) : AbsListItemAdapterDelegate<SessionPresentationModel, SearchableItem, SessionItemAdapterDelegate.SessionItemViewHolder>() {
override fun isForViewType(item: SearchableItem, items: MutableList<SearchableItem>?,
position: Int): Boolean = item is SessionPresentationModel
override fun onBindViewHolder(item: SessionPresentationModel, viewHolder: SessionItemViewHolder) {
val session = item.session()
viewHolder.session = session
viewHolder.title.text = session.title()
// Time
if (item.time() != null) {
viewHolder.time.text = item.dayInWeek() + " " + item.dateShort() + " " + item.time()
viewHolder.time.visibility = View.VISIBLE
} else {
viewHolder.time.visibility = View.GONE
}
// Location
if (session.locationName() != null && session.locationName()!!.isNotEmpty()) {
viewHolder.location.visibility = View.VISIBLE
viewHolder.location.text = session.locationName()!!
} else {
viewHolder.location.visibility = View.GONE
}
// Speakers
val speakers = item.speakers()
if (speakers == null) {
viewHolder.speakers.visibility = View.GONE
} else {
viewHolder.speakers.text = speakers.toString()
viewHolder.speakers.visibility = View.VISIBLE
}
viewHolder.favorite.visibility = if (session.favorite()) {
View.VISIBLE
} else {
View.GONE
}
}
override fun onCreateViewHolder(parent: ViewGroup): SessionItemViewHolder =
SessionItemViewHolder(layoutInflater.inflate(R.layout.item_search_session, parent, false),
clickListener)
/**
* ViewHolder for a Session Item
*/
class SessionItemViewHolder(v: View, clickListener: (Session) -> Unit) : RecyclerView.ViewHolder(
v) {
init {
v.setOnClickListener({ clickListener(session!!) })
}
val title: TextView by bindView(R.id.title)
val speakers: TextView by bindView(R.id.speakers)
val time: TextView by bindView(R.id.time)
val location: TextView by bindView(R.id.location)
val favorite: View by bindView(R.id.favorite)
var session: Session? = null
}
}
|
apache-2.0
|
98dba8a8f9da7e207191feaffaecc41f
| 32.702381 | 249 | 0.726855 | 4.579288 | false | false | false | false |
Esri/arcgis-runtime-samples-android
|
kotlin/display-ogc-api-collection/src/main/java/com/esri/arcgisruntime/sample/displayogcapicollection/MainActivity.kt
|
1
|
6947
|
/* Copyright 2021 Esri
*
* 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.esri.arcgisruntime.sample.displayogcapicollection
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.OgcFeatureCollectionTable
import com.esri.arcgisruntime.data.QueryParameters
import com.esri.arcgisruntime.data.ServiceFeatureTable
import com.esri.arcgisruntime.geometry.Envelope
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.displayogcapicollection.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
class MainActivity : AppCompatActivity() {
// define strings for the service URL and collection id
// note that the service defines the collection id which can be accessed
// via OgcFeatureCollectionInfo.getCollectionId()
private val serviceUrl = "https://demo.ldproxy.net/daraa"
private val collectionId = "TransportationGroundCrv"
// create an OGC feature collection table from the service url and collection id
// keep loadable in scope to avoid garbage collection
private var ogcFeatureCollectionTable: OgcFeatureCollectionTable =
OgcFeatureCollectionTable(serviceUrl, collectionId)
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create a map with the BasemapStyle topographic
val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// set the map to be displayed in the layout's MapView
mapView.map = map
// set the feature request mode to manual (only manual is currently supported).
// in this mode, the table must be manually populated - panning and zooming won't request features automatically
ogcFeatureCollectionTable.featureRequestMode =
ServiceFeatureTable.FeatureRequestMode.MANUAL_CACHE
// load the table
ogcFeatureCollectionTable.loadAsync()
// ensure the feature collection table has loaded successfully before creating a feature layer from it to display on the map
ogcFeatureCollectionTable.addDoneLoadingListener {
if (ogcFeatureCollectionTable.loadStatus == LoadStatus.LOADED) {
// create a feature layer and set a renderer to it to visualize the OGC API features
val featureLayer = FeatureLayer(ogcFeatureCollectionTable)
val simpleRenderer =
SimpleRenderer(SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 3F))
featureLayer.renderer = simpleRenderer
// add the layer to the map
map.operationalLayers.add(featureLayer)
// zoom to a small area within the dataset by default
val datasetExtent = ogcFeatureCollectionTable.extent
if (datasetExtent != null && !datasetExtent.isEmpty) {
mapView.setViewpointGeometryAsync(
Envelope(
datasetExtent.center,
datasetExtent.width / 3,
datasetExtent.height / 3
)
)
}
} else {
// show an alert if there is a loading failure
Log.e(
ogcFeatureCollectionTable.loadError.message,
ogcFeatureCollectionTable.loadError.additionalMessage
)
Toast.makeText(
applicationContext,
"Failed to load OGC Feature Collection Table",
Toast.LENGTH_SHORT
).show()
}
}
// once the map view navigation has completed, query the OGC API feature table for
// additional features within the new visible extent
mapView.addNavigationChangedListener {
if (!it.isNavigating) {
// get the current extent
val currentExtent = mapView.visibleArea.extent
// create a query based on the current visible extent
val visibleExtentQuery = QueryParameters().apply {
geometry = currentExtent
spatialRelationship =
QueryParameters.SpatialRelationship.INTERSECTS
// set a limit of 5000 on the number of returned features per request, the default on some services
// could be as low as 10
maxFeatures = 5000
}
visibleExtentQuery.maxFeatures = 5000
try {
// populate the table with the query, leaving existing table entries intact
// setting the outfields parameter to null requests all fields
ogcFeatureCollectionTable.populateFromServiceAsync(
visibleExtentQuery,
false,
null
)
} catch (e: Exception) {
Toast.makeText(
applicationContext,
"Error populating from service: " + e.message,
Toast.LENGTH_SHORT
).show()
}
}
}
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
|
apache-2.0
|
a8f2954a7401a5be7950782d5f1641ce
| 39.389535 | 132 | 0.64042 | 5.461478 | false | false | false | false |
UweTrottmann/SeriesGuide
|
app/src/main/java/com/battlelancer/seriesguide/dataliberation/AutoBackupViewModel.kt
|
1
|
2407
|
package com.battlelancer.seriesguide.dataliberation
import android.app.Application
import android.text.format.DateUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* View model that checks for available backup files.
*/
class AutoBackupViewModel(application: Application) : AndroidViewModel(application) {
/**
* Try to keep the import task around on config changes
* so it does not have to be finished.
*/
var importTask: Job? = null
val isImportTaskNotCompleted: Boolean
get() {
val importTask = importTask
return importTask != null && !importTask.isCompleted
}
/** Time string of the available backup, or null if no backup is available. */
val availableBackupLiveData = MutableLiveData<String?>()
fun updateAvailableBackupData() = viewModelScope.launch(Dispatchers.IO) {
val backupShows = AutoBackupTools.getLatestBackupOrNull(
JsonExportTask.BACKUP_SHOWS, getApplication()
)
val backupLists = AutoBackupTools.getLatestBackupOrNull(
JsonExportTask.BACKUP_LISTS, getApplication()
)
val backupMovies = AutoBackupTools.getLatestBackupOrNull(
JsonExportTask.BACKUP_MOVIES, getApplication()
)
// All three files required.
if (backupShows == null || backupLists == null || backupMovies == null) {
availableBackupLiveData.postValue(null)
return@launch
}
// All three files must have same time stamp.
if (backupShows.timestamp != backupLists.timestamp
|| backupShows.timestamp != backupMovies.timestamp) {
availableBackupLiveData.postValue(null)
return@launch
}
val availableBackupTimeString = DateUtils.getRelativeDateTimeString(
getApplication(),
backupShows.timestamp,
DateUtils.SECOND_IN_MILLIS,
DateUtils.DAY_IN_MILLIS,
0
)
availableBackupLiveData.postValue(availableBackupTimeString.toString())
}
override fun onCleared() {
if (isImportTaskNotCompleted) {
importTask?.cancel(null)
}
importTask = null
}
}
|
apache-2.0
|
6d922a5391e5d369ed29249efa729dfb
| 31.986301 | 85 | 0.671375 | 5.132196 | false | false | false | false |
Minikloon/generals.io-kotlin
|
src/main/kotlin/net/minikloon/generals/game/Game.kt
|
1
|
989
|
package net.minikloon.generals.game
import net.minikloon.generals.game.generalsapi.messages.GameUpdate
import net.minikloon.generals.game.world.Tile
import net.minikloon.generals.game.world.World
import net.minikloon.generals.utils.versionLazy
class Game(val replayId: String, val chatRoom: String, val teams: Map<Int, Team>) {
val world = World(this)
val players = teams.flatMap { it.value.players }.sortedBy { it.index }.toTypedArray()
var turn = 0
private set
fun update(gu: GameUpdate) {
turn = gu.turn
world.update(gu.mapDiff, gu.citiesDiff, gu.generals)
gu.scores.forEach {
val player = players[it.playerIndex]
player.tilesCount = it.tiles
player.troops = it.troops
player.dead = it.dead
}
gu.stars?.forEachIndexed { index, stars -> players[index].stars = stars }
}
val generals by versionLazy({turn}) { world.generalTiles.map(Tile::general) }
}
|
mit
|
34341f7804c3792ab28f9bb29c072d79
| 34.357143 | 89 | 0.665319 | 3.570397 | false | false | false | false |
arcao/Geocaching4Locus
|
app/src/main/java/org/oshkimaadziig/george/androidutils/SpanFormatter.kt
|
1
|
4519
|
/*
* Copyright © 2014 George T. Steel
*
* 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.oshkimaadziig.george.androidutils
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.SpannedString
import java.util.Locale
import java.util.regex.Pattern
/**
* Provides [String.format] style functions that work with [Spanned] strings and preserve formatting.
*
* @author George T. Steel
*/
object SpanFormatter {
private val FORMAT_SEQUENCE =
Pattern.compile("%([0-9]+\\$|<?)([^a-zA-z%]*)([a-zA-Z%&&[^tT]]|[tT][a-zA-Z])")
/**
* Version of [String.format] that works on [Spanned] strings to preserve rich text formatting.
* Both the `format` as well as any `%s args` can be Spanned and will have their formatting preserved.
* Due to the way [Spanned]s work, any argument's spans will can only be included **once** in the result.
* Any duplicates will appear as text only.
*
* @param format the format string (see [String.format])
* @param args the list of arguments passed to the formatter. If there are
* more arguments than required by `format`,
* additional arguments are ignored.
* @return the formatted string (with spans).
*/
fun format(format: CharSequence, vararg args: Any): SpannedString {
return format(Locale.getDefault(), format, *args)
}
/**
* Version of [String.format] that works on [Spanned] strings to preserve rich text formatting.
* Both the `format` as well as any `%s args` can be Spanned and will have their formatting preserved.
* Due to the way [Spanned]s work, any argument's spans will can only be included **once** in the result.
* Any duplicates will appear as text only.
*
* @param locale the locale to apply; `null` value means no localization.
* @param format the format string (see [String.format])
* @param args the list of arguments passed to the formatter.
* @return the formatted string (with spans).
* @see String.format
*/
fun format(locale: Locale, format: CharSequence, vararg args: Any): SpannedString {
val out = SpannableStringBuilder(format)
var i = 0
var argAt = -1
while (i < out.length) {
val m = FORMAT_SEQUENCE.matcher(out)
if (!m.find(i))
break
i = m.start()
val exprEnd = m.end()
val argTerm = m.group(1).orEmpty()
val modTerm = m.group(2).orEmpty()
val typeTerm = m.group(3).orEmpty()
val cookedArg: CharSequence
when (typeTerm) {
"%" -> cookedArg = "%"
"n" -> cookedArg = "\n"
else -> {
val argIdx: Int = when (argTerm) {
"" -> ++argAt
"<" -> argAt
else -> Integer.parseInt(argTerm.substring(0, argTerm.length - 1)) - 1
}
val argItem = args[argIdx]
cookedArg = if ("s" == typeTerm && argItem is Spanned) {
argItem
} else if ("S" == typeTerm && argItem is Spanned) {
spannedToUpperCase(argItem)
} else {
String.format(locale, "%$modTerm$typeTerm", argItem)
}
}
}
out.replace(i, exprEnd, cookedArg)
i += cookedArg.length
}
return SpannedString(out)
}
private fun spannedToUpperCase(s: Spanned): Spanned {
val spans = s.getSpans(0, s.length, Any::class.java)
val spannableString = SpannableString(s.toString().uppercase())
// reapply the spans to the now uppercase string
for (span in spans) {
spannableString.setSpan(span, s.getSpanStart(span), s.getSpanEnd(span), 0)
}
return spannableString
}
}
|
gpl-3.0
|
0e3ffa828d89d12b57f47c7e57f1fcbf
| 36.032787 | 109 | 0.601594 | 4.246241 | false | false | false | false |
commons-app/apps-android-commons
|
app/src/test/kotlin/fr/free/nrw/commons/bookmarks/BookmarkListRootFragmentUnitTest.kt
|
5
|
12581
|
package fr.free.nrw.commons.bookmarks
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ListAdapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.tabs.TabLayout
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.R
import fr.free.nrw.commons.TestAppAdapter
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.bookmarks.pictures.BookmarkPicturesFragment
import fr.free.nrw.commons.contributions.MainActivity
import fr.free.nrw.commons.explore.ParentViewPager
import fr.free.nrw.commons.media.MediaDetailPagerFragment
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.powermock.api.mockito.PowerMockito.mock
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.wikipedia.AppAdapter
import java.lang.reflect.Field
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class BookmarkListRootFragmentUnitTest {
private lateinit var fragment: BookmarkListRootFragment
private lateinit var fragmentManager: FragmentManager
private lateinit var layoutInflater: LayoutInflater
private lateinit var context: Context
private lateinit var activity: MainActivity
private lateinit var view: View
private lateinit var bookmarkFragment: BookmarkFragment
@Mock
private lateinit var listFragment: Fragment
@Mock
private lateinit var mediaDetails: MediaDetailPagerFragment
@Mock
private lateinit var childFragmentManager: FragmentManager
@Mock
private lateinit var childFragmentTransaction: FragmentTransaction
@Mock
private lateinit var bookmarksPagerAdapter: BookmarksPagerAdapter
@Mock
private lateinit var bundle: Bundle
@Mock
private lateinit var media: Media
@Mock
private lateinit var tabLayout: TabLayout
@Mock
private lateinit var viewPager: ParentViewPager
@Mock
private lateinit var adapter: BookmarksPagerAdapter
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
AppAdapter.set(TestAppAdapter())
activity = Robolectric.buildActivity(MainActivity::class.java).create().get()
context = RuntimeEnvironment.application.applicationContext
fragment = BookmarkListRootFragment()
fragmentManager = activity.supportFragmentManager
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(fragment, null)
fragmentTransaction.commitNowAllowingStateLoss()
bookmarkFragment = BookmarkFragment()
Whitebox.setInternalState(fragment, "mChildFragmentManager", childFragmentManager)
Whitebox.setInternalState(fragment, "mParentFragment", bookmarkFragment)
Whitebox.setInternalState(fragment, "listFragment", listFragment)
Whitebox.setInternalState(fragment, "mediaDetails", mediaDetails)
Whitebox.setInternalState(fragment, "bookmarksPagerAdapter", bookmarksPagerAdapter)
Whitebox.setInternalState(bookmarkFragment, "tabLayout", tabLayout)
Whitebox.setInternalState(bookmarkFragment, "viewPager", viewPager)
Whitebox.setInternalState(bookmarkFragment, "adapter", adapter)
whenever(childFragmentManager.beginTransaction()).thenReturn(childFragmentTransaction)
whenever(childFragmentTransaction.hide(any())).thenReturn(childFragmentTransaction)
whenever(childFragmentTransaction.add(ArgumentMatchers.anyInt(), any()))
.thenReturn(childFragmentTransaction)
whenever(childFragmentTransaction.addToBackStack(any()))
.thenReturn(childFragmentTransaction)
whenever(childFragmentTransaction.show(any())).thenReturn(childFragmentTransaction)
whenever(childFragmentTransaction.replace(ArgumentMatchers.anyInt(), any()))
.thenReturn(childFragmentTransaction)
whenever(childFragmentTransaction.remove(any())).thenReturn(childFragmentTransaction)
layoutInflater = LayoutInflater.from(activity)
view = fragment.onCreateView(layoutInflater, null, null) as View
}
@Test
@Throws(Exception::class)
fun checkFragmentNotNull() {
Assert.assertNotNull(fragment)
}
@Test
@Throws(Exception::class)
fun testConstructorCase0() {
whenever(bundle.getInt("order")).thenReturn(0)
fragment = BookmarkListRootFragment(bundle, bookmarksPagerAdapter)
verify(bundle).getString("categoryName")
verify(bundle).getInt("order")
verify(bundle).getInt("orderItem")
}
@Test
@Throws(Exception::class)
fun testConstructorCase2() {
whenever(bundle.getInt("order")).thenReturn(2)
whenever(bundle.getInt("orderItem")).thenReturn(2)
fragment = BookmarkListRootFragment(bundle, bookmarksPagerAdapter)
verify(bundle).getString("categoryName")
verify(bundle).getInt("order")
verify(bundle).getInt("orderItem")
}
@Test
@Throws(Exception::class)
fun testOnViewCreated() {
fragment.onViewCreated(view, null)
verify(childFragmentManager).beginTransaction()
verify(childFragmentTransaction).hide(mediaDetails)
verify(childFragmentTransaction).add(R.id.explore_container, listFragment)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
verify(childFragmentTransaction).commit()
verify(childFragmentManager).executePendingTransactions()
}
@Test
@Throws(Exception::class)
fun `testSetFragment_Case fragment_isAdded && otherFragment != null`() {
whenever(mediaDetails.isAdded).thenReturn(true)
fragment.setFragment(mediaDetails, listFragment)
verify(childFragmentManager).beginTransaction()
verify(childFragmentTransaction).hide(listFragment)
verify(childFragmentTransaction).show(mediaDetails)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
verify(childFragmentTransaction).commit()
verify(childFragmentManager).executePendingTransactions()
}
@Test
@Throws(Exception::class)
fun `testSetFragment_Case fragment_isAdded && otherFragment == null`() {
whenever(mediaDetails.isAdded).thenReturn(true)
fragment.setFragment(mediaDetails, null)
verify(childFragmentManager).beginTransaction()
verify(childFragmentTransaction).show(mediaDetails)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
verify(childFragmentTransaction).commit()
verify(childFragmentManager).executePendingTransactions()
}
@Test
@Throws(Exception::class)
fun `testSetFragment_Case fragment_isNotAdded && otherFragment != null`() {
whenever(mediaDetails.isAdded).thenReturn(false)
fragment.setFragment(mediaDetails, listFragment)
verify(childFragmentManager).beginTransaction()
verify(childFragmentTransaction).hide(listFragment)
verify(childFragmentTransaction).add(R.id.explore_container, mediaDetails)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
verify(childFragmentTransaction).commit()
verify(childFragmentManager).executePendingTransactions()
}
@Test
@Throws(Exception::class)
fun `testSetFragment_Case fragment_isNotAdded && otherFragment == null`() {
whenever(mediaDetails.isAdded).thenReturn(false)
fragment.setFragment(mediaDetails, null)
verify(childFragmentManager).beginTransaction()
verify(childFragmentTransaction).replace(R.id.explore_container, mediaDetails)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
verify(childFragmentTransaction).commit()
verify(childFragmentManager).executePendingTransactions()
}
@Test
@Throws(Exception::class)
fun testGetMediaAtPositionCaseNull() {
whenever(bookmarksPagerAdapter.mediaAdapter).thenReturn(null)
Assert.assertEquals(fragment.getMediaAtPosition(0), null)
}
@Test
@Throws(Exception::class)
fun testGetMediaAtPositionCaseNonNull() {
val listAdapter = mock(ListAdapter::class.java)
whenever(bookmarksPagerAdapter.mediaAdapter).thenReturn(listAdapter)
whenever(listAdapter.getItem(0)).thenReturn(media)
Assert.assertEquals(fragment.getMediaAtPosition(0), media)
}
@Test
@Throws(Exception::class)
fun testGetTotalMediaCountCaseNull() {
whenever(bookmarksPagerAdapter.mediaAdapter).thenReturn(null)
Assert.assertEquals(fragment.totalMediaCount, 0)
}
@Test
@Throws(Exception::class)
fun testGetTotalMediaCountCaseNonNull() {
val listAdapter = mock(ListAdapter::class.java)
whenever(bookmarksPagerAdapter.mediaAdapter).thenReturn(listAdapter)
whenever(listAdapter.count).thenReturn(1)
Assert.assertEquals(fragment.totalMediaCount, 1)
}
@Test
@Throws(Exception::class)
fun testGetContributionStateAt() {
Assert.assertEquals(fragment.getContributionStateAt(0), null)
}
@Test
@Throws(Exception::class)
fun testRefreshNominatedMedia() {
whenever(listFragment.isVisible).thenReturn(false)
fragment.refreshNominatedMedia(0)
verify(childFragmentManager, times(2)).beginTransaction()
verify(childFragmentTransaction).remove(mediaDetails)
verify(childFragmentTransaction, times(2)).commit()
verify(childFragmentManager, times(2)).executePendingTransactions()
verify(childFragmentTransaction).hide(listFragment)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
}
@Test
@Throws(Exception::class)
fun testViewPagerNotifyDataSetChanged() {
fragment.viewPagerNotifyDataSetChanged()
verify(mediaDetails).notifyDataSetChanged()
}
@Test
@Throws(Exception::class)
fun testOnMediaClicked() {
fragment.onMediaClicked(0)
}
@Test
@Throws(Exception::class)
fun testOnBackStackChanged() {
fragment.onBackStackChanged()
}
@Test
@Throws(Exception::class)
fun testOnItemClick() {
fragment.onItemClick(null, null, 0, 0)
verify(childFragmentManager).beginTransaction()
verify(childFragmentTransaction).commit()
verify(childFragmentManager).executePendingTransactions()
verify(childFragmentTransaction).hide(listFragment)
verify(childFragmentTransaction).addToBackStack("CONTRIBUTION_LIST_FRAGMENT_TAG")
}
@Test
@Throws(Exception::class)
fun `testBackPressed Case NonNull isVisible and backButton clicked`() {
whenever(mediaDetails.isVisible).thenReturn(true)
Assert.assertEquals(fragment.backPressed(), false)
}
@Test
@Throws(Exception::class)
fun `testBackPressed Case NonNull isVisible and backButton not clicked`() {
Whitebox.setInternalState(fragment, "listFragment", mock(BookmarkPicturesFragment::class.java))
whenever(mediaDetails.isVisible).thenReturn(true)
whenever(mediaDetails.removedItems).thenReturn(ArrayList(0))
Assert.assertEquals(fragment.backPressed(), false)
}
@Test
@Throws(Exception::class)
fun `testBackPressed Case NonNull isNotVisible and backButton clicked`() {
whenever(mediaDetails.isVisible).thenReturn(false)
Assert.assertEquals(fragment.backPressed(), false)
}
@Test
@Throws(Exception::class)
fun `testBackPressed Case Null`() {
val field: Field = BookmarkListRootFragment::class.java.getDeclaredField("mediaDetails")
field.isAccessible = true
field.set(fragment, null)
Assert.assertEquals(fragment.backPressed(), false)
}
}
|
apache-2.0
|
45e3fd42fd982a2fd0c34f8172ba09ea
| 37.713846 | 103 | 0.741197 | 5.056672 | false | true | false | false |
FWDekker/intellij-randomness
|
src/test/kotlin/com/fwdekker/randomness/ui/ButtonGroupHelperTest.kt
|
1
|
5025
|
package com.fwdekker.randomness.ui
import org.assertj.core.api.Assertions.assertThat
import org.assertj.swing.edt.FailOnThreadViolationRepaintManager
import org.assertj.swing.edt.GuiActionRunner
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import javax.swing.ButtonGroup
import javax.swing.JButton
import javax.swing.JLabel
import javax.swing.JRadioButton
/**
* Unit tests for the extension functions in `ButtonGroupKt`.
*/
object ButtonGroupHelperTest : Spek({
lateinit var group: ButtonGroup
beforeGroup {
FailOnThreadViolationRepaintManager.install()
}
beforeEachTest {
group = ButtonGroup()
}
describe("forEach") {
it("iterates 0 times over an empty group") {
var sum = 0
group.forEach { sum++ }
assertThat(sum).isEqualTo(0)
}
it("iterates once for each button in a group") {
group.add(createJButton())
group.add(createJButton())
group.add(createJButton())
var sum = 0
group.forEach { sum++ }
assertThat(sum).isEqualTo(3)
}
}
describe("getValue") {
it("returns null if the group is empty") {
assertThat(group.getValue()).isNull()
}
it("returns null if no button is selected") {
group.add(createJButton(actionCommand = "medicine"))
assertThat(group.getValue()).isNull()
}
it("returns an empty string if the selected button has an empty action command") {
group.add(createJButton(actionCommand = "", isSelected = true))
assertThat(group.getValue()).isEmpty()
}
it("returns the action command of the selected button") {
group.add(createJButton(actionCommand = "frequent"))
group.add(createJButton(actionCommand = "umbrella", isSelected = true))
assertThat(group.getValue()).isEqualTo("umbrella")
}
}
describe("setSalue") {
it("deselects the currently selected button if no button has the given action command") {
val buttonA = createJButton(actionCommand = "plenty")
val buttonB = createJButton(actionCommand = "date")
val buttonC = createJButton(actionCommand = "bath", isSelected = true)
group.add(buttonA)
group.add(buttonB)
group.add(buttonC)
GuiActionRunner.execute { group.setValue("formal") }
assertThat(buttonC.isSelected).isFalse()
}
it("selects the button with the given action command") {
val buttonA = createJButton(actionCommand = "cape")
val buttonB = createJButton(actionCommand = "another")
val buttonC = createJButton(actionCommand = "empire")
group.add(buttonA)
group.add(buttonB)
group.add(buttonC)
GuiActionRunner.execute { group.setValue("another") }
assertThat(buttonB.isSelected).isTrue()
}
it("selects exactly one button if multiple buttons have the given action command") {
val buttonA = createJButton(actionCommand = "secrecy")
val buttonB = createJButton(actionCommand = "secrecy")
val buttonC = createJButton(actionCommand = "study")
group.add(buttonA)
group.add(buttonB)
group.add(buttonC)
GuiActionRunner.execute { group.setValue("secrecy") }
assertThat(buttonA.isSelected).isNotEqualTo(buttonB.isSelected)
}
}
describe("buttons") {
it("returns nothing if the group is empty") {
assertThat(group.buttons()).isEmpty()
}
it("returns the elements of the group") {
val buttonA = createJButton(actionCommand = "whole")
val buttonB = createJButton(actionCommand = "melt")
val buttonC = createJButton(actionCommand = "envy")
group.add(buttonA)
group.add(buttonB)
group.add(buttonC)
assertThat(group.buttons()).containsExactly(buttonA, buttonB, buttonC)
}
}
describe("setLabel") {
it("sets the `labelFor` if another button is selected") {
val button1 = GuiActionRunner.execute<JRadioButton> { JRadioButton() }
val button2 = GuiActionRunner.execute<JRadioButton> { JRadioButton() }
group.add(button1)
group.add(button2)
val label = GuiActionRunner.execute<JLabel> { JLabel() }
group.setLabel(label)
GuiActionRunner.execute { button2.isSelected = true }
assertThat(label.labelFor).isEqualTo(button2)
}
}
})
private fun createJButton(actionCommand: String? = null, isSelected: Boolean = false) =
GuiActionRunner.execute<JButton> {
JButton().also {
it.actionCommand = actionCommand
it.isSelected = isSelected
}
}
|
mit
|
33cd437e9c46890310e0d373c1421bc5
| 30.40625 | 97 | 0.613134 | 4.66141 | false | false | false | false |
proxer/ProxerAndroid
|
src/main/kotlin/me/proxer/app/settings/AboutFragment.kt
|
1
|
13437
|
package me.proxer.app.settings
import android.content.ActivityNotFoundException
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.core.os.bundleOf
import com.danielstone.materialaboutlibrary.ConvenienceBuilder
import com.danielstone.materialaboutlibrary.MaterialAboutFragment
import com.danielstone.materialaboutlibrary.items.MaterialAboutActionItem
import com.danielstone.materialaboutlibrary.model.MaterialAboutCard
import com.danielstone.materialaboutlibrary.model.MaterialAboutList
import com.mikepenz.aboutlibraries.LibsBuilder
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorInt
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import me.proxer.app.BuildConfig
import me.proxer.app.R
import me.proxer.app.base.CustomTabsAware
import me.proxer.app.chat.prv.Participant
import me.proxer.app.chat.prv.PrvMessengerActivity
import me.proxer.app.chat.prv.create.CreateConferenceActivity
import me.proxer.app.chat.prv.sync.MessengerDao
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.settings.status.ServerStatusActivity
import me.proxer.app.util.extension.androidUri
import me.proxer.app.util.extension.fallbackHandleLink
import me.proxer.app.util.extension.resolveColor
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.app.util.extension.toPrefixedHttpUrl
import me.proxer.app.util.extension.toast
import me.zhanghai.android.customtabshelper.CustomTabsHelperFragment
import okhttp3.HttpUrl
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class AboutFragment : MaterialAboutFragment(), CustomTabsAware {
companion object {
private val teamLink = "https://proxer.me/team?device=default".toPrefixedHttpUrl()
private val facebookLink = "https://facebook.com/Anime.Proxer.Me".toPrefixedHttpUrl()
private val twitterLink = "https://twitter.com/proxerme".toPrefixedHttpUrl()
private val youtubeLink = "https://youtube.com/channel/UC7h-fT9Y9XFxuZ5GZpbcrtA".toPrefixedHttpUrl()
private val discordLink = "https://discord.gg/XwrEDmA".toPrefixedHttpUrl()
private val repositoryLink = "https://github.com/proxer/ProxerAndroid".toPrefixedHttpUrl()
private const val supportProxerMail = "[email protected]"
private const val supportProxerName = "Support"
private const val developerGithubName = "rubengees"
private const val developerProxerName = "RubyGee"
private const val developerProxerId = "121658"
fun newInstance() = AboutFragment().apply {
arguments = bundleOf()
}
}
private val messengerDao by safeInject<MessengerDao>()
private var customTabsHelper by Delegates.notNull<CustomTabsHelperFragment>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
customTabsHelper = CustomTabsHelperFragment.attachTo(this)
setLikelyUrl(teamLink)
setLikelyUrl(facebookLink)
setLikelyUrl(twitterLink)
setLikelyUrl(youtubeLink)
setLikelyUrl(discordLink)
}
override fun setLikelyUrl(url: HttpUrl): Boolean {
return customTabsHelper.mayLaunchUrl(url.androidUri(), bundleOf(), emptyList())
}
override fun showPage(url: HttpUrl, forceBrowser: Boolean, skipCheck: Boolean) {
customTabsHelper.fallbackHandleLink(requireActivity(), url, forceBrowser, skipCheck)
}
override fun getMaterialAboutList(context: Context): MaterialAboutList = MaterialAboutList.Builder()
.addCard(
MaterialAboutCard.Builder()
.apply { buildInfoItems(context).forEach { addItem(it) } }
.build()
)
.addCard(
MaterialAboutCard.Builder()
.title(R.string.about_social_media_title)
.apply { buildSocialMediaItems(context).forEach { addItem(it) } }
.build()
)
.addCard(
MaterialAboutCard.Builder()
.title(R.string.about_support_title)
.apply { buildSupportItems(context).forEach { addItem(it) } }
.build()
)
.addCard(
MaterialAboutCard.Builder()
.title(getString(R.string.about_developer_title))
.apply { buildDeveloperItems(context).forEach { addItem(it) } }
.build()
)
.build()
override fun shouldAnimate() = false
private fun buildInfoItems(context: Context) = listOf(
ConvenienceBuilder.createAppTitleItem(context),
MaterialAboutActionItem.Builder()
.text(R.string.about_version_title)
.subText(BuildConfig.VERSION_NAME)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon3.cmd_tag).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction {
val title = getString(R.string.clipboard_title)
requireContext().getSystemService<ClipboardManager>()?.setPrimaryClip(
ClipData.newPlainText(title, BuildConfig.VERSION_NAME)
)
requireContext().toast(R.string.clipboard_status)
}.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_licenses_title)
.subText(R.string.about_licenses_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon.cmd_clipboard_text).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction {
LibsBuilder()
.withAutoDetect(false)
.withShowLoadingProgress(false)
.withAboutVersionShown(false)
.withAboutIconShown(false)
.withVersionShown(false)
.withOwnLibsActivityClass(ProxerLibsActivity::class.java)
.withActivityTitle(getString(R.string.about_licenses_activity_title))
.start(requireActivity())
}.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_source_code)
.subText(R.string.about_source_code_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon.cmd_code_braces).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction { showPage(repositoryLink, skipCheck = true) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_server_status)
.subText(R.string.about_server_status_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon3.cmd_server).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction { ServerStatusActivity.navigateTo(requireActivity()) }
.build()
)
private fun buildSocialMediaItems(context: Context) = listOf(
MaterialAboutActionItem.Builder()
.text(R.string.about_facebook_title)
.subText(R.string.about_facebook_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon2.cmd_facebook).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction { showPage(facebookLink, skipCheck = true) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_twitter_title)
.subText(R.string.about_twitter_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon3.cmd_twitter).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction { showPage(twitterLink, skipCheck = true) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_youtube_title)
.subText(R.string.about_youtube_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon3.cmd_youtube).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction { showPage(youtubeLink, skipCheck = true) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_discord_title)
.subText(R.string.about_discord_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon.cmd_discord).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction { showPage(discordLink, skipCheck = true) }
.build()
)
private fun buildSupportItems(context: Context) = listOf(
MaterialAboutActionItem.Builder()
.icon(
IconicsDrawable(context, CommunityMaterial.Icon2.cmd_information).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.subText(R.string.about_support_info)
.setOnClickAction { showPage(teamLink, skipCheck = true) }
.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_support_message_title)
.subText(R.string.about_support_message_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon2.cmd_forum).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction {
Completable
.fromAction {
messengerDao.findConferenceForUser(supportProxerName).let { existingConference ->
when (existingConference) {
null -> CreateConferenceActivity.navigateTo(
requireActivity(),
false,
Participant(supportProxerName)
)
else -> PrvMessengerActivity.navigateTo(requireActivity(), existingConference)
}
}
}
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}.build(),
MaterialAboutActionItem.Builder()
.text(R.string.about_support_mail_title)
.subText(R.string.about_support_mail_description)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon.cmd_email).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction {
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, arrayOf(supportProxerMail))
putExtra(Intent.EXTRA_SUBJECT, getString(R.string.about_support_mail_subject))
}
try {
startActivity(intent)
} catch (error: ActivityNotFoundException) {
requireContext().toast(R.string.about_error_mail_no_activity)
}
}
.build()
)
private fun buildDeveloperItems(context: Context) = listOf(
MaterialAboutActionItem.Builder()
.text(R.string.about_developer_github_title)
.subText(developerGithubName)
.icon(
IconicsDrawable(context, CommunityMaterial.Icon2.cmd_github).apply {
colorInt = context.resolveColor(R.attr.colorIcon)
}
)
.setOnClickAction {
showPage(
"https://github.com/$developerGithubName".toPrefixedHttpUrl(),
skipCheck = true
)
}
.build(),
MaterialAboutActionItem.Builder()
.text(getString(R.string.about_developer_proxer_title))
.subText(developerProxerName)
.icon(
ContextCompat.getDrawable(context, R.drawable.ic_stat_proxer)?.apply {
colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(
context.resolveColor(R.attr.colorIcon),
BlendModeCompat.SRC_IN
)
}
)
.setOnClickAction {
ProfileActivity.navigateTo(requireActivity(), developerProxerId, developerProxerName, null)
}
.build()
)
}
|
gpl-3.0
|
cb994d149643631c73a4722b34a26410
| 41.254717 | 110 | 0.612934 | 4.938258 | false | false | false | false |
MichaelRocks/lightsaber
|
processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/AnalyzerHelper.kt
|
1
|
5234
|
/*
* Copyright 2020 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.analysis
import io.michaelrocks.grip.ClassRegistry
import io.michaelrocks.grip.mirrors.Annotated
import io.michaelrocks.grip.mirrors.AnnotationMirror
import io.michaelrocks.grip.mirrors.FieldMirror
import io.michaelrocks.grip.mirrors.MethodMirror
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.signature.GenericType
import io.michaelrocks.lightsaber.LightsaberTypes
import io.michaelrocks.lightsaber.processor.ErrorReporter
import io.michaelrocks.lightsaber.processor.ProcessingException
import io.michaelrocks.lightsaber.processor.commons.Types
import io.michaelrocks.lightsaber.processor.commons.rawType
import io.michaelrocks.lightsaber.processor.model.Converter
import io.michaelrocks.lightsaber.processor.model.Dependency
import io.michaelrocks.lightsaber.processor.model.Injectee
import io.michaelrocks.lightsaber.processor.model.InjectionPoint
import io.michaelrocks.lightsaber.processor.model.Scope
interface AnalyzerHelper {
fun convertToInjectionPoint(method: MethodMirror, container: Type.Object): InjectionPoint.Method
fun convertToInjectionPoint(field: FieldMirror, container: Type.Object): InjectionPoint.Field
fun convertToInjectee(method: MethodMirror, parameterIndex: Int): Injectee
fun convertToInjectee(field: FieldMirror): Injectee
fun findQualifier(annotated: Annotated): AnnotationMirror?
fun findScope(annotated: Annotated): Scope
}
class AnalyzerHelperImpl(
private val classRegistry: ClassRegistry,
private val scopeRegistry: ScopeRegistry,
private val errorReporter: ErrorReporter
) : AnalyzerHelper {
override fun convertToInjectionPoint(method: MethodMirror, container: Type.Object): InjectionPoint.Method {
return InjectionPoint.Method(container, method, getInjectees(method))
}
override fun convertToInjectionPoint(field: FieldMirror, container: Type.Object): InjectionPoint.Field {
return InjectionPoint.Field(container, field, getInjectee(field))
}
override fun convertToInjectee(method: MethodMirror, parameterIndex: Int): Injectee {
val type = method.signature.parameterTypes[parameterIndex]
return newInjectee(type, method.parameters[parameterIndex])
}
override fun convertToInjectee(field: FieldMirror): Injectee {
return newInjectee(field.signature.type, field)
}
override fun findQualifier(annotated: Annotated): AnnotationMirror? {
fun isQualifier(annotationType: Type.Object): Boolean {
return classRegistry.getClassMirror(annotationType).annotations.contains(Types.QUALIFIER_TYPE)
}
val qualifierCount = annotated.annotations.count { isQualifier(it.type) }
if (qualifierCount > 0) {
if (qualifierCount > 1) {
errorReporter.reportError("Element $this has multiple qualifiers")
}
return annotated.annotations.first { isQualifier(it.type) }
} else {
return null
}
}
override fun findScope(annotated: Annotated): Scope {
val scopeProviders = annotated.annotations.mapNotNull {
scopeRegistry.findScopeProviderByAnnotationType(it.type)
}
return when (scopeProviders.size) {
0 -> Scope.None
1 -> Scope.Class(scopeProviders[0])
else -> {
errorReporter.reportError("Element $this has multiple scopes: $scopeProviders")
Scope.None
}
}
}
private fun getInjectees(method: MethodMirror): List<Injectee> {
return method.parameters.mapIndexed { index, parameter ->
val type = method.signature.parameterTypes[index]
newInjectee(type, parameter)
}
}
private fun getInjectee(field: FieldMirror): Injectee {
return newInjectee(field.signature.type, field)
}
private fun newInjectee(type: GenericType, holder: Annotated): Injectee {
val qualifier = findQualifier(holder)
val dependency = type.toDependency(qualifier)
val converter = type.getConverter()
return Injectee(dependency, converter, holder.annotations)
}
private fun GenericType.getConverter(): Converter {
return when (rawType) {
Types.PROVIDER_TYPE -> Converter.Identity
Types.LAZY_TYPE -> Converter.Adapter(LightsaberTypes.LAZY_ADAPTER_TYPE)
else -> Converter.Instance
}
}
private fun GenericType.toDependency(qualifier: AnnotationMirror?): Dependency {
when (rawType) {
Types.PROVIDER_TYPE,
Types.LAZY_TYPE ->
if (this is GenericType.Parameterized) {
return Dependency(typeArguments[0], qualifier)
} else {
throw ProcessingException("Type $this must be parameterized")
}
}
return Dependency(this, qualifier)
}
}
|
apache-2.0
|
7609ea3b7aa87811a578c795aba4e95b
| 36.385714 | 109 | 0.758502 | 4.539462 | false | false | false | false |
yo1000/dimg
|
src/main/kotlin/com/yo1000/dimg/cli/DimgCommandLineRunner.kt
|
1
|
4750
|
package com.yo1000.dimg.cli
import com.yo1000.dimg.service.ImageDifferenceService
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.HelpFormatter
import org.apache.commons.cli.Options
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Component
import java.io.File
import java.nio.charset.Charset
import java.util.stream.Collectors
/**
*
* @author yo1000
*/
@Component
class DimgCommandLineRunner(val imageDifferenceService: ImageDifferenceService) : CommandLineRunner {
val LOGGER: Logger = LoggerFactory.getLogger(DimgCommandLineRunner::class.java)
override fun run(vararg args: String?) {
val options = Options()
options.addOption("f1", "file1", true, "File to diff 1.\nMust use with f2.")
options.addOption("f2", "file2", true, "File to diff 2.\nMust use with f1.")
options.addOption("d1", "dir1", true, "Directory containing files to diff 1.\nMust use with d2.")
options.addOption("d2", "dir2", true, "Directory containing files to diff 2.\nMust use with d1.")
options.addOption("o", "out", true, "Output location.")
options.addOption("s", "suppress", false, "Suppress standard output.")
options.addOption("b64", "base64", false, "Base64 format input.\nUse only for piped standard input.")
options.addOption("?", "help", false, "Print this message.")
val parser = DefaultParser()
val cl = parser.parse(options, args)
if (cl.hasOption("?")) {
val formatter = HelpFormatter()
formatter.printHelp("""
dimg [-b64 | -f1 <imageFile1> -f2 <imageFile2> |
-d1 <imageContainsDir1> -d2 <imageContainsDir2>]
[-o <outLocation> [-s]]
""",
options)
}
if (cl.hasOption("s") && !cl.hasOption("o")) {
throw IllegalArgumentException("When using `s` option, must use with `o` option.")
}
if (System.console() == null &&
!cl.hasOption("f1") && !cl.hasOption("f2") &&
!cl.hasOption("d1") && !cl.hasOption("d2")) {
val blocks = System.`in`.bufferedReader(Charset.defaultCharset())
.lines()
.collect(Collectors.joining())
.split(Regex("\\s+"))
if (blocks.size != 2) {
throw IllegalArgumentException("Standard input requires 2 blocks separated by white space.")
}
printMatchRatio("stdin", "stdin",
if (cl.hasOption("o"))
imageDifferenceService.compareBinaries(
blocks[0], blocks[1], cl.hasOption("b64"), cl.getOptionValue("o"))
else
imageDifferenceService.compareBinaries(
blocks[0], blocks[1], cl.hasOption("b64")),
cl.hasOption("s"))
return
}
if (cl.hasOption("f1") && cl.hasOption("f2") && !cl.hasOption("d1") && !cl.hasOption("d2")) {
val path1 = cl.getOptionValue("f1")
val path2 = cl.getOptionValue("f2")
printMatchRatio(path1, path2,
if (cl.hasOption("o"))
imageDifferenceService.compareFiles(
path1, path2, cl.getOptionValue("o"))
else
imageDifferenceService.compareFiles(
path1, path2),
cl.hasOption("s"))
return
}
if (cl.hasOption("d1") && cl.hasOption("d2") && !cl.hasOption("f1") && !cl.hasOption("f2")) {
imageDifferenceService.compareDirectories(cl.getOptionValue("d1"), cl.getOptionValue("d2"), {
file1: File, file2: File -> printMatchRatio(
file1.absolutePath,
file2.absolutePath,
if (cl.hasOption("o"))
imageDifferenceService.compareFiles(
file1, file2, File(cl.getOptionValue("o")))
else
imageDifferenceService.compareFiles(
file1, file2),
cl.hasOption("s"))
})
return
}
}
protected fun printMatchRatio(f1: String, f2: String, ratio: Number, suppress: Boolean) {
if (suppress) {
LOGGER.info("$1: $f1")
LOGGER.info("$2: $f2")
LOGGER.info("Diff ratio: $ratio")
} else {
println("$1: $f1")
println("$2: $f2")
println("Diff ratio: $ratio")
}
}
}
|
mit
|
13b02132162798107dd1055da8821936
| 38.264463 | 109 | 0.546947 | 4.233512 | false | false | false | false |
proxer/ProxerAndroid
|
src/main/kotlin/me/proxer/app/chat/prv/conference/info/ConferenceInfoActivity.kt
|
1
|
1138
|
package me.proxer.app.chat.prv.conference.info
import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.commitNow
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.util.extension.getSafeParcelableExtra
import me.proxer.app.util.extension.startActivity
/**
* @author Ruben Gees
*/
class ConferenceInfoActivity : DrawerActivity() {
companion object {
private const val CONFERENCE_EXTRA = "conference"
fun navigateTo(context: Activity, conference: LocalConference) {
context.startActivity<ConferenceInfoActivity>(CONFERENCE_EXTRA to conference)
}
}
val conference: LocalConference
get() = intent.getSafeParcelableExtra(CONFERENCE_EXTRA)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = conference.topic
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, ConferenceInfoFragment.newInstance())
}
}
}
}
|
gpl-3.0
|
897015c31201ee11145c37cece0cdb08
| 28.179487 | 89 | 0.714411 | 4.644898 | false | false | false | false |
gatheringhallstudios/MHGenDatabase
|
app/src/main/java/com/ghstudios/android/features/armor/list/ArmorFamilyListAdapter.kt
|
1
|
4010
|
package com.ghstudios.android.features.armor.list
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.ClickListeners.ArmorClickListener
import com.ghstudios.android.data.classes.ArmorFamily
import com.ghstudios.android.data.classes.Rank
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.mhgendatabase.databinding.ListitemArmorFamilyBinding
import com.ghstudios.android.mhgendatabase.databinding.ListitemArmorHeaderBinding
import com.ghstudios.android.util.setImageAsset
class ArmorFamilyGroup(
val rarity: Int,
val families: List<ArmorFamily>
)
/**
* Expandable list adapter used to render a collection of armor families grouped by rarity.
*/
class ArmorFamilyListAdapter(private val groups: List<ArmorFamilyGroup>) : BaseExpandableListAdapter() {
override fun hasStableIds() = true
override fun isChildSelectable(groupPosition: Int, childPosition: Int) = true
override fun getGroup(groupPosition: Int) = groups[groupPosition]
override fun getGroupCount() = groups.size
override fun getChild(groupPosition: Int, childPosition: Int) = groups[groupPosition].families[childPosition]
override fun getChildrenCount(groupPosition: Int) = groups[groupPosition].families.size
override fun getChildId(groupPosition: Int, childPosition: Int) = groupPosition * 100L + childPosition
override fun getGroupId(groupPosition: Int) = groupPosition.toLong()
override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View {
val group = getGroup(groupPosition)
val inflater = LayoutInflater.from(parent?.context)
val binding = ListitemArmorHeaderBinding.inflate(inflater, parent, false)
binding.nameText.text = AssetLoader.localizeRarityLabel(group.rarity)
binding.rankText.text = when (group.rarity) {
11 -> binding.root.resources.getString(R.string.monster_class_deviant)
else -> AssetLoader.localizeRank(Rank.fromArmorRarity(group.rarity))
}
return binding.root
}
override fun getChildView(groupPosition: Int, childPosition: Int,
isLastChild: Boolean, convertView: View?, parent: ViewGroup): View {
val context = parent.context
val binding = when (convertView) {
null -> ListitemArmorFamilyBinding.inflate(LayoutInflater.from(context), parent, false)
else -> ListitemArmorFamilyBinding.bind(convertView)
}
val family = getChild(groupPosition, childPosition)
with(binding) {
icon.setImageAsset(family)
familyName.text = family.name
binding.minDefense.text = Integer.toString(family.minDef)
binding.maxDefense.text = Integer.toString(family.maxDef)
}
// Get views for slots and skills
val slotViews = with(binding) {
arrayOf(slots1, slots2, slots3, slots4, slots5)
}
val skillViews = with(binding) {
arrayOf(skill1, skill2, skill3, skill4, skill5)
}
// Initialize, hide all slotsViews and skills
slotViews.forEach { it.visibility = View.GONE }
skillViews.forEach { it.visibility = View.GONE }
// Populate slots
for ((i, numSlots) in family.slots.withIndex()) {
val slotsView = slotViews[i]
slotsView.visibility = View.VISIBLE
slotsView.setSlots(numSlots, 0)
}
// Populate skills
for ((i, skillString) in family.skills.withIndex()) {
val skillView = skillViews[i]
skillView.visibility = View.VISIBLE
skillView.text = skillString
}
binding.root.tag = family.id
binding.root.setOnClickListener(ArmorClickListener(context, family))
return binding.root
}
}
|
mit
|
979e741d8028e668af7d758649a3215e
| 39.1 | 118 | 0.699751 | 4.593356 | false | false | false | false |
chinachen01/android-demo
|
app/src/main/kotlin/com/example/chenyong/android_demo/activity/HttpActivity.kt
|
1
|
4009
|
package com.example.chenyong.android_demo.activity
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.util.Log
import android.view.View
import com.example.chenyong.android_demo.APIservice
import com.example.chenyong.android_demo.R
import com.example.chenyong.android_demo.RxBus
import com.example.chenyong.android_demo.TapEvent
import com.example.chenyong.android_demo.databinding.ActivityHttpBinding
import com.example.chenyong.android_demo.http.RetrofitClient
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
/**
* Created by focus on 17/1/18.
*/
class HttpActivity : BaseActivity() {
lateinit var dataBinding: ActivityHttpBinding
lateinit var api: APIservice
var subs:Subscription? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_http)
api = RetrofitClient.getRetrofit().create(APIservice::class.java)
normalObserval()
dataBinding.presenter = Presenter()
subs = RxBus.toObserverable()
.subscribe{tapEvent ->kotlin.run { tapEvent as TapEvent; Log.d(TAG, "event: ${tapEvent.name}") }}
}
override fun onDestroy() {
super.onDestroy()
subs?.unsubscribe()
}
private fun showUser() {
api.getUserInfo("chinachen01asdd")
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({user -> Log.d(TAG, "user: $user")}
,{err -> Log.d(TAG, "error: ${err.message}")})
}
private fun watchRepo() {
api.watchRepo("ReactiveX", "RxAndroid")
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<Any>() {
override fun onCompleted() {
Log.d(TAG, "onCompleted: true")
}
override fun onError(e: Throwable?) {
Log.d(TAG, "onError: true")
}
override fun onNext(t: Any?) {
dataBinding.info.text = "watch success"
}
})
}
private fun stopWatchRepo() {
api.stopWatchRepo("ReactiveX", "RxAndroid")
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<Any>() {
override fun onCompleted() {
Log.d(TAG, "onCompleted: true")
}
override fun onError(e: Throwable?) {
Log.d(TAG, "onError: true")
}
override fun onNext(t: Any?) {
dataBinding.info.text = "stop watch success"
}
})
}
private fun normalObserval() {
var obs = Observable.create<String> { subs ->
kotlin.run {
//dosomething
subs.onNext("123")
Thread.sleep(3000)
subs.onNext("345")
Thread.sleep(3000)
subs.onNext("567")
Thread.sleep(3000)
subs.onNext("789")
subs.onCompleted()
}
}
obs.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({string-> Log.d(TAG, "string: $string")},
{error -> Log.d(TAG, "error: $error")})
}
inner class Presenter {
fun onClick(view: View) {
when (view.id) {
R.id.show_user -> showUser()
R.id.watch -> watchRepo()
R.id.stop_watch -> stopWatchRepo()
}
}
}
}
|
apache-2.0
|
9b4eba3c720c5f2068ccd37d1627865a
| 33.568966 | 113 | 0.550012 | 4.656214 | false | false | false | false |
passsy/gradle-gitVersioner-plugin
|
gitversioner/src/test/java/com/pascalwelsch/gitversioner/ShallowCloneTest.kt
|
1
|
16902
|
package com.pascalwelsch.gitversioner
import org.assertj.core.api.Assertions.*
import org.assertj.core.api.SoftAssertions.assertSoftly
import org.junit.*
import org.junit.runner.*
import org.junit.runners.*
@RunWith(JUnit4::class)
class ShallowCloneTest {
@Test
fun `default - clean on default branch master`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- master, HEAD
)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
@Test
fun `default - with local changes - addSnapshot false`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- master, HEAD
)
val localChanges = LocalChanges(3, 5, 7)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), localChanges, isHistoryShallowed = true)
val versioner = GitVersioner(git)
versioner.addSnapshot = false
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed(3 +5 -7)")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(localChanges)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
@Test
fun `default - with local changes - addLocalChangesDetails false`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- master, HEAD
)
val localChanges = LocalChanges(3, 5, 7)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), localChanges, isHistoryShallowed = true)
val versioner = GitVersioner(git)
versioner.addLocalChangesDetails = false
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-SNAPSHOT")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(localChanges)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
@Test
fun `default - without local changes information`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- master, HEAD
)
val localChanges = LocalChanges(3, 5, 7)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), localChanges, isHistoryShallowed = true)
val versioner = GitVersioner(git)
versioner.addLocalChangesDetails = false
versioner.addSnapshot = false
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(localChanges)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
@Test
fun `default - with local changes`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- master, HEAD
)
val localChanges = LocalChanges(3, 5, 7)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), localChanges, isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-SNAPSHOT(3 +5 -7)")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(localChanges)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
@Test
fun `base branch not in history`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- master, HEAD
)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), isHistoryShallowed = true)
val versioner = GitVersioner(git).apply {
baseBranch = "develop"
}
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-master")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("develop")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
// no commit in both HEAD history and develop because develop is not part of the graph
softly.assertThat(versioner.featureBranchOriginCommit).isNull()
}
}
@Test
fun `on orphan initial commit`() {
val graph = listOf(
Commit(sha1 = "X", parent = null, date = 150_010_000) // <-- HEAD, orphan
)
val git = MockGitRepo(graph, "X", branchHeads = listOf("X" to "orphan"), isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-orphan")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("orphan")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isNull()
}
}
@Test
fun `on orphan few commits`() {
val graph = listOf(
Commit(sha1 = "X", parent = "b'", date = 150_030_000) // <-- HEAD, feature/x
)
val git = MockGitRepo(graph, "X", listOf("X" to "feature/x"), isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-x")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("feature/x")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isNull()
}
}
@Test
fun `first commit - no parent`() {
val graph = listOf(
Commit(sha1 = "X", parent = null, date = 150_006_000) // <-- master, HEAD
)
val git = MockGitRepo(graph, "X", listOf("X" to "master"), isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
@Test
fun `short sha1`() {
val graph = listOf(
Commit(sha1 = "abcdefghijkl", parent = null, date = 150_006_000) // <-- master, HEAD
)
val git = MockGitRepo(graph, "abcdefghijkl", listOf("abcdefghijkl" to "master"), isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("master")
softly.assertThat(versioner.currentSha1).isEqualTo("abcdefghijkl")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.initialCommit).isNull()
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("abcdefghijkl")
}
assertThat(versioner.currentSha1Short).isEqualTo("abcdefg").hasSize(7)
}
@Test
fun `no commits`() {
val git = MockGitRepo(isHistoryShallowed = true) // git initialized but nothing committed
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-undefined")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isNull()
softly.assertThat(versioner.currentSha1).isNull()
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isNull()
}
}
@Test
fun `no branch name - sha1 fallback`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- HEAD
)
val git = MockGitRepo(graph, "X", isHistoryShallowed = true)
val versioner = GitVersioner(git)
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-X")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isNull()
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isNull()
}
}
@Test
fun `default - branchname from ci`() {
val graph = listOf(
Commit(sha1 = "X", parent = "j", date = 150_010_000) // <-- HEAD, master
)
val git = object : MockGitRepo(graph, "X", listOf("X" to "master"), isHistoryShallowed = true) {
// explicitly checked out sha1 not branch
override val currentBranch: String? = null
}
val versioner = GitVersioner(git)
versioner.ciBranchNameProvider = { "nameFromCi" }
assertSoftly { softly ->
softly.assertThat(versioner.versionCode).isEqualTo(1)
softly.assertThat(versioner.versionName).isEqualTo("shallowed-nameFromCi")
softly.assertThat(versioner.baseBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.featureBranchCommitCount).isEqualTo(0)
softly.assertThat(versioner.branchName).isEqualTo("nameFromCi")
softly.assertThat(versioner.currentSha1).isEqualTo("X")
softly.assertThat(versioner.baseBranch).isEqualTo("master")
softly.assertThat(versioner.localChanges).isEqualTo(NO_CHANGES)
softly.assertThat(versioner.yearFactor).isEqualTo(1000)
softly.assertThat(versioner.timeComponent).isEqualTo(0)
softly.assertThat(versioner.featureBranchOriginCommit).isEqualTo("X")
}
}
}
|
apache-2.0
|
f87c1c971e161a86646d7ddc0bdeb2c8
| 47.852601 | 115 | 0.661579 | 4.492823 | false | false | false | false |
DevCharly/kotlin-ant-dsl
|
src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/unjar.kt
|
1
|
2274
|
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Expand
import org.apache.tools.ant.types.PatternSet
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.util.FileNameMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.unjar(
src: String? = null,
dest: String? = null,
overwrite: Boolean? = null,
encoding: String? = null,
failonemptyarchive: Boolean? = null,
stripabsolutepathspec: Boolean? = null,
scanforunicodeextrafields: Boolean? = null,
nested: (KUnjar.() -> Unit)? = null)
{
Expand().execute("unjar") { task ->
if (src != null)
task.setSrc(project.resolveFile(src))
if (dest != null)
task.setDest(project.resolveFile(dest))
if (overwrite != null)
task.setOverwrite(overwrite)
if (encoding != null)
task.setEncoding(encoding)
if (failonemptyarchive != null)
task.setFailOnEmptyArchive(failonemptyarchive)
if (stripabsolutepathspec != null)
task.setStripAbsolutePathSpec(stripabsolutepathspec)
if (scanforunicodeextrafields != null)
task.setScanForUnicodeExtraFields(scanforunicodeextrafields)
if (nested != null)
nested(KUnjar(task))
}
}
class KUnjar(override val component: Expand) :
IFileNameMapperNested,
IResourceCollectionNested,
IPatternSetNested
{
override fun _addFileNameMapper(value: FileNameMapper) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.add(value)
override fun _addPatternSet(value: PatternSet) = component.addPatternset(value)
}
|
apache-2.0
|
6398fcb6fb6b108f9ef1c3deac8a7411
| 33.454545 | 86 | 0.700967 | 3.667742 | false | false | false | false |
vhromada/Catalog-Spring
|
src/main/kotlin/cz/vhromada/catalog/web/mapper/impl/ProgramMapperImpl.kt
|
1
|
1379
|
package cz.vhromada.catalog.web.mapper.impl
import cz.vhromada.catalog.entity.Program
import cz.vhromada.catalog.web.fo.ProgramFO
import cz.vhromada.catalog.web.mapper.ProgramMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for programs.
*
* @author Vladimir Hromada
*/
@Component("webProgramMapper")
class ProgramMapperImpl : ProgramMapper {
override fun map(source: Program): ProgramFO {
return ProgramFO(id = source.id,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toString(),
crack = source.crack,
serialKey = source.serialKey,
otherData = source.otherData,
note = source.note,
position = source.position)
}
override fun mapBack(source: ProgramFO): Program {
return Program(id = source.id,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toInt(),
crack = source.crack,
serialKey = source.serialKey,
otherData = source.otherData,
note = source.note,
position = source.position)
}
}
|
mit
|
e79b30175f877763b558edaac4222ad2
| 31.833333 | 60 | 0.592458 | 4.890071 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/blocks/BlockBuilder.kt
|
2
|
8507
|
package com.cout970.magneticraft.systems.blocks
import com.cout970.magneticraft.AABB
import com.cout970.magneticraft.misc.resource
import net.minecraft.block.material.Material
import net.minecraft.block.state.BlockFaceShape
import net.minecraft.block.state.IBlockState
import net.minecraft.client.renderer.block.model.ModelResourceLocation
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.BlockRenderLayer
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.common.capabilities.ICapabilityProvider
/**
* Created by cout970 on 2017/06/08.
*/
class BlockBuilder {
var constructor: (Material, List<IStatesEnum>) -> BlockBase = { a, b ->
BlockBase.states_ = b
BlockBase(a)
}
var tileConstructor: (Material, List<IStatesEnum>, (World, IBlockState) -> TileEntity?,
((IBlockState) -> Boolean)?) -> BlockBase = { a, b, c, d ->
BlockBase.states_ = b
BlockTileBase(c, d, a)
}
var forceModelBake = false
var customModels: List<Pair<String, ResourceLocation>> = emptyList()
var factory: ((World, IBlockState) -> TileEntity?)? = null
var factoryFilter: ((IBlockState) -> Boolean)? = null
var registryName: ResourceLocation? = null
var material: Material? = null
var creativeTab: CreativeTabs? = null
var boundingBox: ((BoundingBoxArgs) -> List<AABB>)? = null
// default value if false
var onActivated: ((OnActivatedArgs) -> Boolean)? = null
var stateMapper: ((IBlockState) -> ModelResourceLocation)? = null
var onBlockPlaced: ((OnBlockPlacedArgs) -> IBlockState)? = null
var pickBlock: ((PickBlockArgs) -> ItemStack)? = null
var canPlaceBlockOnSide: ((CanPlaceBlockOnSideArgs) -> Boolean)? = null
var capabilityProvider: ICapabilityProvider? = null
var onNeighborChanged: ((OnNeighborChangedArgs) -> Unit)? = null
var blockStatesToPlace: ((BlockStatesToPlaceArgs) -> List<Pair<BlockPos, IBlockState>>)? = null
var onBlockBreak: ((BreakBlockArgs) -> Unit)? = null
var onDrop: ((DropsArgs) -> List<ItemStack>)? = null
var onBlockPostPlaced: ((OnBlockPostPlacedArgs) -> Unit)? = null
var onUpdateTick: ((OnUpdateTickArgs) -> Unit)? = null
var collisionBox: ((CollisionBoxArgs) -> AABB?)? = null
var shouldSideBeRendered: ((ShouldSideBeRendererArgs) -> Boolean)? = null
var onEntityCollidedWithBlock: ((OnEntityCollidedWithBlockArgs) -> Unit)? = null
var canConnectRedstone: ((CanConnectRedstoneArgs) -> Boolean)? = null
var redstonePower: ((RedstonePowerArgs) -> Int)? = null
var blockFaceShape: ((GetBlockFaceShapeArgs) -> BlockFaceShape)? = null
var addInformation: ((AddInformationArgs) -> Unit)? = null
var states: List<IStatesEnum>? = null
var hardness = 1.5f
var explosionResistance = 10.0f
var lightEmission = 0.0f
var generateDefaultItemBlockModel = true
var enableOcclusionOptimization = true
var translucent = false
var tickRandomly = false
var alwaysDropDefault = false
var blockLayer: BlockRenderLayer? = null
var tickRate = 10
var dropWithTileNBT: Boolean = false
var hasCustomModel: Boolean = false
set(value) {
field = value
enableOcclusionOptimization = false
translucent = true
}
fun withName(name: String): BlockBuilder {
registryName = resource(name)
return this
}
fun build(): BlockBase {
requireNotNull(registryName) { "registryName was null" }
requireNotNull(material) { "material was null" }
val block = if (factory != null)
tileConstructor(material!!, states ?: listOf(IStatesEnum.default), factory!!, factoryFilter)
else
constructor(material!!, states ?: listOf(IStatesEnum.default))
block.apply {
registryName = [email protected]!!
creativeTab?.let { setCreativeTab(it) }
boundingBox?.let { aabb = it }
[email protected]?.let { blockLayer_ = it }
setHardness(hardness)
setResistance(explosionResistance)
setLightOpacity(if (translucent) 0 else 255)
setLightLevel(lightEmission)
// @formatter:off
unlocalizedName = "${registryName?.resourceDomain}.${registryName?.resourcePath}"
dropWithTileNBT = [email protected]
onActivated = [email protected]
stateMapper = [email protected]
enableOcclusionOptimization = [email protected]
translucent_ = [email protected]
onBlockPlaced = [email protected]
customModels = [email protected]
forceModelBake = [email protected]
pickBlock = [email protected]
generateDefaultItemModel = [email protected]
canPlaceBlockOnSide = [email protected]
capabilityProvider = [email protected]
onNeighborChanged = [email protected]
alwaysDropDefault = [email protected]
blockStatesToPlace = [email protected]
onBlockBreak = [email protected]
onDrop = [email protected]
onBlockPostPlaced = [email protected]
tickRandomly = [email protected]
onUpdateTick = [email protected]
collisionBox = [email protected]
shouldSideBeRendered_ = [email protected]
tickRate_ = [email protected]
onEntityCollidedWithBlock = [email protected]
canConnectRedstone = [email protected]
redstonePower = [email protected]
getBlockFaceShape = [email protected]
addInformation = [email protected]
// @formatter:on
}
return block
}
inline fun factoryOf(crossinline func: () -> TileEntity): ((World, IBlockState) -> TileEntity?) = { _, _ -> func() }
fun copy(func: BlockBuilder.() -> Unit): BlockBuilder {
val newBuilder = BlockBuilder()
newBuilder.constructor = constructor
newBuilder.tileConstructor = tileConstructor
newBuilder.customModels = customModels
newBuilder.factory = factory
newBuilder.registryName = registryName
newBuilder.material = material
newBuilder.creativeTab = creativeTab
newBuilder.dropWithTileNBT = dropWithTileNBT
newBuilder.boundingBox = boundingBox
newBuilder.onActivated = onActivated
newBuilder.stateMapper = stateMapper
newBuilder.onBlockPlaced = onBlockPlaced
newBuilder.pickBlock = pickBlock
newBuilder.states = states
newBuilder.hardness = hardness
newBuilder.explosionResistance = explosionResistance
newBuilder.enableOcclusionOptimization = enableOcclusionOptimization
newBuilder.translucent = translucent
newBuilder.generateDefaultItemBlockModel = generateDefaultItemBlockModel
newBuilder.canPlaceBlockOnSide = canPlaceBlockOnSide
newBuilder.capabilityProvider = capabilityProvider
newBuilder.onNeighborChanged = onNeighborChanged
newBuilder.alwaysDropDefault = alwaysDropDefault
newBuilder.blockStatesToPlace = blockStatesToPlace
newBuilder.onBlockBreak = onBlockBreak
newBuilder.onDrop = onDrop
newBuilder.onBlockPostPlaced = onBlockPostPlaced
newBuilder.tickRandomly = tickRandomly
newBuilder.blockLayer = blockLayer
newBuilder.onUpdateTick = onUpdateTick
newBuilder.shouldSideBeRendered = shouldSideBeRendered
newBuilder.tickRate = tickRate
newBuilder.onEntityCollidedWithBlock = onEntityCollidedWithBlock
newBuilder.canConnectRedstone = canConnectRedstone
newBuilder.redstonePower = redstonePower
newBuilder.addInformation = addInformation
func(newBuilder)
return newBuilder
}
}
|
gpl-2.0
|
aca5c10204144a9dc9f09a21272a1784
| 43.539267 | 120 | 0.699424 | 4.734001 | false | false | false | false |
robinverduijn/gradle
|
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/Identities.kt
|
1
|
1200
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization
import java.util.IdentityHashMap
class WriteIdentities {
private
val instanceIds = IdentityHashMap<Any, Int>()
fun getId(instance: Any) = instanceIds[instance]
fun putInstance(instance: Any): Int {
val id = instanceIds.size
instanceIds[instance] = id
return id
}
}
class ReadIdentities {
private
val instanceIds = HashMap<Int, Any>()
fun getInstance(id: Int) = instanceIds[id]
fun putInstance(id: Int, instance: Any) {
instanceIds[id] = instance
}
}
|
apache-2.0
|
1ef17299555eba3e0b5e8ee1d84f44db
| 24.531915 | 75 | 0.701667 | 4.152249 | false | false | false | false |
anton-okolelov/intellij-rust
|
src/main/kotlin/org/rust/ide/intentions/MoveTypeConstraintToParameterListIntention.kt
|
2
|
2476
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
class MoveTypeConstraintToParameterListIntention : RsElementBaseIntentionAction<RsWhereClause>() {
override fun getText() = "Move type constraint to parameter list"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsWhereClause? {
val whereClause = element.ancestorStrict<RsWhereClause>() ?: return null
val wherePredList = whereClause.wherePredList
if (wherePredList.isEmpty()) return null
val typeParameterList = whereClause.ancestorStrict<RsGenericDeclaration>()?.typeParameterList ?: return null
val lifetimes = typeParameterList.lifetimeParameterList
val types = typeParameterList.typeParameterList
if (wherePredList.any {
it.lifetime?.reference?.resolve() !in lifetimes &&
(it.typeReference?.typeElement as? RsBaseType)?.path?.reference?.resolve() !in types
}) return null
return whereClause
}
override fun invoke(project: Project, editor: Editor, ctx: RsWhereClause) {
val declaration = ctx.ancestorStrict<RsGenericDeclaration>() ?: return
val typeParameterList = declaration.typeParameterList ?: return
val lifetimes = typeParameterList.lifetimeParameterList.mapNotNull { typeParameterText(it, it.bounds) }
val types = typeParameterList.typeParameterList.mapNotNull { typeParameterText(it, it.bounds) }
val newElement = RsPsiFactory(project).createTypeParameterList(lifetimes + types)
val offset = typeParameterList.textRange.startOffset + newElement.textLength
typeParameterList.replace(newElement)
ctx.delete()
editor.caretModel.moveToOffset(offset)
}
private fun typeParameterText(param: RsNamedElement, bounds: List<RsElement>): String? {
val name = param.name ?: return null
val bs = bounds.distinctBy { it.text }
return buildString {
append(name)
if (bs.isNotEmpty()) {
append(bs.joinToString(separator = "+", prefix = ":") { it.text })
}
}
}
}
|
mit
|
8404e8cdadff9f8f5e8f97b99bc44321
| 40.966102 | 116 | 0.697092 | 5.063395 | false | false | false | false |
chenxyu/android-banner
|
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/Indicator.kt
|
1
|
4755
|
package com.chenxyu.bannerlibrary.indicator
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.chenxyu.bannerlibrary.extend.dpToPx
/**
* @Author: ChenXingYu
* @CreateDate: 2020/8/19 13:19
* @Description: 自定义指示器需继承此类
* @Version: 1.0
*/
abstract class Indicator {
/**
* 指示器是否重叠在Banner上
* 最下面或最右边根据方向决定
*/
var overlap: Boolean = true
/**
* 指示器布局的宽和高(DP)
* 宽和高根据方向决定
*/
var indicatorLayoutWH: Int = 20
/**
* 指示器的位置
*/
var indicatorGravity: Int = Gravity.CENTER
/**
* ViewPager2页面变化监听
*/
var mVp2PageChangeCallback: ViewPager2.OnPageChangeCallback? = null
/**
* RecyclerView滑动监听
*/
var mRvScrollListener: RecyclerView.OnScrollListener? = null
/**
* 是否循环
*/
var isLoop: Boolean = true
/**
* 添加OnPageChangeCallback
*/
abstract fun registerOnPageChangeCallback(viewPager2: ViewPager2?)
/**
* 删除OnPageChangeCallback
*/
fun unregisterOnPageChangeCallback(viewPager2: ViewPager2?) {
mVp2PageChangeCallback?.let {
viewPager2?.unregisterOnPageChangeCallback(it)
}
}
/**
* 添加OnScrollListener
*/
abstract fun addOnScrollListener(recyclerView: RecyclerView?)
/**
* 删除OnScrollListener
*/
fun removeScrollListener(recyclerView: RecyclerView?) {
mRvScrollListener?.let {
recyclerView?.removeOnScrollListener(it)
}
}
/**
* 设置指示器
* @param relativeLayout BannerView or BannerView2
* @param count 真实数量
* @param orientation 方向
* @param isLoop 是否循环
*/
fun initialize(relativeLayout: RelativeLayout, count: Int, orientation: Int, isLoop: Boolean = true) {
this.isLoop = isLoop
if (relativeLayout.childCount == 2) relativeLayout.removeViewAt(1)
if (relativeLayout.childCount > 2) throw RuntimeException("There can only be one child view")
val indicatorLayout = LinearLayout(relativeLayout.context).apply {
this.orientation = orientation
this.gravity = indicatorGravity
}
initIndicator(indicatorLayout, count, orientation)
when (orientation) {
RecyclerView.HORIZONTAL -> {
val layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
indicatorLayoutWH.dpToPx(relativeLayout.context))
if (overlap) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
} else {
val h = if (relativeLayout.layoutParams.height == -1) {
relativeLayout.context.resources.displayMetrics.heightPixels
} else {
relativeLayout.layoutParams.height
}
relativeLayout.getChildAt(0).layoutParams.height = h - indicatorLayoutWH.dpToPx(relativeLayout.context)
layoutParams.addRule(RelativeLayout.BELOW, relativeLayout.getChildAt(0).id)
}
relativeLayout.addView(indicatorLayout, layoutParams)
}
RecyclerView.VERTICAL -> {
val layoutParams = RelativeLayout.LayoutParams(
indicatorLayoutWH.dpToPx(relativeLayout.context),
RelativeLayout.LayoutParams.MATCH_PARENT)
if (overlap) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_END)
} else {
val w = if (relativeLayout.layoutParams.width == -1) {
relativeLayout.context.resources.displayMetrics.widthPixels
} else {
relativeLayout.layoutParams.width
}
relativeLayout.getChildAt(0).layoutParams.width = w - indicatorLayoutWH.dpToPx(relativeLayout.context)
layoutParams.addRule(RelativeLayout.END_OF, relativeLayout.getChildAt(0).id)
}
relativeLayout.addView(indicatorLayout, layoutParams)
}
}
}
/**
* 设置指示器
* @param container 指示器ViewGroup
* @param count 真实数量
* @param orientation 方向
*/
abstract fun initIndicator(container: LinearLayout, count: Int, orientation: Int)
}
|
mit
|
42abfdfcf8a4b50c41443eaf65e02b3a
| 31.869565 | 123 | 0.605292 | 5.005519 | false | false | false | false |
Deletescape-Media/Lawnchair
|
lawnchair/src/app/lawnchair/bugreport/BugReportReceiver.kt
|
1
|
7011
|
package app.lawnchair.bugreport
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.*
import android.graphics.drawable.Icon
import android.net.Uri
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
class BugReportReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val report = intent.getParcelableExtra<BugReport>("report")!!
when (intent.action) {
COPY_ACTION -> copyReport(context, report)
UPLOAD_ACTION -> startUpload(context, report)
UPLOAD_COMPLETE_ACTION -> notify(context, report)
}
}
private fun copyReport(context: Context, report: BugReport) {
val clipData = ClipData.newPlainText(context.getString(R.string.lawnchair_bug_report), report.link ?: report.contents)
context.getSystemService<ClipboardManager>()!!.setPrimaryClip(clipData)
Toast.makeText(context, R.string.copied_toast, Toast.LENGTH_LONG).show()
}
private fun startUpload(context: Context, report: BugReport) {
notify(context, report, true)
context.startService(Intent(context, UploaderService::class.java)
.putExtra("report", report))
}
companion object {
const val notificationChannelId = "${BuildConfig.APPLICATION_ID}.BugReport"
const val statusChannelId = "${BuildConfig.APPLICATION_ID}.status"
private const val GROUP_KEY = "${BuildConfig.APPLICATION_ID}.crashes"
private const val GROUP_ID = 0
private const val COPY_ACTION = "${BuildConfig.APPLICATION_ID}.bugreport.COPY"
private const val UPLOAD_ACTION = "${BuildConfig.APPLICATION_ID}.bugreport.UPLOAD"
const val UPLOAD_COMPLETE_ACTION = "${BuildConfig.APPLICATION_ID}.bugreport.UPLOAD_COMPLETE"
fun notify(context: Context, report: BugReport, uploading: Boolean = false) {
val manager = context.getSystemService<NotificationManager>()!!
val notificationId = report.notificationId
val builder = Notification.Builder(context, notificationChannelId)
.setContentTitle(report.getTitle(context))
.setContentText(report.description)
.setSmallIcon(R.drawable.ic_bug_notification)
.setColor(ContextCompat.getColor(context, R.color.bugNotificationColor))
.setOnlyAlertOnce(true)
.setGroup(GROUP_KEY)
.setShowWhen(true)
.setWhen(report.timestamp)
val count = manager.activeNotifications.filter { it.groupKey == GROUP_KEY }.count()
val summary = if (count > 99 || count < 0) {
context.getString(R.string.bugreport_group_summary_multiple)
} else {
context.getString(R.string.bugreport_group_summary, count)
}
val groupBuilder = Notification.Builder(context, notificationChannelId)
.setContentTitle(context.getString(R.string.bugreport_channel_name))
.setContentText(summary)
.setSmallIcon(R.drawable.ic_bug_notification)
.setColor(ContextCompat.getColor(context, R.color.bugNotificationColor))
.setStyle(Notification.InboxStyle()
.setBigContentTitle(summary)
.setSummaryText(context.getString(R.string.bugreport_channel_name)))
.setGroupSummary(true)
.setGroup(GROUP_KEY)
val fileUri = report.getFileUri(context)
if (report.link != null) {
val openIntent = Intent(Intent.ACTION_VIEW, Uri.parse(report.link))
val pendingOpenIntent = PendingIntent.getActivity(
context, notificationId, openIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
builder.setContentIntent(pendingOpenIntent)
} else if (fileUri != null) {
val openIntent = Intent(Intent.ACTION_VIEW)
.setDataAndType(fileUri, "text/plain")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val pendingOpenIntent = PendingIntent.getActivity(
context, notificationId, openIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
builder.setContentIntent(pendingOpenIntent)
}
val pendingShareIntent = PendingIntent.getActivity(
context, notificationId, report.createShareIntent(context), FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
val icon = Icon.createWithResource(context, R.drawable.ic_share)
val shareActionBuilder = Notification.Action.Builder(
icon, context.getString(R.string.action_share), pendingShareIntent)
builder.addAction(shareActionBuilder.build())
if (report.link != null || fileUri == null) {
val copyIntent = Intent(COPY_ACTION)
.setPackage(BuildConfig.APPLICATION_ID)
.putExtra("report", report)
val pendingCopyIntent = PendingIntent.getBroadcast(
context, notificationId, copyIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
val copyText = if (report.link != null) R.string.action_copy_link else R.string.action_copy
val copyIcon = Icon.createWithResource(context, R.drawable.ic_copy)
val copyActionBuilder = Notification.Action.Builder(
copyIcon, context.getString(copyText), pendingCopyIntent)
builder.addAction(copyActionBuilder.build())
}
if (uploading) {
builder.setOngoing(true)
builder.setProgress(0, 0, true)
} else if (report.link == null && UploaderUtils.isAvailable) {
val uploadIntent = Intent(UPLOAD_ACTION)
.setPackage(BuildConfig.APPLICATION_ID)
.putExtra("report", report)
val pendingUploadIntent = PendingIntent.getBroadcast(
context, notificationId, uploadIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
val uploadText = if (report.uploadError) R.string.action_upload_error else R.string.action_upload_crash_report
val uploadIcon = Icon.createWithResource(context, R.drawable.ic_upload)
val uploadActionBuilder = Notification.Action.Builder(
uploadIcon, context.getString(uploadText), pendingUploadIntent)
builder.addAction(uploadActionBuilder.build())
}
manager.notify(notificationId, builder.build())
manager.notify(GROUP_ID, groupBuilder.build())
}
}
}
|
gpl-3.0
|
382a1bb360e27c3e18016de5f522e2a3
| 50.551471 | 126 | 0.645985 | 5.000713 | false | true | false | false |
AllanWang/Frost-for-Facebook
|
app/src/main/kotlin/com/pitchedapps/frost/utils/Downloader.kt
|
1
|
3552
|
/*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.utils
import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.webkit.URLUtil
import androidx.core.content.getSystemService
import ca.allanwang.kau.permissions.PERMISSION_WRITE_EXTERNAL_STORAGE
import ca.allanwang.kau.permissions.kauRequestPermissions
import ca.allanwang.kau.utils.isAppEnabled
import ca.allanwang.kau.utils.materialDialog
import ca.allanwang.kau.utils.showAppInfo
import ca.allanwang.kau.utils.string
import ca.allanwang.kau.utils.toast
import com.pitchedapps.frost.R
import com.pitchedapps.frost.facebook.USER_AGENT
/**
* Created by Allan Wang on 2017-08-04.
*
* With reference to <a
* href="https://stackoverflow.com/questions/33434532/android-webview-download-files-like-browsers-do">Stack
* Overflow</a>
*/
fun Context.frostDownload(
cookie: String?,
url: String?,
userAgent: String = USER_AGENT,
contentDisposition: String? = null,
mimeType: String? = null,
contentLength: Long = 0L
) {
url ?: return
frostDownload(cookie, Uri.parse(url), userAgent, contentDisposition, mimeType, contentLength)
}
fun Context.frostDownload(
cookie: String?,
uri: Uri?,
userAgent: String = USER_AGENT,
contentDisposition: String? = null,
mimeType: String? = null,
contentLength: Long = 0L
) {
uri ?: return
L.d { "Received download request" }
if (uri.scheme != "http" && uri.scheme != "https") {
toast(R.string.error_invalid_download)
return L.e { "Invalid download $uri" }
}
val dm = getSystemService<DownloadManager>()
if (dm == null || !isAppEnabled(DOWNLOAD_MANAGER_PACKAGE)) {
materialDialog {
title(R.string.no_download_manager)
message(R.string.no_download_manager_desc)
positiveButton(R.string.kau_yes) { showAppInfo(DOWNLOAD_MANAGER_PACKAGE) }
negativeButton(R.string.kau_no)
}
return
}
kauRequestPermissions(PERMISSION_WRITE_EXTERNAL_STORAGE) { granted, _ ->
if (!granted) return@kauRequestPermissions
val request = DownloadManager.Request(uri)
request.setMimeType(mimeType)
val title = URLUtil.guessFileName(uri.toString(), contentDisposition, mimeType)
if (cookie != null) {
request.addRequestHeader("Cookie", cookie)
}
request.addRequestHeader("User-Agent", userAgent)
request.setDescription(string(R.string.downloading))
request.setTitle(title)
request.allowScanningByMediaScanner()
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Frost/$title")
try {
dm.enqueue(request)
} catch (e: Exception) {
toast(R.string.error_generic)
L.e(e) { "Download" }
}
}
}
private const val DOWNLOAD_MANAGER_PACKAGE = "com.android.providers.downloads"
|
gpl-3.0
|
e4b4d3442e50f5239e02516d98504739
| 34.168317 | 108 | 0.740146 | 3.955457 | false | false | false | false |
alygin/intellij-rust
|
src/main/kotlin/org/rust/ide/hints/RsParameterInfoHandler.kt
|
2
|
5682
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.hints
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.parameterInfo.*
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.rust.ide.utils.CallInfo
import org.rust.lang.core.psi.RsCallExpr
import org.rust.lang.core.psi.RsMethodCall
import org.rust.lang.core.psi.RsValueArgumentList
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.utils.buildList
/**
* Provides functions/methods arguments hint.
*/
class RsParameterInfoHandler : ParameterInfoHandler<PsiElement, RsArgumentsDescription> {
var hintText: String = ""
override fun couldShowInLookup() = true
override fun tracksParameterIndex() = true
override fun getParameterCloseChars() = ",)"
override fun getParametersForLookup(item: LookupElement, context: ParameterInfoContext?): Array<out Any>? {
val el = item.`object` as? PsiElement ?: return null
val p = el.parent?.parent ?: return null
val isCall = p is RsCallExpr && CallInfo.resolve(p) != null || p is RsMethodCall && CallInfo.resolve(p) != null
return if (isCall) arrayOf(p) else emptyArray()
}
override fun getParametersForDocumentation(p: RsArgumentsDescription, context: ParameterInfoContext?) =
p.arguments
override fun findElementForParameterInfo(context: CreateParameterInfoContext): PsiElement? {
val contextElement = context.file.findElementAt(context.editor.caretModel.offset) ?: return null
return findElementForParameterInfo(contextElement)
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext) =
context.file.findElementAt(context.editor.caretModel.offset)
override fun showParameterInfo(element: PsiElement, context: CreateParameterInfoContext) {
if (element !is RsValueArgumentList) return
val argsDescr = RsArgumentsDescription.findDescription(element) ?: return
context.itemsToShow = arrayOf(argsDescr)
context.showHint(element, element.textRange.startOffset, this)
}
override fun updateParameterInfo(place: PsiElement, context: UpdateParameterInfoContext) {
val argIndex = findArgumentIndex(place)
if (argIndex == INVALID_INDEX) {
context.removeHint()
return
}
context.setCurrentParameter(argIndex)
when {
context.parameterOwner == null -> context.parameterOwner = place
context.parameterOwner != findElementForParameterInfo(place) -> {
context.removeHint()
return
}
}
context.objectsToView.indices.map { context.setUIComponentEnabled(it, true) }
}
override fun updateUI(p: RsArgumentsDescription?, context: ParameterInfoUIContext) {
if (p == null) {
context.isUIComponentEnabled = false
return
}
val range = p.getArgumentRange(context.currentParameterIndex)
hintText = p.presentText
context.setupUIComponentPresentation(
hintText,
range.startOffset,
range.endOffset,
!context.isUIComponentEnabled,
false,
false,
context.defaultParameterColor)
}
private fun findElementForParameterInfo(contextElement: PsiElement) =
contextElement.parentOfType<RsValueArgumentList>()
/**
* Finds index of the argument in the given place
*/
private fun findArgumentIndex(place: PsiElement): Int {
val callArgs = place.parentOfType<RsValueArgumentList>() ?: return INVALID_INDEX
val descr = RsArgumentsDescription.findDescription(callArgs) ?: return INVALID_INDEX
var index = -1
if (descr.arguments.isNotEmpty()) {
index += generateSequence(callArgs.firstChild, { c -> c.nextSibling })
.filter { it.text == "," }
.count({ it.textRange.startOffset < place.textRange.startOffset }) + 1
if (index >= descr.arguments.size) {
index = -1
}
}
return index
}
private companion object {
val INVALID_INDEX: Int = -2
}
}
/**
* Holds information about arguments from func/method declaration
*/
class RsArgumentsDescription(
val arguments: Array<String>
) {
fun getArgumentRange(index: Int): TextRange {
if (index < 0 || index >= arguments.size) return TextRange.EMPTY_RANGE
val start = arguments.take(index).sumBy { it.length + 2 }
val range = TextRange(start, start + arguments[index].length)
return range
}
val presentText = if (arguments.isEmpty()) "<no arguments>" else arguments.joinToString(", ")
companion object {
/**
* Finds declaration of the func/method and creates description of its arguments
*/
fun findDescription(args: RsValueArgumentList): RsArgumentsDescription? {
val call = args.parent
val callInfo = when (call) {
is RsCallExpr -> CallInfo.resolve(call)
is RsMethodCall -> CallInfo.resolve(call)
else -> null
} ?: return null
val params = buildList<String> {
if (callInfo.selfParameter != null && call is RsCallExpr) {
add(callInfo.selfParameter)
}
addAll(callInfo.parameters.map { "${it.pattern}: ${it.type}" })
}
return RsArgumentsDescription(params.toTypedArray())
}
}
}
|
mit
|
b25644e326e36966ac3fcb0282f89cae
| 36.381579 | 119 | 0.655579 | 4.839864 | false | false | false | false |
charlesmadere/smash-ranks-android
|
smash-ranks-android/app/src/main/java/com/garpr/android/features/rankings/RankingItemView.kt
|
1
|
2988
|
package com.garpr.android.features.rankings
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.garpr.android.R
import com.garpr.android.data.models.AbsPlayer
import com.garpr.android.data.models.PreviousRank
import com.garpr.android.extensions.setTintedImageResource
import kotlinx.android.synthetic.main.item_ranking.view.*
class RankingItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs), View.OnClickListener, View.OnLongClickListener {
private var _player: AbsPlayer? = null
val player: AbsPlayer
get() = checkNotNull(_player)
private val originalBackground: Drawable? = background
@ColorInt
private val cardBackgroundColor: Int = ContextCompat.getColor(context, R.color.card_background)
@ColorInt
private val loseColor: Int = ContextCompat.getColor(context, R.color.lose)
@ColorInt
private val winColor: Int = ContextCompat.getColor(context, R.color.win)
var listeners: Listeners? = null
interface Listeners {
fun onClick(v: RankingItemView)
fun onLongClick(v: RankingItemView)
}
init {
setOnClickListener(this)
setOnLongClickListener(this)
}
override fun onClick(v: View) {
listeners?.onClick(this)
}
override fun onLongClick(v: View): Boolean {
listeners?.onLongClick(this)
return true
}
fun setContent(
player: AbsPlayer,
isIdentity: Boolean,
previousRank: PreviousRank,
rank: String?,
rating: String?
) {
_player = player
name.text = player.name
if (isIdentity) {
name.typeface = Typeface.DEFAULT_BOLD
setBackgroundColor(cardBackgroundColor)
} else {
name.typeface = Typeface.DEFAULT
ViewCompat.setBackground(this, originalBackground)
}
when (previousRank) {
PreviousRank.DECREASE -> {
previousRankView.setTintedImageResource(R.drawable.ic_arrow_downward_white_18dp, loseColor)
previousRankView.visibility = VISIBLE
}
PreviousRank.GONE -> {
previousRankView.visibility = GONE
}
PreviousRank.INCREASE -> {
previousRankView.setTintedImageResource(R.drawable.ic_arrow_upward_white_18dp, winColor)
previousRankView.visibility = VISIBLE
}
PreviousRank.INVISIBLE -> {
previousRankView.visibility = INVISIBLE
}
}
this.rank.text = rank
this.rating.text = rating
}
}
|
unlicense
|
525ef914dfb7b8b4b9fe99e0b3528b24
| 28.294118 | 107 | 0.662985 | 4.834951 | false | false | false | false |
Fitbit/MvRx
|
launcher/src/main/java/com/airbnb/mvrx/launcher/MavericksLauncherBaseFragment.kt
|
1
|
2873
|
package com.airbnb.mvrx.launcher
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import com.airbnb.epoxy.EpoxyController
import com.airbnb.epoxy.EpoxyRecyclerView
import com.airbnb.mvrx.MavericksView
/**
* Provides base UI (epoxy, toolbar, back handling) for fragments to extend.
*/
abstract class MavericksLauncherBaseFragment : Fragment(), MavericksView {
protected lateinit var recyclerView: EpoxyRecyclerView
protected lateinit var toolbar: Toolbar
protected lateinit var coordinatorLayout: CoordinatorLayout
protected val epoxyController by lazy { epoxyController() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
epoxyController.onRestoreInstanceState(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (!onBackPressed()) {
// Pass on back press to other listeners, or the activity's default handling
isEnabled = false
requireActivity().onBackPressed()
isEnabled = true
}
}
})
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.mavericks_fragment_base_launcher, container, false).apply {
recyclerView = findViewById(R.id.recycler_view)
toolbar = findViewById(R.id.toolbar)
coordinatorLayout = findViewById(R.id.coordinator_layout)
}
recyclerView.setController(epoxyController)
toolbar.setNavigationOnClickListener { activity?.onBackPressed() }
// We don't want a title shown. By default it adds "Mavericks"
activity?.title = ""
return view
}
protected open fun onBackPressed(): Boolean = false
override fun invalidate() {
recyclerView.requestModelBuild()
}
/**
* Provide the EpoxyController to use when building models for this Fragment.
* Basic usages can simply use [simpleController]
*/
abstract fun epoxyController(): EpoxyController
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
epoxyController.onSaveInstanceState(outState)
}
override fun onDestroyView() {
epoxyController.cancelPendingModelBuild()
super.onDestroyView()
}
}
|
apache-2.0
|
8a50ca323928dd8612d2432b9f645cc5
| 33.202381 | 104 | 0.68117 | 5.677866 | false | false | false | false |
http4k/http4k
|
http4k-client/websocket/src/main/kotlin/org/http4k/client/internal/internal.kt
|
1
|
3482
|
package org.http4k.client.internal
import org.http4k.core.Body
import org.http4k.core.Headers
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.StreamBody
import org.http4k.core.Uri
import org.http4k.websocket.PushPullAdaptingWebSocket
import org.http4k.websocket.WsClient
import org.http4k.websocket.WsConsumer
import org.http4k.websocket.WsMessage
import org.http4k.websocket.WsStatus
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.nio.ByteBuffer
import java.time.Duration
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.atomic.AtomicReference
class AdaptingWebSocket(uri: Uri, private val client: WebSocketClient) : PushPullAdaptingWebSocket(Request(Method.GET, uri)) {
override fun send(message: WsMessage) =
when (message.body) {
is StreamBody -> client.send(message.body.payload)
else -> client.send(message.bodyString())
}
override fun close(status: WsStatus) = client.close(status.code, status.description)
}
class BlockingQueueClient(uri: Uri, headers: Headers, timeout: Duration, draft: Draft, private val queue: LinkedBlockingQueue<() -> WsMessage?>) : WebSocketClient(URI.create(uri.toString()), draft, headers.combineToMap(), timeout.toMillis().toInt()) {
override fun onOpen(sh: ServerHandshake) {}
override fun onClose(code: Int, reason: String?, remote: Boolean) {
queue += { null }
}
override fun onMessage(message: String) {
queue += { WsMessage(message) }
}
override fun onMessage(bytes: ByteBuffer) {
queue += { WsMessage(Body(bytes.array().inputStream())) }
}
override fun onError(e: Exception): Unit = throw e
}
class NonBlockingClient(uri: Uri, headers: Headers, timeout: Duration, private val onConnect: WsConsumer, draft: Draft, private val socket: AtomicReference<PushPullAdaptingWebSocket>) : WebSocketClient(URI.create(uri.toString()), draft, headers.combineToMap(), timeout.toMillis().toInt()) {
override fun onOpen(handshakedata: ServerHandshake?) {
onConnect(socket.get())
}
override fun onClose(code: Int, reason: String, remote: Boolean) = socket.get().triggerClose(WsStatus(code, reason))
override fun onMessage(message: String) = socket.get().triggerMessage(WsMessage(message))
override fun onMessage(bytes: ByteBuffer) = socket.get().triggerMessage(WsMessage(Body(bytes.array().inputStream())))
override fun onError(e: Exception) = socket.get().triggerError(e)
}
class BlockingWsClient(private val queue: LinkedBlockingQueue<() -> WsMessage?>, private val client: BlockingQueueClient, private val autoReconnection: Boolean) : WsClient {
override fun received() = generateSequence { queue.take()() }
override fun close(status: WsStatus) = client.close(status.code, status.description)
override fun send(message: WsMessage) {
if (autoReconnection && (client.isClosing || client.isClosed)) {
client.closeBlocking() // ensure it's closed
client.reconnectBlocking()
}
return when (message.body) {
is StreamBody -> client.send(message.body.payload)
else -> client.send(message.bodyString())
}
}
}
private fun Headers.combineToMap() = groupBy { it.first }.mapValues { it.value.map { it.second }.joinToString(", ") }
|
apache-2.0
|
fd4b301b36e49e6884dc7e1d7b221e17
| 40.951807 | 290 | 0.72602 | 4.025434 | false | false | false | false |
openMF/android-client
|
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/groupslist/GroupsListFragment.kt
|
1
|
14636
|
/*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.groupslist
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.*
import android.widget.ProgressBar
import androidx.appcompat.view.ActionMode
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.adapters.GroupNameListAdapter
import com.mifos.mifosxdroid.core.EndlessRecyclerViewScrollListener
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.dialogfragments.syncgroupsdialog.SyncGroupsDialogFragment
import com.mifos.mifosxdroid.online.GroupsActivity
import com.mifos.mifosxdroid.online.createnewgroup.CreateNewGroupFragment
import com.mifos.objects.group.Group
import com.mifos.utils.Constants
import com.mifos.utils.FragmentConstants
import java.util.*
import javax.inject.Inject
/**
* Created by nellyk on 2/27/2016.
*
*
* This class loading and showing groups, Here is two way to load the Groups. First one to load
* Groups from Rest API
*
*
* >demo.openmf.org/fineract-provider/api/v1/groups?paged=true&offset=offset_value&limit
* =limit_value>
*
*
* Offset : From Where index, Groups will be fetch.
* limit : Total number of client, need to fetch
*
*
* and showing in the GroupList.
*
*
* and Second one is showing Groups provided by Parent(Fragment or Activity).
* Parent(Fragment or Activity) load the GroupList and send the
* Groups to GroupsListFragment newInstance(List<Group> groupList,
* boolean isParentFragment) {...}
* and unregister the ScrollListener and SwipeLayout.
</Group> */
class GroupsListFragment : MifosBaseFragment(), GroupsListMvpView, OnRefreshListener {
@JvmField
@BindView(R.id.rv_groups)
var rv_groups: RecyclerView? = null
@JvmField
@BindView(R.id.progressbar_group)
var pb_groups: ProgressBar? = null
@JvmField
@BindView(R.id.swipe_container)
var swipeRefreshLayout: SwipeRefreshLayout? = null
@JvmField
@BindView(R.id.layout_error)
var errorView: View? = null
@JvmField
@Inject
var mGroupsListPresenter: GroupsListPresenter? = null
val mGroupListAdapter by lazy {
GroupNameListAdapter(
onGroupClick = { position ->
if (actionMode != null) {
toggleSelection(position)
} else {
val groupActivityIntent = Intent(activity, GroupsActivity::class.java)
groupActivityIntent.putExtra(Constants.GROUP_ID, mGroupList!![position].id)
startActivity(groupActivityIntent)
}
},
onGroupLongClick = { position ->
if (actionMode == null) {
actionMode = (activity as MifosBaseActivity?)!!.startSupportActionMode(actionModeCallback!!)
}
toggleSelection(position)
}
)
}
var mLayoutManager: LinearLayoutManager? = null
private var mGroupList: List<Group>? = null
private var selectedGroups: MutableList<Group>? = null
private var isParentFragment = false
private lateinit var rootView: View
private var actionModeCallback: ActionModeCallback? = null
private var actionMode: ActionMode? = null
private var sweetUIErrorHandler: SweetUIErrorHandler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
mGroupList = ArrayList()
selectedGroups = ArrayList()
actionModeCallback = ActionModeCallback()
if (arguments != null) {
mGroupList = requireArguments().getParcelableArrayList(Constants.GROUPS)
isParentFragment = requireArguments()
.getBoolean(Constants.IS_A_PARENT_FRAGMENT)
}
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_groups, container, false)
ButterKnife.bind(this, rootView)
mGroupsListPresenter!!.attachView(this)
//setting all the UI content to the view
showUserInterface()
/**
* This is the LoadMore of the RecyclerView. It called When Last Element of RecyclerView
* is shown on the Screen.
*/
rv_groups!!.addOnScrollListener(object : EndlessRecyclerViewScrollListener(mLayoutManager) {
override fun onLoadMore(page: Int, totalItemsCount: Int) {
mGroupsListPresenter!!.loadGroups(true, totalItemsCount)
}
})
/**
* First Check the Parent Fragment is true or false. If parent fragment is true then no
* need to fetch groupList from Rest API, just need to show parent fragment groupList
* and if Parent Fragment is false then Presenter make the call to Rest API and fetch the
* Group List to show. and Presenter make transaction to Database to load saved clients.
* To show user that is there already any group is synced already or not.
*/
if (isParentFragment) {
mGroupList?.let { mGroupsListPresenter!!.showParentClients(it) }
} else {
mGroupsListPresenter!!.loadGroups(false, 0)
}
mGroupsListPresenter!!.loadDatabaseGroups()
return rootView
}
/**
* This method Initializing the UI.
*/
override fun showUserInterface() {
setToolbarTitle(resources.getString(R.string.groups))
mLayoutManager = LinearLayoutManager(activity)
mLayoutManager!!.orientation = LinearLayoutManager.VERTICAL
rv_groups!!.layoutManager = mLayoutManager
rv_groups!!.setHasFixedSize(true)
rv_groups!!.adapter = mGroupListAdapter
swipeRefreshLayout!!.setColorSchemeColors(*activity
?.getResources()!!.getIntArray(R.array.swipeRefreshColors))
swipeRefreshLayout!!.setOnRefreshListener(this)
sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView)
}
@OnClick(R.id.fab_create_group)
fun onClickCreateNewGroup() {
(activity as MifosBaseActivity?)!!.replaceFragment(CreateNewGroupFragment.newInstance(),
true, R.id.container_a)
}
/**
* This Method will be called. Whenever user will swipe down to refresh the group list.
*/
override fun onRefresh() {
mGroupsListPresenter!!.loadGroups(false, 0)
mGroupsListPresenter!!.loadDatabaseGroups()
if (actionMode != null) actionMode!!.finish()
}
/**
* This method will be called, whenever first time error occurred during the fetching group
* list from REST API.
* As the error will occurred. user is able to see the error message and ability to reload
* groupList.
*/
@OnClick(R.id.btn_try_again)
fun reloadOnError() {
sweetUIErrorHandler!!.hideSweetErrorLayoutUI(rv_groups, errorView)
mGroupsListPresenter!!.loadGroups(false, 0)
mGroupsListPresenter!!.loadDatabaseGroups()
}
/**
* Setting GroupList to the Adapter and updating the Adapter.
*/
override fun showGroups(groups: List<Group?>?) {
mGroupList = groups as List<Group>?
Collections.sort(mGroupList) { grp1, grp2 -> grp1.name.compareTo(grp2.name) }
mGroupListAdapter!!.setGroups(mGroupList ?: emptyList())
}
/**
* Adding the More Groups in List and Update the Adapter.
*
* @param groups
*/
override fun showLoadMoreGroups(clients: List<Group?>?) {
mGroupList.addAll()
mGroupListAdapter!!.notifyDataSetChanged()
}
/**
* This method will be called, if fetched groupList is Empty and show there is no Group to show.
*
* @param message String Message.
*/
override fun showEmptyGroups(message: Int) {
sweetUIErrorHandler!!.showSweetEmptyUI(getString(R.string.group), getString(message),
R.drawable.ic_error_black_24dp, rv_groups, errorView)
}
/**
* This Method unregistered the SwipeLayout and OnScrollListener
*/
override fun unregisterSwipeAndScrollListener() {
rv_groups!!.clearOnScrollListeners()
swipeRefreshLayout!!.isEnabled = false
}
/**
* This Method showing the Simple Taster Message to user.
*
* @param message String Message to show.
*/
override fun showMessage(message: Int) {
Toaster.show(rootView, getStringMessage(message))
}
/**
* If Any any exception occurred during fetching the Groups. like No Internet or etc.
* then this method show the error message to user and give the ability to refresh groups.
*/
override fun showFetchingError() {
val errorMessage = getStringMessage(R.string.failed_to_fetch_groups)
sweetUIErrorHandler!!.showSweetErrorUI(errorMessage,
R.drawable.ic_error_black_24dp, rv_groups, errorView)
}
/**
* This Method showing the Progressbar during fetching the group List on first time and
* otherwise showing swipe refresh layout
*
* @param show Status of Progressbar or SwipeRefreshLayout
*/
override fun showProgressbar(show: Boolean) {
swipeRefreshLayout!!.isRefreshing = show
if (show && mGroupListAdapter!!.itemCount == 0) {
pb_groups!!.visibility = View.VISIBLE
swipeRefreshLayout!!.isRefreshing = false
} else {
pb_groups!!.visibility = View.GONE
}
}
override fun onDestroyView() {
super.onDestroyView()
mGroupsListPresenter!!.detachView()
//As the Fragment Detach Finish the ActionMode
if (actionMode != null) actionMode!!.finish()
}
/**
* Toggle the selection state of an item.
*
*
* If the item was the last one in the selection and is unselected, then selection will stopped.
* Note that the selection must already be started (actionMode must not be null).
*
* @param position Position of the item to toggle the selection state
*/
private fun toggleSelection(position: Int) {
mGroupListAdapter!!.toggleSelection(position)
val count = mGroupListAdapter!!.selectedItemCount
if (count == 0) {
actionMode!!.finish()
} else {
actionMode!!.title = count.toString()
actionMode!!.invalidate()
}
}
/**
* This ActionModeCallBack Class handling the User Event after the Selection of Clients. Like
* Click of Menu Sync Button and finish the ActionMode
*/
private inner class ActionModeCallback : ActionMode.Callback {
private val LOG_TAG = ActionModeCallback::class.java.simpleName
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.menu_sync, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_sync -> {
selectedGroups!!.clear()
for (position in mGroupListAdapter!!.selectedItems) {
selectedGroups!!.add(mGroupList!![position!!])
}
val syncGroupsDialogFragment = SyncGroupsDialogFragment.newInstance(selectedGroups)
val fragmentTransaction = activity
?.getSupportFragmentManager()!!.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_GROUP_SYNC)
syncGroupsDialogFragment.isCancelable = false
syncGroupsDialogFragment.show(fragmentTransaction,
resources.getString(R.string.sync_groups))
mode.finish()
true
}
else -> false
}
}
override fun onDestroyActionMode(mode: ActionMode) {
mGroupListAdapter!!.clearSelection()
actionMode = null
}
}
companion object {
/**
* This Method will be called, whenever isParentFragment will be true
* and Presenter do not need to make Rest API call to server. Parent (Fragment or Activity)
* already fetched the groups and for showing, they call GroupsListFragment.
*
*
* Example : Showing Parent Groups.
*
* @param groupList List<Group>
* @param isParentFragment true
* @return GroupsListFragment
</Group> */
@JvmStatic
fun newInstance(groupList: List<Group?>?,
isParentFragment: Boolean): GroupsListFragment {
val groupListFragment = GroupsListFragment()
val args = Bundle()
if (isParentFragment && groupList != null) {
args.putParcelableArrayList(Constants.GROUPS,
groupList as ArrayList<out Parcelable?>?)
args.putBoolean(Constants.IS_A_PARENT_FRAGMENT, true)
groupListFragment.arguments = args
}
return groupListFragment
}
/**
* This method will be called, whenever GroupsListFragment will not have Parent Fragment.
* So, Presenter make the call to Rest API and fetch the Client List and show in UI
*
* @return GroupsListFragment
*/
@JvmStatic
fun newInstance(): GroupsListFragment {
val arguments = Bundle()
val groupListFragment = GroupsListFragment()
groupListFragment.arguments = arguments
return groupListFragment
}
}
}
private fun <E> List<E>?.addAll() {
}
|
mpl-2.0
|
6aa17e5f8a198a5c474acbdb3d4858c3
| 36.917098 | 116 | 0.654619 | 5.121064 | false | false | false | false |
msebire/intellij-community
|
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt
|
1
|
15577
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.LineSeparator
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.diff.Diff
import org.jetbrains.jps.model.JpsSimpleElement
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.*
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
data class ModifiedClass(val module: JpsModule, val file: Path, val result: CharSequence)
class IconsClassGenerator(private val projectHome: File, val util: JpsModule, private val writeChangesToDisk: Boolean = true) {
private val processedClasses = AtomicInteger()
private val processedIcons = AtomicInteger()
private val processedPhantom = AtomicInteger()
private val modifiedClasses = ContainerUtil.createConcurrentList<ModifiedClass>()
private val obsoleteClasses = ContainerUtil.createConcurrentList<Path>()
fun processModule(module: JpsModule) {
val customLoad: Boolean
val packageName: String
val className: String
val outFile: Path
if ("intellij.platform.icons" == module.name) {
customLoad = false
packageName = "com.intellij.icons"
className = "AllIcons"
val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons"
outFile = Paths.get(dir, "AllIcons.java")
}
else if ("intellij.android.artwork" == module.name) {
// backward compatibility - AndroidIcons class should be not modified
packageName = "icons"
customLoad = true
className = "AndroidArtworkIcons"
val dir = module.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath
outFile = Paths.get(dir, "icons", "AndroidArtworkIcons.java")
}
else {
customLoad = true
packageName = "icons"
val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() ?: return
val firstRootDir = firstRoot.file.toPath().resolve("icons")
var oldClassName: String?
// this is added to remove unneeded empty directories created by previous version of this script
if (Files.isDirectory(firstRootDir)) {
try {
Files.delete(firstRootDir)
println("deleting empty directory $firstRootDir")
}
catch (ignore: DirectoryNotEmptyException) {
}
oldClassName = findIconClass(firstRootDir)
}
else {
oldClassName = null
}
val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources }
val targetRoot = (generatedRoot ?: firstRoot).file.toPath().resolve("icons")
if (generatedRoot != null && oldClassName != null) {
val oldFile = firstRootDir.resolve("$oldClassName.java")
println("deleting $oldFile from source root which isn't marked as 'generated'")
Files.delete(oldFile)
}
if (oldClassName == null) {
try {
oldClassName = findIconClass(targetRoot)
}
catch (ignored: NoSuchFileException) {
}
}
className = oldClassName ?: directoryName(module) + "Icons"
outFile = targetRoot.resolve("$className.java")
}
val oldText = try {
Files.readAllBytes(outFile).toString(StandardCharsets.UTF_8)
}
catch (ignored: NoSuchFileException) {
null
}
val newText = generate(module, className, packageName, customLoad, getCopyrightComment(oldText))
val oldLines = oldText?.lines() ?: emptyList()
val newLines = newText?.lines() ?: emptyList()
if (newLines.isNotEmpty()) {
processedClasses.incrementAndGet()
if (oldLines != newLines) {
if (writeChangesToDisk) {
val separator = getSeparators(oldText)
Files.createDirectories(outFile.parent)
Files.write(outFile, newLines.joinToString(separator = separator.separatorString).toByteArray())
println("Updated icons class: ${outFile.fileName}")
}
else {
val sb = StringBuilder()
var ch = Diff.buildChanges(oldLines.toTypedArray(), newLines.toTypedArray())
while (ch != null) {
val deleted = oldLines.subList(ch.line0, ch.line0 + ch.deleted)
val inserted = newLines.subList(ch.line1, ch.line1 + ch.inserted)
if (sb.isNotEmpty()) sb.append("=".repeat(20)).append("\n")
deleted.forEach { sb.append("-").append(it).append("\n") }
inserted.forEach { sb.append("+").append(it).append("\n") }
ch = ch.link
}
modifiedClasses.add(ModifiedClass(module, outFile, sb))
}
}
}
else {
if (Files.exists(outFile)) {
obsoleteClasses.add(outFile)
}
}
}
fun printStats() {
println()
println("Generated classes: ${processedClasses.get()}. Processed icons: ${processedIcons.get()}. Phantom icons: ${processedPhantom.get()}")
if (obsoleteClasses.isNotEmpty()) {
println("\nObsolete classes:")
println(obsoleteClasses.joinToString("\n"))
println("\nObsolete class it is class for icons that cannot be found anymore. Possible reasons:")
println("1. Icons not located under resources root.\n Solution - move icons to resources root or fix existing root type (must be \"resources\")")
println("2. Icons were removed but not class.\n Solution - remove class.")
println("3. Icons located under resources root named \"compatibilityResources\". \"compatibilityResources\" for icons that not used externally as icon class fields, " +
"but maybe referenced directly by path.\n Solution - remove class or move icons to another resources root")
}
}
fun getModifiedClasses(): List<ModifiedClass> = modifiedClasses
private fun findIconClass(dir: Path): String? {
if (!dir.toFile().exists()) return null
Files.newDirectoryStream(dir).use { stream ->
for (it in stream) {
val name = it.fileName.toString()
if (name.endsWith("Icons.java")) {
return name.substring(0, name.length - ".java".length)
}
}
}
return null
}
private fun getCopyrightComment(text: String?): String {
if (text == null) return ""
val i = text.indexOf("package ")
if (i == -1) return ""
val comment = text.substring(0, i)
return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else ""
}
private fun getSeparators(text: String?): LineSeparator {
if (text == null) return LineSeparator.LF
return StringUtil.detectSeparators(text) ?: LineSeparator.LF
}
private fun generate(module: JpsModule, className: String, packageName: String, customLoad: Boolean, copyrightComment: String): String? {
val imageCollector = ImageCollector(projectHome.toPath(), iconsOnly = true, className = className)
val images = imageCollector.collect(module, includePhantom = true)
if (images.isEmpty()) {
return null
}
imageCollector.printUsedIconRobots()
val answer = StringBuilder()
answer.append(copyrightComment)
append(answer, "package $packageName;\n", 0)
append(answer, "import com.intellij.openapi.util.IconLoader;", 0)
append(answer, "", 0)
append(answer, "import javax.swing.*;", 0)
append(answer, "", 0)
// IconsGeneratedSourcesFilter depends on following comment, if you going to change the text
// please do corresponding changes in IconsGeneratedSourcesFilter as well
append(answer, "/**", 0)
append(answer, " * NOTE THIS FILE IS AUTO-GENERATED", 0)
append(answer, " * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead", 0)
append(answer, " */", 0)
answer.append("public")
// backward compatibility
if (className != "AllIcons") {
answer.append(" final")
}
answer.append(" class ").append(className).append(" {\n")
if (customLoad) {
append(answer, "private static Icon load(String path) {", 1)
append(answer, "return IconLoader.getIcon(path, ${className}.class);", 2)
append(answer, "}", 1)
append(answer, "", 0)
val customExternalLoad = images.any { it.deprecation?.replacementContextClazz != null }
if (customExternalLoad) {
append(answer, "private static Icon load(String path, Class<?> clazz) {", 1)
append(answer, "return IconLoader.getIcon(path, clazz);", 2)
append(answer, "}", 1)
append(answer, "", 0)
}
}
val inners = StringBuilder()
processIcons(images, inners, customLoad, 0)
if (inners.isEmpty()) return null
answer.append(inners)
append(answer, "}", 0)
return answer.toString()
}
private fun processIcons(images: List<ImagePaths>, answer: StringBuilder, customLoad: Boolean, depth: Int) {
val level = depth + 1
val (nodes, leafs) = images.partition { getImageId(it, depth).contains('/') }
val nodeMap = nodes.groupBy { getImageId(it, depth).substringBefore('/') }
val leafMap = ContainerUtil.newMapFromValues(leafs.iterator()) { getImageId(it, depth) }
fun getWeight(key: String): Int {
val image = leafMap[key]
if (image == null) {
return 0
}
return if (image.deprecated) 1 else 0
}
val sortedKeys = (nodeMap.keys + leafMap.keys)
.sortedWith(NAME_COMPARATOR)
.sortedWith(kotlin.Comparator(function = { o1, o2 ->
getWeight(o1) - getWeight(o2)
}))
for (key in sortedKeys) {
val group = nodeMap[key]
val image = leafMap[key]
if (group != null) {
val inners = StringBuilder()
processIcons(group, inners, customLoad, depth + 1)
if (inners.isNotEmpty()) {
append(answer, "", level)
append(answer, "public final static class " + className(key) + " {", level)
append(answer, inners.toString(), 0)
append(answer, "}", level)
}
}
if (image != null) {
appendImage(image, answer, level, customLoad)
}
}
}
private fun appendImage(image: ImagePaths,
answer: StringBuilder,
level: Int,
customLoad: Boolean) {
val file = image.file ?: return
if (!image.phantom && !isIcon(file)) {
return
}
processedIcons.incrementAndGet()
if (image.phantom) {
processedPhantom.incrementAndGet()
}
if (image.used || image.deprecated) {
val deprecationComment = image.deprecation?.comment
append(answer, "", level)
if (deprecationComment != null) {
append(answer, "/** @deprecated $deprecationComment */", level)
}
append(answer, "@SuppressWarnings(\"unused\")", level)
}
if (image.deprecated) {
append(answer, "@Deprecated", level)
}
val sourceRoot = image.sourceRoot
var rootPrefix = "/"
if (sourceRoot.rootType == JavaSourceRootType.SOURCE) {
@Suppress("UNCHECKED_CAST")
val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix
if (!packagePrefix.isEmpty()) {
rootPrefix += packagePrefix.replace('.', '/') + "/"
}
}
val iconName = iconName(file)
val deprecation = image.deprecation
if (deprecation?.replacementContextClazz != null) {
val method = if (customLoad) "load" else "IconLoader.getIcon"
append(answer,
"public static final Icon $iconName = $method(\"${deprecation.replacement}\", ${deprecation.replacementContextClazz}.class);",
level)
return
}
else if (deprecation?.replacementReference != null) {
append(answer, "public static final Icon $iconName = ${deprecation.replacementReference};", level)
return
}
val sourceRootFile = Paths.get(JpsPathUtil.urlToPath(sourceRoot.url))
val imageFile: Path
if (deprecation?.replacement == null) {
imageFile = file
}
else {
imageFile = sourceRootFile.resolve(deprecation.replacement.removePrefix("/").removePrefix(File.separator))
assert(isIcon(imageFile)) { "Overriding icon should be valid: $iconName - $imageFile" }
}
val size = if (imageFile.toFile().exists()) imageSize(imageFile) else null
if (size != null) {
append(answer, "/**", level)
append(answer, " * ${size.width}x${size.height}", level)
append(answer, " */", level)
}
else if (!image.phantom) error("Can't get icon size: $imageFile")
val method = if (customLoad) "load" else "IconLoader.getIcon"
val relativePath = rootPrefix + FileUtilRt.toSystemIndependentName(sourceRootFile.relativize(imageFile).toString())
append(answer, "public static final Icon $iconName = $method(\"$relativePath\");", level)
}
private fun append(answer: StringBuilder, text: String, level: Int) {
if (text.isNotBlank()) {
for (i in 0 until level) {
answer.append(" ")
}
}
answer.append(text).append('\n')
}
private fun getImageId(image: ImagePaths, depth: Int): String {
val path = image.id.removePrefix("/").split("/")
if (path.size < depth) {
throw IllegalArgumentException("Can't get image ID - ${image.id}, $depth")
}
return path.drop(depth).joinToString("/")
}
private fun directoryName(module: JpsModule): String {
return directoryNameFromConfig(module) ?: className(module.name)
}
private fun directoryNameFromConfig(module: JpsModule): String? {
val rootUrl = getFirstContentRootUrl(module) ?: return null
val rootDir = File(JpsPathUtil.urlToPath(rootUrl))
if (!rootDir.isDirectory) return null
val file = File(rootDir, ROBOTS_FILE_NAME)
if (!file.exists()) return null
val prefix = "name:"
var moduleName: String? = null
file.forEachLine {
if (it.startsWith(prefix)) {
val name = it.substring(prefix.length).trim()
if (name.isNotEmpty()) moduleName = name
}
}
return moduleName
}
private fun getFirstContentRootUrl(module: JpsModule): String? {
return module.contentRootsList.urls.firstOrNull()
}
private fun className(name: String): String {
val answer = StringBuilder()
name.removePrefix("intellij.").split("-", "_", ".").forEach {
answer.append(capitalize(it))
}
return toJavaIdentifier(answer.toString())
}
private fun iconName(file: Path): String {
val name = capitalize(file.fileName.toString().substringBeforeLast('.'))
return toJavaIdentifier(name)
}
private fun toJavaIdentifier(id: String): String {
val sb = StringBuilder()
id.forEach {
if (Character.isJavaIdentifierPart(it)) {
sb.append(it)
}
else {
sb.append('_')
}
}
if (Character.isJavaIdentifierStart(sb.first())) {
return sb.toString()
}
else {
return "_" + sb.toString()
}
}
private fun capitalize(name: String): String {
if (name.length == 2) return name.toUpperCase()
return name.capitalize()
}
// legacy ordering
private val NAME_COMPARATOR: Comparator<String> = compareBy { it.toLowerCase() + "." }
}
|
apache-2.0
|
87d6ca7227d7e23633f09094b218e15a
| 34.727064 | 174 | 0.653463 | 4.424027 | false | false | false | false |
TangHao1987/intellij-community
|
platform/configuration-store-impl/src/FileBasedStorage.kt
|
2
|
5808
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.FileStorage
import com.intellij.openapi.components.impl.stores.StateMap
import com.intellij.openapi.components.impl.stores.StorageUtil
import com.intellij.openapi.components.impl.stores.StreamProvider
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import org.jdom.Element
import org.jdom.JDOMException
import java.io.File
import java.io.IOException
import java.nio.ByteBuffer
open class FileBasedStorage(private volatile var file: File,
fileSpec: String,
rootElementName: String,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider), FileStorage {
private volatile var cachedVirtualFile: VirtualFile? = null
private var lineSeparator: LineSeparator? = null
private var blockSavingTheContent = false
init {
if (ApplicationManager.getApplication().isUnitTestMode() && file.getPath().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog: Boolean = false
// we never set io file to null
override fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: File?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (!storage.blockSavingTheContent) {
super.save()
}
}
override fun saveLocally(element: Element?) {
if (storage.lineSeparator == null) {
storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
}
val virtualFile = storage.getVirtualFile()
if (element == null) {
StorageUtil.deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else {
storage.cachedVirtualFile = StorageUtil.writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog)
}
}
}
override fun getVirtualFile(): VirtualFile? {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByIoFile(file)
cachedVirtualFile = result
}
return cachedVirtualFile
}
override fun getFile() = file
override fun loadLocalData(): Element? {
blockSavingTheContent = false
try {
val file = getVirtualFile()
if (file == null || file.isDirectory() || !file.isValid()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Document was not loaded for $fileSpec file is ${if (file == null) "null" else "directory"}")
}
}
else if (file.getLength() == 0L) {
processReadException(null)
}
else {
val charBuffer = CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(file.contentsToByteArray()))
lineSeparator = StorageUtil.detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF)
return JDOMUtil.loadDocument(charBuffer).detachRootElement()
}
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
private fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated && (StorageUtil.isProjectOrModuleFile(fileSpec) || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (!ApplicationManager.getApplication().isUnitTestMode() && !ApplicationManager.getApplication().isHeadlessEnvironment()) {
if (e != null) {
LOG.info(e)
}
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.getMessage()}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING).notify(null)
}
}
override fun toString() = file.systemIndependentPath
}
|
apache-2.0
|
83b95d0b36ff055fa557200079fa7100
| 39.901408 | 327 | 0.72228 | 4.917866 | false | false | false | false |
android/media-samples
|
PictureInPictureKotlin/app/src/main/java/com/example/android/pictureinpicture/widget/MovieView.kt
|
1
|
14511
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.pictureinpicture.widget
import android.content.Context
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.transition.TransitionManager
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageButton
import android.widget.RelativeLayout
import androidx.annotation.RawRes
import com.example.android.pictureinpicture.R
import java.io.IOException
import java.lang.ref.WeakReference
/**
* Provides video playback. There is nothing directly related to Picture-in-Picture here.
*
* This is similar to [android.widget.VideoView], but it comes with a custom control
* (play/pause, fast forward, and fast rewind).
*/
class MovieView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
companion object {
private const val TAG = "MovieView"
/** The amount of time we are stepping forward or backward for fast-forward and fast-rewind. */
private const val FAST_FORWARD_REWIND_INTERVAL = 5000 // ms
/** The amount of time until we fade out the controls. */
private const val TIMEOUT_CONTROLS = 3000L // ms
}
/**
* Monitors all events related to [MovieView].
*/
abstract class MovieListener {
/**
* Called when the video is started or resumed.
*/
open fun onMovieStarted() {}
/**
* Called when the video is paused or finished.
*/
open fun onMovieStopped() {}
/**
* Called when this view should be minimized.
*/
open fun onMovieMinimized() {}
}
/** Shows the video playback. */
private val surfaceView: SurfaceView
// Controls
private val toggle: ImageButton
private val shade: View
private val fastForward: ImageButton
private val fastRewind: ImageButton
private val minimize: ImageButton
/** This plays the video. This will be null when no video is set. */
internal var mediaPlayer: MediaPlayer? = null
/** The resource ID for the video to play. */
@RawRes
private var videoResourceId: Int = 0
var title: String = ""
/** Whether we adjust our view bounds or we fill the remaining area with black bars */
private var adjustViewBounds: Boolean = false
/** Handles timeout for media controls. */
private var timeoutHandler: TimeoutHandler? = null
/** The listener for all the events we publish. */
private var movieListener: MovieListener? = null
private var savedCurrentPosition: Int = 0
init {
setBackgroundColor(Color.BLACK)
// Inflate the content
View.inflate(context, R.layout.view_movie, this)
surfaceView = findViewById(R.id.surface)
shade = findViewById(R.id.shade)
toggle = findViewById(R.id.toggle)
fastForward = findViewById(R.id.fast_forward)
fastRewind = findViewById(R.id.fast_rewind)
minimize = findViewById(R.id.minimize)
// Attributes
val a = context.obtainStyledAttributes(attrs, R.styleable.MovieView,
defStyleAttr, R.style.Widget_PictureInPicture_MovieView)
setVideoResourceId(a.getResourceId(R.styleable.MovieView_android_src, 0))
setAdjustViewBounds(a.getBoolean(R.styleable.MovieView_android_adjustViewBounds, false))
title = a.getString(R.styleable.MovieView_android_title) ?: ""
a.recycle()
// Bind view events
val listener = OnClickListener { view ->
when (view.id) {
R.id.surface -> toggleControls()
R.id.toggle -> toggle()
R.id.fast_forward -> fastForward()
R.id.fast_rewind -> fastRewind()
R.id.minimize -> movieListener?.onMovieMinimized()
}
// Start or reset the timeout to hide controls
mediaPlayer?.let { player ->
if (timeoutHandler == null) {
timeoutHandler = TimeoutHandler(this@MovieView)
}
timeoutHandler?.let { handler ->
handler.removeMessages(TimeoutHandler.MESSAGE_HIDE_CONTROLS)
if (player.isPlaying) {
handler.sendEmptyMessageDelayed(TimeoutHandler.MESSAGE_HIDE_CONTROLS,
TIMEOUT_CONTROLS)
}
}
}
}
surfaceView.setOnClickListener(listener)
toggle.setOnClickListener(listener)
fastForward.setOnClickListener(listener)
fastRewind.setOnClickListener(listener)
minimize.setOnClickListener(listener)
// Prepare video playback
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
openVideo(holder.surface)
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int,
width: Int, height: Int) {
// Do nothing
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
mediaPlayer?.let { savedCurrentPosition = it.currentPosition }
closeVideo()
}
})
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
mediaPlayer?.let { player ->
val videoWidth = player.videoWidth
val videoHeight = player.videoHeight
if (videoWidth != 0 && videoHeight != 0) {
val aspectRatio = videoHeight.toFloat() / videoWidth
val width = MeasureSpec.getSize(widthMeasureSpec)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
if (adjustViewBounds) {
if (widthMode == MeasureSpec.EXACTLY
&& heightMode != MeasureSpec.EXACTLY) {
super.onMeasure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec((width * aspectRatio).toInt(),
MeasureSpec.EXACTLY))
} else if (widthMode != MeasureSpec.EXACTLY
&& heightMode == MeasureSpec.EXACTLY) {
super.onMeasure(MeasureSpec.makeMeasureSpec((height / aspectRatio).toInt(),
MeasureSpec.EXACTLY), heightMeasureSpec)
} else {
super.onMeasure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec((width * aspectRatio).toInt(),
MeasureSpec.EXACTLY))
}
} else {
val viewRatio = height.toFloat() / width
if (aspectRatio > viewRatio) {
val padding = ((width - height / aspectRatio) / 2).toInt()
setPadding(padding, 0, padding, 0)
} else {
val padding = ((height - width * aspectRatio) / 2).toInt()
setPadding(0, padding, 0, padding)
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
return
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onDetachedFromWindow() {
timeoutHandler?.removeMessages(TimeoutHandler.MESSAGE_HIDE_CONTROLS)
timeoutHandler = null
super.onDetachedFromWindow()
}
/**
* The raw resource id of the video to play.
* @return ID of the video resource.
*/
fun getVideoResourceId(): Int = videoResourceId
/**
* Sets the listener to monitor movie events.
* @param movieListener The listener to be set.
*/
fun setMovieListener(movieListener: MovieListener?) {
this.movieListener = movieListener
}
/**
* Sets the raw resource ID of video to play.
* @param id The raw resource ID.
*/
private fun setVideoResourceId(@RawRes id: Int) {
if (id == videoResourceId) {
return
}
videoResourceId = id
val surface = surfaceView.holder.surface
if (surface != null && surface.isValid) {
closeVideo()
openVideo(surface)
}
}
fun setAdjustViewBounds(adjustViewBounds: Boolean) {
if (this.adjustViewBounds == adjustViewBounds) {
return
}
this.adjustViewBounds = adjustViewBounds
if (adjustViewBounds) {
background = null
} else {
setBackgroundColor(Color.BLACK)
}
requestLayout()
}
/**
* Shows all the controls.
*/
fun showControls() {
TransitionManager.beginDelayedTransition(this)
shade.visibility = View.VISIBLE
toggle.visibility = View.VISIBLE
fastForward.visibility = View.VISIBLE
fastRewind.visibility = View.VISIBLE
minimize.visibility = View.VISIBLE
}
/**
* Hides all the controls.
*/
fun hideControls() {
TransitionManager.beginDelayedTransition(this)
shade.visibility = View.INVISIBLE
toggle.visibility = View.INVISIBLE
fastForward.visibility = View.INVISIBLE
fastRewind.visibility = View.INVISIBLE
minimize.visibility = View.INVISIBLE
}
/**
* Fast-forward the video.
*/
private fun fastForward() {
mediaPlayer?.let { it.seekTo(it.currentPosition + FAST_FORWARD_REWIND_INTERVAL) }
}
/**
* Fast-rewind the video.
*/
private fun fastRewind() {
mediaPlayer?.let { it.seekTo(it.currentPosition - FAST_FORWARD_REWIND_INTERVAL) }
}
/**
* Returns the current position of the video. If the the player has not been created, then
* assumes the beginning of the video.
* @return The current position of the video.
*/
fun getCurrentPosition(): Int = mediaPlayer?.currentPosition ?: 0
val isPlaying: Boolean
get() = mediaPlayer?.isPlaying ?: false
fun play() {
if (mediaPlayer == null) {
return
}
mediaPlayer!!.start()
adjustToggleState()
keepScreenOn = true
movieListener?.onMovieStarted()
}
fun pause() {
if (mediaPlayer == null) {
adjustToggleState()
return
}
mediaPlayer!!.pause()
adjustToggleState()
keepScreenOn = false
movieListener?.onMovieStopped()
}
internal fun openVideo(surface: Surface) {
if (videoResourceId == 0) {
return
}
mediaPlayer = MediaPlayer()
mediaPlayer?.let { player ->
player.setSurface(surface)
startVideo()
}
}
/**
* Restarts playback of the video.
*/
fun startVideo() {
mediaPlayer?.let { player ->
player.reset()
try {
resources.openRawResourceFd(videoResourceId).use { fd ->
player.setDataSource(fd)
player.setOnPreparedListener { mediaPlayer ->
// Adjust the aspect ratio of this view
requestLayout()
if (savedCurrentPosition > 0) {
mediaPlayer.seekTo(savedCurrentPosition)
savedCurrentPosition = 0
} else {
// Start automatically
play()
}
}
player.setOnCompletionListener {
adjustToggleState()
keepScreenOn = false
movieListener?.onMovieStopped()
}
player.prepare()
}
} catch (e: IOException) {
Log.e(TAG, "Failed to open video", e)
}
}
}
internal fun closeVideo() {
mediaPlayer?.release()
mediaPlayer = null
}
private fun toggle() {
mediaPlayer?.let { if (it.isPlaying) pause() else play() }
}
private fun toggleControls() {
if (shade.visibility == View.VISIBLE) {
hideControls()
} else {
showControls()
}
}
private fun adjustToggleState() {
mediaPlayer?.let {
if (it.isPlaying) {
toggle.contentDescription = resources.getString(R.string.pause)
toggle.setImageResource(R.drawable.ic_pause_64dp)
} else {
toggle.contentDescription = resources.getString(R.string.play)
toggle.setImageResource(R.drawable.ic_play_arrow_64dp)
}
}
}
private class TimeoutHandler(view: MovieView) : Handler(Looper.getMainLooper()) {
private val movieViewRef: WeakReference<MovieView> = WeakReference(view)
override fun handleMessage(msg: Message) {
when (msg.what) {
MESSAGE_HIDE_CONTROLS -> {
movieViewRef.get()?.hideControls()
}
else -> super.handleMessage(msg)
}
}
companion object {
const val MESSAGE_HIDE_CONTROLS = 1
}
}
}
|
apache-2.0
|
4023f2cd5e90648d5f8ac69476ff9742
| 32.358621 | 104 | 0.578527 | 5.232961 | false | false | false | false |
pdvrieze/ProcessManager
|
ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/processModel/engine/ExecutableJoin.kt
|
1
|
6962
|
/*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel.engine
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.engine.processModel.IProcessNodeInstance
import nl.adaptivity.process.engine.processModel.JoinInstance
import nl.adaptivity.process.engine.processModel.NodeInstanceState
import nl.adaptivity.process.engine.processModel.ProcessNodeInstance
import nl.adaptivity.process.processModel.*
import nl.adaptivity.process.util.Identified
class ExecutableJoin(
builder: Join.Builder,
buildHelper: ProcessModel.BuildHelper<ExecutableProcessNode, *, *, *>,
otherNodes: Iterable<ProcessNode.Builder>
) : JoinBase<ExecutableProcessNode, ExecutableModelCommon>(builder, buildHelper, otherNodes), ExecutableProcessNode {
override val ownerModel: ExecutableModelCommon
get() = super.ownerModel as ExecutableModelCommon
override val id: String get() = super.id ?: throw IllegalStateException("Excecutable nodes must have an id")
override fun startTask(instance: ProcessNodeInstance.Builder<*, *>): Boolean {
return super.startTask(instance)
}
fun getExistingInstance(
data: ProcessEngineDataAccess,
processInstanceBuilder: ProcessInstance.Builder,
predecessor: IProcessNodeInstance,
entryNo: Int,
allowFinalInstance: Boolean
): Pair<JoinInstance.Builder?, Int> {
var candidateNo = if (isMultiInstance || isMultiMerge) entryNo else 1
for (candidate in processInstanceBuilder.getChildren(this).sortedBy { it.entryNo }) {
if (predecessor.handle in candidate.predecessors) {
return (candidate as JoinInstance.Builder) to candidateNo
}
if ((allowFinalInstance || candidate.state != NodeInstanceState.Complete) &&
(candidate.entryNo == entryNo || candidate.predecessors.any {
when (predecessor.handle.isValid && it.isValid) {
true -> predecessor.handle == it
else -> data.nodeInstance(it).withPermission()
.run { entryNo == entryNo && node.id == predecessor.node.id }
}
})
) {
return (candidate as JoinInstance.Builder) to candidateNo
}
// TODO Throw exceptions for cases where this is not allowed
if (candidate.entryNo == candidateNo) {
candidateNo++
} // Increase the candidate entry number
}
return null to candidateNo
}
override fun isOtherwiseCondition(predecessor: ExecutableProcessNode): Boolean {
return conditions.get(predecessor.identifier)?.toExecutableCondition()?.isOtherwise == true
}
override fun evalCondition(
nodeInstanceSource: IProcessInstance,
predecessor: IProcessNodeInstance,
nodeInstance: IProcessNodeInstance
): ConditionResult {
val predCondResult = (conditions[predecessor.node.identifier] as ExecutableCondition?)
.evalCondition(nodeInstanceSource, predecessor, nodeInstance)
var neverCount = 0
var alwaysCount = 0
for (hPred in nodeInstance.predecessors) {
val siblingResult = when (hPred) {
predecessor.handle -> predCondResult
else -> {
val sibling = nodeInstanceSource.getChildNodeInstance(hPred)
(conditions[sibling.node.identifier] as ExecutableCondition?)
.evalCondition(nodeInstanceSource, sibling, nodeInstance)
}
}
@Suppress("NON_EXHAUSTIVE_WHEN")
when (siblingResult) {
ConditionResult.TRUE -> alwaysCount++
ConditionResult.NEVER -> neverCount++
}
}
if (alwaysCount>=min) return ConditionResult.TRUE
if (neverCount>(predecessors.size-min)) return ConditionResult.NEVER
if (neverCount+1==predecessors.size && isOtherwiseCondition(predecessor.node)) return ConditionResult.TRUE
return ConditionResult.MAYBE
}
override fun createOrReuseInstance(
data: MutableProcessEngineDataAccess,
processInstanceBuilder: ProcessInstance.Builder,
predecessor: IProcessNodeInstance,
entryNo: Int,
allowFinalInstance: Boolean
): ProcessNodeInstance.Builder<out ExecutableProcessNode, out ProcessNodeInstance<*>> {
val (existingInstance, candidateNo) = getExistingInstance(
data,
processInstanceBuilder,
predecessor,
entryNo,
allowFinalInstance
)
existingInstance?.let {
if (predecessor.handle.isValid) {
if (it.predecessors.add(predecessor.handle)) {
// Store the new predecessor, so when resetting the predecessor isn't lost
processInstanceBuilder.storeChild(it)
processInstanceBuilder.store(data)
}
}
return it
}
if (!(isMultiInstance || isMultiMerge) && candidateNo != 1) {
throw ProcessException("Attempting to start a second instance of a single instantiation join $id:$entryNo")
}
return JoinInstance.BaseBuilder(
this,
listOf(predecessor.handle),
processInstanceBuilder,
processInstanceBuilder.owner,
candidateNo
)
}
class Builder : JoinBase.Builder, ExecutableProcessNode.Builder {
constructor(
id: String? = null,
predecessors: Collection<Identified> = emptyList(),
successor: Identified? = null, label: String? = null,
defines: Collection<IXmlDefineType> = emptyList(),
results: Collection<IXmlResultType> = emptyList(),
min: Int = -1,
max: Int = -1,
x: Double = Double.NaN,
y: Double = Double.NaN,
isMultiMerge: Boolean = false,
isMultiInstance: Boolean = false
) : super(
id, predecessors, successor, label, defines, results, x, y, min, max, isMultiMerge, isMultiInstance
)
constructor(node: Join) : super(node)
}
}
|
lgpl-3.0
|
87009f73b169e40528f589cabdc4df4a
| 39.952941 | 119 | 0.643493 | 5.351268 | false | false | false | false |
pdvrieze/ProcessManager
|
PE-common/src/commonMain/kotlin/nl/adaptivity/process/util/IdentifyableSet.kt
|
1
|
19429
|
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.util
import net.devrieze.util.ArraySet
import net.devrieze.util.MutableReadMap
import net.devrieze.util.ReadMap
import net.devrieze.util.toArraySet
interface MutableIdentifyableSet<T : Identifiable> : IdentifyableSet<T>, MutableSet<T>, MutableReadMap<String, T> {
fun addAll(c: Iterable<T>) = c.fold(false) { result, elem -> add(elem) or result }
operator fun set(index: Int, value: T): T
fun addAll(sequence: Sequence<T>) = sequence.fold(false) { r, elem -> add(elem) or r }
fun removeAt(index: Int): T
override fun removeAll(elements: Collection<T>) = elements.map { remove(it) }.reduce(Boolean::or)
override fun retainAll(elements: Collection<T>): Boolean {
val it = iterator()
var result = false
while (it.hasNext()) {
if (it.next() !in elements) {
it.remove()
result = true
}
}
return result
}
override fun iterator(): MutableIterator<T>
}
interface IdentifyableSet<out T : Identifiable> : ListSet<T>, List<T>, Set<T>, ReadMap<String, T>, RandomAccess {
private class ReadonlyIterator<T> constructor(private val mIterator: ListIterator<T>) : ListIterator<T> {
override fun hasNext() = mIterator.hasNext()
override fun next() = mIterator.next()
override fun hasPrevious() = mIterator.hasPrevious()
override fun previous() = mIterator.previous()
override fun nextIndex() = mIterator.nextIndex()
override fun previousIndex() = mIterator.previousIndex()
}
private class ReadOnlyIdentifyableSet<T : Identifiable> private constructor(private val data: Array<T>) :
IdentifyableSet<T> {
@Suppress("UNCHECKED_CAST")
constructor(delegate: IdentifyableSet<T>) : this(delegate.toTypedArray<Identifiable>() as Array<T>)
fun clone(): ReadOnlyIdentifyableSet<T> {
return this
}
override fun subList(fromIndex: Int, toIndex: Int) = ReadOnlyIdentifyableSet(
data.copyOfRange(fromIndex, toIndex)
)
override fun get(index: Int): T {
return data[index]
}
override fun contains(element: T) = indexOf(element) >= 0
override fun indexOf(element: T) = data.indexOf(element)
override fun lastIndexOf(element: T) = data.lastIndexOf(element)
override val size: Int get() = data.size
override fun listIterator(index: Int): ListIterator<T> {
return ReadonlyArrayIterator(data, index)
}
override fun equals(other: Any?): Boolean {
return other is IdentifyableSet<*>
&& data.size == other.size &&
other.all { it in data }
}
override fun hashCode() = data.hashCode()
override fun toString(): String {
return data.joinToString(prefix = "ReadOnlyIdentifyableSet{", postfix = "}")
}
}
private class BaseIdentifyableSet<V : Identifiable>(private val data: ArraySet<V> = ArraySet()) :
MutableIdentifyableSet<V>, MutableSet<V> by data {
constructor(initialcapacity: Int) : this(ArraySet(initialcapacity))
constructor(c: Sequence<V>) : this() {
addAll(c)
}
constructor(c: Iterable<V>) : this((c as? Collection<*>)?.let { ArraySet<V>(it.size) } ?: ArraySet<V>()) {
addAll(c)
}
constructor(a: Array<out V>) : this(ArraySet<V>(a.size)) {
addAll(a)
}
override fun get(index: Int) = data[index]
override fun containsAll(elements: Collection<V>) = data.containsAll(elements)
override fun isEmpty() = data.isEmpty()
override fun subList(fromIndex: Int, toIndex: Int): MutableList<V> {
TODO("not implemented, we don't really need it")
}
override fun listIterator(index: Int): MutableListIterator<V> {
return data.listIterator(index)
}
override fun iterator(): MutableIterator<V> {
return data.iterator()
}
// override fun spliterator() = data.spliterator()
fun clone(): BaseIdentifyableSet<V> {
return BaseIdentifyableSet(data.toArraySet())
}
override fun add(element: V): Boolean {
val name = element.id
if (name == null) {
if (data.contains(element)) {
return false
}
} else if (containsKey(name)) {
return false
}
data.add(element)
return true
}
override fun set(index: Int, value: V) = data.set(index, value)
override fun removeAll(elements: Collection<V>) = data.removeAll(elements)
override fun retainAll(elements: Collection<V>) = data.removeAll(elements)
override fun removeAt(index: Int) = data.removeAt(index)
override operator fun contains(element: V): Boolean {
val elementId = element.id
return if (elementId != null) {
data.any { it.id == elementId }
} else {
data.any { it == element }
}
}
override fun clear() {
data.clear()
}
override fun values(): IdentifyableSet<V> {
return ReadOnlyIdentifyableSet(this)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IdentifyableSet<*>) return false
if (size!=other.size) return false
return other.all { it in data }
}
override fun hashCode(): Int {
return data.hashCode()
}
override fun toString(): String {
return data.joinToString(prefix = "BaseIdentifyableSet{", postfix = "}")
}
}
private object EmptyIdentifyableSet : MutableIdentifyableSet<Identifiable> {
fun clone() = this
override fun isEmpty() = true
override val keys: Set<String> get() = emptySet()
override fun values() = this
override fun get(index: Int) = throw IndexOutOfBoundsException()
override fun set(index: Int, value: Identifiable) = throw IndexOutOfBoundsException()
override val size: Int get() = 0
override fun contains(element: Identifiable) = false
override fun containsAll(elements: Collection<Identifiable>) = elements.isEmpty()
override fun indexOf(element: Identifiable) = -1
override fun lastIndexOf(element: Identifiable) = -1
private val _iterator = mutableListOf<Identifiable>().toUnmodifyableList().iterator() as MutableIterator
override fun iterator() = _iterator
override fun listIterator(): ListIterator<Identifiable> = emptyList<Identifiable>().listIterator()
override fun listIterator(index: Int): ListIterator<Identifiable> {
if (index != 0) throw IndexOutOfBoundsException(index.toString()) else return listIterator()
}
override fun subList(fromIndex: Int, toIndex: Int): EmptyIdentifyableSet {
if (fromIndex != 0 || toIndex != 0) throw IndexOutOfBoundsException() else return this
}
override fun removeAt(index: Int) = throw IndexOutOfBoundsException()
override fun add(element: Identifiable) = throw IllegalStateException("No elements can be added to this list")
override fun addAll(elements: Collection<Identifiable>) =
if (elements.isEmpty()) false else throw IllegalStateException(
"No elements can be added to this list"
)
override fun clear() = Unit // No meaning
override fun remove(element: Identifiable) = false
override fun hashCode() = 1
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is IdentifyableSet<*>) {
return false
}
return other.isEmpty()
}
}
private class SingletonIdentifyableSet<V : Identifiable> : AbstractSet<V>, MutableIdentifyableSet<V> {
private var element: V? = null
constructor() {}
constructor(element: V?) {
if (element == null) throw NullPointerException()
this.element = element
}
fun clone(): SingletonIdentifyableSet<V> {
if (element == null) {
return SingletonIdentifyableSet()
} else {
return SingletonIdentifyableSet(element)
}
}
override fun add(e: V): Boolean {
if (e == element) {
return false
} else if (element == null) {
element = e
return true
} else {
throw IllegalStateException("Singleton node set can only contain one element")
}
}
override fun addAll(elements: Collection<V>): Boolean {
if (size + elements.size > 1) throw IllegalStateException(
"Attempting to increase singleton set to more than one element"
)
return elements.fold(false) { acc, elem -> acc or add(elem) }
}
override fun values(): IdentifyableSet<V> = this
override fun get(index: Int): V {
element.let {
if (it == null || index != 0) {
throw IndexOutOfBoundsException()
}
return it
}
}
override fun set(index: Int, element: V): V {
this.element.let {
if (it == null || index != 0) throw IndexOutOfBoundsException()
this.element = element
return it
}
}
override fun subList(fromIndex: Int, toIndex: Int): List<V> {
if (fromIndex == toIndex) return emptyList()
if (fromIndex == 0 && toIndex >= 1) return this
throw UnsupportedOperationException("No sublist is possible for a singleton identifyable set")
}
override val size: Int get() = if (element == null) 0 else 1
override fun isEmpty() = element == null
override fun removeAt(index: Int): V {
element.let { element ->
if (element == null || index != 0) throw IndexOutOfBoundsException()
this.element = null
return element
}
}
override fun iterator(): MutableIterator<V> {
return object : MutableIterator<V> {
var pos = 0
override fun hasNext() = pos == 0 && element != null
override fun next(): V {
if (!hasNext()) throw NoSuchElementException()
pos++
return element!!
}
override fun remove() {
if (pos != 1 || element == null) throw NoSuchElementException()
element = null
}
}
}
override fun listIterator(initialPos: Int): ListIterator<V> {
return when (element) {
null -> {
if (initialPos != 0) throw IndexOutOfBoundsException()
emptyList<V>().listIterator()
}
else -> ReadonlyIterator(listOf(element!!).listIterator(initialPos))
}
}
override fun indexOf(element: V) = if (this.element == element) 0 else -1
override fun lastIndexOf(element: V) = indexOf(element)
override fun clear() {
element = null
}
override fun remove(element: V): Boolean {
if (this.element == element) {
this.element = null
return true
} else return false
}
override fun removeAll(elements: Collection<V>) = elements.map { remove(it) }.reduce(Boolean::or)
override fun retainAll(elements: Collection<V>) = element?.let { element ->
if (element in elements) {
this.element = null
true
} else {
false
}
} ?: false
override fun containsAll(elements: Collection<V>) = element != null && elements.all { it == element }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IdentifyableSet<*>) return false
if (other.size!=1) return false
return other.single() == element
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (element?.hashCode() ?: 0)
return result
}
}
private class MyKeyIterator(private val mParent: Iterator<Identifiable>) : MutableIterator<String> {
override fun hasNext() = mParent.hasNext()
override fun next() = mParent.next().id!!
override fun remove() {
(mParent as? MutableIterator<Identifiable>)?.remove() ?: throw UnsupportedOperationException(
"The key set is not mutable"
)
}
}
private class MyKeySet(private val delegate: IdentifyableSet<*>) : AbstractSet<String>() {
override fun iterator(): MutableIterator<String> {
return MyKeyIterator(delegate.iterator())
}
override val size = delegate.size
}
override fun containsAll(elements: Collection<@kotlin.UnsafeVariance T>) = elements.all { contains(it) }
override fun containsKey(key: String): Boolean {
return get(key) != null
}
override fun containsValue(value: @kotlin.UnsafeVariance T): Boolean {
return contains(value)
}
override fun isEmpty() = size == 0
override operator fun get(pos: Int): T
operator fun get(key: Identifiable): T? {
return key.id?.let { get(it) }
}
override fun get(key: String): T? {
if (key == null) {
for (elem in this) {
if (elem.id == null) {
return elem
}
}
} else {
for (elem in this) {
if (key == elem.id) {
return elem
}
}
}
return null
}
override fun indexOf(element: @kotlin.UnsafeVariance T): Int = indexOfFirst { it == element }
override fun lastIndexOf(element: @kotlin.UnsafeVariance T): Int = indexOfLast { it == element }
override val keys: Set<String> get() = MyKeySet(this)
override fun iterator(): Iterator<T> = listIterator(0)
override fun listIterator(): ListIterator<T> = listIterator(0)
override fun listIterator(initialPos: Int): ListIterator<T>
override fun values() = readOnly()
fun readOnly(): IdentifyableSet<T> {
if (this is IdentifyableSet.ReadOnlyIdentifyableSet) {
return this
}
return ReadOnlyIdentifyableSet(this)
}
companion object {
fun <V : Identifiable> processNodeSet(): MutableIdentifyableSet<V> {
return BaseIdentifyableSet<V>()
}
fun <V : Identifiable> processNodeSet(initialCapacity: Int): MutableIdentifyableSet<V> {
return BaseIdentifyableSet(initialCapacity)
}
fun <V : Identifiable> processNodeSet(collection: Array<out V>): MutableIdentifyableSet<V> {
return BaseIdentifyableSet(collection)
}
fun <V : Identifiable> processNodeSet(collection: Sequence<V>): MutableIdentifyableSet<V> {
return BaseIdentifyableSet(collection)
}
fun <V : Identifiable> processNodeSet(collection: Iterable<V>): MutableIdentifyableSet<V> {
return BaseIdentifyableSet(collection)
}
fun <V : Identifiable> processNodeSet(maxSize: Int, elements: Collection<V>): MutableIdentifyableSet<V> {
when (maxSize) {
0 -> {
if (elements.isNotEmpty()) {
throw IllegalArgumentException("More elements than allowed")
}
return empty<V>()
}
1 -> {
run {
if (elements.size > 1) {
throw IllegalArgumentException("More elements than allowed")
}
val iterator = elements.iterator()
if (iterator.hasNext())
return singleton(iterator.next())
else
return singleton()
}
}
else -> return processNodeSet(elements)
}
}
fun <V : Identifiable> processNodeSet(maxSize: Int, elements: Sequence<V>): IdentifyableSet<V> {
val it = elements.iterator()
when (maxSize) {
0 -> {
if (it.hasNext()) {
throw IllegalArgumentException("More elements than allowed")
}
return empty()
}
1 -> {
if (it.hasNext()) {
try {
return singleton(it.next())
} finally {
if (it.hasNext()) {
throw IllegalArgumentException("More elements than allowed")
}
}
} else {
return singleton()
}
}
else -> return processNodeSet(elements)
}
}
@Suppress("UNCHECKED_CAST")
fun <V : Identifiable> empty(): MutableIdentifyableSet<V> {
// This can be unsafe as it is actually empty
return EmptyIdentifyableSet as MutableIdentifyableSet<V>
}
fun <V : Identifiable> singleton(): MutableIdentifyableSet<V> {
return SingletonIdentifyableSet()
}
fun <V : Identifiable> singleton(element: V): MutableIdentifyableSet<V> {
return SingletonIdentifyableSet(element)
}
}
}
expect interface ListSet<out E>//: List<E>, Set<E>
|
lgpl-3.0
|
3ae0d01edfd31ad0ef408372a48ee8a1
| 31.874788 | 118 | 0.549076 | 4.957642 | false | false | false | false |
pdvrieze/ProcessManager
|
ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/processModel/engine/ExecutableProcessNode.kt
|
1
|
7361
|
/*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel.engine
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.engine.processModel.DefaultProcessNodeInstance
import nl.adaptivity.process.engine.processModel.IProcessNodeInstance
import nl.adaptivity.process.engine.processModel.NodeInstanceState
import nl.adaptivity.process.engine.processModel.ProcessNodeInstance
import nl.adaptivity.process.processModel.ProcessNode
import nl.adaptivity.process.processModel.XmlResultType
import nl.adaptivity.process.util.Identified
import nl.adaptivity.process.util.Identifier
import nl.adaptivity.process.util.IdentifyableSet
/**
* Base type for any process node that can be executed
*/
interface ExecutableProcessNode : ProcessNode, Identified {
interface Builder : ProcessNode.Builder {
override fun result(builder: XmlResultType.Builder.() -> Unit) {
results.add(XmlResultType.Builder().apply(builder).build())
}
}
override val ownerModel: ExecutableModelCommon
override val identifier: Identifier
get() = Identifier(id)
// override val defines: List<XmlDefineType>
/**
* Create an instance of the node or return it if it already exist.
*
* TODO handle failRetry nodes
*/
fun createOrReuseInstance(
data: MutableProcessEngineDataAccess,
processInstanceBuilder: ProcessInstance.Builder,
predecessor: IProcessNodeInstance,
entryNo: Int,
allowFinalInstance: Boolean,
): ProcessNodeInstance.Builder<out ExecutableProcessNode, out ProcessNodeInstance<*>> {
processInstanceBuilder.getChildNodeInstance(this, entryNo)?.let { return it }
if (!isMultiInstance && entryNo > 1) {
processInstanceBuilder.allChildNodeInstances { it.node == this && it.entryNo != entryNo }.forEach {
processInstanceBuilder.updateChild(it) {
invalidateTask(data)
}
}
}
return DefaultProcessNodeInstance.BaseBuilder(
this, listOf(predecessor.handle),
processInstanceBuilder,
processInstanceBuilder.owner, entryNo
)
}
fun isOtherwiseCondition(predecessor: ExecutableProcessNode): Boolean = false
/**
* Should this node be able to be provided?
* @param engineData
*
* @param The predecessor that is evaluating the condition
*
* @param nodeInstance The instance against which the condition should be evaluated.
*
* @return `true` if the node can be started, `false` if
* not.
*/
fun evalCondition(
nodeInstanceSource: IProcessInstance,
predecessor: IProcessNodeInstance,
nodeInstance: IProcessNodeInstance
): ConditionResult = when {
nodeInstance.state==NodeInstanceState.Complete || !nodeInstance.state.isFinal -> ConditionResult.TRUE
else -> ConditionResult.NEVER
}
/**
* Take action to make task available
*
* @param engineData
*
* @param instanceBuilder The processnode instance involved.
*
* @return `true` if the task can/must be automatically taken
*/
fun provideTask(engineData: ProcessEngineDataAccess, instanceBuilder: ProcessNodeInstance.Builder<*, *>): Boolean
= true
fun takeTask(instance: ProcessNodeInstance.Builder<*, *>): Boolean = true
fun startTask(instance: ProcessNodeInstance.Builder<*, *>): Boolean = true
private fun preceeds(node: ExecutableProcessNode, reference: ExecutableProcessNode, seenIds: MutableSet<String>):Boolean {
if (node in reference.predecessors) return true
seenIds+=id
return reference.predecessors.asSequence()
.filter { it.id !in seenIds }
.map { ownerModel.getNode(it)!! }
.firstOrNull()
?.let { preceeds(node, it, seenIds) }
?: false
}
/**
* Determine whether this node is a "possible" predecessor of the reference node.
*/
public infix fun preceeds(reference: ExecutableProcessNode): Boolean {
if (this===reference) return false
return preceeds(this, reference, HashSet<String>())
}
/**
* Determine whether this node is a "possible" successor of the reference node.
*/
public infix fun succceeds(reference: ExecutableProcessNode): Boolean {
if (this===reference) return false
return preceeds(reference, this, HashSet<String>())
}
fun transitivePredecessors(): IdentifyableSet<ExecutableProcessNode> {
val preds = IdentifyableSet.processNodeSet<ExecutableProcessNode>()
fun addPreds(node: ExecutableProcessNode) {
for (predId in node.predecessors) {
val pred = ownerModel.requireNode(predId)
if(preds.add(pred)) {
addPreds(pred)
}
}
}
addPreds(this)
return preds
}
}
/**
* Should this node be able to be provided?
* @param engineData
*
* @param The predecessor that is evaluating the condition
*
* @param nodeInstanceBuilder The instance against which the condition should be evaluated.
*
* @return `true` if the node can be started, `false` if not.
*/
internal fun ExecutableCondition?.evalCondition(
nodeInstanceSource: IProcessInstance,
predecessor: IProcessNodeInstance,
nodeInstance: IProcessNodeInstance
): ConditionResult {
// If the instance is final, the condition maps to the state
if (nodeInstance.state.isFinal) {
return if(nodeInstance.state == NodeInstanceState.Complete) ConditionResult.TRUE else ConditionResult.NEVER
}
// A lack of condition is a true result
if (this==null) return ConditionResult.TRUE
if (isOtherwise) { // An alternate is only true if all others are never/finalised
val successorCount = predecessor.node.successors.size
val hPred = predecessor.handle
var nonTakenSuccessorCount:Int = 0
for (sibling in nodeInstanceSource.allChildNodeInstances()) {
if (sibling.handle != nodeInstance.handle && hPred in sibling.predecessors) {
when (sibling.condition(nodeInstanceSource, predecessor)) {
ConditionResult.TRUE -> return ConditionResult.NEVER
ConditionResult.MAYBE -> return ConditionResult.MAYBE
ConditionResult.NEVER -> nonTakenSuccessorCount++
}
}
}
if (nonTakenSuccessorCount+1>=successorCount) return ConditionResult.TRUE
return ConditionResult.MAYBE
}
return eval(nodeInstanceSource, nodeInstance)
}
|
lgpl-3.0
|
b91fec165902bf8e44faef4d9f4b3d6b
| 35.621891 | 126 | 0.681837 | 4.973649 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/util/TableBuilder.kt
|
1
|
5745
|
package com.boardgamegeek.util
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import com.boardgamegeek.extensions.joinTo
import timber.log.Timber
/**
* A builder for creating and replacing tables.
*/
class TableBuilder {
private var tableName: String? = null
private var primaryKey: Column? = null
private var columns = mutableListOf<Column>()
private var uniqueColumnNames = mutableListOf<String>()
private var resolution = ConflictResolution.IGNORE
private var isFtsTable = false
fun reset(): TableBuilder {
tableName = null
primaryKey = null
columns = mutableListOf()
uniqueColumnNames = mutableListOf()
resolution = ConflictResolution.IGNORE
return this
}
fun create(db: SQLiteDatabase) {
check(tableName?.isNotEmpty() == true) { "Table not specified" }
checkNotNull(primaryKey) { "Primary key not specified" }
val sb = StringBuilder()
if (isFtsTable) {
sb.append("CREATE VIRTUAL TABLE $tableName USING fts3")
} else {
sb.append("CREATE TABLE $tableName")
}
sb.append(" (").append(primaryKey!!.build()).append(" PRIMARY KEY AUTOINCREMENT,")
sb.append(columns.joinToString(", ") { it.build() })
if (uniqueColumnNames.isNotEmpty()) {
sb.append(", UNIQUE (")
sb.append(uniqueColumnNames.joinTo(","))
sb.append(") ON CONFLICT ").append(resolution)
}
sb.append(")")
Timber.d(sb.toString())
db.execSQL(sb.toString())
}
fun replace(db: SQLiteDatabase, columnMap: Map<String, String>? = null, joinTable: String? = null, joinColumn: String? = null) {
check(tableName?.isNotEmpty() == true) { "Table not specified" }
db.beginTransaction()
try {
db.execSQL("ALTER TABLE $tableName RENAME TO ${tempTable()}")
create(db)
copy(db, columnMap, joinTable, joinColumn)
db.execSQL("DROP TABLE ${tempTable()}")
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
}
private fun tempTable() = tableName + "_tmp"
private fun copy(db: SQLiteDatabase, columnMap: Map<String, String>?, joinTable: String?, joinColumn: String?) {
val destinationColumns = columns.joinToString(",")
val sourceColumns = columns.map {
columnMap?.get(it.name)?.let { mappedColumn ->
mappedColumn.ifBlank { it.name }
} ?: it.name
}.joinToString(",")
var destinationTable = tempTable()
if (joinTable?.isNotEmpty() == true && joinColumn?.isNotEmpty() == true) destinationTable += " INNER JOIN $joinTable ON $joinTable.$joinColumn=${tempTable()}.$joinColumn"
val sql = "INSERT INTO $tableName($destinationColumns) SELECT $sourceColumns FROM $destinationTable"
Timber.d(sql)
db.execSQL(sql)
}
fun setTable(table: String?) = apply {
tableName = table
isFtsTable = false
}
@Suppress("unused")
fun setFtsTable(table: String?) = apply {
tableName = table
isFtsTable = true
}
fun setConflictResolution(resolution: ConflictResolution) = apply {
this.resolution = resolution
}
@Suppress("unused")
fun setPrimaryKey(columnName: String, type: ColumnType) = apply {
primaryKey = Column(columnName, type)
}
/**
* Add an _ID column and sets it as the primary key.
*/
fun useDefaultPrimaryKey() = apply {
primaryKey = Column(BaseColumns._ID, ColumnType.INTEGER)
}
fun addColumn(name: String, type: ColumnType?, notNull: Boolean, defaultValue: Int) =
addColumn(name, type, notNull, defaultValue = defaultValue.toString())
fun addColumn(
name: String, type: ColumnType?, notNull: Boolean = false, unique: Boolean = false,
referenceTable: String? = null, referenceColumn: String? = null, onCascadeDelete: Boolean = false, defaultValue: String? = null
) = apply {
val column = Column(name, type, notNull, onCascadeDelete, defaultValue)
column.setReference(referenceTable, referenceColumn)
columns.add(column)
if (unique) {
check(notNull) { "Unique columns must be non-null" }
uniqueColumnNames.add(name)
}
}
enum class ColumnType {
INTEGER, TEXT, REAL
}
@Suppress("unused")
enum class ConflictResolution {
ROLLBACK, ABORT, FAIL, IGNORE, REPLACE
}
private inner class Column(
val name: String? = null,
val type: ColumnType? = null,
val notNull: Boolean = false,
val onCascadeDelete: Boolean = false,
val defaultValue: String? = null,
) {
private var refTable: String? = null
private var refColumn: String? = null
fun setReference(table: String?, column: String?) {
check(
!((table.isNullOrBlank() && !column.isNullOrBlank()) ||
(column.isNullOrBlank() && !table.isNullOrBlank()))
) { "Table and column must be specified" }
refTable = table
refColumn = column
}
fun build(): String {
// "COLUMN_NAME TEXT NOT NULL DEFAULT DEFAULT_VALUE REFERENCES PARENT(NAME) ON DELETE CASCADE"
var s = "$name $type"
if (notNull) s += " NOT NULL"
if (defaultValue?.isNotEmpty() == true) s += " DEFAULT $defaultValue "
if (refTable != null) s += " REFERENCES $refTable($refColumn)"
if (onCascadeDelete) s += " ON DELETE CASCADE"
return s
}
}
}
|
gpl-3.0
|
803048913ce4c008b5182fea8f98d5c6
| 34.90625 | 178 | 0.606963 | 4.678339 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/dialog/GameSuggestedPlayerCountPollDialogFragment.kt
|
1
|
4700
|
package com.boardgamegeek.ui.dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentPollSuggestedPlayerCountBinding
import com.boardgamegeek.extensions.setViewBackground
import com.boardgamegeek.extensions.showAndSurvive
import com.boardgamegeek.ui.viewmodel.GameViewModel
import com.boardgamegeek.ui.widget.PlayerNumberRow
class GameSuggestedPlayerCountPollDialogFragment : DialogFragment() {
private var _binding: FragmentPollSuggestedPlayerCountBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<GameViewModel>()
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentPollSuggestedPlayerCountBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog?.setTitle(R.string.suggested_numplayers)
addKeyRow(R.color.best, R.string.best)
addKeyRow(R.color.recommended, R.string.recommended)
addKeyRow(R.color.not_recommended, R.string.not_recommended)
viewModel.playerPoll.observe(viewLifecycleOwner) {
it?.let { entity ->
val totalVoteCount = entity.totalVotes
binding.totalVoteView.text = resources.getQuantityString(R.plurals.votes_suffix, totalVoteCount, totalVoteCount)
binding.pollList.isVisible = totalVoteCount > 0
binding.keyContainer.isVisible = totalVoteCount > 0
binding.noVotesSwitch.isVisible = totalVoteCount > 0
if (totalVoteCount > 0) {
binding.pollList.removeAllViews()
for ((_, playerCount, bestVoteCount, recommendedVoteCount, notRecommendedVoteCount) in entity.results) {
val row = PlayerNumberRow(requireContext()).apply {
setText(playerCount)
setVotes(bestVoteCount, recommendedVoteCount, notRecommendedVoteCount, totalVoteCount)
setOnClickListener { view ->
binding.pollList.children.forEach { v ->
(v as? PlayerNumberRow)?.clearHighlight()
}
(view as? PlayerNumberRow)?.let { playerNumberRow ->
playerNumberRow.setHighlight()
binding.keyContainer.children.forEachIndexed { index, view ->
view.findViewById<TextView>(R.id.infoView).text = playerNumberRow.votes[index].toString()
}
}
}
}
binding.pollList.addView(row)
}
binding.noVotesSwitch.setOnClickListener {
binding.pollList.children.forEach { row ->
(row as? PlayerNumberRow)?.showNoVotes(binding.noVotesSwitch.isChecked)
}
}
}
binding.progressView.hide()
binding.scrollView.isVisible = true
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun addKeyRow(@ColorRes colorResId: Int, @StringRes textResId: Int) {
val row = (layoutInflater.inflate(R.layout.row_poll_key, binding.keyContainer, false) as ViewGroup).apply {
findViewById<TextView>(R.id.textView).setText(textResId)
findViewById<View>(R.id.colorView).setViewBackground(ContextCompat.getColor(requireContext(), colorResId))
}
binding.keyContainer.addView(row)
}
companion object {
fun launch(host: Fragment) {
host.showAndSurvive(GameSuggestedPlayerCountPollDialogFragment().apply {
setStyle(STYLE_NORMAL, R.style.Theme_bgglight_Dialog)
})
}
}
}
|
gpl-3.0
|
d62410a286d46c39ae231268c5af7b50
| 43.761905 | 129 | 0.630638 | 5.29876 | false | false | false | false |
fossasia/open-event-android
|
app/src/main/java/org/fossasia/openevent/general/event/EventsViewModel.kt
|
1
|
5570
|
package org.fossasia.openevent.general.event
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.PagedList
import androidx.paging.RxPagedListBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.connectivity.MutableConnectionLiveData
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.event.paging.EventsDataSourceFactory
import org.fossasia.openevent.general.favorite.FavoriteEvent
import org.fossasia.openevent.general.search.location.SAVED_LOCATION
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
const val NEW_NOTIFICATIONS = "newNotifications"
class EventsViewModel(
private val eventService: EventService,
private val preference: Preference,
private val resource: Resource,
private val mutableConnectionLiveData: MutableConnectionLiveData,
private val config: PagedList.Config,
private val authHolder: AuthHolder
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val connection: LiveData<Boolean> = mutableConnectionLiveData
private val mutableProgress = MediatorLiveData<Boolean>()
val progress: MediatorLiveData<Boolean> = mutableProgress
private val mutablePagedEvents = MutableLiveData<PagedList<Event>>()
val pagedEvents: LiveData<PagedList<Event>> = mutablePagedEvents
private val mutableMessage = SingleLiveEvent<String>()
val message: SingleLiveEvent<String> = mutableMessage
var lastSearch = ""
private val mutableSavedLocation = MutableLiveData<String>()
val savedLocation: LiveData<String> = mutableSavedLocation
private lateinit var sourceFactory: EventsDataSourceFactory
fun loadLocation() {
mutableSavedLocation.value = preference.getString(SAVED_LOCATION)
?: resource.getString(R.string.enter_location)
}
fun loadLocationEvents() {
val location = mutableSavedLocation.value
if (location == null || location == resource.getString(R.string.enter_location) ||
location == resource.getString(R.string.no_location)) {
mutableProgress.value = false
return
}
sourceFactory = EventsDataSourceFactory(
compositeDisposable,
eventService,
mutableSavedLocation.value,
mutableProgress
)
val eventPagedList = RxPagedListBuilder(sourceFactory, config)
.setFetchScheduler(Schedulers.io())
.buildObservable()
.cache()
compositeDisposable += eventPagedList
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.distinctUntilChanged()
.doOnSubscribe {
mutableProgress.value = true
}.subscribe({
val currentPagedEvents = mutablePagedEvents.value
if (currentPagedEvents == null) {
mutablePagedEvents.value = it
} else {
currentPagedEvents.addAll(it)
mutablePagedEvents.value = currentPagedEvents
}
}, {
Timber.e(it, "Error fetching events")
mutableMessage.value = resource.getString(R.string.error_fetching_events_message)
})
}
fun isConnected(): Boolean = mutableConnectionLiveData.value ?: false
fun clearEvents() {
mutablePagedEvents.value = null
}
fun clearLastSearch() {
lastSearch = ""
}
fun isLoggedIn() = authHolder.isLoggedIn()
fun setFavorite(event: Event, favorite: Boolean) {
if (favorite) {
addFavorite(event)
} else {
removeFavorite(event)
}
}
private fun addFavorite(event: Event) {
val favoriteEvent = FavoriteEvent(authHolder.getId(), EventId(event.id))
compositeDisposable += eventService.addFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutableMessage.value = resource.getString(R.string.add_event_to_shortlist_message)
}, {
mutableMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on adding like for event ID ${event.id}")
})
}
private fun removeFavorite(event: Event) {
val favoriteEventId = event.favoriteEventId ?: return
val favoriteEvent = FavoriteEvent(favoriteEventId, EventId(event.id))
compositeDisposable += eventService.removeFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutableMessage.value = resource.getString(R.string.remove_event_from_shortlist_message)
}, {
mutableMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on removing like for event ID ${event.id}")
})
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
|
apache-2.0
|
5a0edd763074a64f2e983e766b9e6cfb
| 37.951049 | 103 | 0.68456 | 5.26465 | false | false | false | false |
shkschneider/android_Skeleton
|
core/src/main/kotlin/me/shkschneider/skeleton/helper/ApplicationHelper.kt
|
1
|
4948
|
package me.shkschneider.skeleton.helper
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import me.shkschneider.skeleton.SkeletonApplication
import me.shkschneider.skeleton.helperx.Logger
import me.shkschneider.skeleton.helperx.SystemServices
object ApplicationHelper {
// ApplicationInfo.loadDefaultIcon(packageManager)
const val DEFAULT_ICON = android.R.drawable.sym_def_app_icon
const val INSTALLER = "com.android.vending"
fun debuggable(): Boolean {
// <https://stackoverflow.com/a/25517680/603270>
return SkeletonApplication.DEBUGGABLE
}
fun resources(): Resources {
// Resources.getSystem()
return ContextHelper.applicationContext().resources
}
fun packageName(): String {
return ContextHelper.applicationContext().packageName
}
fun packageManager(): PackageManager {
return ContextHelper.applicationContext().packageManager
}
fun applicationInfo(packageName: String = ApplicationHelper.packageName()): ApplicationInfo? {
try {
return packageManager().getApplicationInfo(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
Logger.wtf(e)
return null
}
}
fun name(packageName: String = ApplicationHelper.packageName()): String? {
applicationInfo(packageName)?.loadLabel(packageManager())?.let { label ->
return label.toString()
}
Logger.warning("Label was NULL")
return null
}
fun exists(packageName: String = ApplicationHelper.packageName()): Boolean {
try {
return (packageManager().getApplicationInfo(packageName, 0) != null)
} catch (e: PackageManager.NameNotFoundException) {
Logger.wtf(e)
return false
}
}
fun packageInfo(packageName: String = ApplicationHelper.packageName(), flags: Int = 0): PackageInfo? {
try {
val packageManager = packageManager()
return packageManager.getPackageInfo(packageName, flags)
} catch (e: PackageManager.NameNotFoundException) {
Logger.wtf(e)
return null
}
}
fun versionName(packageName: String = ApplicationHelper.packageName()): String? {
return packageInfo(packageName, PackageManager.GET_META_DATA)?.versionName ?: run {
Logger.warning("VersionName was NULL")
return null
}
}
@SuppressLint("NewApi")
fun versionCode(packageName: String = ApplicationHelper.packageName()): Long? {
val packageInfo = packageInfo(packageName, PackageManager.GET_META_DATA)
if (Build.VERSION.SDK_INT >= 28) {
return packageInfo?.longVersionCode ?: run {
Logger.warning("LongVersionCode was NULL")
return null
}
} else {
@Suppress("DEPRECATION")
return packageInfo?.versionCode?.toLong() ?: run {
Logger.warning("VersionCode was NULL")
return null
}
}
}
fun buildTime(packageName: String = ApplicationHelper.packageName()): Long? {
return packageInfo(packageName, PackageManager.GET_META_DATA)?.lastUpdateTime ?: run {
Logger.warning("LastUpdateTime was NULL")
return null
}
}
fun permissions(packageName: String = ApplicationHelper.packageName()): List<String>? {
return packageInfo(packageName, PackageManager.GET_PERMISSIONS)?.requestedPermissions?.toList()
?: run {
Logger.warning("RequestedPermissions was NULL")
return null
}
}
fun icon(packageName: String = ApplicationHelper.packageName()): Int? {
try {
val packageManager = packageManager()
val applicationInfo = packageManager.getApplicationInfo(packageName, 0)
return applicationInfo.icon
} catch (e: PackageManager.NameNotFoundException) {
Logger.wtf(e)
return null
}
}
fun drawable(packageName: String = ApplicationHelper.packageName()) : Drawable? {
try {
val packageManager = packageManager()
val applicationInfo = packageManager.getApplicationInfo(packageName, 0)
return applicationInfo.loadIcon(packageManager)
} catch (e: PackageManager.NameNotFoundException) {
Logger.wtf(e)
return null
}
}
@TargetApi(AndroidHelper.API_19)
fun clear() {
Logger.info("clearApplicationUserData()")
SystemServices.activityManager()?.clearApplicationUserData()
}
}
|
apache-2.0
|
9b9d2ead3864fd12e0cbce470ecbd6f0
| 33.84507 | 106 | 0.645513 | 5.354978 | false | false | false | false |
Kotlin/kotlinx.serialization
|
formats/cbor/jvmTest/src/kotlinx/serialization/cbor/RandomTests.kt
|
1
|
8280
|
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.cbor
import io.kotlintest.properties.*
import io.kotlintest.specs.*
import kotlinx.serialization.*
class RandomTest : ShouldSpec() {
companion object {
fun Gen<String>.generateNotEmpty() = nextPrintableString(Gen.choose(1, 100).generate())
}
object KTestData {
@Serializable
data class KTestInt32(val a: Int) {
companion object : Gen<KTestInt32> {
override fun generate(): KTestInt32 = KTestInt32(Gen.int().generate())
}
}
@Serializable
data class KTestSignedInt(val a: Int) {
companion object : Gen<KTestSignedInt> {
override fun generate(): KTestSignedInt = KTestSignedInt(Gen.int().generate())
}
}
@Serializable
data class KTestSignedLong(val a: Long) {
companion object : Gen<KTestSignedLong> {
override fun generate(): KTestSignedLong = KTestSignedLong(Gen.long().generate())
}
}
@Serializable
data class KTestFixedInt(val a: Int) {
companion object : Gen<KTestFixedInt> {
override fun generate(): KTestFixedInt = KTestFixedInt(Gen.int().generate())
}
}
@Serializable
data class KTestDouble(val a: Double) {
companion object : Gen<KTestDouble> {
override fun generate(): KTestDouble = KTestDouble(Gen.double().generate())
}
}
@Serializable
data class KTestBoolean(val a: Boolean) {
companion object : Gen<KTestBoolean> {
override fun generate(): KTestBoolean = KTestBoolean(Gen.bool().generate())
}
}
@Serializable
data class KTestAllTypes(
val i32: Int,
val si32: Int,
val f32: Int,
val i64: Long,
val si64: Long,
val f64: Long,
val f: Float,
val d: Double,
val b: Boolean = false,
val s: String
) {
companion object : Gen<KTestAllTypes> {
override fun generate(): KTestAllTypes = KTestAllTypes(
Gen.int().generate(),
Gen.int().generate(),
Gen.int().generate(),
Gen.long().generate(),
Gen.long().generate(),
Gen.long().generate(),
Gen.float().generate(),
Gen.double().generate(),
Gen.bool().generate(),
Gen.string().generateNotEmpty()
)
}
}
@Serializable
data class KTestOuterMessage(
val a: Int,
val b: Double,
val inner: KTestAllTypes,
val s: String
) {
companion object : Gen<KTestOuterMessage> {
override fun generate(): KTestOuterMessage = KTestOuterMessage(
Gen.int().generate(),
Gen.double().generate(),
KTestAllTypes.generate(),
Gen.string().generateNotEmpty()
)
}
}
@Serializable
data class KTestIntListMessage(
val s: Int,
val l: List<Int>
) {
companion object : Gen<KTestIntListMessage> {
override fun generate() = KTestIntListMessage(Gen.int().generate(), Gen.list(Gen.int()).generate())
}
}
@Serializable
data class KTestObjectListMessage(
val inner: List<KTestAllTypes>
) {
companion object : Gen<KTestObjectListMessage> {
override fun generate() = KTestObjectListMessage(Gen.list(KTestAllTypes.Companion).generate())
}
}
enum class KCoffee { AMERICANO, LATTE, CAPPUCCINO }
@Serializable
data class KTestEnum(val a: KCoffee) {
companion object : Gen<KTestEnum> {
override fun generate(): KTestEnum = KTestEnum(Gen.oneOf<KCoffee>().generate())
}
}
@Serializable
data class KTestMap(val s: Map<String, String>, val o: Map<Int, KTestAllTypes> = emptyMap()) {
companion object : Gen<KTestMap> {
override fun generate(): KTestMap =
KTestMap(Gen.map(Gen.string(), Gen.string()).generate(), Gen.map(Gen.int(), KTestAllTypes).generate())
}
}
}
init {
"CBOR Writer" {
should("serialize random int32") { forAll(KTestData.KTestInt32.Companion) { dumpCborCompare(it) } }
should("serialize random signed int32") { forAll(KTestData.KTestSignedInt.Companion) { dumpCborCompare(it) } }
should("serialize random signed int64") { forAll(KTestData.KTestSignedLong.Companion) { dumpCborCompare(it) } }
should("serialize random fixed int32") { forAll(KTestData.KTestFixedInt.Companion) { dumpCborCompare(it) } }
should("serialize random doubles") { forAll(KTestData.KTestDouble.Companion) { dumpCborCompare(it) } }
should("serialize random booleans") { forAll(KTestData.KTestBoolean.Companion) { dumpCborCompare(it) } }
should("serialize random enums") { forAll(KTestData.KTestEnum.Companion) { dumpCborCompare(it) } }
should("serialize all base random types") { forAll(KTestData.KTestAllTypes.Companion) { dumpCborCompare(it) } }
should("serialize random messages with embedded message") {
forAll(KTestData.KTestOuterMessage.Companion) {
dumpCborCompare(
it
)
}
}
should("serialize random messages with primitive list fields") {
forAll(KTestData.KTestIntListMessage.Companion) {
dumpCborCompare(
it
)
}
}
should("serialize messages with object list fields") {
forAll(KTestData.KTestObjectListMessage.Companion) {
dumpCborCompare(
it
)
}
}
should("serialize messages with scalar-key maps") {
forAll(KTestData.KTestMap.Companion) {
dumpCborCompare(
it
)
}
}
}
"CBOR Reader" {
should("read random int32") { forAll(KTestData.KTestInt32.Companion) { readCborCompare(it) } }
should("read random signed int32") { forAll(KTestData.KTestSignedInt.Companion) { readCborCompare(it) } }
should("read random signed int64") { forAll(KTestData.KTestSignedLong.Companion) { readCborCompare(it) } }
should("read random fixed int32") { forAll(KTestData.KTestFixedInt.Companion) { readCborCompare(it) } }
should("read random doubles") { forAll(KTestData.KTestDouble.Companion) { readCborCompare(it) } }
should("read random enums") { forAll(KTestData.KTestEnum.Companion) { readCborCompare(it) } }
should("read all base random types") { forAll(KTestData.KTestAllTypes.Companion) { readCborCompare(it) } }
should("read random messages with embedded message") {
forAll(KTestData.KTestOuterMessage.Companion) {
readCborCompare(
it
)
}
}
should("read random messages with primitive list fields") {
forAll(KTestData.KTestIntListMessage.Companion) {
readCborCompare(
it
)
}
}
should("read random messages with object list fields") {
forAll(KTestData.KTestObjectListMessage.Companion) {
readCborCompare(
it
)
}
}
}
}
}
|
apache-2.0
|
2ba5d6ffebb16b704303288d48f94c8d
| 37.511628 | 123 | 0.532246 | 5.092251 | false | true | false | false |
simo-andreev/Colourizmus
|
app/src/main/java/bg/o/sim/colourizmus/view/widgets/TextDrawable.kt
|
1
|
1091
|
package bg.o.sim.colourizmus.view.widgets
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.PixelFormat.OPAQUE
import android.graphics.drawable.Drawable
import android.text.TextPaint
import androidx.annotation.ColorInt
import kotlin.math.min
class CharDrawable(
private val char: Char,
@ColorInt private val backgroundColour: Int,
@ColorInt private val textColour: Int,
private val textPaint: TextPaint = TextPaint()
) : Drawable() {
override fun setAlpha(alpha: Int) {
textPaint.alpha = alpha
}
override fun getOpacity(): Int {
return OPAQUE
}
override fun setColorFilter(colorFilter: ColorFilter?) {
textPaint.colorFilter = colorFilter
}
override fun draw(canvas: Canvas) {
canvas.drawColor(backgroundColour) // set background
textPaint.color = textColour
textPaint.textSize = min(bounds.width(), bounds.height()).toFloat()
canvas.drawText(char.toString(), 0.toFloat(), bounds.height().toFloat() - textPaint.descent(), textPaint)
}
}
|
apache-2.0
|
9d879af2f556db97bc65f6843d17de1f
| 25.634146 | 113 | 0.712191 | 4.584034 | false | false | false | false |
colmcoughlan/alchemy
|
app/src/main/java/com/colmcoughlan/colm/alchemy/adapters/DonationsAdapter.kt
|
1
|
1730
|
package com.colmcoughlan.colm.alchemy.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.colmcoughlan.colm.alchemy.R
class DonationsAdapter(
private val mContext: Context,
private val donations: Map<String, Int>
) : BaseAdapter() {
private val charities = donations.entries.sortedBy { (_, v) -> v }.map { (k,_) -> k }
override fun getCount(): Int {
return donations.size
}
override fun getItem(position: Int): String {
return charities[position]
}
override fun getItemId(position: Int): Long {
return 0
}
// create a new ImageView for each item referenced by the Adapter
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
return if (convertView == null) {
val inflater = mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val newView = inflater.inflate(R.layout.my_donations_layout, null)
val textView = newView.findViewById<TextView>(R.id.my_donations_gridview_text)
newView.tag = textView
setTextView(position, textView)
newView
} else {
val textView = convertView.tag as TextView
setTextView(position, textView)
convertView;
}
}
private fun setTextView(position: Int, textView: TextView){
val charityName = charities[position]
textView.text = String.format("%s: €%s", charityName, donations[charityName])
}
}
|
mit
|
24460c594ef63ab82536791fbd10e471
| 31.921569 | 90 | 0.644676 | 4.408163 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/inventory/LanternInventoryColumn.kt
|
1
|
1765
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory
import org.lanternpowered.api.item.inventory.ExtendedInventoryColumn
import org.lanternpowered.api.item.inventory.slot.Slot
import org.lanternpowered.api.item.inventory.slot.ExtendedSlot
import org.lanternpowered.api.util.collections.toImmutableList
import org.spongepowered.math.vector.Vector2i
open class LanternInventoryColumn : AbstractInventory2D(), ExtendedInventoryColumn {
override val width: Int
get() = 1
override fun init(children: List<AbstractInventory>, slots: List<AbstractSlot>) =
super.init(children, slots, width = 1, height = slots.size)
override fun init(children: List<AbstractInventory>) =
this.init(children, children.asSequence().slots().toImmutableList())
override fun slotOrNull(position: Vector2i): ExtendedSlot? {
if (position.x != 0)
return null
return this.slot(position.y)
}
override fun slotPositionOrNull(slot: Slot): Vector2i? {
val index = this.slotIndexOrNull(slot) ?: return null
return Vector2i(0, index)
}
override fun instantiateView(): InventoryView<LanternInventoryColumn> = View(this)
private class View(override val backing: LanternInventoryColumn) : LanternInventoryColumn(), InventoryView<LanternInventoryColumn> {
init {
this.init(this.backing.children().createViews(this).asInventories())
}
}
}
|
mit
|
1bc9a33064483dbd5c2f20585c03346f
| 35.020408 | 136 | 0.718414 | 4.192399 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/network/entity/parameter/ParameterValueType.kt
|
1
|
1655
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.entity.parameter
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.value.ContextualValueWriter
import java.util.concurrent.atomic.AtomicInteger
internal inline fun <T> parameterValueType(crossinline write: (buf: ByteBuffer, value: T) -> Unit): ParameterValueType<T> {
val writer = object : ContextualValueWriter<T> {
override fun write(ctx: CodecContext, buf: ByteBuffer, value: T) = write(buf, value)
}
return ParameterValueType(writer)
}
internal inline fun <T> parameterValueType(crossinline write: (ctx: CodecContext, buf: ByteBuffer, value: T) -> Unit): ParameterValueType<T> {
val writer = object : ContextualValueWriter<T> {
override fun write(ctx: CodecContext, buf: ByteBuffer, value: T) = write(ctx, buf, value)
}
return ParameterValueType(writer)
}
/**
* @property internalId The internal id of the parameter value type.
* @property writer The serializer to encode the values.
*/
class ParameterValueType<T> internal constructor(
val writer: ContextualValueWriter<T>
) {
companion object {
private val counter = AtomicInteger()
}
val internalId: Byte = counter.getAndIncrement().toByte()
}
|
mit
|
27c7e54efbfccf881651216058b376c5
| 35.777778 | 142 | 0.735347 | 4.1067 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/xevent/LanternXeventBus.kt
|
1
|
7904
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.xevent
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.collect.HashMultimap
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.util.type.typeToken
import org.lanternpowered.api.util.uncheckedCast
import org.lanternpowered.api.xevent.Xevent
import org.lanternpowered.api.xevent.XeventBus
import org.lanternpowered.api.xevent.XeventHandler
import org.lanternpowered.api.xevent.XeventListener
import org.lanternpowered.lmbda.LambdaFactory
import org.lanternpowered.lmbda.LambdaType
import org.lanternpowered.lmbda.kt.privateLookupIn
import org.lanternpowered.server.game.Lantern
import java.lang.invoke.MethodHandles
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.ArrayList
import java.util.Optional
import java.util.concurrent.ConcurrentHashMap
class LanternXeventBus : XeventBus {
companion object {
interface UntargetedHandler {
fun handle(target: Any, xevent: Xevent)
}
private val lookup = MethodHandles.lookup()
private val untargetedHandlerType = object : LambdaType<UntargetedHandler>() {}
/**
* A handler that isn't targeting a specific handler object. This means
* that this handler can be reused for multiple objects. This is only
* used for method event handlers.
*/
internal class UntargetedMethodHandler(val eventClass: Class<*>,
val handler: UntargetedHandler)
/**
* Cache all the method event handlers, things will get registered/unregistered
* quite a lot so avoid regenerating classes/reflection lookups.
*/
private val untargetedMethodHandlersByObjectClass = ConcurrentHashMap<Class<*>, List<UntargetedMethodHandler>>()
/**
* A map with all the generated [UntargetedMethodHandler] for a specific method.
*/
private val untargetedMethodHandlerByMethod = ConcurrentHashMap<Method, UntargetedMethodHandler>()
private fun loadUntargetedMethodHandlers(objectClass: Class<*>): List<UntargetedMethodHandler> {
val handlers = ArrayList<UntargetedMethodHandler>()
loadUntargetedMethodHandlers(handlers, objectClass)
return handlers
}
private fun loadUntargetedMethodHandlers(handlers: MutableList<UntargetedMethodHandler>, objectClass: Class<*>) {
for (method in objectClass.declaredMethods) {
// Only add entries for methods that are declared, to avoid
// duplicate entries when methods are overridden.
if (method.getDeclaredAnnotation(XeventListener::class.java) == null) {
continue
}
check(!Modifier.isStatic(method.modifiers)) { "ShardeventListener methods cannot be static" }
check(method.returnType == Void.TYPE) { "ShardeventListener methods cannot have a return type" }
check(method.parameterCount == 1 && Xevent::class.java.isAssignableFrom(method.parameterTypes[0])) {
"ShardeventListener methods can only have one parameter and must extend Shardevent"}
// Generate a Shardevent handler for the method
val methodHandler = this.untargetedMethodHandlerByMethod.computeIfAbsent(method) {
// Convert the method to a method handle
val methodHandle = this.lookup.privateLookupIn(method.declaringClass).unreflect(method)
UntargetedMethodHandler(method.parameterTypes[0], LambdaFactory.create(this.untargetedHandlerType, methodHandle))
}
handlers.add(methodHandler)
}
for (interf in objectClass.interfaces) {
loadUntargetedMethodHandlers(handlers, interf)
}
val superclass = objectClass.superclass
if (superclass != null && superclass != Any::class.java) {
loadUntargetedMethodHandlers(handlers, superclass)
}
}
/**
* Gets all the [UntargetedMethodHandler]s that are
* present on the given object class.
*
* @param objectClass The object class
* @return The untargeted method handlers
*/
private fun getUntargetedMethodHandlers(objectClass: Class<*>): List<UntargetedMethodHandler> {
return this.untargetedMethodHandlersByObjectClass.computeIfAbsent(objectClass, ::loadUntargetedMethodHandlers)
}
}
private abstract class InternalHandler(val handle: Any) {
abstract fun handle(event: Xevent)
}
private val handlersByClass = HashMultimap.create<Class<*>, InternalHandler>()
private val handlerCache = Caffeine.newBuilder().build(::loadHandlers)
private fun loadHandlers(eventClass: Class<*>): List<InternalHandler> {
val handlers = ArrayList<InternalHandler>()
val types = eventClass.typeToken.types.rawTypes()
synchronized(this.handlersByClass) {
for (type in types) {
if (Xevent::class.java.isAssignableFrom(type)) {
handlers.addAll(this.handlersByClass.get(type))
}
}
}
return handlers
}
override fun post(event: Xevent) {
post(event, this.handlerCache.get(event.javaClass)!!)
}
override fun <T : Xevent> post(eventType: Class<T>, supplier: () -> T): Optional<T> {
val handlers = this.handlerCache.get(eventType)!!
var event: T? = null
if (handlers.isNotEmpty()) {
event = supplier()
post(event, handlers)
}
return event.asOptional()
}
private fun post(event: Xevent, handlers: List<InternalHandler>) {
for (handler in handlers) {
try {
handler.handle(event)
} catch (e: Exception) {
Lantern.getLogger().error("Failed to handle Shardevent", e)
}
}
}
override fun register(any: Any) {
val untargetedHandlers = getUntargetedMethodHandlers(any.javaClass)
synchronized(this.handlersByClass) {
for (handler in untargetedHandlers) {
this.handlersByClass.put(handler.eventClass, object : InternalHandler(any) {
override fun handle(event: Xevent) {
handler.handler.handle(this.handle, event)
}
})
}
}
this.handlerCache.invalidateAll()
}
override fun <T : Xevent> register(eventType: Class<T>, handler: XeventHandler<T>) {
synchronized(this.handlersByClass) {
this.handlersByClass.put(eventType, object : InternalHandler(handler) {
override fun handle(event: Xevent) {
handler.handle(event.uncheckedCast())
}
})
}
this.handlerCache.invalidateAll()
}
override fun unregister(any: Any) {
synchronized(this.handlersByClass) {
this.handlersByClass.values().removeIf { it.handle === any }
}
this.handlerCache.invalidateAll()
}
override fun <T : Xevent> unregister(eventType: Class<T>, handler: XeventHandler<T>) {
synchronized(this.handlersByClass) {
this.handlersByClass.get(eventType).removeIf { it.handle === handler }
}
this.handlerCache.invalidateAll()
}
}
|
mit
|
69d1bf8e06950aff811dd920e8031528
| 39.953368 | 133 | 0.644484 | 4.772947 | false | false | false | false |
cdietze/brewcontrol
|
src/main/kotlin/brewcontrol/MashSystem.kt
|
1
|
6305
|
package brewcontrol
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import react.Connection
import react.Value
import react.ValueView
import react.Values
import java.time.Duration
import java.time.Instant
import java.util.concurrent.Future
/** A recipe is a immutable list of steps.
*/
data class Recipe(val steps: List<Step> = emptyList())
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value = HeatStep::class, name = "Heat"),
JsonSubTypes.Type(value = RestStep::class, name = "Rest"),
JsonSubTypes.Type(value = HoldStep::class, name = "Hold")
)
interface Step {
}
data class HeatStep(val temperature: Double) : Step
data class RestStep(val duration: Duration) : Step
object HoldStep : Step
/** A [RecipeProcess] is the run-time representation of [Recipe] */
@JsonIgnoreProperties("recipe")
class RecipeProcess(val recipe: Recipe = Recipe()) {
/** The index of the currently active task if any.
*
* - `activeTaskIndex < 0` means the program has not started yet
* - `activeTaskIndex == tasks.size` means the program is done
*/
var activeTaskIndex: Int = -1
val tasks: List<Task> = recipeToTasks(recipe)
}
fun recipeToTasks(recipe: Recipe): List<Task> {
var lastTemperature: Double? = null
return recipe.steps.flatMap<Step, Task> { step ->
when (step) {
is HeatStep -> {
lastTemperature = step.temperature
listOf(HeatTask(step))
}
is RestStep -> listOf(RestTask(step, lastTemperature))
is HoldStep -> listOf(HoldTask(step, lastTemperature))
else -> error("Unknown step type: $step")
}
}
}
interface Task {
class Context(val instant: Instant, val potTemperature: Double, val heater: Value<Boolean>)
enum class StepResult {
RUNNING, DONE
}
fun step(ctx: Context): StepResult
}
private val temperatureTolerance = 1.0
data class HeatTask(val step: HeatStep, var startTime: Instant? = null) : Task {
override fun step(ctx: Task.Context): Task.StepResult {
if (startTime == null) startTime = ctx.instant
val shouldHeat = ctx.potTemperature < (step.temperature - temperatureTolerance)
ctx.heater.update(shouldHeat)
return if (shouldHeat) Task.StepResult.RUNNING else Task.StepResult.DONE
}
}
data class RestTask(val step: RestStep, val temperature: Double?, var startTime: Instant? = null) : Task {
override fun step(ctx: Task.Context): Task.StepResult {
if (startTime == null) startTime = ctx.instant
val shouldHeat = temperature != null && ctx.potTemperature < (temperature - temperatureTolerance)
ctx.heater.update(shouldHeat)
return if (Duration.between(startTime!!, ctx.instant) > step.duration) Task.StepResult.DONE else Task.StepResult.RUNNING
}
}
data class HoldTask(val step: HoldStep, val temperature: Double?, var startTime: Instant? = null) : Task {
override fun step(ctx: Task.Context): Task.StepResult {
if (startTime == null) startTime = ctx.instant
val shouldHeat = temperature != null && ctx.potTemperature < (temperature - temperatureTolerance)
ctx.heater.update(shouldHeat)
return Task.StepResult.RUNNING
}
}
class MashSystem(
val potTemperature: ValueView<Double?>,
val potHeater: Value<Boolean>,
val clock: ValueView<Instant>
) {
val recipe: Recipe get() = recipeProcess.recipe
var recipeProcess: RecipeProcess = RecipeProcess()
fun setRecipe(recipe: Recipe) {
stop()
recipeProcess = RecipeProcess(recipe)
}
var reactConnection: Connection? = null
fun start() {
if (reactConnection != null) {
log.warn("Already running")
} else {
reactConnection = Values.join(clock, potTemperature).connectNotify { t1, t2 ->
log.info("Stepping, clock: {}, pot: {}", clock.get(), potTemperature.get())
step()
}
}
}
private fun stop() {
potHeater.update(false)
reactConnection?.close()
reactConnection = null
}
fun reset() {
stop()
recipeProcess = RecipeProcess(recipeProcess.recipe)
}
fun skipTask() {
if (recipeProcess.activeTaskIndex < recipeProcess.tasks.size) recipeProcess.activeTaskIndex++
step()
}
fun isRunning(): Boolean {
return reactConnection != null
}
private fun step() {
val potTemp = potTemperature.get()
if (potTemp == null) {
log.error("Pot temperature not available while running recipe, will turn off heater")
potHeater.update(false)
return
}
val ctx = Task.Context(clock.get(), potTemp, potHeater)
// Start the recipe if it has not already
if (recipeProcess.activeTaskIndex < 0) recipeProcess.activeTaskIndex = 0
tailrec fun impl() {
val currentTask = recipeProcess.tasks.getOrElse(recipeProcess.activeTaskIndex, {
log.info("Recipe done")
stop()
return
})
when (currentTask.step(ctx)) {
Task.StepResult.RUNNING -> {
}
Task.StepResult.DONE -> {
recipeProcess.activeTaskIndex++
impl() // Run the following task immediately
}
}
}
impl()
}
}
/** Wrapper around [MashSystem] that runs all methods on the [UpdateThread] */
class SynchronizedMashSystem(val mashSystem: MashSystem, val updateThread: UpdateThread) {
fun start(): Future<*> {
return updateThread.runOnUpdateThread { mashSystem.start() }
}
fun reset(): Future<*> {
return updateThread.runOnUpdateThread { mashSystem.reset() }
}
fun skipTask(): Future<*> {
return updateThread.runOnUpdateThread { mashSystem.skipTask() }
}
fun setRecipe(recipe: Recipe): Future<*> {
return updateThread.runOnUpdateThread { mashSystem.setRecipe(recipe) }
}
}
|
apache-2.0
|
e98bef2fab5441c6cc27469cd90b2279
| 31.333333 | 128 | 0.639175 | 4.254386 | false | false | false | false |
Mithrandir21/Duopoints
|
app/src/main/java/com/duopoints/android/fragments/points/steps/media/GivePointsMediaPresenter.kt
|
1
|
1898
|
package com.duopoints.android.fragments.points.steps.media
import android.net.Uri
import com.duopoints.android.fragments.base.BasePresenter
class GivePointsMediaPresenter(givePointsMediaFrag: GivePointsMediaFrag) : BasePresenter<GivePointsMediaFrag>(givePointsMediaFrag) {
val oneImageChosen = 1
val twoImageChosen = 2
val threeImageChosen = 3
val fourImageChosen = 4
val fiveImageChosen = 5
val sixImageChosen = 6
val oneImageCropped = 7
val twoImageCropped = 8
val threeImageCropped = 9
val fourImageCropped = 10
val fiveImageCropped = 11
val sixImageCropped = 12
fun handleImageSelected(imageUri: Uri, imageChosenRequestCode: Int) {
when (imageChosenRequestCode) {
oneImageChosen -> view.startCroppingImage(imageUri, oneImageCropped)
twoImageChosen -> view.startCroppingImage(imageUri, twoImageCropped)
threeImageChosen -> view.startCroppingImage(imageUri, threeImageCropped)
fourImageChosen -> view.startCroppingImage(imageUri, fourImageCropped)
fiveImageChosen -> view.startCroppingImage(imageUri, fiveImageCropped)
sixImageChosen -> view.startCroppingImage(imageUri, sixImageCropped)
}
}
fun handleImageCropped(imageUri: Uri?, imageCroppedRequestCode: Int) {
when (imageCroppedRequestCode) {
oneImageCropped -> view.setImageOne(imageUri)
twoImageCropped -> view.setImageTwo(imageUri)
threeImageCropped -> view.setImageThree(imageUri)
fourImageCropped -> view.setImageFour(imageUri)
fiveImageCropped -> view.setImageFive(imageUri)
sixImageCropped -> view.setImageSix(imageUri)
}
// Regardless of which image was selected, we need to update the clickables and Uri's.
view.updateClickables()
view.updateEventMediaUris()
}
}
|
gpl-3.0
|
a76dd48f41c9a61b2b1ceb2bc9a75ac2
| 38.5625 | 132 | 0.711275 | 4.519048 | false | false | false | false |
ykrank/S1-Next
|
library/src/main/java/com/github/ykrank/androidtools/ui/UiGlobalData.kt
|
1
|
461
|
package com.github.ykrank.androidtools.ui
/**
* Created by ykrank on 2017/11/6.
*/
object UiGlobalData {
var provider: UiDataProvider? = null
var R: RProvider? = null
lateinit var toast: (CharSequence?, Int) -> Unit
/**
* 初始化全局参数
*/
fun init(uiProvider: UiDataProvider?, R: RProvider?, toast: (CharSequence?, Int) -> Unit) {
this.provider = uiProvider
this.R = R
this.toast = toast
}
}
|
apache-2.0
|
ef917feedaa116d11db6fb25bd004755
| 22.578947 | 95 | 0.610738 | 3.694215 | false | false | false | false |
Mithrandir21/Duopoints
|
app/src/main/java/com/duopoints/android/ui/views/ThinNavLineView.kt
|
1
|
2081
|
package com.duopoints.android.ui.views
import android.content.Context
import android.graphics.Color
import android.support.annotation.DrawableRes
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import com.duopoints.android.R
import kotlinx.android.synthetic.main.custom_view_thin_nav.view.*
class ThinNavLineView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(context, attrs, defStyleAttr) {
init {
attrs?.let {
val ta = context.obtainStyledAttributes(it, R.styleable.ThinNavLineView, 0, 0)
val iconResource: Int
val iconBackgroundColor: Int
val navTitle: String?
val showEndIcon: Boolean
try {
iconResource = ta.getResourceId(R.styleable.ThinNavLineView_nav_icon_resource, R.drawable.ic_check_black)
iconBackgroundColor = ta.getColor(R.styleable.ThinNavLineView_nav_icon_background, Color.RED)
navTitle = ta.getString(R.styleable.ThinNavLineView_nav_title)
showEndIcon = ta.getBoolean(R.styleable.ThinNavLineView_nav_show_end_icon, true)
} finally {
ta.recycle()
}
View.inflate(context, R.layout.custom_view_thin_nav, this)
setNavIcon(iconResource)
setNavIconBackground(iconBackgroundColor)
setNavTitle(navTitle ?: "Missing Title")
showNavIconEnd(showEndIcon)
}
}
fun setNavIcon(@DrawableRes icon: Int) = thinNavIcon.setImageResource(icon)
fun setNavIcon(@DrawableRes icon: Int, badgeCount: Int) {
setNavIcon(icon)
thinNavIconBadge.setNumber(badgeCount, true)
}
fun setNavIconBackground(color: Int) = thinNavIcon.setBackgroundColor(color)
fun setNavTitle(title: String) {
thinNavTitle.text = title
}
fun showNavIconEnd(show: Boolean) {
thinNavIconEnd.visibility = if (show) View.VISIBLE else View.GONE
}
}
|
gpl-3.0
|
adb141abeae997ba0665347dedbdc88f
| 34.271186 | 121 | 0.678039 | 4.212551 | false | false | false | false |
thm-projects/arsnova-backend
|
websocket/src/main/kotlin/de/thm/arsnova/service/wsgateway/event/RoomSubscriptionEventDispatcher.kt
|
1
|
4145
|
package de.thm.arsnova.service.wsgateway.event
import de.thm.arsnova.service.wsgateway.model.RoomSubscription
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationEventPublisher
import org.springframework.context.event.EventListener
import org.springframework.messaging.simp.stomp.StompHeaderAccessor
import org.springframework.stereotype.Component
import org.springframework.web.socket.messaging.SessionDisconnectEvent
import org.springframework.web.socket.messaging.SessionSubscribeEvent
import org.springframework.web.socket.messaging.SessionUnsubscribeEvent
import java.util.concurrent.ConcurrentHashMap
@Component
class RoomSubscriptionEventDispatcher(
private val applicationEventPublisher: ApplicationEventPublisher,
) {
private val logger = LoggerFactory.getLogger(this::class.java)
private val roomTopicPattern = Regex("^/topic/([0-9a-f]{32})\\.stream$")
private val wsSessionIdToSubscriptionMapping = ConcurrentHashMap<String, RoomSubscription>()
fun getWsSessionCount(): Int {
return wsSessionIdToSubscriptionMapping.size
}
@EventListener
fun dispatchSubscribeEvent(event: SessionSubscribeEvent) {
val accessor = StompHeaderAccessor.wrap(event.message)
logger.trace("Handling session subscribe event: {}", accessor)
val result = roomTopicPattern.find(accessor.destination!!) ?: return
val roomId = result.groups[1]!!.value
val userId = accessor.user?.name ?: return
val roomSubscription: RoomSubscription
synchronized(wsSessionIdToSubscriptionMapping) {
val oldRoomSubscription = wsSessionIdToSubscriptionMapping[accessor.sessionId]
if (oldRoomSubscription != null) {
applicationEventPublisher.publishEvent(
RoomLeaveEvent(
wsSessionId = accessor.sessionId!!,
userId = userId,
roomId = oldRoomSubscription.roomId,
)
)
}
roomSubscription = RoomSubscription(
subscriptionId = accessor.subscriptionId!!,
roomId = roomId,
)
logger.debug("Adding WS session -> subscription mapping: {} -> {}, ", accessor.sessionId, roomSubscription)
wsSessionIdToSubscriptionMapping[accessor.sessionId!!] = roomSubscription
applicationEventPublisher.publishEvent(
RoomJoinEvent(
wsSessionId = accessor.sessionId!!,
userId = userId,
roomId = roomSubscription.roomId,
)
)
}
}
@EventListener
fun dispatchUnsubscribeEvent(event: SessionUnsubscribeEvent) {
val accessor = StompHeaderAccessor.wrap(event.message)
logger.trace("Handling session unsubscribe event: {}", accessor)
val userId = accessor.user?.name ?: return
synchronized(wsSessionIdToSubscriptionMapping) {
val roomSubscription = wsSessionIdToSubscriptionMapping[accessor.sessionId]
if (roomSubscription == null || accessor.subscriptionId != roomSubscription.subscriptionId) {
return
}
logger.debug("Removing WS session -> subscription mapping: {} -> {}, ", accessor.sessionId, roomSubscription)
wsSessionIdToSubscriptionMapping.remove(accessor.sessionId)
applicationEventPublisher.publishEvent(
RoomLeaveEvent(
wsSessionId = accessor.sessionId!!,
userId = userId,
roomId = roomSubscription.roomId,
)
)
}
}
@EventListener
fun dispatchDisconnectEvent(event: SessionDisconnectEvent) {
val accessor = StompHeaderAccessor.wrap(event.message)
logger.trace("Handling session disconnect event: {}", accessor)
val userId = accessor.user?.name ?: return
synchronized(wsSessionIdToSubscriptionMapping) {
val roomSubscription = wsSessionIdToSubscriptionMapping[accessor.sessionId] ?: return
logger.debug("Removing WS session -> subscription mapping: {} -> {}, ", accessor.sessionId, roomSubscription)
wsSessionIdToSubscriptionMapping.remove(accessor.sessionId)
applicationEventPublisher.publishEvent(
RoomLeaveEvent(
wsSessionId = accessor.sessionId!!,
userId = userId,
roomId = roomSubscription.roomId,
)
)
}
}
}
|
gpl-3.0
|
aa4071dea97e802c7e222b65eb2552e4
| 40.039604 | 115 | 0.730277 | 4.987966 | false | false | false | false |
didi/DoraemonKit
|
Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/DoKitPlugin.kt
|
2
|
8645
|
package com.didichuxing.doraemonkit.plugin
import com.android.build.gradle.AppExtension
import com.android.build.gradle.LibraryExtension
import com.didichuxing.doraemonkit.plugin.extension.DoKitExt
import com.didichuxing.doraemonkit.plugin.extension.SlowMethodExt
import com.didichuxing.doraemonkit.plugin.processor.DoKitPluginConfigProcessor
import com.didichuxing.doraemonkit.plugin.stack_method.MethodStackNodeUtil
import com.didichuxing.doraemonkit.plugin.transform.*
import com.didiglobal.booster.gradle.GTE_V3_4
import com.didiglobal.booster.gradle.dependencies
import com.didiglobal.booster.gradle.getAndroid
import com.didiglobal.booster.gradle.getProperty
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.result.ResolvedArtifactResult
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/5/14-10:01
* 描 述:
* 修订历史:
* ================================================
*/
class DoKitPlugin : Plugin<Project> {
override fun apply(project: Project) {
//创建指定扩展 并将project 传入构造函数
val doKitExt = project.extensions.create("dokitExt", DoKitExt::class.java)
project.gradle.addListener(DoKitTransformTaskExecutionListener(project))
//println("project.plugins===>${project.plugins}")
/**
* when 也可以用来取代 if-else if链。
* 如果不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支:
*/
/**
* 作用域函数:let、run、with、apply 以及 also
* 它们的唯一目的是在对象的上下文中执行代码块
* 由于作用域函数本质上都非常相似,因此了解它们之间的区别很重要。每个作用域函数之间有两个主要区别:
* 引用上下文对象的方式:
* 作为 lambda 表达式的接收者(this)或者作为 lambda 表达式的参数(it)
* run、with 以及 apply 通过关键字 this 引用上下文对象
* let 及 also 将上下文对象作为 lambda 表达式参数
*
* 返回值:
* apply 及 also 返回上下文对象。
* let、run 及 with 返回 lambda 表达式结果.
*/
/**
* 函数 对象引用 返回值 是否是扩展函数
* let it Lambda 表达式结果 是
* run this Lambda 表达式结果 是
* run - Lambda 表达式结果 不是:调用无需上下文对象
* with this Lambda 表达式结果 不是:把上下文对象当做参数
* apply this 上下文对象 是
* also it 上下文对象 是
*/
/**
*对一个非空(non-null)对象执行 lambda 表达式:let
*将表达式作为变量引入为局部作用域中:let
*对象配置:apply
*对象配置并且计算结果:run
*在需要表达式的地方运行语句:非扩展的 run
*附加效果:also
*一个对象的一组函数调用:with
*/
when {
project.plugins.hasPlugin("com.android.application") || project.plugins.hasPlugin("com.android.dynamic-feature") -> {
if (!isReleaseTask(project)) {
project.getAndroid<AppExtension>().let { androidExt ->
val pluginSwitch = project.getProperty("DOKIT_PLUGIN_SWITCH", true)
val logSwitch = project.getProperty("DOKIT_LOG_SWITCH", false)
val slowMethodSwitch = project.getProperty("DOKIT_METHOD_SWITCH", false)
val slowMethodStrategy = project.getProperty("DOKIT_METHOD_STRATEGY", 0)
val methodStackLevel = project.getProperty("DOKIT_METHOD_STACK_LEVEL", 5)
val webViewClassName = project.getProperty("DOKIT_WEBVIEW_CLASS_NAME", "")
val thirdLibInfo = project.getProperty("DOKIT_THIRD_LIB_SWITCH", true)
DoKitExtUtil.DOKIT_PLUGIN_SWITCH = pluginSwitch
DoKitExtUtil.DOKIT_LOG_SWITCH = logSwitch
DoKitExtUtil.SLOW_METHOD_SWITCH = slowMethodSwitch
DoKitExtUtil.SLOW_METHOD_STRATEGY = slowMethodStrategy
DoKitExtUtil.STACK_METHOD_LEVEL = methodStackLevel
DoKitExtUtil.WEBVIEW_CLASS_NAME = webViewClassName
DoKitExtUtil.THIRD_LIBINFO_SWITCH = thirdLibInfo
"application module ${project.name} is executing...".println()
MethodStackNodeUtil.METHOD_STACK_KEYS.clear()
if (DoKitExtUtil.DOKIT_PLUGIN_SWITCH) {
//注册transform
androidExt.registerTransform(commNewInstance(project))
if (slowMethodSwitch && slowMethodStrategy == SlowMethodExt.STRATEGY_STACK) {
MethodStackNodeUtil.METHOD_STACK_KEYS.add(0, mutableSetOf<String>())
val methodStackRange = 1 until methodStackLevel
if (methodStackLevel > 1) {
for (index in methodStackRange) {
MethodStackNodeUtil.METHOD_STACK_KEYS.add(
index,
mutableSetOf<String>()
)
androidExt.registerTransform(
dependNewInstance(project, index)
)
}
}
}
}
//项目评估完毕回调
// project.afterEvaluate { project ->
// "===afterEvaluate===".println()
// androidExt.applicationVariants.forEach { variant ->
// DoKitPluginConfigProcessor(project).process(variant)
// }
// }
/**
* 所有项目的build.gradle执行完毕
* wiki:https://juejin.im/post/6844903607679057934
*
* **/
project.gradle.projectsEvaluated {
"===projectsEvaluated===".println()
androidExt.applicationVariants.forEach { variant ->
DoKitPluginConfigProcessor(project).process(variant)
}
}
//task依赖关系图建立完毕
project.gradle.taskGraph.whenReady {
"===taskGraph.whenReady===".println()
}
}
}
}
project.plugins.hasPlugin("com.android.library") -> {
if (!isReleaseTask(project)) {
project.getAndroid<LibraryExtension>().let { libraryExt ->
"library module ${project.name} is executing...".println()
if (DoKitExtUtil.DOKIT_PLUGIN_SWITCH) {
libraryExt.registerTransform(commNewInstance(project))
}
project.afterEvaluate {
libraryExt.libraryVariants.forEach { variant ->
DoKitPluginConfigProcessor(project).process(variant)
}
}
}
}
}
}
}
private fun isReleaseTask(project: Project): Boolean {
return project.gradle.startParameter.taskNames.any {
it.contains("release") || it.contains("Release")
}
}
private fun commNewInstance(project: Project): DoKitBaseTransform = when {
GTE_V3_4 -> DoKitCommTransformV34(project)
else -> DoKitCommTransform(project)
}
private fun dependNewInstance(project: Project, index: Int): DoKitBaseTransform = when {
GTE_V3_4 -> DoKitDependTransformV34(project, index)
else -> DoKitDependTransform(project, index)
}
}
|
apache-2.0
|
4cdcb339e174888bd60e4c9f8c17a2e2
| 41.906077 | 129 | 0.516162 | 4.819988 | false | false | false | false |
nickthecoder/paratask
|
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/GenerateCompletionTask.kt
|
1
|
3738
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.parameters.StringParameter
import uk.co.nickthecoder.paratask.util.child
import uk.co.nickthecoder.paratask.util.currentDirectory
import java.io.PrintStream
/**
* Generates a bash script suitable for adding to /etc/bash_completion.d, which aids prompting of the
* paratask script (which is the main entry point into the application, and can launch any of the
* registered tasks or tools).
*
* See Gnu's documentation on how command completion works :
* https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html
*/
class GenerateCompletionTask : AbstractTask() {
val commandNameP = StringParameter("commandName", value = "paratask")
val commandName by commandNameP
val outputFileP = FileParameter("output", expectFile = true, mustExist = null,
value = currentDirectory.child("src", "dist", "bash_complete.d", "paratask"))
override val taskD = TaskDescription("generateCompletion")
.addParameters(commandNameP, outputFileP)
lateinit var out: PrintStream
override fun run() {
if (outputFileP.value == null) {
out = System.out
} else {
out = PrintStream(outputFileP.value)
}
try {
out.println("# Generated by : paratask ${taskD.name} --commandName ${commandName}")
out.println("# Copy to /etc/bash_completion.d/$commandName for system wide tab-completion of paratask commands.")
out.println()
GenerateTaskCompletionTask.generateFileComplete(out, commandName)
out.println("_${commandName}Complete()")
out.println("{")
out.println(" local taskName cur prev")
out.println(" COMPREPLY=()")
out.println(" _get_comp_words_by_ref cur prev\n")
out.println(" if [ \"\${COMP_CWORD}\" == 1 ]")
out.println(" then")
out.println(" COMPREPLY=( \$( compgen -W '${TaskRegistry.allTasks().map { it.taskD.name }.sorted().joinToString(separator = " ")}' -- \$cur ) )")
out.println(" else")
out.println(" taskName=\${COMP_WORDS[1]}")
out.println(" case \$taskName in")
TaskRegistry.allTasks().sortedBy { it.taskD.name }.forEach { task ->
out.println(" ${task.taskD.name})\n")
GenerateTaskCompletionTask.generateForTask(out, task, commandName)
out.println(" ;;\n")
}
out.println(" esac") // End case TASK
out.println(" ")
out.println(" fi")
out.println("}\n")
out.println("complete -F _${commandName}Complete $commandName")
} finally {
if (out != System.out) {
out.close()
}
}
}
}
fun main(args: Array<String>) {
TaskParser(GenerateCompletionTask()).go(args)
}
|
gpl-3.0
|
75333bf42d82857adc5e88af7a86230e
| 37.142857 | 164 | 0.633226 | 4.346512 | false | false | false | false |
arturbosch/detekt
|
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Debt.kt
|
1
|
1411
|
package io.gitlab.arturbosch.detekt.api
/**
* Debt describes the estimated amount of work needed to fix a given issue.
*/
@Suppress("MagicNumber")
data class Debt(val days: Int = 0, val hours: Int = 0, val mins: Int = 0) {
init {
require(days >= 0 && hours >= 0 && mins >= 0)
require(!(days == 0 && hours == 0 && mins == 0))
}
/**
* Adds the other debt to this debt.
* This recalculates the potential overflow resulting from the addition.
*/
operator fun plus(other: Debt): Debt {
var minutes = mins + other.mins
var hours = hours + other.hours
var days = days + other.days
hours += minutes / MINUTES_PER_HOUR
minutes %= MINUTES_PER_HOUR
days += hours / HOURS_PER_DAY
hours %= HOURS_PER_DAY
return Debt(days, hours, minutes)
}
override fun toString(): String {
return with(StringBuilder()) {
if (days > 0) append("${days}d ")
if (hours > 0) append("${hours}h ")
if (mins > 0) append("${mins}min")
toString()
}.trimEnd()
}
companion object {
val TWENTY_MINS: Debt =
Debt(0, 0, 20)
val TEN_MINS: Debt =
Debt(0, 0, 10)
val FIVE_MINS: Debt =
Debt(0, 0, 5)
private const val HOURS_PER_DAY = 24
private const val MINUTES_PER_HOUR = 60
}
}
|
apache-2.0
|
3f31920845b188ad7491cd582c9d8eb5
| 28.395833 | 76 | 0.540043 | 3.908587 | false | false | false | false |
Guardsquare/proguard
|
base/src/test/kotlin/proguard/AfterInitConfigurationCheckerTest.kt
|
1
|
5871
|
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2022 Guardsquare NV
*/
package proguard
import io.kotest.assertions.throwables.shouldNotThrow
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.string.shouldContain
import proguard.classfile.ProgramClass
import proguard.classfile.VersionConstants.CLASS_VERSION_11
import proguard.classfile.VersionConstants.CLASS_VERSION_12
import proguard.classfile.VersionConstants.CLASS_VERSION_17
import proguard.classfile.VersionConstants.CLASS_VERSION_18
import proguard.classfile.VersionConstants.CLASS_VERSION_1_6
import testutils.asConfiguration
import testutils.getLogOutputOf
import java.util.UUID
/**
* Test the after init checks.
*/
class AfterInitConfigurationCheckerTest : FreeSpec({
// Mock a program class with the given class file version.
class FakeClass(version: Int) : ProgramClass(version, 1, emptyArray(), 1, -1, -1) {
override fun getClassName(constantIndex: Int): String {
return "Fake${UUID.randomUUID()}"
}
}
"Given a configuration with target specified" - {
val configuration = """
-verbose
-target 6
""".trimIndent().asConfiguration()
"It should throw an exception if program class pool contains a class with class file version > jdk 11" {
val view = AppView()
view.programClassPool.addClass(FakeClass(CLASS_VERSION_12))
val exception = shouldThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
exception.message shouldContain "-target can only be used with class file versions <= 55 (Java 11)."
exception.message shouldContain "The input classes contain version 56 class files which cannot be backported to target version (50)."
}
"It should not throw an exception if program class pool contains classes with class file version = jdk 11" {
val view = AppView()
view.programClassPool.addClass(FakeClass(CLASS_VERSION_11))
shouldNotThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
}
"It should not throw an exception if program class pool contains classes with class file version < jdk 11" {
val view = AppView()
view.programClassPool.addClass(FakeClass(CLASS_VERSION_1_6))
shouldNotThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
}
}
"Given a configuration with a target specified and classes above Java 11" - {
val configuration = """
-target 17
""".trimIndent().asConfiguration()
"It should not throw an exception if -target is set but all the classes are already at the targeted version (no backport needed)" {
val view = AppView()
with(view.programClassPool) {
addClass(FakeClass(CLASS_VERSION_17))
addClass(FakeClass(CLASS_VERSION_17))
}
shouldNotThrow<RuntimeException> { AfterInitConfigurationChecker(configuration).execute(view) }
}
"It should print a warning" {
val view = AppView()
with(view.programClassPool) {
addClass(FakeClass(CLASS_VERSION_17))
addClass(FakeClass(CLASS_VERSION_17))
}
val output = getLogOutputOf {
AfterInitConfigurationChecker(configuration).execute(view)
}
output shouldContain "-target is deprecated when using class file above"
}
"It should throw an exception if -target is set and the version of one of the classes version is different from the target version" {
val view = AppView()
with(view.programClassPool) {
addClass(FakeClass(CLASS_VERSION_18))
addClass(FakeClass(CLASS_VERSION_17))
}
val exception = shouldThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
exception.message shouldContain "-target can only be used with class file versions <= 55 (Java 11)."
exception.message shouldContain "The input classes contain version 62 class files which cannot be backported to target version (61)."
}
}
"Given a configuration with no target specified" - {
val configuration = """
-verbose
""".trimIndent().asConfiguration()
"It should not throw an exception if program class pool contains classes with class file version > jdk 11" {
val view = AppView()
view.programClassPool.addClass(FakeClass(CLASS_VERSION_12))
shouldNotThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
}
"It should not throw an exception if program class pool contains classes with class file version = jdk 11" {
val view = AppView()
view.programClassPool.addClass(FakeClass(CLASS_VERSION_11))
shouldNotThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
}
"It should not throw an exception if program class pool contains classes with class file version < jdk 11" {
val view = AppView()
view.programClassPool.addClass(FakeClass(CLASS_VERSION_1_6))
shouldNotThrow<RuntimeException> {
AfterInitConfigurationChecker(configuration).execute(view)
}
}
}
})
|
gpl-2.0
|
f3fb2b768512b5eea1fd54d5e8f9ff55
| 37.880795 | 145 | 0.648782 | 5.005115 | false | true | false | false |
cout970/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/misc/world/ParticleSpawner.kt
|
2
|
1678
|
package com.cout970.magneticraft.misc.world
import com.cout970.magneticraft.AABB
import com.cout970.magneticraft.IVector3
import com.cout970.magneticraft.misc.vector.vec3Of
import com.cout970.magneticraft.misc.vector.xd
import com.cout970.magneticraft.misc.vector.yd
import com.cout970.magneticraft.misc.vector.zd
import com.cout970.vector.extensions.Vector3
import net.minecraft.block.Block
import net.minecraft.block.state.IBlockState
import net.minecraft.util.EnumParticleTypes
import net.minecraft.world.World
class ParticleSpawner(
val particlesPerSecond: Double,
val particle: EnumParticleTypes,
val block: IBlockState,
val speed: () -> IVector3 = { Vector3.ORIGIN },
val area: () -> AABB
) {
fun spawn(world: World) {
val perTick = (particlesPerSecond / 20)
val integer = perTick.toInt()
val fraction = perTick - integer
repeat(integer) {
forceSpawn(world)
}
if (fraction > 0 && world.rand.nextFloat() <= fraction) {
forceSpawn(world)
}
}
fun forceSpawn(world: World) {
if (world.isServer) return
val aabb = area()
val point = vec3Of(
aabb.minX.interp(aabb.maxX, world.rand.nextDouble()),
aabb.minY.interp(aabb.maxY, world.rand.nextDouble()),
aabb.minZ.interp(aabb.maxZ, world.rand.nextDouble())
)
val dir = speed()
world.spawnParticle(particle, false,
point.xd, point.yd, point.zd,
dir.xd, dir.yd, dir.zd,
Block.getStateId(block)
)
}
fun Double.interp(other: Double, point: Double) = this + (other - this) * point
}
|
gpl-2.0
|
b71ab5389dda6acc293b1f33cd01a588
| 30.092593 | 83 | 0.653754 | 3.804989 | false | false | false | false |
goodwinnk/intellij-community
|
plugins/stats-collector/src/com/intellij/completion/FeatureManagerImpl.kt
|
1
|
1690
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.BaseComponent
import com.jetbrains.completion.feature.*
import com.jetbrains.completion.feature.impl.CompletionFactors
import com.jetbrains.completion.feature.impl.FeatureInterpreterImpl
import com.jetbrains.completion.feature.impl.FeatureManagerFactory
import com.jetbrains.completion.feature.impl.FeatureReader
class FeatureManagerImpl : FeatureManager, BaseComponent {
companion object {
fun getInstance(): FeatureManager = ApplicationManager.getApplication().getComponent(FeatureManager::class.java)
}
private lateinit var manager: FeatureManager
override val binaryFactors: List<BinaryFeature> get() = manager.binaryFactors
override val doubleFactors: List<DoubleFeature> get() = manager.doubleFactors
override val categoricalFactors: List<CategoricalFeature> get() = manager.categoricalFactors
override val ignoredFactors: Set<String> get() = manager.ignoredFactors
override val completionFactors: CompletionFactors get() = manager.completionFactors
override val featureOrder: Map<String, Int> get() = manager.featureOrder
override fun createTransformer(): Transformer {
return manager.createTransformer()
}
override fun isUserFeature(name: String): Boolean = false
override fun initComponent() {
manager = FeatureManagerFactory().createFeatureManager(FeatureReader, FeatureInterpreterImpl())
}
override fun allFeatures(): List<Feature> = manager.allFeatures()
}
|
apache-2.0
|
9562dfd69ee2211028faa35304ffe178
| 43.5 | 140 | 0.808284 | 4.760563 | false | false | false | false |
ibaton/3House
|
mobile/src/main/java/treehou/se/habit/ui/control/CommandService.kt
|
1
|
3616
|
package treehou.se.habit.ui.control
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v4.app.JobIntentService
import android.util.Log
import io.realm.Realm
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import treehou.se.habit.connector.Communicator
import treehou.se.habit.core.db.model.ItemDB
import treehou.se.habit.service.CommandReceiver
import treehou.se.habit.util.ConnectionFactory
import treehou.se.habit.util.Util
import javax.inject.Inject
class CommandService : JobIntentService() {
@Inject lateinit var connectionFactory: ConnectionFactory
override fun onCreate() {
super.onCreate()
Util.getApplicationComponent(this).inject(this)
}
override fun onHandleWork(intent: Intent) {
Log.d(TAG, "onHandleIntent")
val realm = Realm.getDefaultInstance()
val itemId = intent.getLongExtra(ARG_ITEM, -1)
val action = intent.action
if (ACTION_COMMAND == action && itemId > 0) {
val command = intent.getStringExtra(ARG_COMMAND)
val item = ItemDB.load(realm, itemId)
handleActionCommand(command, item!!.toGeneric())
} else if (ACTION_INC_DEC == action && itemId > 0) {
val min = intent.getIntExtra(ARG_MIN, 0)
val max = intent.getIntExtra(ARG_MAX, 0)
val value = intent.getIntExtra(ARG_VALUE, 0)
val item = ItemDB.load(realm, itemId)
val communicator = Communicator.instance(this)
val server = item!!.server!!.toGeneric()
communicator.incDec(server, item.name, value, min, max)
}
realm.close()
}
private fun handleActionCommand(command: String, item: OHItem) {
val server = item.server
val serverHandler = connectionFactory.createServerHandler(server, this)
serverHandler.sendCommand(item.name, command)
}
companion object {
private val TAG = "CommandService"
private val ARG_ITEM = "ARG_ITEM"
private val ACTION_COMMAND = "ACTION_COMMAND"
private val ARG_COMMAND = "ARG_COMMAND"
private val ACTION_INC_DEC = "ACTION_INC_DEC"
private val ARG_MAX = "ARG_MAX"
private val ARG_MIN = "ARG_MIN"
private val ARG_VALUE = "ARG_VALUE"
private val JOB_ID = 5153
fun getActionCommand(context: Context, command: String, itemId: Long): Intent {
val intent = Intent(context, CommandReceiver::class.java)
intent.action = ACTION_COMMAND
intent.putExtra(ARG_COMMAND, command)
intent.putExtra(ARG_ITEM, itemId)
return intent
}
fun getActionIncDec(context: Context, min: Int, max: Int, value: Int, itemId: Long): Intent {
val intent = Intent(context, CommandReceiver::class.java)
intent.action = ACTION_INC_DEC
intent.putExtra(ARG_MIN, min)
intent.putExtra(ARG_MAX, max)
intent.putExtra(ARG_VALUE, value)
intent.putExtra(ARG_ITEM, itemId)
return intent
}
/**
* Convenience method for enqueuing work in to this service.
*/
fun enqueueWork(context: Context, work: Intent) {
enqueueWork(context, CommandService::class.java, JOB_ID, work);
}
fun createCommand(context: Context, requestCode: Int, intent: Intent): PendingIntent {
return PendingIntent.getBroadcast(context.applicationContext, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT)
}
}
}
|
epl-1.0
|
8653d48452be92775c0a186b96e5d632
| 35.16 | 129 | 0.650719 | 4.330539 | false | false | false | false |
nickbutcher/plaid
|
designernews/src/test/java/io/plaidapp/designernews/domain/GetStoryUseCaseTest.kt
|
1
|
2736
|
/*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.domain
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.stories.StoriesRepository
import io.plaidapp.core.designernews.data.stories.model.Story
import io.plaidapp.core.designernews.data.stories.model.StoryResponse
import io.plaidapp.designernews.storyLinks
import java.lang.Exception
import java.util.Date
import java.util.GregorianCalendar
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Tests for [GetStoryUseCase] mocking all the dependencies.
*/
class GetStoryUseCaseTest {
private val createdDate: Date = GregorianCalendar(2018, 1, 13).time
private val storyId = 45L
private val storyResponse =
StoryResponse(
id = storyId,
title = "Plaid 2.0 was released",
created_at = createdDate,
links = storyLinks
)
private val story =
Story(
id = storyId,
title = "Plaid 2.0 was released",
page = 0,
createdAt = createdDate,
userId = storyLinks.user,
links = storyLinks
)
private val storiesRepository: StoriesRepository = mock()
private val getStoryUseCase = GetStoryUseCase(storiesRepository)
@Test
fun getStory_whenStoryInRepository() {
// Given that the repository returns a story request for the id
whenever(storiesRepository.getStory(storyId)).thenReturn(Result.Success(storyResponse))
// When getting the story
val result = getStoryUseCase(storyId)
// The story is returned
assertEquals(Result.Success(story), result)
}
@Test
fun getStory_whenStoryNotInRepository() {
// Given that the repository returns with error
whenever(storiesRepository.getStory(storyId)).thenReturn(Result.Error(Exception("exception")))
// When getting the story
val result = getStoryUseCase(storyId)
// Error is return
assertTrue(result is Result.Error)
}
}
|
apache-2.0
|
1312addfa1a680e351422ea200617b25
| 32.365854 | 102 | 0.701754 | 4.463295 | false | true | false | false |
mockk/mockk
|
modules/mockk/src/commonMain/kotlin/io/mockk/impl/verify/TimeoutVerifier.kt
|
2
|
1847
|
package io.mockk.impl.verify
import io.mockk.MockKGateway.*
import io.mockk.RecordedCall
import io.mockk.impl.InternalPlatform
import io.mockk.impl.stub.StubRepository
class TimeoutVerifier(
val stubRepo: StubRepository,
val verifierChain: CallVerifier
) : CallVerifier {
override fun verify(
verificationSequence: List<RecordedCall>,
params: VerificationParameters
): VerificationResult {
val stubs = verificationSequence.allStubs(stubRepo)
val session = stubRepo.openRecordCallAwaitSession(stubs, params.timeout)
try {
while (true) {
val result = verifierChain.verify(verificationSequence, params)
if (params.inverse != result.matches) {
return result // passed
}
if (!session.wait()) {
val lastCheck = verifierChain.verify(verificationSequence, params)
if (params.inverse != lastCheck.matches) {
return lastCheck // passed
}
return lastCheck.addTimeoutToMessage(params.timeout)
}
}
} finally {
session.close()
}
}
override fun captureArguments() {
verifierChain.captureArguments()
}
private fun List<RecordedCall>.allStubs(stubRepo: StubRepository) =
this.map { InternalPlatform.ref(it.matcher.self) }
.distinct()
.map { it.value }
.map { stubRepo.stubFor(it) }
.distinct()
}
private fun VerificationResult.addTimeoutToMessage(timeout: Long) =
when (this) {
is VerificationResult.OK -> VerificationResult.OK(verifiedCalls)
is VerificationResult.Failure -> VerificationResult.Failure("$message (timeout = $timeout ms)")
}
|
apache-2.0
|
3fddac15a0e6a59f3e34aeec1de95b5f
| 32.581818 | 103 | 0.609096 | 4.978437 | false | false | false | false |
gameofbombs/kt-postgresql-async
|
postgresql-async/src/test/kotlin/com/github/mauricio/async/db/postgresql/column/ArrayDecoderSpec.kt
|
2
|
1398
|
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares 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 com.github.mauricio.async.db.postgresql.column
import com.github.mauricio.async.db.column.IntegerEncoderDecoder
import io.netty.buffer.Unpooled
import io.netty.util.CharsetUtil
import org.specs2.mutable.Specification
class ArrayDecoderSpec extends Specification {
fun execute( data : String ) : Any = {
val numbers = data.getBytes( CharsetUtil.UTF_8 )
val encoder = new ArrayDecoder(IntegerEncoderDecoder)
encoder.decode(null, Unpooled.wrappedBuffer(numbers), CharsetUtil.UTF_8)
}
"encoder/decoder" should {
"parse an array of numbers" in {
execute("{1,2,3}") === List(1, 2, 3)
}
"parse an array of array of numbers" in {
execute("{{1,2,3},{4,5,6}}") === List(List(1, 2, 3), List(4, 5, 6))
}
}
}
|
apache-2.0
|
3f3e5f95baa1acc22465eb7febacfeac
| 30.727273 | 78 | 0.713467 | 3.783198 | false | false | false | false |
is00hcw/anko
|
dsl/src/org/jetbrains/android/anko/utils/Property.kt
|
2
|
1704
|
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.utils
import org.jetbrains.android.anko.utils.MethodNodeWithClass
import org.jetbrains.android.anko.utils.fqName
import org.jetbrains.android.anko.returnType
import org.objectweb.asm.Type
class Property(val node: MethodNodeWithClass) {
val name: String
val getterName: String
get() = (if (node.method.returnType == Type.BOOLEAN_TYPE) "is" else "get") + name.capitalize()
val setterName: String
get() = "set" + name.capitalize()
val setterIdentifier: String
get() = node.clazz.fqName + "#" + setterName
val propertyFqName: String
get() = node.clazz.fqName + "." + name
init {
val methodName = node.method.name
if (methodName.startsWith("get") || methodName.startsWith("set")) {
name = methodName.substring(3).decapitalize()
} else if (methodName.startsWith("is")) {
name = methodName.substring(2).decapitalize()
} else throw IllegalArgumentException("Method $methodName is not a property")
}
}
fun MethodNodeWithClass.toProperty() = Property(this)
|
apache-2.0
|
bf7751728aac23f89f17b696e2efb53e
| 32.431373 | 102 | 0.698357 | 4.217822 | false | false | false | false |
panpf/sketch
|
sample/src/main/java/com/github/panpf/sketch/sample/ui/common/list/MyLoadStateAdapter.kt
|
1
|
1826
|
/*
* 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.sample.ui.common.list
import android.annotation.SuppressLint
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import com.github.panpf.assemblyadapter.recycler.paging.AssemblyLoadStateAdapter
class MyLoadStateAdapter(
alwaysShowWhenEndOfPaginationReached: Boolean = true
) : AssemblyLoadStateAdapter(LoadStateItemFactory(), alwaysShowWhenEndOfPaginationReached) {
var disableDisplay = false
@SuppressLint("NotifyDataSetChanged")
set(value) {
field = value
notifyDataSetChanged()
}
private var pagingDataAdapter: PagingDataAdapter<*, *>? = null
fun noDisplayLoadStateWhenPagingEmpty(pagingDataAdapter: PagingDataAdapter<*, *>) {
this.pagingDataAdapter = pagingDataAdapter
}
override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
if (disableDisplay) {
return false
}
val pagingDataAdapter = pagingDataAdapter
if (pagingDataAdapter != null && loadState is LoadState.NotLoading && pagingDataAdapter.itemCount == 0) {
return false
}
return super.displayLoadStateAsItem(loadState)
}
}
|
apache-2.0
|
0c755589c1f544bc09a012cb40bd0fb8
| 35.54 | 113 | 0.726725 | 4.767624 | false | false | false | false |
mctoyama/PixelClient
|
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/State10WaitingBeginGameResources.kt
|
1
|
1072
|
package org.pixelndice.table.pixelclient.connection.lobby.client
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelprotocol.Protobuf
import org.pixelndice.table.pixelclient.ds.FromProtobufContext
private val logger = LogManager.getLogger(State10WaitingBeginGameResources::class.java)
/**
* State that awaits for [org.pixelndice.table.pixelprotocol.Protobuf.BeginGameResources] packet
* @param fromProtobufContext Context for loading campaign data structure
*/
class State10WaitingBeginGameResources(private val fromProtobufContext: FromProtobufContext): State {
override fun process(ctx: Context) {
val packet = ctx.channel.packet
if( packet != null ){
if( packet.payloadCase == Protobuf.Packet.PayloadCase.BEGINGAMERESOURCES){
ctx.state = State11WaitingGameResource(fromProtobufContext)
}else{
val message = "Expecting BeginGameResources, instead received: $packet. IP: ${ctx.channel.address}"
logger.error(message)
}
}
}
}
|
bsd-2-clause
|
4515aed4e94b0ff7a85b11f77b43ad1e
| 41.92 | 115 | 0.73041 | 4.448133 | false | false | false | false |
joeygibson/raspimorse
|
src/main/kotlin/com/joeygibson/raspimorse/reader/Input.kt
|
1
|
1579
|
package com.joeygibson.raspimorse.reader
/*
* MIT License
*
* Copyright (c) 2017 Joey Gibson
*
* 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.
*/
enum class InputType {
KEY_PRESS,
SILENCE
}
data class Input(val inputType: InputType, val duration: Long) {
fun isKeyPress() = inputType == InputType.KEY_PRESS
fun isSilence() = !isKeyPress()
companion object {}
}
fun Input.Companion.silence(duration: Long) = Input(InputType.SILENCE, duration)
fun Input.Companion.keyPress(duration: Long) = Input(InputType.KEY_PRESS, duration)
|
mit
|
7161fe52c456ced6c0c9be445001cad2
| 38.5 | 83 | 0.751742 | 4.244624 | false | false | false | false |
AndroidX/androidx
|
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/WidgetLayout.kt
|
3
|
15187
|
/*
* 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.glance.appwidget
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.DataStore
import androidx.datastore.core.DataStoreFactory
import androidx.datastore.dataStoreFile
import androidx.glance.Emittable
import androidx.glance.EmittableButton
import androidx.glance.EmittableImage
import androidx.glance.EmittableWithChildren
import androidx.glance.GlanceModifier
import androidx.glance.action.ActionModifier
import androidx.glance.appwidget.lazy.EmittableLazyColumn
import androidx.glance.appwidget.lazy.EmittableLazyList
import androidx.glance.appwidget.lazy.EmittableLazyListItem
import androidx.glance.appwidget.lazy.EmittableLazyVerticalGrid
import androidx.glance.appwidget.lazy.EmittableLazyVerticalGridListItem
import androidx.glance.appwidget.proto.LayoutProto
import androidx.glance.appwidget.proto.LayoutProto.LayoutConfig
import androidx.glance.appwidget.proto.LayoutProto.LayoutDefinition
import androidx.glance.appwidget.proto.LayoutProto.LayoutNode
import androidx.glance.appwidget.proto.LayoutProto.LayoutType
import androidx.glance.appwidget.proto.LayoutProto.NodeIdentity
import androidx.glance.appwidget.proto.LayoutProtoSerializer
import androidx.glance.findModifier
import androidx.glance.layout.Alignment
import androidx.glance.layout.EmittableBox
import androidx.glance.layout.EmittableColumn
import androidx.glance.layout.EmittableRow
import androidx.glance.layout.EmittableSpacer
import androidx.glance.layout.HeightModifier
import androidx.glance.layout.WidthModifier
import androidx.glance.state.GlanceState
import androidx.glance.state.GlanceStateDefinition
import androidx.glance.text.EmittableText
import androidx.glance.unit.Dimension
import java.io.File
import java.io.IOException
/**
* Manager for layout configurations and their associated layout indexes.
*
* An instance of this object should be created for each update of an App Widget ID. The same
* instance must be used for all the variants of the layout. It will detect layout changes and
* ensure the same layout IDs are not re-used.
*
* Layout indexes are numbers between 0 and [TopLevelLayoutsCount]-1, which need to be passed to
* [translateComposition] to generate the [android.widget.RemoteViews] corresponding to a given
* layout.
*/
internal class LayoutConfiguration private constructor(
private val context: Context,
/**
* Map the known layout configs to a unique layout index. It will contain all the layouts stored
* in files, and the layouts currently in use.
*/
private val layoutConfig: MutableMap<LayoutNode, Int>,
private var nextIndex: Int,
private val appWidgetId: Int,
/** Set of layout indexes that have been assigned since the creation of this object. */
private val usedLayoutIds: MutableSet<Int> = mutableSetOf(),
/** Set of all layout ids in [layoutConfig]. None of them can be re-used. */
private val existingLayoutIds: MutableSet<Int> = mutableSetOf(),
) {
internal companion object {
/**
* Creates a [LayoutConfiguration] retrieving known layouts from file, if they exist.
*/
internal suspend fun load(
context: Context,
appWidgetId: Int
): LayoutConfiguration {
val config = try {
GlanceState.getValue(
context,
LayoutStateDefinition,
layoutDatastoreKey(appWidgetId)
)
} catch (ex: CorruptionException) {
Log.e(
GlanceAppWidgetTag,
"Set of layout structures for App Widget id $appWidgetId is corrupted",
ex
)
LayoutProto.LayoutConfig.getDefaultInstance()
} catch (ex: IOException) {
Log.e(
GlanceAppWidgetTag,
"I/O error reading set of layout structures for App Widget id $appWidgetId",
ex
)
LayoutProto.LayoutConfig.getDefaultInstance()
}
val layouts = config.layoutList.associate {
it.layout to it.layoutIndex
}.toMutableMap()
return LayoutConfiguration(
context,
layouts,
nextIndex = config.nextIndex,
appWidgetId = appWidgetId,
existingLayoutIds = layouts.values.toMutableSet()
)
}
/**
* Create a new, empty, [LayoutConfiguration].
*/
internal fun create(context: Context, appWidgetId: Int) =
LayoutConfiguration(
context,
layoutConfig = mutableMapOf(),
nextIndex = 0,
appWidgetId = appWidgetId,
)
/** Create a new, pre-defined [LayoutConfiguration]. */
@VisibleForTesting
internal fun create(
context: Context,
appWidgetId: Int,
nextIndex: Int,
existingLayoutIds: Collection<Int> = emptyList()
) =
LayoutConfiguration(
context,
appWidgetId = appWidgetId,
layoutConfig = mutableMapOf(),
nextIndex = nextIndex,
existingLayoutIds = existingLayoutIds.toMutableSet(),
)
}
/**
* Add a layout to the set of known layouts.
*
* The layout index is retricted to the range 0 - [TopLevelLayoutsCount]-1. Once the layout
* index reaches [TopLevelLayoutsCount], it cycles back to 0, making sure we are not re-using
* any layout index used either for the current or previous set of layouts. The number of
* layout indexes we have should be sufficient to mostly avoid collisions, but there is still
* a risk if many updates are not rendered, or if all the indexes are used for lazy list items.
*
* @return the layout index that should be used to generate it
*/
fun addLayout(layoutRoot: Emittable): Int {
val root = createNode(context, layoutRoot)
synchronized(this) {
layoutConfig[root]?.let { index ->
usedLayoutIds += index
return index
}
var index = nextIndex
while (index in existingLayoutIds) {
index = (index + 1) % TopLevelLayoutsCount
require(index != nextIndex) {
"Cannot assign a valid layout index to the new layout: no free index left."
}
}
nextIndex = (index + 1) % TopLevelLayoutsCount
usedLayoutIds += index
existingLayoutIds += index
layoutConfig[root] = index
return index
}
}
/**
* Save the known layouts to file at the end of the layout generation.
*/
suspend fun save() {
GlanceState.updateValue(
context,
LayoutStateDefinition,
layoutDatastoreKey(appWidgetId)
) { config ->
config.toBuilder().apply {
nextIndex = nextIndex
clearLayout()
layoutConfig.entries.forEach { (node, index) ->
if (index in usedLayoutIds) {
addLayout(
LayoutDefinition.newBuilder().apply {
layout = node
layoutIndex = index
}
)
}
}
}.build()
}
}
}
/**
* Returns the proto layout tree corresponding to the provided root node.
*
* A node should change if either the [LayoutType] selected by the translation of that node changes,
* if the [SizeSelector] used to find the stub to be replaced changes or if the [ContainerSelector]
* used to find the container's layout changes.
*
* Note: The number of children, although an element in [ContainerSelector] is not used, as this
* will anyway invalidate the structure.
*/
internal fun createNode(context: Context, element: Emittable): LayoutNode =
LayoutNode.newBuilder().apply {
type = element.getLayoutType()
width = element.modifier.widthModifier.toProto(context)
height = element.modifier.heightModifier.toProto(context)
hasAction = element.modifier.findModifier<ActionModifier>() != null
if (element.modifier.findModifier<AppWidgetBackgroundModifier>() != null) {
identity = NodeIdentity.BACKGROUND_NODE
}
when (element) {
is EmittableImage -> setImageNode(element)
is EmittableColumn -> setColumnNode(element)
is EmittableRow -> setRowNode(element)
is EmittableBox -> setBoxNode(element)
is EmittableLazyColumn -> setLazyListColumn(element)
}
if (element is EmittableWithChildren && element !is EmittableLazyList) {
addAllChildren(element.children.map { createNode(context, it) })
}
}.build()
private fun LayoutNode.Builder.setImageNode(element: EmittableImage) {
imageScale = when (element.contentScale) {
androidx.glance.layout.ContentScale.Fit -> LayoutProto.ContentScale.FIT
androidx.glance.layout.ContentScale.Crop -> LayoutProto.ContentScale.CROP
androidx.glance.layout.ContentScale.FillBounds -> LayoutProto.ContentScale.FILL_BOUNDS
else -> error("Unknown content scale ${element.contentScale}")
}
}
private fun LayoutNode.Builder.setColumnNode(element: EmittableColumn) {
horizontalAlignment = element.horizontalAlignment.toProto()
}
private fun LayoutNode.Builder.setLazyListColumn(element: EmittableLazyColumn) {
horizontalAlignment = element.horizontalAlignment.toProto()
}
private fun LayoutNode.Builder.setRowNode(element: EmittableRow) {
verticalAlignment = element.verticalAlignment.toProto()
}
private fun LayoutNode.Builder.setBoxNode(element: EmittableBox) {
horizontalAlignment = element.contentAlignment.horizontal.toProto()
verticalAlignment = element.contentAlignment.vertical.toProto()
}
private val GlanceModifier.widthModifier: Dimension
get() = findModifier<WidthModifier>()?.width ?: Dimension.Wrap
private val GlanceModifier.heightModifier: Dimension
get() = findModifier<HeightModifier>()?.height ?: Dimension.Wrap
private fun layoutDatastoreKey(appWidgetId: Int) = "appWidgetLayout-$appWidgetId"
private object LayoutStateDefinition : GlanceStateDefinition<LayoutProto.LayoutConfig> {
override fun getLocation(context: Context, fileKey: String): File =
context.dataStoreFile(fileKey)
override suspend fun getDataStore(
context: Context,
fileKey: String,
): DataStore<LayoutProto.LayoutConfig> =
DataStoreFactory.create(serializer = LayoutProtoSerializer) {
context.dataStoreFile(fileKey)
}
}
private fun Alignment.Vertical.toProto() = when (this) {
Alignment.Vertical.Top -> LayoutProto.VerticalAlignment.TOP
Alignment.Vertical.CenterVertically -> LayoutProto.VerticalAlignment.CENTER_VERTICALLY
Alignment.Vertical.Bottom -> LayoutProto.VerticalAlignment.BOTTOM
else -> error("unknown vertical alignment $this")
}
private fun Alignment.Horizontal.toProto() = when (this) {
Alignment.Horizontal.Start -> LayoutProto.HorizontalAlignment.START
Alignment.Horizontal.CenterHorizontally -> LayoutProto.HorizontalAlignment.CENTER_HORIZONTALLY
Alignment.Horizontal.End -> LayoutProto.HorizontalAlignment.END
else -> error("unknown horizontal alignment $this")
}
private fun Emittable.getLayoutType(): LayoutProto.LayoutType =
when (this) {
is EmittableBox -> LayoutProto.LayoutType.BOX
is EmittableButton -> LayoutProto.LayoutType.BUTTON
is EmittableRow -> {
if (modifier.isSelectableGroup) {
LayoutProto.LayoutType.RADIO_ROW
} else {
LayoutProto.LayoutType.ROW
}
}
is EmittableColumn -> {
if (modifier.isSelectableGroup) {
LayoutProto.LayoutType.RADIO_COLUMN
} else {
LayoutProto.LayoutType.COLUMN
}
}
is EmittableText -> LayoutProto.LayoutType.TEXT
is EmittableLazyListItem -> LayoutProto.LayoutType.LIST_ITEM
is EmittableLazyColumn -> LayoutProto.LayoutType.LAZY_COLUMN
is EmittableAndroidRemoteViews -> LayoutProto.LayoutType.ANDROID_REMOTE_VIEWS
is EmittableCheckBox -> LayoutProto.LayoutType.CHECK_BOX
is EmittableSpacer -> LayoutProto.LayoutType.SPACER
is EmittableSwitch -> LayoutProto.LayoutType.SWITCH
is EmittableImage -> LayoutProto.LayoutType.IMAGE
is EmittableLinearProgressIndicator -> LayoutProto.LayoutType.LINEAR_PROGRESS_INDICATOR
is EmittableCircularProgressIndicator -> LayoutProto.LayoutType.CIRCULAR_PROGRESS_INDICATOR
is EmittableLazyVerticalGrid -> LayoutProto.LayoutType.LAZY_VERTICAL_GRID
is EmittableLazyVerticalGridListItem -> LayoutProto.LayoutType.LIST_ITEM
is RemoteViewsRoot -> LayoutProto.LayoutType.REMOTE_VIEWS_ROOT
is EmittableRadioButton -> LayoutProto.LayoutType.RADIO_BUTTON
is EmittableSizeBox -> LayoutProto.LayoutType.SIZE_BOX
else ->
throw IllegalArgumentException("Unknown element type ${this.javaClass.canonicalName}")
}
private fun Dimension.toProto(context: Context): LayoutProto.DimensionType {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
return WidgetLayoutImpl31.toProto(this)
}
return when (resolveDimension(context)) {
is Dimension.Dp -> LayoutProto.DimensionType.EXACT
is Dimension.Wrap -> LayoutProto.DimensionType.WRAP
is Dimension.Fill -> LayoutProto.DimensionType.FILL
is Dimension.Expand -> LayoutProto.DimensionType.EXPAND
else -> error("After resolution, no other type should be present")
}
}
@RequiresApi(Build.VERSION_CODES.S)
private object WidgetLayoutImpl31 {
@DoNotInline
fun toProto(dimension: Dimension) =
if (dimension is Dimension.Expand) {
LayoutProto.DimensionType.EXPAND
} else {
LayoutProto.DimensionType.WRAP
}
}
|
apache-2.0
|
dbe454626696b720dc64072ff5467f2c
| 40.271739 | 100 | 0.676763 | 4.948517 | false | true | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/psi/ext/RsVisibility.kt
|
2
|
4578
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.psi.impl.ElementBase
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.PlatformIcons
import org.rust.lang.core.psi.*
import javax.swing.Icon
interface RsVisible : RsElement {
val visibility: RsVisibility
val isPublic: Boolean // restricted visibility considered as public
}
interface RsVisibilityOwner : RsVisible {
val vis: RsVis?
get() = PsiTreeUtil.getStubChildOfType(this, RsVis::class.java)
override val visibility: RsVisibility
get() = vis?.visibility ?: RsVisibility.Private
override val isPublic: Boolean
get() = vis != null
}
fun RsVisibilityOwner.iconWithVisibility(flags: Int, icon: Icon): Icon {
val visibilityIcon = when (vis?.stubKind) {
RsVisStubKind.PUB -> PlatformIcons.PUBLIC_ICON
RsVisStubKind.CRATE, RsVisStubKind.RESTRICTED -> PlatformIcons.PROTECTED_ICON
null -> PlatformIcons.PRIVATE_ICON
}
return ElementBase.iconWithVisibilityIfNeeded(flags, icon, visibilityIcon)
}
fun RsVisible.isVisibleFrom(mod: RsMod): Boolean {
// XXX: this hack fixes false-positive "E0603 module is private" for modules with multiple
// declarations. It produces false-negatives, see
if (this is RsFile && declarations.size > 1) return true
val elementMod = when (val visibility = visibility) {
RsVisibility.Public -> return true
RsVisibility.Private -> (if (this is RsMod) this.`super` else containingMod) ?: return true
is RsVisibility.Restricted -> visibility.inMod
}
// We have access to any item in any super module of `mod`
// Note: `mod.superMods` contains `mod`
if (mod.superMods.contains(elementMod)) return true
if (mod is RsFile && mod.originalFile == elementMod) return true
// Enum variants in a pub enum are public by default
if (this is RsNamedFieldDecl && parent.parent is RsEnumVariant) return true
val members = this.context as? RsMembers ?: return false
val parent = members.context ?: return true
return when {
// Associated items in a pub Trait are public by default
parent is RsImplItem && parent.traitRef != null -> {
parent.traitRef?.resolveToTrait()?.isVisibleFrom(mod) ?: true
}
parent is RsTraitItem -> parent.isVisibleFrom(mod)
else -> false
}
}
enum class RsVisStubKind {
PUB, CRATE, RESTRICTED
}
val RsVis.stubKind: RsVisStubKind
get() = greenStub?.kind ?: when {
crate != null -> RsVisStubKind.CRATE
visRestriction != null -> RsVisStubKind.RESTRICTED
else -> RsVisStubKind.PUB
}
sealed class RsVisibility {
object Private : RsVisibility()
object Public : RsVisibility()
data class Restricted(val inMod: RsMod) : RsVisibility()
}
fun RsVisibility.intersect(other: RsVisibility): RsVisibility = when (this) {
RsVisibility.Private -> this
RsVisibility.Public -> other
is RsVisibility.Restricted -> when (other) {
RsVisibility.Private -> other
RsVisibility.Public -> this
is RsVisibility.Restricted -> {
RsVisibility.Restricted(if (inMod.superMods.contains(other.inMod)) inMod else other.inMod)
}
}
}
fun RsVisibility.unite(other: RsVisibility): RsVisibility = when {
this is RsVisibility.Restricted && other is RsVisibility.Restricted -> {
val commonParent = commonParentMod(inMod, other.inMod)
if (commonParent != null) {
RsVisibility.Restricted(commonParent)
} else {
RsVisibility.Public
}
}
this == RsVisibility.Private && other is RsVisibility.Private -> RsVisibility.Private
else -> RsVisibility.Public
}
fun RsVisibility.format(): String = when (this) {
RsVisibility.Private -> ""
RsVisibility.Public -> "pub "
is RsVisibility.Restricted ->
if (inMod.isCrateRoot) {
"pub(crate) "
} else {
"pub(in crate${inMod.crateRelativePath}) "
}
}
val RsVis.visibility: RsVisibility
get() = when (stubKind) {
RsVisStubKind.PUB -> RsVisibility.Public
RsVisStubKind.CRATE -> crateRoot?.let { RsVisibility.Restricted(it) } ?: RsVisibility.Public
RsVisStubKind.RESTRICTED -> {
val restrictedIn = visRestriction!!.path.reference?.resolve() as? RsMod
if (restrictedIn != null) RsVisibility.Restricted(restrictedIn) else RsVisibility.Public
}
}
|
mit
|
d1ce1fbd2388534a5c5e3c03a17a2e95
| 33.946565 | 102 | 0.677152 | 4.161818 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.