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
mdaniel/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/PackageSearchProjectService.kt
1
15782
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.data import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.application.readAction import com.intellij.openapi.components.Service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiManager import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment import com.jetbrains.packagesearch.intellij.plugin.api.PackageSearchApiClient import com.jetbrains.packagesearch.intellij.plugin.api.ServerURLs import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackagesToUpgrade import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider import com.jetbrains.packagesearch.intellij.plugin.util.BackgroundLoadingBarController import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo import com.jetbrains.packagesearch.intellij.plugin.util.batchAtIntervals import com.jetbrains.packagesearch.intellij.plugin.util.catchAndLog import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.mapLatestTimedWithLoading import com.jetbrains.packagesearch.intellij.plugin.util.modifiedBy import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow import com.jetbrains.packagesearch.intellij.plugin.util.moduleTransformers import com.jetbrains.packagesearch.intellij.plugin.util.nativeModulesFlow import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap import com.jetbrains.packagesearch.intellij.plugin.util.parallelUpdatedKeys import com.jetbrains.packagesearch.intellij.plugin.util.replayOnSignals import com.jetbrains.packagesearch.intellij.plugin.util.showBackgroundLoadingBar import com.jetbrains.packagesearch.intellij.plugin.util.throttle import com.jetbrains.packagesearch.intellij.plugin.util.timer import com.jetbrains.packagesearch.intellij.plugin.util.toolWindowManagerFlow import com.jetbrains.packagesearch.intellij.plugin.util.trustedProjectFlow import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combineTransform import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.take import kotlinx.serialization.json.Json import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.seconds @Service(Service.Level.PROJECT) internal class PackageSearchProjectService(private val project: Project) { private val retryFromErrorChannel = Channel<Unit>() private val restartChannel = Channel<Unit>() val dataProvider = ProjectDataProvider( PackageSearchApiClient(ServerURLs.base), project.packageSearchProjectCachesService.installedDependencyCache ) private val projectModulesLoadingFlow = MutableStateFlow(false) private val knownRepositoriesLoadingFlow = MutableStateFlow(false) private val moduleModelsLoadingFlow = MutableStateFlow(false) private val allInstalledKnownRepositoriesLoadingFlow = MutableStateFlow(false) private val installedPackagesStep1LoadingFlow = MutableStateFlow(false) private val installedPackagesStep2LoadingFlow = MutableStateFlow(false) private val installedPackagesDifferenceLoadingFlow = MutableStateFlow(false) private val packageUpgradesLoadingFlow = MutableStateFlow(false) private val availableUpgradesLoadingFlow = MutableStateFlow(false) private val canShowLoadingBar = MutableStateFlow(false) private val operationExecutedChannel = Channel<List<ProjectModule>>() private val json = Json { prettyPrint = true } private val cacheDirectory = project.packageSearchProjectCachesService.projectCacheDirectory.resolve("installedDependencies") val isLoadingFlow = combineTransform( projectModulesLoadingFlow, knownRepositoriesLoadingFlow, moduleModelsLoadingFlow, allInstalledKnownRepositoriesLoadingFlow, installedPackagesStep1LoadingFlow, installedPackagesStep2LoadingFlow, installedPackagesDifferenceLoadingFlow, packageUpgradesLoadingFlow ) { booleans -> emit(booleans.any { it }) } .stateIn(project.lifecycleScope, SharingStarted.Eagerly, false) private val projectModulesSharedFlow = project.trustedProjectFlow .flatMapLatest { isProjectTrusted -> if (isProjectTrusted) project.nativeModulesFlow else flowOf(emptyList()) } .replayOnSignals( retryFromErrorChannel.receiveAsFlow().throttle(10.seconds), project.moduleChangesSignalFlow, restartChannel.receiveAsFlow() ) .mapLatestTimedWithLoading("projectModulesSharedFlow", projectModulesLoadingFlow) { modules -> project.moduleTransformers .map { async { it.transformModules(project, modules) } } .awaitAll() .flatten() } .catchAndLog( context = "${this::class.qualifiedName}#projectModulesSharedFlow", message = "Error while elaborating latest project modules", fallbackValue = emptyList(), retryChannel = retryFromErrorChannel ) .shareIn(project.lifecycleScope, SharingStarted.Eagerly) val projectModulesStateFlow = projectModulesSharedFlow.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val isAvailable get() = projectModulesStateFlow.value.isNotEmpty() private val knownRepositoriesFlow = timer(1.hours) .mapLatestTimedWithLoading("knownRepositoriesFlow", knownRepositoriesLoadingFlow) { dataProvider.fetchKnownRepositories() } .catchAndLog( context = "${this::class.qualifiedName}#knownRepositoriesFlow", message = "Error while refreshing known repositories", fallbackValue = emptyList() ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) private val buildFileChangesFlow = combine( projectModulesSharedFlow, project.filesChangedEventFlow.map { it.mapNotNull { it.file } } ) { modules, changedBuildFiles -> modules.filter { it.buildFile in changedBuildFiles } } .shareIn(project.lifecycleScope, SharingStarted.Eagerly) private val projectModulesChangesFlow = merge( buildFileChangesFlow.filter { it.isNotEmpty() }, operationExecutedChannel.consumeAsFlow() ) .batchAtIntervals(1.seconds) .map { it.flatMap { it }.distinct() } .catchAndLog( context = "${this::class.qualifiedName}#projectModulesChangesFlow", message = "Error while checking Modules changes", fallbackValue = emptyList() ) .shareIn(project.lifecycleScope, SharingStarted.Eagerly) val moduleModelsStateFlow = projectModulesSharedFlow .mapLatestTimedWithLoading( loggingContext = "moduleModelsStateFlow", loadingFlow = moduleModelsLoadingFlow ) { projectModules -> projectModules.parallelMap { it to ModuleModel(it) }.toMap() } .modifiedBy(projectModulesChangesFlow) { repositories, changedModules -> repositories.parallelUpdatedKeys(changedModules) { ModuleModel(it) } } .map { it.values.toList() } .catchAndLog( context = "${this::class.qualifiedName}#moduleModelsStateFlow", message = "Error while evaluating modules models", fallbackValue = emptyList(), retryChannel = retryFromErrorChannel ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val allInstalledKnownRepositoriesStateFlow = combine(moduleModelsStateFlow, knownRepositoriesFlow) { moduleModels, repos -> moduleModels to repos } .mapLatestTimedWithLoading( loggingContext = "allInstalledKnownRepositoriesFlow", loadingFlow = allInstalledKnownRepositoriesLoadingFlow ) { (moduleModels, repos) -> allKnownRepositoryModels(moduleModels, repos) } .catchAndLog( context = "${this::class.qualifiedName}#allInstalledKnownRepositoriesFlow", message = "Error while evaluating installed repositories", fallbackValue = KnownRepositories.All.EMPTY ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, KnownRepositories.All.EMPTY) val dependenciesByModuleStateFlow = projectModulesSharedFlow .mapLatestTimedWithLoading("installedPackagesStep1LoadingFlow", installedPackagesStep1LoadingFlow) { fetchProjectDependencies(it, cacheDirectory, json) } .modifiedBy(projectModulesChangesFlow) { installed, changedModules -> val (result, time) = installedPackagesDifferenceLoadingFlow.whileLoading { installed.parallelUpdatedKeys(changedModules) { it.installedDependencies(cacheDirectory, json) } } logTrace("installedPackagesStep1LoadingFlow") { "Took ${time} to process diffs for ${changedModules.size} module" + if (changedModules.size > 1) "s" else "" } result } .catchAndLog( context = "${this::class.qualifiedName}#dependenciesByModuleStateFlow", message = "Error while evaluating installed dependencies", fallbackValue = emptyMap(), retryChannel = retryFromErrorChannel ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyMap()) val installedPackagesStateFlow = dependenciesByModuleStateFlow .mapLatestTimedWithLoading("installedPackagesStep2LoadingFlow", installedPackagesStep2LoadingFlow) { installedPackages( it, project, dataProvider, TraceInfo(TraceInfo.TraceSource.INIT) ) } .catchAndLog( context = "${this::class.qualifiedName}#installedPackagesStateFlow", message = "Error while evaluating installed packages", fallbackValue = emptyList(), retryChannel = retryFromErrorChannel ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val packageUpgradesStateFlow = combine( installedPackagesStateFlow, moduleModelsStateFlow, knownRepositoriesFlow ) { installedPackages, moduleModels, repos -> coroutineScope { availableUpgradesLoadingFlow.whileLoading { val allKnownRepos = allKnownRepositoryModels(moduleModels, repos) val nativeModulesMap = moduleModels.associateBy { it.projectModule } val getUpgrades: suspend (Boolean) -> PackagesToUpgrade = { computePackageUpgrades(installedPackages, it, packageVersionNormalizer, allKnownRepos, nativeModulesMap) } val stableUpdates = async { getUpgrades(true) } val allUpdates = async { getUpgrades(false) } PackageUpgradeCandidates(stableUpdates.await(), allUpdates.await()) }.value } } .catchAndLog( context = "${this::class.qualifiedName}#packageUpgradesStateFlow", message = "Error while evaluating packages upgrade candidates", fallbackValue = PackageUpgradeCandidates.EMPTY, retryChannel = retryFromErrorChannel ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, PackageUpgradeCandidates.EMPTY) init { // allows rerunning PKGS inspections on already opened files // when the data is finally available or changes for PackageUpdateInspection // or when a build file changes packageUpgradesStateFlow.throttle(5.seconds) .map { projectModulesStateFlow.value.mapNotNull { it.buildFile?.path }.toSet() } .filter { it.isNotEmpty() } .flatMapLatest { knownBuildFiles -> FileEditorManager.getInstance(project).openFiles .filter { it.path in knownBuildFiles }.asFlow() } .mapNotNull { readAction { PsiManager.getInstance(project).findFile(it) } } .onEach { readAction { DaemonCodeAnalyzer.getInstance(project).restart(it) } } .launchIn(project.lifecycleScope) var controller: BackgroundLoadingBarController? = null project.toolWindowManagerFlow .filter { it.id == PackageSearchToolWindowFactory.ToolWindowId } .take(1) .onEach { canShowLoadingBar.emit(true) } .launchIn(project.lifecycleScope) if (PluginEnvironment.isNonModalLoadingEnabled) { canShowLoadingBar.filter { it } .flatMapLatest { isLoadingFlow } .throttle(1.seconds) .onEach { controller?.clear() } .onEach { controller = showBackgroundLoadingBar( project, PackageSearchBundle.message("toolwindow.stripe.Dependencies"), PackageSearchBundle.message("packagesearch.ui.loading") ) }.launchIn(project.lifecycleScope) } } fun notifyOperationExecuted(successes: List<ProjectModule>) { operationExecutedChannel.trySend(successes) } suspend fun restart() { restartChannel.send(Unit) } }
apache-2.0
c23a21bd5781199897ce4cc620c2d4c8
47.860681
131
0.719237
5.845185
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentAbEntityImpl.kt
1
8197
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ParentAbEntityImpl : ParentAbEntity, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentAbEntity::class.java, ChildAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, ) } override val children: List<ChildAbstractBaseEntity> get() = snapshot.extractOneToAbstractManyChildren<ChildAbstractBaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ParentAbEntityData?) : ModifiableWorkspaceEntityBase<ParentAbEntity>(), ParentAbEntity.Builder { constructor() : this(ParentAbEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ParentAbEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field ParentAbEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field ParentAbEntity#children should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ParentAbEntity this.entitySource = dataSource.entitySource if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var children: List<ChildAbstractBaseEntity> get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyChildren<ChildAbstractBaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildAbstractBaseEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<ChildAbstractBaseEntity> ?: emptyList() } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence()) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override fun getEntityData(): ParentAbEntityData = result ?: super.getEntityData() as ParentAbEntityData override fun getEntityClass(): Class<ParentAbEntity> = ParentAbEntity::class.java } } class ParentAbEntityData : WorkspaceEntityData<ParentAbEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentAbEntity> { val modifiable = ParentAbEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ParentAbEntity { val entity = ParentAbEntityImpl() entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ParentAbEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ParentAbEntity(entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ParentAbEntityData if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ParentAbEntityData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
598a411a1a7eb8533b81a0f0583f0fa1
35.110132
180
0.686349
5.595222
false
false
false
false
android/nowinandroid
core/network/src/main/java/com/google/samples/apps/nowinandroid/core/network/retrofit/RetrofitNiaNetwork.kt
1
4444
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.network.retrofit import com.google.samples.apps.nowinandroid.core.network.BuildConfig import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import javax.inject.Inject import javax.inject.Singleton import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.http.GET import retrofit2.http.Query /** * Retrofit API declaration for NIA Network API */ private interface RetrofitNiaNetworkApi { @GET(value = "topics") suspend fun getTopics( @Query("id") ids: List<String>?, ): NetworkResponse<List<NetworkTopic>> @GET(value = "authors") suspend fun getAuthors( @Query("id") ids: List<String>?, ): NetworkResponse<List<NetworkAuthor>> @GET(value = "newsresources") suspend fun getNewsResources( @Query("id") ids: List<String>?, ): NetworkResponse<List<NetworkNewsResource>> @GET(value = "changelists/topics") suspend fun getTopicChangeList( @Query("after") after: Int?, ): List<NetworkChangeList> @GET(value = "changelists/authors") suspend fun getAuthorsChangeList( @Query("after") after: Int?, ): List<NetworkChangeList> @GET(value = "changelists/newsresources") suspend fun getNewsResourcesChangeList( @Query("after") after: Int?, ): List<NetworkChangeList> } private const val NiaBaseUrl = BuildConfig.BACKEND_URL /** * Wrapper for data provided from the [NiaBaseUrl] */ @Serializable private data class NetworkResponse<T>( val data: T ) /** * [Retrofit] backed [NiaNetworkDataSource] */ @Singleton class RetrofitNiaNetwork @Inject constructor( networkJson: Json ) : NiaNetworkDataSource { private val networkApi = Retrofit.Builder() .baseUrl(NiaBaseUrl) .client( OkHttpClient.Builder() .addInterceptor( // TODO: Decide logging logic HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.BODY) } ) .build() ) .addConverterFactory( @OptIn(ExperimentalSerializationApi::class) networkJson.asConverterFactory("application/json".toMediaType()) ) .build() .create(RetrofitNiaNetworkApi::class.java) override suspend fun getTopics(ids: List<String>?): List<NetworkTopic> = networkApi.getTopics(ids = ids).data override suspend fun getAuthors(ids: List<String>?): List<NetworkAuthor> = networkApi.getAuthors(ids = ids).data override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> = networkApi.getNewsResources(ids = ids).data override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> = networkApi.getTopicChangeList(after = after) override suspend fun getAuthorChangeList(after: Int?): List<NetworkChangeList> = networkApi.getAuthorsChangeList(after = after) override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> = networkApi.getNewsResourcesChangeList(after = after) }
apache-2.0
5b29055d7ceacb4643468056c5e37445
33.992126
90
0.718497
4.444
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-plugins/parcelize/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/gradleJava/ParcelizeProjectResolverExtension.kt
7
2235
// 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.compilerPlugin.parcelize.gradleJava import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.serialization.PropertyMapping import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.kotlin.idea.gradleTooling.model.parcelize.ParcelizeGradleModel import org.jetbrains.kotlin.idea.gradleTooling.model.parcelize.ParcelizeModelBuilderService import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension import org.jetbrains.plugins.gradle.util.GradleConstants class ParcelizeIdeModel @PropertyMapping("isEnabled") constructor( val isEnabled: Boolean ) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) { companion object { val KEY = Key.create(ParcelizeIdeModel::class.java, ProjectKeys.CONTENT_ROOT.processingWeight + 1) } } class ParcelizeIdeModelDataService : AbstractProjectDataService<ParcelizeIdeModel, Void>() { override fun getTargetDataKey() = ParcelizeIdeModel.KEY } class ParcelizeProjectResolverExtension : AbstractProjectResolverExtension() { override fun getExtraProjectModelClasses() = setOf(ParcelizeGradleModel::class.java) override fun getToolingExtensionsClasses() = setOf(ParcelizeModelBuilderService::class.java, Unit::class.java) override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { val parcelizeModel = resolverCtx.getExtraProject(gradleModule, ParcelizeGradleModel::class.java) if (parcelizeModel != null && parcelizeModel.isEnabled) { ideModule.createChild(ParcelizeIdeModel.KEY, ParcelizeIdeModel(isEnabled = parcelizeModel.isEnabled)) } super.populateModuleExtraModels(gradleModule, ideModule) } }
apache-2.0
581b641ab434bdb60128af1e64ce98c1
49.795455
120
0.819239
4.966667
false
false
false
false
carrotengineer/Warren
src/test/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl332HandlerTests.kt
2
1813
package engineer.carrot.warren.warren.handler.rpl import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl332Message import engineer.carrot.warren.kale.irc.message.utility.CaseMapping import engineer.carrot.warren.warren.state.* import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class Rpl332HandlerTests { lateinit var handler: Rpl332Handler lateinit var channelsState: ChannelsState val caseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459) @Before fun setUp() { channelsState = emptyChannelsState(caseMappingState) handler = Rpl332Handler(channelsState.joined, caseMappingState) } @Test fun test_handle_NonexistentChannel_DoesNothing() { channelsState.joined += ChannelState(name = "#channel", users = generateUsers("test-nick", mappingState = caseMappingState)) handler.handle(Rpl332Message(source = "", target = "", channel = "#somewhere", topic = "test topic"), mapOf()) val expectedChannelState = ChannelState(name = "#channel", users = generateUsers("test-nick", mappingState = caseMappingState)) assertEquals(channelsStateWith(listOf(expectedChannelState), caseMappingState), channelsState) } @Test fun test_handle_ValidChannel_SetsTopic() { channelsState.joined += ChannelState(name = "#channel", users = generateUsers("test-nick", mappingState = caseMappingState)) handler.handle(Rpl332Message(source = "", target = "", channel = "#channel", topic = "test topic"), mapOf()) val expectedChannelState = ChannelState(name = "#channel", users = generateUsers("test-nick", mappingState = caseMappingState), topic = "test topic") assertEquals(channelsStateWith(listOf(expectedChannelState), caseMappingState), channelsState) } }
isc
ac063982478cf736079147554c45122f
43.243902
157
0.739106
4.783641
false
true
false
false
android/gradle-recipes
BuildSrc/manifestUpdaterTest/buildSrc/src/main/kotlin/ManifestTransformerTask.kt
1
1506
/* * Copyright (C) 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. */ import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction abstract class ManifestTransformerTask: DefaultTask() { @get:InputFile abstract val gitInfoFile: RegularFileProperty @get:InputFile abstract val mergedManifest: RegularFileProperty @get:OutputFile abstract val updatedManifest: RegularFileProperty @TaskAction fun taskAction() { val gitVersion = gitInfoFile.get().asFile.readText() var manifest = mergedManifest.asFile.get().readText() manifest = manifest.replace("android:versionCode=\"1\"", "android:versionCode=\"${gitVersion}\"") println("Writes to " + updatedManifest.get().asFile.getAbsolutePath()) updatedManifest.get().asFile.writeText(manifest) } }
apache-2.0
e934b352922c0d469bf648d152fe271a
34.857143
105
0.737052
4.495522
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/actions/SortTranslationsAction.kt
1
1042
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n.actions import com.demonwav.mcdev.i18n.lang.I18nFileType import com.demonwav.mcdev.i18n.sorting.I18nSorter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys class SortTranslationsAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val file = e.getData(LangDataKeys.PSI_FILE) ?: return I18nSorter.query(file.project, file) } override fun update(e: AnActionEvent) { val file = e.getData(LangDataKeys.PSI_FILE) val editor = e.getData(PlatformDataKeys.EDITOR) if (file == null || editor == null) { e.presentation.isEnabled = false return } e.presentation.isEnabled = file.fileType === I18nFileType } }
mit
cd7349b930e252fdf6f2191b9d3bcd55
27.944444
65
0.709213
3.961977
false
false
false
false
emoji-gen/Emoji-Android
example-slack/src/main/java/moe/pine/emoji/example/slack/AddEmojiTask.kt
1
2842
package moe.pine.emoji.example.slack import android.app.AlertDialog import android.app.ProgressDialog import android.content.Context import android.os.AsyncTask import moe.pine.emoji.lib.slack.MessageResult import moe.pine.emoji.lib.slack.RegisterClient import java.io.FileNotFoundException import java.io.IOException /** * AddEmojiTask * Created by pine on Apr 17, 2017. */ class AddEmojiTask( val context: Context ) : AsyncTask<AddEmojiTask.Arguments, Unit, MessageResult>() { data class Arguments( val team: String, val username: String, val password: String, val emojiName: String, val emojiUrl: String ) lateinit var dialog: ProgressDialog override fun onPreExecute() { super.onPreExecute() this.dialog = ProgressDialog(this.context).also { it.setProgressStyle(ProgressDialog.STYLE_SPINNER) it.isIndeterminate = true it.setTitle("Loading ...") it.setMessage("Try to register") it.setCancelable(false) it.setCanceledOnTouchOutside(false) it.show() } } override fun doInBackground(vararg params: Arguments): MessageResult { val param = params[0] val client = RegisterClient() try { val istream = this.context.openFileInput("cookie.dat") istream.use { client.loadCookie(it) } } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } val result = client.register( param.team, param.username, param.password, param.emojiName, param.emojiUrl ) try { val ostream = this.context.openFileOutput("cookie.dat", Context.MODE_PRIVATE) ostream.use { client.saveCookie(it) } } catch (e: IOException) { e.printStackTrace() } return result } override fun onPostExecute(result: MessageResult) { super.onPostExecute(result) this.dialog.dismiss() if (result.ok) { AlertDialog.Builder(this.context) .setTitle("Successful") .setMessage(result.message ?: "Successful") .setCancelable(false) .setPositiveButton("Close") { dialog, _ -> dialog.dismiss() } .show() } else { AlertDialog.Builder(this.context) .setTitle("Failure") .setMessage(result.message ?: "Error") .setCancelable(false) .setPositiveButton("Close") { dialog, _ -> dialog.dismiss() } .show() } } }
mit
f0f3c1e92de09b520fbeb85872fd0f5a
29.569892
89
0.567206
4.85812
false
false
false
false
pureal-code/pureal-os
traits/src/net/pureal/traits/math/simplifier/rotateBasicOperations.kt
1
3149
package net.pureal.traits.math.simplifier import net.pureal.traits.math.* import net.pureal.traits.math.operations.* import net.pureal.traits.replaceElements fun rotateBasicOperations(it: Real): Real { class pnRealArray(val p: List<Real>, val n: List<Real>) class mdRealArray(val m: List<Real>, val d: List<Real>) // Inner fun fun rotateInnerAdd(it: Real): Real { if (it !is AdditionValue && it !is SubtractionValue) return it fun pn_add(it: Real): pnRealArray { if (it.isZero) return pnRealArray(listOf(), listOf()) if (it !is AdditionValue && it !is SubtractionValue) return if (it.isPositive) pnRealArray(listOf(rotateBasicOperations(it)), listOf()) else pnRealArray(listOf(), listOf(rotateBasicOperations(-it))) val r1 = pn_add(it.subReals[0]) val r2 = pn_add(it.subReals[1]) if (it is AdditionValue) return pnRealArray((r1.p + r2.p), (r1.n + r2.n)) return pnRealArray((r1.p + r2.n), (r1.n + r2.p)) } val pn = pn_add(it) val p = pn.p filter { !it.isZero } val n = pn.n filter { !it.isZero } var pos: Real = if (!p.isEmpty()) p[0] else real(0) var i: Int = 1 while (p.size > i) { pos = pos + p[i] i++ } if (n.isEmpty()) return pos var neg: Real = n[0] i = 1 while (n.size > i) { neg = neg + n[i] i++ } return pos - neg } // Inner Fun fun rotateInnerMul(it: Real): Real { if (it !is MultiplicationValue && it !is DivisionValue) return it fun md_add(it: Real): mdRealArray { if (it is RealPrimitive && it.value equals 1) return mdRealArray(listOf(), listOf()) if (it !is MultiplicationValue && it !is DivisionValue) return mdRealArray(listOf(rotateBasicOperations(it)), listOf()) val r1 = md_add(it.subReals[0]) val r2 = md_add(it.subReals[1]) if (it is MultiplicationValue) return mdRealArray((r1.m + r2.m), (r1.d + r2.d)) return mdRealArray((r1.m + r2.d), (r1.d + r2.m)) } val md = md_add(it) val m = if (md.m.isEmpty() || md.m any { it.isZero }) listOf(real(0)) else md.m val d = if (md.d any { it.isZero }) listOf(real(0)) else md.d var mul: Real = if (m.isEmpty()) real(1) else m[0] var i: Int = 1 while (m.size > i) { mul = mul * m[i] i++ } if (d.isEmpty()) return mul var div: Real = d[0] i = 1 while (d.size > i) { div = div * d[i] i++ } return mul / div } // Code starts here when (it) { is RealBinaryOperation -> { if (it is AdditionValue || it is SubtractionValue) return rotateInnerAdd(it) if (it is MultiplicationValue || it is DivisionValue) return rotateInnerMul(it) } } return it.replaceSubReals(it.subReals replaceElements { rotateBasicOperations(it) }) } fun Real.rotate(): Real = rotateBasicOperations(this)
bsd-3-clause
353a58e30c64bc6b56838693c12c8f85
36.951807
131
0.551286
3.37152
false
false
false
false
google/android-fhir
engine/src/test/java/com/google/android/fhir/sync/AcceptRemoteConflictResolverTest.kt
1
1895
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.sync import ca.uhn.fhir.context.FhirContext import ca.uhn.fhir.context.FhirVersionEnum import com.google.android.fhir.resource.TestingUtils import com.google.common.truth.Truth.assertThat import org.hl7.fhir.r4.model.HumanName import org.hl7.fhir.r4.model.Patient import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class AcceptRemoteConflictResolverTest { private val testingUtils = TestingUtils(FhirContext.forCached(FhirVersionEnum.R4).newJsonParser()) @Test fun resolve_shouldReturnRemoteChange() { val localResource = Patient().apply { id = "patient-id-1" addName( HumanName().apply { family = "Local" addGiven("Patient1") } ) } val remoteResource = Patient().apply { id = "patient-id-1" addName( HumanName().apply { family = "Remote" addGiven("Patient1") } ) } val result = AcceptRemoteConflictResolver.resolve(localResource, remoteResource) assertThat(result).isInstanceOf(Resolved::class.java) testingUtils.assertResourceEquals(remoteResource, (result as Resolved).resolved) } }
apache-2.0
93bc022c2f680a43907a92463b79a8f8
30.065574
100
0.701847
4.075269
false
true
false
false
google/ground-android
ground/src/main/java/com/google/android/ground/persistence/local/room/converter/ResponseJsonConverter.kt
1
4040
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.persistence.local.room.converter import com.google.android.ground.model.submission.* import com.google.android.ground.model.task.Task import com.google.android.ground.persistence.remote.DataStoreException import com.google.common.collect.ImmutableList import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* import java8.util.Optional import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import timber.log.Timber internal object ResponseJsonConverter { private val ISO_INSTANT_FORMAT: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.getDefault()) fun toJsonObject(taskData: TaskData): Any = when (taskData) { is TextTaskData -> taskData.text is MultipleChoiceTaskData -> toJsonArray(taskData) is NumberTaskData -> taskData.value is DateTaskData -> dateToIsoString(taskData.date) is TimeTaskData -> dateToIsoString(taskData.time) else -> throw UnsupportedOperationException("Unimplemented taskData ${taskData.javaClass}") } fun dateToIsoString(date: Date): String { synchronized(ISO_INSTANT_FORMAT) { ISO_INSTANT_FORMAT.timeZone = TimeZone.getTimeZone("UTC") return ISO_INSTANT_FORMAT.format(date) } } fun isoStringToDate(isoString: String): Date { synchronized(ISO_INSTANT_FORMAT) { ISO_INSTANT_FORMAT.timeZone = TimeZone.getTimeZone("UTC") return ISO_INSTANT_FORMAT.parse(isoString) } } private fun toJsonArray(response: MultipleChoiceTaskData): JSONArray = JSONArray().apply { response.selectedOptionIds.forEach { this.put(it) } } fun toResponse(task: Task, obj: Any): Optional<TaskData> = when (task.type) { Task.Type.TEXT, Task.Type.PHOTO -> { if (obj === JSONObject.NULL) { TextTaskData.fromString("") } else { DataStoreException.checkType(String::class.java, obj) TextTaskData.fromString(obj as String) } } Task.Type.MULTIPLE_CHOICE -> { if (obj === JSONObject.NULL) { MultipleChoiceTaskData.fromList(task.multipleChoice, emptyList()) } else { DataStoreException.checkType(JSONArray::class.java, obj) MultipleChoiceTaskData.fromList(task.multipleChoice, toList(obj as JSONArray)) } } Task.Type.NUMBER -> { if (JSONObject.NULL === obj) { NumberTaskData.fromNumber("") } else { DataStoreException.checkType(Number::class.java, obj) NumberTaskData.fromNumber(obj.toString()) } } Task.Type.DATE -> { DataStoreException.checkType(String::class.java, obj) DateTaskData.fromDate(isoStringToDate(obj as String)) } Task.Type.TIME -> { DataStoreException.checkType(String::class.java, obj) TimeTaskData.fromDate(isoStringToDate(obj as String)) } Task.Type.UNKNOWN -> throw DataStoreException("Unknown type in task: " + obj.javaClass.name) } private fun toList(jsonArray: JSONArray): ImmutableList<String> { val list: MutableList<String> = ArrayList(jsonArray.length()) for (i in 0 until jsonArray.length()) { try { list.add(jsonArray.getString(i)) } catch (e: JSONException) { Timber.e("Error parsing JSONArray in db: %s", jsonArray) } } return ImmutableList.builder<String>().addAll(list).build() } }
apache-2.0
93e6cd50030066a9929149ce20f1acd9
34.752212
98
0.690842
4.156379
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/io/RewireDBImporter.kt
1
6136
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.io import org.isoron.uhabits.core.database.Cursor import org.isoron.uhabits.core.database.Database import org.isoron.uhabits.core.database.DatabaseOpener import org.isoron.uhabits.core.models.Entry import org.isoron.uhabits.core.models.Frequency import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.models.ModelFactory import org.isoron.uhabits.core.models.Reminder import org.isoron.uhabits.core.models.Timestamp import org.isoron.uhabits.core.models.WeekdayList import org.isoron.uhabits.core.utils.DateUtils import org.isoron.uhabits.core.utils.isSQLite3File import java.io.File import javax.inject.Inject /** * Class that imports database files exported by Rewire. */ class RewireDBImporter @Inject constructor( private val habitList: HabitList, private val modelFactory: ModelFactory, private val opener: DatabaseOpener ) : AbstractImporter() { override fun canHandle(file: File): Boolean { if (!file.isSQLite3File()) return false val db = opener.open(file) val c = db.query( "select count(*) from SQLITE_MASTER " + "where name='CHECKINS' or name='UNIT'" ) val result = c.moveToNext() && c.getInt(0) == 2 c.close() db.close() return result } override fun importHabitsFromFile(file: File) { val db = opener.open(file) db.beginTransaction() createHabits(db) db.setTransactionSuccessful() db.endTransaction() db.close() } private fun createHabits(db: Database) { var c: Cursor? = null try { c = db.query( "select _id, name, description, schedule, " + "active_days, repeating_count, days, period " + "from habits" ) if (!c.moveToNext()) return do { val id = c.getInt(0)!! val name = c.getString(1) val description = c.getString(2) val schedule = c.getInt(3)!! val activeDays = c.getString(4) val repeatingCount = c.getInt(5)!! val days = c.getInt(6)!! val periodIndex = c.getInt(7)!! val habit = modelFactory.buildHabit() habit.name = name!! habit.description = description ?: "" val periods = intArrayOf(7, 31, 365) var numerator: Int var denominator: Int when (schedule) { 0 -> { numerator = activeDays!!.split(",").toTypedArray().size denominator = 7 } 1 -> { numerator = days denominator = periods[periodIndex] } 2 -> { numerator = 1 denominator = repeatingCount } else -> throw IllegalStateException() } habit.frequency = Frequency(numerator, denominator) habitList.add(habit) createReminder(db, habit, id) createCheckmarks(db, habit, id) } while (c.moveToNext()) } finally { c?.close() } } private fun createCheckmarks( db: Database, habit: Habit, rewireHabitId: Int ) { var c: Cursor? = null try { c = db.query( "select distinct date from checkins where habit_id=? and type=2", rewireHabitId.toString(), ) if (!c.moveToNext()) return do { val date = c.getString(0) val year = date!!.substring(0, 4).toInt() val month = date.substring(4, 6).toInt() val day = date.substring(6, 8).toInt() val cal = DateUtils.getStartOfTodayCalendar() cal[year, month - 1] = day habit.originalEntries.add(Entry(Timestamp(cal), Entry.YES_MANUAL)) } while (c.moveToNext()) } finally { c?.close() } } private fun createReminder(db: Database, habit: Habit, rewireHabitId: Int) { var c: Cursor? = null try { c = db.query( "select time, active_days from reminders where habit_id=? limit 1", rewireHabitId.toString(), ) if (!c.moveToNext()) return val rewireReminder = c.getInt(0)!! if (rewireReminder <= 0 || rewireReminder >= 1440) return val reminderDays = BooleanArray(7) val activeDays = c.getString(1)!!.split(",").toTypedArray() for (d in activeDays) { val idx = (d.toInt() + 1) % 7 reminderDays[idx] = true } val hour = rewireReminder / 60 val minute = rewireReminder % 60 val days = WeekdayList(reminderDays) val reminder = Reminder(hour, minute, days) habit.reminder = reminder habitList.update(habit) } finally { c?.close() } } }
gpl-3.0
367888c951e49fd853efd8ac12ce7aba
34.877193
83
0.555827
4.531019
false
false
false
false
ilya-g/intellij-markdown
src/org/intellij/markdown/parser/markerblocks/impl/CodeFenceMarkerBlock.kt
1
3221
package org.intellij.markdown.parser.markerblocks.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl import org.intellij.markdown.parser.sequentialparsers.SequentialParser import kotlin.text.Regex public class CodeFenceMarkerBlock(myConstraints: MarkdownConstraints, private val productionHolder: ProductionHolder, private val fenceStart: String) : MarkerBlockImpl(myConstraints, productionHolder.mark()) { override fun allowsSubBlocks(): Boolean = false override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true //pos.char == '\n' private val endLineRegex = Regex("^ {0,3}${fenceStart}+ *$") private var realInterestingOffset = -1 override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int { return pos.nextLineOrEofOffset } override fun getDefaultAction(): MarkerBlock.ClosingAction { return MarkerBlock.ClosingAction.DONE } override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult { if (pos.offset < realInterestingOffset) { return MarkerBlock.ProcessingResult.CANCEL } // Eat everything if we're on code line if (pos.offsetInCurrentLine != -1) { return MarkerBlock.ProcessingResult.CANCEL } assert(pos.char == '\n') val nextLineConstraints = MarkdownConstraints.fromBase(pos, constraints) if (!nextLineConstraints.extendsPrev(constraints)) { return MarkerBlock.ProcessingResult.DEFAULT } val nextLineOffset = pos.nextLineOrEofOffset realInterestingOffset = nextLineOffset val currentLine = nextLineConstraints.eatItselfFromString(pos.currentLine) if (endsThisFence(currentLine)) { productionHolder.addProduction(listOf(SequentialParser.Node(pos.offset + 1..pos.nextLineOrEofOffset, MarkdownTokenTypes.CODE_FENCE_END))) scheduleProcessingResult(nextLineOffset, MarkerBlock.ProcessingResult.DEFAULT) } else { val contentRange = Math.min(pos.offset + 1 + constraints.getCharsEaten(pos.currentLine), nextLineOffset)..nextLineOffset if (contentRange.start < contentRange.endInclusive) { productionHolder.addProduction(listOf(SequentialParser.Node( contentRange, MarkdownTokenTypes.CODE_FENCE_CONTENT))) } } return MarkerBlock.ProcessingResult.CANCEL } private fun endsThisFence(line: CharSequence): Boolean { return endLineRegex.matches(line) } override fun getDefaultNodeType(): IElementType { return MarkdownElementTypes.CODE_FENCE } }
apache-2.0
73cc937708c0f8102fb0c88a438f3255
40.831169
132
0.710028
5.582322
false
false
false
false
dahlstrom-g/intellij-community
platform/util/src/com/intellij/util/io/IOCancellationCallbackHolder.kt
9
1024
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.io import java.util.* internal object IOCancellationCallbackHolder { val usedIoCallback by lazy { loadSingleCallback() } private fun loadSingleCallback(): IOCancellationCallback { val serviceLoader = ServiceLoader.load(IOCancellationCallback::class.java, IOCancellationCallback::class.java.classLoader) val allCallbacks = serviceLoader.toList() if (allCallbacks.size > 1) { throw IllegalStateException("Few io cancellation callbacks are registered: ${allCallbacks.map { it.javaClass.name }}") } return allCallbacks.firstOrNull() ?: object : IOCancellationCallback { override fun checkCancelled() = Unit override fun interactWithUI() = Unit } } @JvmStatic fun checkCancelled() = usedIoCallback.checkCancelled() @JvmStatic fun interactWithUI() = usedIoCallback.interactWithUI() }
apache-2.0
220b01adffa4174ba205de78f51d9bb6
36.962963
158
0.75293
4.675799
false
false
false
false
dahlstrom-g/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMethodReferenceExpressionImpl.kt
12
2049
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl import com.intellij.lang.ASTNode import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.GroovyTokenSets.METHOD_REFERENCE_DOTS import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrReferenceExpressionImpl import org.jetbrains.plugins.groovy.lang.resolve.GrMethodReferenceResolver import org.jetbrains.plugins.groovy.lang.typing.GrTypeCalculator.getTypeFromCalculators class GrMethodReferenceExpressionImpl(node: ASTNode) : GrReferenceExpressionImpl(node) { companion object { @NlsSafe const val CONSTRUCTOR_REFERENCE_NAME = "new" } override fun getDotToken(): PsiElement = findNotNullChildByType(METHOD_REFERENCE_DOTS) override fun resolve(incomplete: Boolean): Collection<GroovyResolveResult> { return TypeInferenceHelper.getCurrentContext().resolve(this, incomplete, GrMethodReferenceResolver) } override fun getType(): PsiType? = TypeInferenceHelper.getCurrentContext().getExpressionType(this, ::getTypeFromCalculators) override fun getNominalType(): PsiType? = type override fun hasMemberPointer(): Boolean = true override fun handleElementRename(newElementName: String): PsiElement { if (referenceName == CONSTRUCTOR_REFERENCE_NAME && resolvesToConstructors()) { return this // don't update reference name } return super.handleElementRename(newElementName) } private fun resolvesToConstructors(): Boolean { return resolve(false).all { result -> (result.element as? PsiMethod)?.isConstructor ?: false } } override fun toString(): String = "Method reference expression" }
apache-2.0
8a12756f52ff41df70f1ceef8bfe67b8
40.816327
140
0.794534
4.533186
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/ActPost.kt
1
16340
package jp.juggler.subwaytooter import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.os.Handler import android.text.Editable import android.text.InputType import android.text.TextWatcher import android.view.KeyEvent import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.view.inputmethod.EditorInfo import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.action.saveWindowSize import jp.juggler.subwaytooter.actpost.* import jp.juggler.subwaytooter.api.entity.TootScheduled import jp.juggler.subwaytooter.api.entity.TootStatus import jp.juggler.subwaytooter.databinding.ActPostBinding import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.span.MyClickableSpan import jp.juggler.subwaytooter.span.MyClickableSpanHandler import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.util.* import jp.juggler.subwaytooter.view.MyEditText import jp.juggler.subwaytooter.view.MyNetworkImageView import jp.juggler.util.* import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.delay import java.lang.ref.WeakReference import java.util.concurrent.CancellationException import java.util.concurrent.ConcurrentHashMap class ActPost : AppCompatActivity(), View.OnClickListener, PostAttachment.Callback, MyClickableSpanHandler, AttachmentPicker.Callback { companion object { private val log = LogCategory("ActPost") var refActPost: WeakReference<ActPost>? = null const val EXTRA_POSTED_ACCT = "posted_acct" const val EXTRA_POSTED_STATUS_ID = "posted_status_id" const val EXTRA_POSTED_REPLY_ID = "posted_reply_id" const val EXTRA_POSTED_REDRAFT_ID = "posted_redraft_id" const val EXTRA_MULTI_WINDOW = "multiWindow" const val KEY_ACCOUNT_DB_ID = "account_db_id" const val KEY_REPLY_STATUS = "reply_status" const val KEY_REDRAFT_STATUS = "redraft_status" const val KEY_EDIT_STATUS = "edit_status" const val KEY_INITIAL_TEXT = "initial_text" const val KEY_SHARED_INTENT = "sent_intent" const val KEY_QUOTE = "quote" const val KEY_SCHEDULED_STATUS = "scheduled_status" const val STATE_ALL = "all" ///////////////////////////////////////////////// fun createIntent( context: Context, accountDbId: Long, multiWindowMode: Boolean, // 再編集する投稿。アカウントと同一のタンスであること redraftStatus: TootStatus? = null, // 編集する投稿。アカウントと同一のタンスであること editStatus: TootStatus? = null, // 返信対象の投稿。同一タンス上に同期済みであること replyStatus: TootStatus? = null, //初期テキスト initialText: String? = null, // 外部アプリから共有されたインテント sharedIntent: Intent? = null, // 返信ではなく引用トゥートを作成する quote: Boolean = false, //(Mastodon) 予約投稿の編集 scheduledStatus: TootScheduled? = null, ) = Intent(context, ActPost::class.java).apply { putExtra(EXTRA_MULTI_WINDOW, multiWindowMode) putExtra(KEY_ACCOUNT_DB_ID, accountDbId) initialText?.let { putExtra(KEY_INITIAL_TEXT, it) } redraftStatus?.let { putExtra(KEY_REDRAFT_STATUS, it.json.toString()) } editStatus?.let { putExtra(KEY_EDIT_STATUS, it.json.toString()) } replyStatus?.let { putExtra(KEY_REPLY_STATUS, it.json.toString()) putExtra(KEY_QUOTE, quote) } sharedIntent?.let { putExtra(KEY_SHARED_INTENT, it) } scheduledStatus?.let { putExtra(KEY_SCHEDULED_STATUS, it.src.toString()) } } } val views by lazy { ActPostBinding.inflate(layoutInflater) } lateinit var ivMedia: List<MyNetworkImageView> lateinit var etChoices: List<MyEditText> lateinit var handler: Handler lateinit var pref: SharedPreferences lateinit var appState: AppState lateinit var attachmentUploader: AttachmentUploader lateinit var attachmentPicker: AttachmentPicker lateinit var completionHelper: CompletionHelper var density: Float = 0f val languages by lazy { loadLanguageList() } private lateinit var progressChannel: Channel<Unit> /////////////////////////////////////////////////// // SavedAccount.acctAscii => FeaturedTagCache val featuredTagCache = ConcurrentHashMap<String, FeaturedTagCache>() // background job var jobFeaturedTag: WeakReference<Job>? = null var jobMaxCharCount: WeakReference<Job>? = null /////////////////////////////////////////////////// var states = ActPostStates() var accountList: ArrayList<SavedAccount> = ArrayList() var account: SavedAccount? = null var attachmentList = ArrayList<PostAttachment>() var isPostComplete: Boolean = false var scheduledStatus: TootScheduled? = null ///////////////////////////////////////////////////////////////////// val isMultiWindowPost: Boolean get() = intent.getBooleanExtra(EXTRA_MULTI_WINDOW, false) val arMushroom = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.getStringExtra("replace_key")?.let { text -> when (states.mushroomInput) { 0 -> applyMushroomText(views.etContent, text) 1 -> applyMushroomText(views.etContentWarning, text) else -> for (i in 0..3) { if (states.mushroomInput == i + 2) { applyMushroomText(etChoices[i], text) } } } } } //////////////////////////////////////////////////////////////// override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) backPressed { finish() // 戻るボタンを押したときとonPauseで2回保存することになるが、 // 同じ内容はDB上は重複しないはず… saveDraft() } if (isMultiWindowPost) ActMain.refActMain?.get()?.closeList?.add(WeakReference(this)) App1.setActivityTheme(this, noActionBar = true) appState = App1.getAppState(this) handler = appState.handler pref = appState.pref attachmentUploader = AttachmentUploader(this, handler) attachmentPicker = AttachmentPicker(this, this) density = resources.displayMetrics.density arMushroom.register(this) progressChannel = Channel(capacity = Channel.CONFLATED) launchMain { try { while (true) { progressChannel.receive() showMedisAttachmentProgress() delay(1000L) } } catch (ex: Throwable) { when (ex) { is CancellationException, is ClosedReceiveChannelException -> Unit else -> log.trace(ex) } } } initUI() when (savedInstanceState) { null -> updateText(intent, confirmed = true, saveDraft = false) else -> restoreState(savedInstanceState) } } override fun onDestroy() { try { progressChannel.close() } catch (ex: Throwable) { log.e(ex) } completionHelper.onDestroy() attachmentUploader.onActivityDestroy() super.onDestroy() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) saveState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) showContentWarningEnabled() showMediaAttachment() showVisibility() updateTextCount() showReplyTo() showPoll() showQuotedRenote() } override fun onResume() { super.onResume() refActPost = WeakReference(this) } override fun onPause() { super.onPause() // 編集中にホーム画面を押したり他アプリに移動する場合は下書きを保存する // やや過剰な気がするが、自アプリに戻ってくるときにランチャーからアイコンタップされると // メイン画面より上にあるアクティビティはすべて消されてしまうので // このタイミングで保存するしかない if (!isPostComplete) saveDraft() } override fun onClick(v: View) { refActPost = WeakReference(this) when (v.id) { R.id.btnAccount -> performAccountChooser() R.id.btnVisibility -> openVisibilityPicker() R.id.btnAttachment -> openAttachment() R.id.ivMedia1 -> performAttachmentClick(0) R.id.ivMedia2 -> performAttachmentClick(1) R.id.ivMedia3 -> performAttachmentClick(2) R.id.ivMedia4 -> performAttachmentClick(3) R.id.btnPost -> performPost() R.id.btnRemoveReply -> removeReply() R.id.btnMore -> performMore() R.id.btnPlugin -> openMushroom() R.id.btnEmojiPicker -> completionHelper.openEmojiPickerFromMore() R.id.btnFeaturedTag -> completionHelper.openFeaturedTagList( featuredTagCache[account?.acct?.ascii ?: ""]?.list ) R.id.ibSchedule -> performSchedule() R.id.ibScheduleReset -> resetSchedule() } } override fun onKeyShortcut(keyCode: Int, event: KeyEvent?): Boolean { return when { super.onKeyShortcut(keyCode, event) -> true event?.isCtrlPressed == true && keyCode == KeyEvent.KEYCODE_T -> { views.btnPost.performClick() true } else -> false } } override fun onMyClickableSpanClicked(viewClicked: View, span: MyClickableSpan) { openBrowser(span.linkInfo.url) } override fun onPickAttachment(uri: Uri, mimeType: String?) { addAttachment(uri, mimeType) } override fun onPostAttachmentProgress() { launchIO { try { progressChannel.send(Unit) } catch (ex: Throwable) { log.w(ex) } } } override fun onPostAttachmentComplete(pa: PostAttachment) { onPostAttachmentCompleteImpl(pa) } override fun resumeCustomThumbnailTarget(id: String?): PostAttachment? { id ?: return null return attachmentList.find { it.attachment?.id?.toString() == id } } override fun onPickCustomThumbnail(pa: PostAttachment, src: GetContentResultEntry) { onPickCustomThumbnailImpl(pa, src) } fun initUI() { setContentView(views.root) App1.initEdgeToEdge(this) if (PrefB.bpPostButtonBarTop(pref)) { val bar = findViewById<View>(R.id.llFooterBar) val parent = bar.parent as ViewGroup parent.removeView(bar) parent.addView(bar, 0) } if (!isMultiWindowPost) { Styler.fixHorizontalMargin(findViewById(R.id.scrollView)) Styler.fixHorizontalMargin(findViewById(R.id.llFooterBar)) } views.root.callbackOnSizeChanged = { _, _, _, _ -> if (isMultiWindowPost) saveWindowSize() // ビューのw,hはシステムバーその他を含まないので使わない } // https://github.com/tateisu/SubwayTooter/issues/123 // 早い段階で指定する必要がある views.etContent.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE views.etContent.imeOptions = EditorInfo.IME_ACTION_NONE views.spPollType.apply { this.adapter = ArrayAdapter( this@ActPost, android.R.layout.simple_spinner_item, arrayOf( getString(R.string.poll_dont_make), getString(R.string.poll_make), ) ).apply { setDropDownViewResource(R.layout.lv_spinner_dropdown) } this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { showPoll() updateTextCount() } override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long, ) { showPoll() updateTextCount() } } } ivMedia = listOf( views.ivMedia1, views.ivMedia2, views.ivMedia3, views.ivMedia4, ) etChoices = listOf( views.etChoice1, views.etChoice2, views.etChoice3, views.etChoice4, ) arrayOf( views.ibSchedule, views.ibScheduleReset, views.btnAccount, views.btnVisibility, views.btnAttachment, views.btnPost, views.btnRemoveReply, views.btnFeaturedTag, views.btnPlugin, views.btnEmojiPicker, views.btnMore, ).forEach { it.setOnClickListener(this) } ivMedia.forEach { it.setOnClickListener(this) } views.cbContentWarning.setOnCheckedChangeListener { _, _ -> showContentWarningEnabled() } completionHelper = CompletionHelper(this, pref, appState.handler) completionHelper.attachEditText( views.root, views.etContent, false, object : CompletionHelper.Callback2 { override fun onTextUpdate() { updateTextCount() } override fun canOpenPopup(): Boolean = true }) val textWatcher: TextWatcher = object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun afterTextChanged(editable: Editable) { updateTextCount() } } views.etContentWarning.addTextChangedListener(textWatcher) for (et in etChoices) { et.addTextChangedListener(textWatcher) } val scrollListener: ViewTreeObserver.OnScrollChangedListener = ViewTreeObserver.OnScrollChangedListener { completionHelper.onScrollChanged() } views.scrollView.viewTreeObserver.addOnScrollChangedListener(scrollListener) views.etContent.contentMineTypeArray = AttachmentUploader.acceptableMimeTypes.toTypedArray() views.etContent.contentCallback = { addAttachment(it) } views.spLanguage.adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, languages.map { it.second }.toTypedArray() ).apply { setDropDownViewResource(R.layout.lv_spinner_dropdown) } } }
apache-2.0
9c52806ff738b34ace38c53e1218d59c
33.431151
100
0.587283
4.69378
false
false
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/MultiStaticSelectElementBuilder.kt
1
5032
package com.slack.api.model.kotlin_extension.block.element import com.slack.api.model.block.composition.ConfirmationDialogObject import com.slack.api.model.block.composition.OptionGroupObject import com.slack.api.model.block.composition.OptionObject import com.slack.api.model.block.composition.PlainTextObject import com.slack.api.model.block.element.MultiStaticSelectElement import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.Builder import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder import com.slack.api.model.kotlin_extension.block.composition.container.MultiOptionContainer import com.slack.api.model.kotlin_extension.block.composition.container.MultiOptionGroupObjectContainer import com.slack.api.model.kotlin_extension.block.composition.dsl.OptionGroupObjectDsl import com.slack.api.model.kotlin_extension.block.composition.dsl.OptionObjectDsl @BlockLayoutBuilder class MultiStaticSelectElementBuilder : Builder<MultiStaticSelectElement> { private var placeholder: PlainTextObject? = null private var actionId: String? = null private var confirm: ConfirmationDialogObject? = null private var options: List<OptionObject>? = null private var optionGroups: List<OptionGroupObject>? = null private var initialOptions: List<OptionObject>? = null private var maxSelectedItems: Int? = null /** * Adds a plain text object in the placeholder field. * * The placeholder text shown on the menu. Maximum length for the text in this field is 150 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun placeholder(text: String, emoji: Boolean? = null) { placeholder = PlainTextObject(text, emoji) } /** * An identifier for the action triggered when a menu option is selected. You can use this when you receive an * interaction payload to identify the source of the action. Should be unique among all other action_ids used * elsewhere by your app. Maximum length for this field is 255 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun actionId(id: String) { actionId = id } /** * An array of option objects. Maximum number of options is 100. If option_groups is specified, this field should * not be. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun options(builder: OptionObjectDsl.() -> Unit) { options = MultiOptionContainer().apply(builder).underlying } /** * An array of option group objects. Maximum number of option groups is 100. If options is specified, this field * should not be. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun optionGroups(builder: OptionGroupObjectDsl.() -> Unit) { optionGroups = MultiOptionGroupObjectContainer().apply(builder).underlying } /** * An array of option objects that exactly match one or more of the options within options or option_groups. * These options will be selected when the menu initially loads. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun initialOptions(builder: OptionObjectDsl.() -> Unit) { initialOptions = MultiOptionContainer().apply(builder).underlying } /** * Specifies the maximum number of items that can be selected in the menu. Minimum number is 1. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun maxSelectedItems(max: Int) { maxSelectedItems = max } /** * A confirm object that defines an optional confirmation dialog that appears before the multi-select choices are submitted. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#static_multi_select">Multi static select element documentation</a> */ fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) { confirm = ConfirmationDialogObjectBuilder().apply(builder).build() } override fun build(): MultiStaticSelectElement { return MultiStaticSelectElement.builder() .placeholder(placeholder) .actionId(actionId) .options(options) .optionGroups(optionGroups) .initialOptions(initialOptions) .confirm(confirm) .maxSelectedItems(maxSelectedItems) .build() } }
mit
339787eabd1da4e9ac36d112d686a617
46.037383
144
0.71721
4.35671
false
false
false
false
micgn/stock-charts
stock-server/src/main/java/de/mg/stock/server/util/KeyDataStringBuilder.kt
1
1776
package de.mg.stock.server.util import de.mg.stock.dto.StockKeyDataDto import java.text.DecimalFormat import java.time.LocalDate import java.time.LocalDate.now import java.time.format.DateTimeFormatter.ofPattern import javax.inject.Singleton @Singleton class KeyDataStringBuilder { fun asCsv(list: List<StockKeyDataDto>): String { val s = StringBuilder("stock;since;min date;min;max date;max;max-min;performance; average performance\n") for (data in list) { s.append(data.stock!!.toString()).append(";") s.append(since(data.distanceInDays!!)).append(";") s.append(date(data.minDate)).append(";") s.append(amount(data.min)).append(";") s.append(date(data.maxDate)).append(";") s.append(amount(data.max)).append(";") s.append(data.minToMaxPercentage).append("%").append("%;") s.append(data.exactPerformancePercentage).append("%").append(";") s.append(if (data.averagePerformancePercentage != null) data.averagePerformancePercentage?.toString() + "%" else "") s.append("\n") } return s.toString() } fun asHtml(list: List<StockKeyDataDto>) = "<table border=\"1\" cellpadding=\"5px\"><tr><td>" + asCsv(list).dropLast(1).replace(";".toRegex(), "</td><td>"). replace("\n".toRegex(), "</td></tr><tr><td>") + "</td></tr></table>" private fun amount(l: Long?) = if (l == null) "" else DecimalFormat("#0.00").format(l / 100.0) private fun date(date: LocalDate?) = if (date == null) "" else date.format(ofPattern("dd.MM.yyyy")) private fun since(distance: Int) = now().minusDays(distance.toLong()).format(ofPattern("dd.MM.yyyy")) }
apache-2.0
9b83f847319b1120c324d0e8862cd6b1
36.787234
128
0.609234
3.886214
false
false
false
false
orauyeu/SimYukkuri
subprojects/messageutil/src/main/kotlin/osdntogit/ReformatMessage.kt
1
2352
package osdntogit import messageutil.* import java.io.InputStream import java.nio.file.Files import java.nio.file.Path /** OSDN形式のゆっくりのデータをパラメータとセリフのペアに分割し, セリフデータを現行形式に変換する. */ fun reformatOsdnMessage(path: Path): Pair<Map<String, Any>, MessageCollection> = Files.newInputStream(path).use { reformatOsdnMessage(it) } /** OSDN形式のゆっくりのデータをパラメータとセリフのペアに分割し, セリフデータを現行形式に変換する. */ fun reformatOsdnMessage(input: InputStream): Pair<Map<String, Any>, MessageCollection> { val yukkuriData = @Suppress("UNCHECKED_CAST") (myYaml.load(input) as Map<String, Any>) val params: MutableMap<String, Any> = mutableMapOf() var keyToDamageToGrowthToMsgs: Map<String, List<List<String>>> = emptyMap() for ((key, value) in yukkuriData) { if (key == "dialogue") keyToDamageToGrowthToMsgs = @Suppress("UNCHECKED_CAST") (value as Map<String, List<List<String>>>) else params.put(key, value) } val newMessageData = mutableMessageCollection() for ((rawMsgKey, damageToGrowthToMsgs) in keyToDamageToGrowthToMsgs) { val isImmoral: Boolean // RudeHogeという名前はHogeに置き換える val msgKey: String if (rawMsgKey.contains("Rude")) { isImmoral = true msgKey = rawMsgKey.substring(4) } else { isImmoral = false msgKey = rawMsgKey } val newCondToMsgs = newMessageData.getOrPut(msgKey) { linkedMapOf() } for (damageIndex in damageToGrowthToMsgs.indices) { val growthToMsgs = damageToGrowthToMsgs[damageIndex] val isDamaged = damageIndex == 1 for (growthIndex in growthToMsgs.indices) { val message = growthToMsgs[growthIndex] val growth = when (growthIndex) { 0 -> Growth.BABY 1 -> Growth.CHILD else -> Growth.ADULT } val type = Condition(growth, isImmoral, isDamaged, false, Love.ALL, false) newCondToMsgs.getOrPut(type) { mutableListOf() }.add(message) } } } return Pair(params, newMessageData) }
apache-2.0
abfe006377c3a92318d881b2b0fc5a77
35.491525
110
0.631041
3.522095
false
false
false
false
sachil/Essence
app/src/main/java/xyz/sachil/essence/activity/ImageActivity.kt
1
5403
package xyz.sachil.essence.activity import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.lifecycle.lifecycleScope import com.bumptech.glide.request.target.CustomViewTarget import com.bumptech.glide.request.transition.Transition import kotlinx.coroutines.* import xyz.sachil.essence.databinding.ActivityImageBinding import xyz.sachil.essence.model.net.GlideApp import xyz.sachil.essence.widget.ScalableImageView @Suppress("DEPRECATION") class ImageActivity : AppCompatActivity() { companion object { private val TAG = "ImageActivity" } private lateinit var viewBinding: ActivityImageBinding private lateinit var autoHideSystemBarJob: Job override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initViews() showImage() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } } private fun initViews() { showSystemBars() viewBinding = ActivityImageBinding.inflate(layoutInflater) setContentView(viewBinding.root) setSupportActionBar(viewBinding.toolBar) val title = intent.getStringExtra("title") supportActionBar?.title = title supportActionBar?.setDisplayHomeAsUpEnabled(true) viewBinding.image.setOnClickListener { if (window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) { hideSystemBars() if(autoHideSystemBarJob.isActive){ autoHideSystemBarJob.cancel() } } else { showSystemBars() autoHideSystemBars() } } registerSystemBarVisibilityChangedListener() autoHideSystemBars() } private fun showImage() { val imageUrl = intent.getStringExtra("image") if (imageUrl != null) { GlideApp.with(this) .asBitmap() .load(imageUrl) .into(object : CustomViewTarget<ScalableImageView, Bitmap>(viewBinding.image) { override fun onLoadFailed(errorDrawable: Drawable?) { } override fun onResourceCleared(placeholder: Drawable?) { } override fun onResourceReady( resource: Bitmap, transition: Transition<in Bitmap>? ) { view.setImage(resource, false) } }) } } private fun Toolbar.show() { if (this.alpha > 0) { return } val alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 0F, 1.0F) val translationAnimator = ObjectAnimator.ofFloat( viewBinding.toolBar, "translationY", this.translationY, 0F ) val animatorSet = AnimatorSet() animatorSet.duration = 300 animatorSet.playTogether(alphaAnimator, translationAnimator) animatorSet.start() } private fun Toolbar.hide() { if (this.alpha > 0F) { val alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 1.0F, 0F) val translationAnimator = ObjectAnimator.ofFloat( viewBinding.toolBar, "translationY", this.translationY - this.height ) val animatorSet = AnimatorSet() animatorSet.duration = 300 animatorSet.playTogether(alphaAnimator, translationAnimator) animatorSet.start() } } private fun autoHideSystemBars() { autoHideSystemBarJob = lifecycleScope.launch { withContext(Dispatchers.IO) { delay(2 * 1000) } hideSystemBars() } } private fun showSystemBars() { window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) } private fun hideSystemBars() { window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) } private fun registerSystemBarVisibilityChangedListener() { window.decorView.setOnSystemUiVisibilityChangeListener { if (it and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) { //system bar is visible viewBinding.toolBar.show() } else { //system bar is not visible viewBinding.toolBar.hide() } } } }
apache-2.0
dfff597155d5a39af16cc3b5e06fc1c2
32.358025
95
0.603368
5.27122
false
false
false
false
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/events/namedays/calendar/resource/AndroidJSONResourceLoader.kt
3
1637
package com.alexstyl.specialdates.events.namedays.calendar.resource import android.content.res.Resources import com.alexstyl.specialdates.R import com.alexstyl.specialdates.events.namedays.NamedayLocale import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStream import org.json.JSONException import org.json.JSONObject class AndroidJSONResourceLoader(private val resources: Resources) : NamedayJSONResourceLoader { @Throws(JSONException::class) override fun loadJSON(locale: NamedayLocale): JSONObject { val inputStream = resources.openRawResource(locale.rawResId()) val outputStream = ByteArrayOutputStream() var ctr: Int try { ctr = inputStream.read() while (ctr != -1) { outputStream.write(ctr) ctr = inputStream.read() } inputStream.close() return JSONObject(outputStream.toString("UTF-8")) } catch (e: IOException) { throw JSONException(e.message) } catch (e: JSONException) { throw JSONException(e.message) } } } private fun NamedayLocale.rawResId(): Int = when(this){ NamedayLocale.GREEK -> R.raw.gr_namedays NamedayLocale.ROMANIAN -> R.raw.ro_namedays NamedayLocale.RUSSIAN -> R.raw.ru_namedays NamedayLocale.LATVIAN -> R.raw.lv_namedays NamedayLocale.LATVIAN_EXTENDED -> R.raw.lv_ext_namedays NamedayLocale.SLOVAK -> R.raw.sk_namedays NamedayLocale.ITALIAN -> R.raw.it_namedays NamedayLocale.CZECH -> R.raw.cs_namedays NamedayLocale.HUNGARIAN -> R.raw.hu_namedays }
mit
3982b3ece724abb58234b5b2f518ef62
31.098039
95
0.688454
4.002445
false
false
false
false
java-graphics/assimp
src/main/kotlin/assimp/defs.kt
2
3895
package assimp import glm_.glm import glm_.mat3x3.Mat3 import glm_.vec2.Vec2 import glm_.vec3.Vec3 import glm_.vec4.Vec4 import glm_.mat4x4.Mat4 import glm_.quat.Quat import org.w3c.dom.Element import java.io.File import java.net.URI import java.net.URL import kotlin.math.cos import kotlin.math.sin /** * Created by elect on 14/11/2016. */ typealias ai_real = Float typealias AiVector3D = Vec3 typealias AiColor3D = Vec3 typealias AiColor4D = Vec4 typealias AiMatrix3x3 = Mat3 typealias AiMatrix4x4 = Mat4 typealias AiVector2D = Vec2 typealias AiQuaternion = Quat /* To avoid running out of memory * This can be adjusted for specific use cases * It's NOT a total limit, just a limit for individual allocations */ fun AI_MAX_ALLOC(size: Int) = (256 * 1024 * 1024) / size /** Consider using extension property Float.rad */ fun AI_DEG_TO_RAD(x: Float) = ((x) * 0.0174532925f) /** Consider using extension property Float.deg */ fun AI_RAD_TO_DEG(x: Float) = ((x) * 57.2957795f) fun is_special_float(f: Float): Boolean { return f == (1 shl 8) - 1f } // TODO file operators overloading, https://youtrack.jetbrains.com/issue/KT-15009 internal infix operator fun File.plus(another: String) = File(this, another) internal fun URL.exists() = File(toURI()).exists() internal fun URI.exists() = File(this).exists() internal val URI.extension get() = if (path.contains(".")) path.substringAfterLast('.', "").toLowerCase() else "" internal val URI.s get() = toString() internal fun Vec3.distance(other: Vec3): Float { return Math.sqrt(Math.pow(this.x.toDouble() + other.x.toDouble(), 2.0) + Math.pow(this.y.toDouble() + other.y.toDouble(), 2.0) + Math.pow(this.z.toDouble() + other.z.toDouble(), 2.0)).toFloat() } internal fun Vec3.squareLength() = Math.sqrt(Math.pow(x.toDouble(), 2.0) // TODO this is Vec3.length2() + Math.pow(y.toDouble(), 2.0) + Math.pow(z.toDouble(), 2.0)).toFloat() internal fun Element.elementChildren(): ArrayList<Element> { val res = ArrayList<Element>() repeat(childNodes.length) { val element = childNodes.item(it) if (element is Element) res.add(element) } return res } internal operator fun Element.get(attribute: String) = if (hasAttribute(attribute)) getAttribute(attribute) else null internal val String.words: List<String> get() = trim().split("\\s+".toRegex()) ////////////////////////////////////////////////////////////////////////// /* Useful constants */ ////////////////////////////////////////////////////////////////////////// /* This is PI. Hi PI. */ val AI_MATH_TWO_PI = glm.PI2 val AI_MATH_TWO_PIf = glm.PI2f val AI_MATH_HALF_PI = glm.HPIf internal val AiVector3D.squareLength get() = x * x + y * y + z * z internal fun rotationX(a: Float) = AiMatrix4x4().apply { /* | 1 0 0 0 | M = | 0 cos(A) sin(A) 0 | | 0 -sin(A) cos(A) 0 | | 0 0 0 1 | */ b1 = cos(a) c2 = b1 c1 = sin(a) b2 = -c1 } internal fun rotationY(a: Float) = AiMatrix4x4().apply { /* | cos(A) 0 -sin(A) 0 | M = | 0 1 0 0 | | sin(A) 0 cos(A) 0 | | 0 0 0 1 | */ a0 = cos(a) c2 = a0 a2 = sin(a) c0 = -a2 } internal fun rotationZ(a: Float) = AiMatrix4x4().apply { /* | cos(A) sin(A) 0 0 | M = | -sin(A) cos(A) 0 0 | | 0 0 1 0 | | 0 0 0 1 | */ a0 = cos(a) b1 = a0 b0 = sin(a) a1 = -b0 } internal fun translation(v: Vec3) = AiMatrix4x4().apply { d0 = v.x d1 = v.y d2 = v.z } internal fun scaling(v: Vec3) = AiMatrix4x4().apply { a0 = v.x b1 = v.y c2 = v.z } internal operator fun StringBuilder.plusAssign(c: Char) { append(c) }
bsd-3-clause
fed0a79d536861756270c3035231dd6a
24.298701
117
0.572015
3.064516
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/course/interactor/CourseEnrollmentInteractor.kt
1
4530
package org.stepik.android.domain.course.interactor import io.reactivex.Completable import io.reactivex.Single import io.reactivex.subjects.PublishSubject import okhttp3.ResponseBody import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.util.then import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.course.repository.CourseRepository import org.stepik.android.domain.course.repository.EnrollmentRepository import org.stepik.android.domain.lesson.repository.LessonRepository import org.stepik.android.domain.personal_deadlines.repository.DeadlinesRepository import org.stepik.android.domain.user_courses.interactor.UserCoursesInteractor import org.stepik.android.domain.wishlist.model.WishlistOperationData import org.stepik.android.domain.wishlist.repository.WishlistRepository import org.stepik.android.model.Course import org.stepik.android.presentation.wishlist.model.WishlistAction import org.stepik.android.view.injection.course.EnrollmentCourseUpdates import org.stepik.android.view.injection.course_list.WishlistOperationBus import retrofit2.HttpException import retrofit2.Response import java.net.HttpURLConnection import javax.inject.Inject class CourseEnrollmentInteractor @Inject constructor( private val enrollmentRepository: EnrollmentRepository, private val sharedPreferenceHelper: SharedPreferenceHelper, private val courseRepository: CourseRepository, private val lessonRepository: LessonRepository, private val deadlinesRepository: DeadlinesRepository, private val wishlistRepository: WishlistRepository, @WishlistOperationBus private val wishlistOperationPublisher: PublishSubject<WishlistOperationData>, @EnrollmentCourseUpdates private val enrollmentSubject: PublishSubject<Course>, private val userCoursesInteractor: UserCoursesInteractor ) { companion object { private val UNAUTHORIZED_EXCEPTION_STUB = HttpException(Response.error<Nothing>(HttpURLConnection.HTTP_UNAUTHORIZED, ResponseBody.create(null, ""))) } private val requireAuthorization: Completable = Completable.create { emitter -> if (sharedPreferenceHelper.authResponseFromStore != null) { emitter.onComplete() } else { emitter.onError(UNAUTHORIZED_EXCEPTION_STUB) } } fun fetchCourseEnrollmentAfterPurchaseInWeb(courseId: Long): Completable = requireAuthorization then courseRepository .getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false) .toSingle() .flatMapCompletable { course -> if (course.enrollment > 0) { userCoursesInteractor.addUserCourse(course.id) .andThen(lessonRepository.removeCachedLessons(course.id)) .doOnComplete { enrollmentSubject.onNext(course) } } else { Completable.complete() } } fun enrollCourse(courseId: Long): Single<Course> = requireAuthorization then enrollmentRepository .addEnrollment(courseId) .andThen(userCoursesInteractor.addUserCourse(courseId)) .andThen(lessonRepository.removeCachedLessons(courseId)) .andThen(removeCourseFromWishlist(courseId)) .andThen(courseRepository.getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false).toSingle()) .doOnSuccess(enrollmentSubject::onNext) // notify everyone about changes fun dropCourse(courseId: Long): Single<Course> = requireAuthorization then enrollmentRepository .removeEnrollment(courseId) .andThen(deadlinesRepository.removeDeadlineRecordByCourseId(courseId).onErrorComplete()) .andThen(userCoursesInteractor.removeUserCourse(courseId)) .andThen(lessonRepository.removeCachedLessons(courseId)) .andThen(courseRepository.getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false).toSingle()) .doOnSuccess(enrollmentSubject::onNext) // notify everyone about changes private fun removeCourseFromWishlist(courseId: Long): Completable = wishlistRepository .removeCourseFromWishlist(courseId, sourceType = DataSourceType.CACHE) .doOnComplete { wishlistOperationPublisher.onNext(WishlistOperationData(courseId, WishlistAction.REMOVE)) } }
apache-2.0
6f633ad86066de7291c16ecb83ac23a7
45.71134
128
0.743709
5.348288
false
false
false
false
vvv1559/intellij-community
platform/lang-impl/src/com/intellij/psi/stubs/PrebuiltStubs.kt
1
2547
/* * 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.psi.stubs import com.google.common.hash.HashCode import com.google.common.hash.Hashing import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileTypes.FileTypeExtension import com.intellij.util.indexing.FileContent import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.KeyDescriptor import java.io.DataInput import java.io.DataOutput /** * @author traff */ val EP_NAME = "com.intellij.filetype.prebuiltStubsProvider" object PrebuiltStubsProviders : FileTypeExtension<PrebuiltStubsProvider>(EP_NAME) { val EXTENSION_POINT_NAME = ExtensionPointName.create<BinaryFileStubBuilder>(EP_NAME) } interface PrebuiltStubsProvider { fun findStub(fileContent: FileContent): Stub? } class FileContentHashing { private val hashing = Hashing.sha256() fun hashString(fileContent: FileContent): HashCode { return hashing.hashBytes(fileContent.content) } } class HashCodeDescriptor : HashCodeExternalizers(), KeyDescriptor<HashCode> { override fun getHashCode(value: HashCode): Int = value.hashCode() override fun isEqual(val1: HashCode, val2: HashCode): Boolean = val1 == val2 companion object { val instance = HashCodeDescriptor() } } open class HashCodeExternalizers : DataExternalizer<HashCode> { override fun save(out: DataOutput, value: HashCode) { val bytes = value.asBytes() DataInputOutputUtil.writeINT(out, bytes.size) out.write(bytes, 0, bytes.size) } override fun read(`in`: DataInput): HashCode { val len = DataInputOutputUtil.readINT(`in`) val bytes = ByteArray(len) `in`.readFully(bytes) return HashCode.fromBytes(bytes) } } class StubTreeExternalizer : DataExternalizer<SerializedStubTree> { override fun save(out: DataOutput, value: SerializedStubTree) { value.write(out) } override fun read(`in`: DataInput) = SerializedStubTree(`in`) }
apache-2.0
179d812f23fe0cb074af8f2c6a379407
29.333333
86
0.76168
4.128039
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/service/MattermostService.kt
1
2899
package no.skatteetaten.aurora.boober.service import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.JsonNode import mu.KotlinLogging import no.skatteetaten.aurora.boober.ServiceTypes import no.skatteetaten.aurora.boober.TargetService import no.skatteetaten.aurora.boober.utils.RetryingRestTemplateWrapper import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.stereotype.Component import org.springframework.stereotype.Service import org.springframework.web.client.RestTemplate private val logger = KotlinLogging.logger {} data class MattermostSendMessageRequest( val message: String, @JsonProperty("channel_id") val channelId: String, val props: MattermostProps ) data class MattermostProps( val attachments: List<Attachment> ) @JsonInclude(JsonInclude.Include.NON_NULL) data class Attachment( val color: String? = null, val text: String? = null, val title: String? = null, @JsonProperty("title_link") val titleLink: String? = null, val fields: List<AttachmentField>? = null ) data class AttachmentField( val short: Boolean, val title: String, val value: String ) enum class AttachmentColor(val hex: String) { Red("#FF0000"), Green("#008000"); override fun toString(): String = hex } @Component class MattermostRestTemplateWrapper( @TargetService(ServiceTypes.GENERAL) restTemplate: RestTemplate, @Value("\${integrations.mattermost.url}") val url: String ) : RetryingRestTemplateWrapper( restTemplate = restTemplate, retries = 0, baseUrl = "$url/api/v4" ) @Service class MattermostService( val restTemplateWrapper: MattermostRestTemplateWrapper, @Value("\${integrations.mattermost.token}") val mattermostToken: String ) { fun sendMessage(channelId: String, message: String, attachments: List<Attachment> = emptyList()): Exception? { val response = runCatching { restTemplateWrapper.post( url = "/posts", body = MattermostSendMessageRequest( message = message, channelId = channelId, props = MattermostProps( attachments ) ), type = JsonNode::class, headers = HttpHeaders().apply { setBearerAuth(mattermostToken) } ) }.onFailure { logger.error { it } }.getOrNull() if (response == null || response.statusCode != HttpStatus.CREATED) { return NotificationServiceException("Was not able to send notification to mattermost channel_id=$channelId") } return null } }
apache-2.0
89efdc8a67ef896f9aff186735763cdc
29.840426
120
0.681269
4.565354
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.kt
1
17045
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.platform import com.intellij.configurationStore.runInAutoSaveDisabledMode import com.intellij.conversion.CannotConvertException import com.intellij.conversion.ConversionService import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.runActivity import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeEventQueue import com.intellij.ide.SaveAndSyncHandler import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.lightEdit.LightEditUtil import com.intellij.ide.util.PsiNavigationSupport import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.projectImport.ProjectAttachProcessor import com.intellij.projectImport.ProjectOpenProcessor import com.intellij.projectImport.ProjectOpenedCallback import com.intellij.ui.IdeUICustomization import org.jetbrains.annotations.ApiStatus import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* private val LOG = logger<PlatformProjectOpenProcessor>() class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectOpenProcessor { enum class Option { FORCE_NEW_FRAME, @Suppress("unused") TEMP_PROJECT } companion object { @JvmField val PROJECT_OPENED_BY_PLATFORM_PROCESSOR = Key.create<Boolean>("PROJECT_OPENED_BY_PLATFORM_PROCESSOR") @JvmStatic fun getInstance() = getInstanceIfItExists()!! @JvmStatic fun getInstanceIfItExists(): PlatformProjectOpenProcessor? { for (processor in EXTENSION_POINT_NAME.extensionList) { if (processor is PlatformProjectOpenProcessor) { return processor } } return null } @JvmStatic @Suppress("UNUSED_PARAMETER") @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use {@link #doOpenProject(Path, OpenProjectTask)} ") fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean, line: Int, callback: ProjectOpenedCallback?, isReopen: Boolean): Project? { val options = OpenProjectTask(forceOpenInNewFrame, projectToClose) options.line = line return doOpenProject(Paths.get(virtualFile.path), options) } @JvmStatic @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use {@link #doOpenProject(Path, OpenProjectTask)} ") fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, line: Int, callback: ProjectOpenedCallback?, options: EnumSet<Option>): Project? { val openProjectOptions = OpenProjectTask(forceOpenInNewFrame = options.contains(Option.FORCE_NEW_FRAME), projectToClose = projectToClose, callback = callback) openProjectOptions.line = line return doOpenProject(Paths.get(virtualFile.path), openProjectOptions) } @ApiStatus.Internal @JvmStatic fun createTempProjectAndOpenFile(file: Path, options: OpenProjectTask): Project? { val dummyProjectName = file.fileName.toString() val baseDir = FileUtil.createTempDirectory(dummyProjectName, null, true).toPath() val copy = options.copy(isNewProject = true, projectName = dummyProjectName, isDummyProject = true) val project = openExistingProject(file, baseDir, copy) ?: return null openFileFromCommandLine(project, file, copy.line, copy.column) return project } @ApiStatus.Internal @JvmStatic fun doOpenProject(file: Path, options: OpenProjectTask): Project? { LOG.info("Opening $file") var baseDir = file if (!Files.isDirectory(file)) { if (LightEditUtil.openFile(file)) { return LightEditUtil.getProject() } var baseDirCandidate = file.parent while (baseDirCandidate != null && !Files.exists(baseDirCandidate.resolve(Project.DIRECTORY_STORE_FOLDER))) { baseDirCandidate = baseDirCandidate.parent } // no reasonable directory -> create new temp one or use parent if (baseDirCandidate == null) { LOG.info("No project directory found") if (Registry.`is`("ide.open.file.in.temp.project.dir")) { return createTempProjectAndOpenFile(file, options) } baseDir = file.parent options.isNewProject = !Files.isDirectory(baseDir.resolve(Project.DIRECTORY_STORE_FOLDER)) } else { baseDir = baseDirCandidate LOG.info("Project directory found: $baseDir") } } SaveAndSyncHandler.getInstance().disableAutoSave().use { val project = openExistingProject(file, baseDir, options) if (project != null && file !== baseDir && !Files.isDirectory(file)) { openFileFromCommandLine(project, file, options.line, options.column) } return project } } @ApiStatus.Internal @JvmStatic fun openExistingProject(file: Path, projectDir: Path?, options: OpenProjectTask): Project? { if (options.project != null) { val projectManager = ProjectManagerEx.getInstanceExIfCreated() if (projectManager != null && projectManager.isProjectOpened(options.project)) { return null } } val activity = StartUpMeasurer.startMainActivity("project opening preparation") if (!options.forceOpenInNewFrame) { val openProjects = ProjectUtil.getOpenProjects() if (openProjects.isNotEmpty()) { var projectToClose = options.projectToClose if (projectToClose == null) { // if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching) val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame projectToClose = lastFocusedFrame?.project if (projectToClose == null || LightEdit.owns(projectToClose)) { projectToClose = openProjects[openProjects.size - 1] } } if (checkExistingProjectOnOpen(projectToClose!!, options.callback, projectDir)) { return null } } } var result: PrepareProjectResult? = null runInAutoSaveDisabledMode { val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) ProjectFrameAllocator() else ProjectUiFrameAllocator(options, file) val isCompleted = frameAllocator.run { var project = options.project if (project == null) { var cannotConvertException: CannotConvertException? = null try { activity.end() result = prepareProject(file, options, projectDir!!) } catch (e: ProcessCanceledException) { throw e } catch (e: CannotConvertException) { LOG.info(e) cannotConvertException = e result = null } catch (e: Exception) { result = null LOG.error(e) } project = result?.project if (project == null) { frameAllocator.projectNotLoaded(cannotConvertException) return@run } } else { result = PrepareProjectResult(project, null) } frameAllocator.projectLoaded(project) if (ProjectManagerEx.getInstanceEx().openProject(project)) { frameAllocator.projectOpened(project) } else { result = null } } if (!isCompleted) { result = null } } val project = result?.project if (project == null) { if (options.showWelcomeScreen) { WelcomeFrame.showIfNoProjectOpened() } return null } if (options.callback != null) { var module = result?.module if (module == null) { module = ModuleManager.getInstance(project).modules[0] } options.callback!!.projectOpened(project, module) } return project } @Suppress("DeprecatedCallableAddReplaceWith") @JvmStatic @Deprecated("Use {@link #runDirectoryProjectConfigurators(Path, Project, boolean)}") fun runDirectoryProjectConfigurators(baseDir: VirtualFile, project: Project): Module { return runDirectoryProjectConfigurators(Paths.get(baseDir.path), project, false) } @JvmStatic fun runDirectoryProjectConfigurators(baseDir: Path, project: Project, newProject: Boolean): Module { val moduleRef = Ref<Module>() val virtualFile = ProjectUtil.getFileAndRefresh(baseDir) LOG.assertTrue(virtualFile != null) DirectoryProjectConfigurator.EP_NAME.forEachExtensionSafe { configurator: DirectoryProjectConfigurator -> configurator.configureProject(project, virtualFile!!, moduleRef, newProject) } return moduleRef.get() } @JvmStatic fun attachToProject(project: Project, projectDir: Path, callback: ProjectOpenedCallback?): Boolean { return ProjectAttachProcessor.EP_NAME.findFirstSafe { processor -> processor.attachToProject(project, projectDir, callback) } != null } } override fun canOpenProject(file: VirtualFile) = file.isDirectory override fun isProjectFile(file: VirtualFile) = false override fun lookForProjectsInDirectory() = false override fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? { val options = OpenProjectTask(forceOpenInNewFrame = forceOpenInNewFrame, projectToClose = projectToClose) if (ApplicationManager.getApplication().isUnitTestMode) { // doesn't make sense to use default project in tests for heavy projects options.useDefaultProjectAsTemplate = false } val baseDir = Paths.get(virtualFile.path) options.isNewProject = !ProjectUtil.isValidProjectPath(baseDir) return doOpenProject(baseDir, options) } override fun openProjectAndFile(virtualFile: VirtualFile, line: Int, column: Int, tempProject: Boolean): Project? { // force open in a new frame if temp project val options = OpenProjectTask(forceOpenInNewFrame = tempProject) val file = Paths.get(virtualFile.path) if (tempProject) { return createTempProjectAndOpenFile(file, options) } else { options.line = line options.column = column return doOpenProject(file, options) } } @Suppress("HardCodedStringLiteral") override fun getName() = "text editor" } internal data class PrepareProjectResult(val project: Project, val module: Module?) private fun prepareProject(file: Path, options: OpenProjectTask, baseDir: Path): PrepareProjectResult? { val project: Project? val isNewProject = options.isNewProject if (isNewProject) { val projectName = options.projectName ?: baseDir.fileName.toString() project = ProjectManagerEx.getInstanceEx().newProject(baseDir, projectName, options) } else { val indicator = ProgressManager.getInstance().progressIndicator indicator?.text = IdeUICustomization.getInstance().projectMessage("project.checking.configuration") project = convertAndLoadProject(baseDir, options) indicator?.text = "" } if (project == null) { return null } val module = configureNewProject(project, baseDir, file, options.isDummyProject, isNewProject) if (isNewProject) { project.save() } return PrepareProjectResult(project, module) } private fun configureNewProject(project: Project, baseDir: Path, dummyFileContentRoot: Path, dummyProject: Boolean, newProject: Boolean): Module? { val runConfigurators = newProject || ModuleManager.getInstance(project).modules.isEmpty() var module: Module? = null if (runConfigurators) { ApplicationManager.getApplication().invokeAndWait { module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(baseDir, project, newProject) } } if (runConfigurators && dummyProject) { // add content root for chosen (single) file ModuleRootModificationUtil.updateModel(module!!) { model -> val entries = model.contentEntries // remove custom content entry created for temp directory if (entries.size == 1) { model.removeContentEntry(entries[0]) } model.addContentEntry(VfsUtilCore.pathToUrl(dummyFileContentRoot.toString())) } } return module } private fun checkExistingProjectOnOpen(projectToClose: Project, callback: ProjectOpenedCallback?, projectDir: Path?): Boolean { if (projectDir != null && ProjectAttachProcessor.canAttachToProject() && GeneralSettings.getInstance().confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK) { val exitCode = ProjectUtil.confirmOpenOrAttachProject() if (exitCode == -1) { return true } else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) { if (!ProjectManagerEx.getInstanceEx().closeAndDispose(projectToClose)) { return true } } else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) { if (PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) { return true } } // process all pending events that can interrupt focus flow // todo this can be removed after taming the focus beast IdeEventQueue.getInstance().flushQueue() } else { val exitCode = ProjectUtil.confirmOpenNewProject(false) if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) { if (!ProjectManagerEx.getInstanceEx().closeAndDispose(projectToClose)) { return true } } else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) { // not in a new window return true } } return false } private fun openFileFromCommandLine(project: Project, file: Path, line: Int, column: Int) { StartupManager.getInstance(project).registerPostStartupDumbAwareActivity { ApplicationManager.getApplication().invokeLater(Runnable { if (project.isDisposed || !Files.exists(file)) { return@Runnable } val virtualFile = ProjectUtil.getFileAndRefresh(file) ?: return@Runnable val navigatable = if (line > 0) { OpenFileDescriptor(project, virtualFile, line - 1, column.coerceAtLeast(0)) } else { PsiNavigationSupport.getInstance().createNavigatable(project, virtualFile, -1) } navigatable.navigate(true) }, ModalityState.NON_MODAL, project.disposed) } } private fun convertAndLoadProject(path: Path, options: OpenProjectTask): Project? { val conversionResult = runActivity("project conversion", category = ActivityCategory.MAIN) { ConversionService.getInstance().convert(path) } if (conversionResult.openingIsCanceled()) { return null } val project = ProjectManagerImpl.doCreateProject(options.projectName, path) try { val progressManager = ProgressManager.getInstance() if (!ApplicationManager.getApplication().isDispatchThread && progressManager.progressIndicator != null) { ProjectManagerImpl.initProject(path, project, /* isRefreshVfsNeeded = */ true, null, progressManager.progressIndicator) } else { progressManager.runProcessWithProgressSynchronously({ ProjectManagerImpl.initProject(path, project, /* isRefreshVfsNeeded = */ true, null, progressManager.progressIndicator) }, IdeUICustomization.getInstance().projectMessage("project.load.progress"), !ProgressManager.getInstance().isInNonCancelableSection, project) } } catch (e: ProcessCanceledException) { return null } if (!conversionResult.conversionNotNeeded()) { StartupManager.getInstance(project).registerPostStartupActivity { conversionResult.postStartupActivity(project) } } return project }
apache-2.0
f282cfefedaa3ef29855afe7aeb150d3
38.274194
179
0.710179
5.057864
false
false
false
false
RobWin/javaslang-circuitbreaker
resilience4j-kotlin/src/test/kotlin/io/github/resilience4j/kotlin/timelimiter/CoroutineTimeLimiterTest.kt
2
5795
/* * * Copyright 2019: Brad Newman * * 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.github.resilience4j.kotlin.timelimiter import io.github.resilience4j.kotlin.CoroutineHelloWorldService import io.github.resilience4j.timelimiter.TimeLimiter import io.github.resilience4j.timelimiter.event.TimeLimiterOnErrorEvent import io.github.resilience4j.timelimiter.event.TimeLimiterOnSuccessEvent import io.github.resilience4j.timelimiter.event.TimeLimiterOnTimeoutEvent import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions import org.junit.Test import java.time.Duration import java.util.concurrent.TimeoutException class CoroutineTimeLimiterTest { @Test fun `should execute successful function`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val successfulEvents = mutableListOf<TimeLimiterOnSuccessEvent>() timelimiter.eventPublisher.onSuccess(successfulEvents::add) //When val result = timelimiter.executeSuspendFunction { helloWorldService.returnHelloWorld() } //Then Assertions.assertThat(result).isEqualTo("Hello world") // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(successfulEvents).hasSize(1) } } @Test fun `should execute unsuccessful function`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val errorEvents = mutableListOf<TimeLimiterOnErrorEvent>() timelimiter.eventPublisher.onError(errorEvents::add) //When try { timelimiter.executeSuspendFunction { helloWorldService.throwException() } Assertions.failBecauseExceptionWasNotThrown<Nothing>(IllegalStateException::class.java) } catch (e: IllegalStateException) { // nothing - proceed } //Then // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(errorEvents).hasSize(1) } } @Test fun `should cancel operation that times out`() { runBlocking { val timelimiter = TimeLimiter.of(TimeLimiterConfig { timeoutDuration(Duration.ofMillis(10)) }) val helloWorldService = CoroutineHelloWorldService() val timeoutEvents = mutableListOf<TimeLimiterOnTimeoutEvent>() timelimiter.eventPublisher.onTimeout(timeoutEvents::add) //When try { timelimiter.executeSuspendFunction { helloWorldService.wait() } Assertions.failBecauseExceptionWasNotThrown<Nothing>(TimeoutException::class.java) } catch (e: TimeoutException) { // nothing - proceed } //Then // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(timeoutEvents).hasSize(1) } } @Test fun `should ignore non-timeout cancellations`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val timeoutEvents = mutableListOf<TimeLimiterOnTimeoutEvent>() timelimiter.eventPublisher.onTimeout(timeoutEvents::add) val successfulEvents = mutableListOf<TimeLimiterOnSuccessEvent>() timelimiter.eventPublisher.onSuccess(successfulEvents::add) //When try { timelimiter.executeSuspendFunction { throw CancellationException("result not required") } } catch (e: CancellationException) { // nothing - proceed } //Then Assertions.assertThat(timeoutEvents).hasSize(0) Assertions.assertThat(successfulEvents).hasSize(0) } } @Test fun `should decorate successful function`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val successfulEvents = mutableListOf<TimeLimiterOnSuccessEvent>() timelimiter.eventPublisher.onSuccess(successfulEvents::add) //When val function = timelimiter.decorateSuspendFunction { helloWorldService.returnHelloWorld() } //Then Assertions.assertThat(function()).isEqualTo("Hello world") // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(successfulEvents).hasSize(1) } } }
apache-2.0
c80f12493cca51dba7b39a6021a77e94
37.377483
106
0.653494
5.311641
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinRawStringTypedHandler.kt
6
1963
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtFile class KotlinRawStringTypedHandler : TypedHandlerDelegate() { override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result { if (c != '"') { return Result.CONTINUE } if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) { return Result.CONTINUE } if (file !is KtFile) { return Result.CONTINUE } // A quote is typed after 2 other quotes val offset = editor.caretModel.offset if (offset < 2) { return Result.CONTINUE } val openQuote = file.findElementAt(offset - 2) if (openQuote == null || openQuote !is LeafPsiElement || openQuote.elementType != KtTokens.OPEN_QUOTE) { return Result.CONTINUE } val closeQuote = file.findElementAt(offset - 1) if (closeQuote == null || closeQuote !is LeafPsiElement || closeQuote.elementType != KtTokens.CLOSING_QUOTE) { return Result.CONTINUE } if (closeQuote.text != "\"") { // Check it is not a multi-line quote return Result.CONTINUE } editor.document.insertString(offset, "\"\"\"\"") editor.caretModel.currentCaret.moveToOffset(offset + 1) return Result.STOP } }
apache-2.0
231a72f2bf7145ed03ecce88cb8e31b5
36.056604
158
0.670912
4.586449
false
false
false
false
smmribeiro/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/PythonLangSupport.kt
1
933
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift import com.intellij.openapi.project.Project import training.project.ProjectUtils import training.project.ReadMeCreator import training.util.getFeedbackLink class PythonLangSupport : PythonBasedLangSupport() { override val contentRootDirectoryName = "PyCharmLearningProject" override val primaryLanguage = "Python" override val defaultProductName: String = "PyCharm" private val sourcesDirectoryName: String = "src" override val filename: String = "Learning.py" override val langCourseFeedback get() = getFeedbackLink(this, false) override val readMeCreator = ReadMeCreator() override fun applyToProjectAfterConfigure(): (Project) -> Unit = { project -> ProjectUtils.markDirectoryAsSourcesRoot(project, sourcesDirectoryName) } }
apache-2.0
657e18957fe5c8f638285b3293a4a693
33.555556
140
0.790997
4.507246
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/libs/utils/extensions/ContextExt.kt
1
4537
@file:JvmName("ContextExt") package com.kickstarter.libs.utils.extensions import android.app.AlertDialog import android.app.Application import android.content.Context import android.content.pm.PackageManager import androidx.core.content.ContextCompat import com.kickstarter.KSApplication import com.kickstarter.R import com.kickstarter.libs.Environment import com.stripe.android.paymentsheet.PaymentSheet fun Context.isKSApplication() = (this is KSApplication) && !this.isInUnitTests fun Context.getEnvironment(): Environment? { return (this.applicationContext as KSApplication).component().environment() } /** * if the current context is an instance of Application android base class * register the callbacks provided on the parameter. * * @param callbacks */ fun Context.registerActivityLifecycleCallbacks(callbacks: Application.ActivityLifecycleCallbacks) { if (this is Application) { this.registerActivityLifecycleCallbacks(callbacks) } } fun Context.checkPermissions(permission: String): Boolean { return ContextCompat.checkSelfPermission( this, permission ) == PackageManager.PERMISSION_DENIED } fun Context.showAlertDialog( title: String? = "", message: String? = "", positiveActionTitle: String? = null, negativeActionTitle: String? = null, isCancelable: Boolean = true, positiveAction: (() -> Unit)? = null, negativeAction: (() -> Unit)? = null ) { // setup the alert builder val builder = AlertDialog.Builder(this).apply { setTitle(title) setMessage(message) // add a button positiveActionTitle?.let { setPositiveButton(positiveActionTitle) { dialog, _ -> dialog.dismiss() positiveAction?.invoke() } } negativeActionTitle?.let { setNegativeButton(negativeActionTitle) { dialog, _ -> dialog.dismiss() negativeAction?.invoke() } } setCancelable(isCancelable) } // create and show the alert dialog val dialog: AlertDialog = builder.create() dialog.show() } /** * Provides the configuration for the PaymentSheet, following the specs * @see [link](https://stripe.com/docs/payments/accept-a-payment?platform=android&ui=elements#android-flowcontroller) */ fun Context.getPaymentSheetConfiguration(): PaymentSheet.Configuration { return PaymentSheet.Configuration( merchantDisplayName = getString(R.string.app_name), allowsDelayedPaymentMethods = true, appearance = this.getPaymentSheetAppearance() ) } /** * Provides the color configuration for the PaymentSheet, following the specs * @see [link](https://stripe.com/docs/elements/appearance-api?platform=android#colors-android) */ fun Context.getPaymentSheetAppearance(): PaymentSheet.Appearance { return PaymentSheet.Appearance( colorsLight = PaymentSheet.Colors( primary = getColor(R.color.primary), surface = getColor(R.color.kds_white), component = getColor(R.color.kds_white), componentBorder = getColor(R.color.kds_support_400), componentDivider = getColor(R.color.kds_black), onComponent = getColor(R.color.kds_black), subtitle = getColor(R.color.kds_black), placeholderText = getColor(R.color.kds_support_500), onSurface = getColor(R.color.kds_black), appBarIcon = getColor(R.color.kds_black), error = getColor(R.color.kds_alert), ), colorsDark = PaymentSheet.Colors( primary = getColor(R.color.primary), surface = getColor(R.color.kds_white), component = getColor(R.color.kds_white), componentBorder = getColor(R.color.kds_support_400), componentDivider = getColor(R.color.kds_black), onComponent = getColor(R.color.kds_black), subtitle = getColor(R.color.kds_black), placeholderText = getColor(R.color.kds_support_500), onSurface = getColor(R.color.kds_black), appBarIcon = getColor(R.color.kds_black), error = getColor(R.color.kds_alert), ), shapes = PaymentSheet.Shapes( cornerRadiusDp = 12.0f, borderStrokeWidthDp = 0.5f ), primaryButton = PaymentSheet.PrimaryButton( shape = PaymentSheet.PrimaryButtonShape( cornerRadiusDp = 12.0f ), ) ) }
apache-2.0
3563104ad275e4bf275d0e73b2660da6
33.633588
118
0.659467
4.532468
false
false
false
false
chickenbane/workshop-jb
src/ii_collections/_22_Fold_.kt
13
552
package ii_collections fun example9() { val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult }) result == 24 } // The same as fun whatFoldDoes(): Int { var result = 1 listOf(1, 2, 3, 4).forEach { element -> result = element * result} return result } fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> { // Return the set of products ordered by every customer return customers.fold(allOrderedProducts, { orderedByAll, customer -> todoCollectionTask() }) }
mit
f6704908cd57d4c33bffa2fc30ad05ff
25.285714
92
0.657609
3.971223
false
false
false
false
ncoe/rosetta
Non-transitive_dice/Kotlin/src/main/kotlin/Dice.kt
1
2790
fun fourFaceCombos(): List<Array<Int>> { val res = mutableListOf<Array<Int>>() val found = mutableSetOf<Int>() for (i in 1..4) { for (j in 1..4) { for (k in 1..4) { for (l in 1..4) { val c = arrayOf(i, j, k, l) c.sort() val key = 64 * (c[0] - 1) + 16 * (c[1] - 1) + 4 * (c[2] - 1) + (c[3] - 1) if (!found.contains(key)) { found.add(key) res.add(c) } } } } } return res } fun cmp(x: Array<Int>, y: Array<Int>): Int { var xw = 0 var yw = 0 for (i in 0 until 4) { for (j in 0 until 4) { if (x[i] > y[j]) { xw++ } else if (y[j] > x[i]) { yw++ } } } if (xw < yw) { return -1 } if (xw > yw) { return 1 } return 0 } fun findIntransitive3(cs: List<Array<Int>>): List<Array<Array<Int>>> { val c = cs.size val res = mutableListOf<Array<Array<Int>>>() for (i in 0 until c) { for (j in 0 until c) { if (cmp(cs[i], cs[j]) == -1) { for (k in 0 until c) { if (cmp(cs[j], cs[k]) == -1 && cmp(cs[k], cs[i]) == -1) { res.add(arrayOf(cs[i], cs[j], cs[k])) } } } } } return res } fun findIntransitive4(cs: List<Array<Int>>): List<Array<Array<Int>>> { val c = cs.size val res = mutableListOf<Array<Array<Int>>>() for (i in 0 until c) { for (j in 0 until c) { if (cmp(cs[i], cs[j]) == -1) { for (k in 0 until c) { if (cmp(cs[j], cs[k]) == -1) { for (l in 0 until c) { if (cmp(cs[k], cs[l]) == -1 && cmp(cs[l], cs[i]) == -1) { res.add(arrayOf(cs[i], cs[j], cs[k], cs[l])) } } } } } } } return res } fun main() { val combos = fourFaceCombos() println("Number of eligible 4-faced dice: ${combos.size}") println() val it3 = findIntransitive3(combos) println("${it3.size} ordered lists of 3 non-transitive dice found, namely:") for (a in it3) { println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") }) } println() val it4 = findIntransitive4(combos) println("${it4.size} ordered lists of 4 non-transitive dice found, namely:") for (a in it4) { println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") }) } }
mit
649062871844a8a3e87b02a84da89a62
26.352941
93
0.38853
3.414933
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/DefaultResourceStorage.kt
1
2262
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import com.google.common.util.concurrent.AtomicDouble import java.util.* /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ class DefaultResourceStorage(val id:String) : IResourceStorage { val amountsByResource = HashMap<String, AtomicDouble>() val infiniteResources = HashSet<String>() override fun put(res: String, amt:Double) { var storedAmount = amountsByResource.get(res) if (storedAmount == null) { storedAmount = AtomicDouble(0.0) amountsByResource.put(res, storedAmount) } storedAmount.getAndAdd(amt) } override fun amount(res: String): Double { val mapAmt = amountsByResource.get(res) if (mapAmt != null) { return mapAmt.get() } return 0.0 } override fun remove(res: String, amt: Double) { val mapAmt = amountsByResource.get(res) if (mapAmt != null) { mapAmt.getAndAdd(-amt) } } override fun setInfinite(res: String) { infiniteResources.add(res) } override fun isInfinite(res:String):Boolean = infiniteResources.contains(res) override fun id(): String = id }
gpl-3.0
c5a2976d6e9eb3b684da514f7f983acc
27.763158
81
0.648541
3.9
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt
3
15050
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.breakpoints import com.intellij.debugger.JavaDebuggerBundle import com.intellij.debugger.DebuggerManagerEx import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.impl.PositionUtil import com.intellij.debugger.requests.Requestor import com.intellij.debugger.ui.breakpoints.BreakpointCategory import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter import com.intellij.debugger.ui.breakpoints.FieldBreakpoint import com.intellij.icons.AllIcons import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.xdebugger.breakpoints.XBreakpoint import com.sun.jdi.AbsentInformationException import com.sun.jdi.Method import com.sun.jdi.ReferenceType import com.sun.jdi.event.* import com.sun.jdi.request.EventRequest import com.sun.jdi.request.MethodEntryRequest import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.debugger.safeAllLineLocations import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.resolve.BindingContext import javax.swing.Icon class KotlinFieldBreakpoint( project: Project, breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties> ) : BreakpointWithHighlighter<KotlinPropertyBreakpointProperties>(project, breakpoint) { companion object { private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFieldBreakpoint") private val CATEGORY: Key<FieldBreakpoint> = BreakpointCategory.lookup("field_breakpoints") } private enum class BreakpointType { FIELD, METHOD } private var breakpointType: BreakpointType = BreakpointType.FIELD override fun isValid(): Boolean { if (!isPositionValid(xBreakpoint.sourcePosition)) return false return runReadAction { val field = getField() field != null && field.isValid } } private fun getField(): KtCallableDeclaration? { val sourcePosition = sourcePosition return getProperty(sourcePosition) } private fun getProperty(sourcePosition: SourcePosition?): KtCallableDeclaration? { val property: KtProperty? = PositionUtil.getPsiElementAt(project, KtProperty::class.java, sourcePosition) if (property != null) { return property } val parameter: KtParameter? = PositionUtil.getPsiElementAt(project, KtParameter::class.java, sourcePosition) if (parameter != null) { return parameter } return null } override fun reload() { super.reload() val property = getProperty(sourcePosition) ?: return val propertyName = property.name ?: return setFieldName(propertyName) if (property is KtProperty && property.isTopLevel) { properties.myClassName = JvmFileClassUtil.getFileClassInfoNoResolve(property.getContainingKtFile()).fileClassFqName.asString() } else { val ktClass: KtClassOrObject? = PsiTreeUtil.getParentOfType(property, KtClassOrObject::class.java) if (ktClass is KtClassOrObject) { val fqName = ktClass.fqName if (fqName != null) { properties.myClassName = fqName.asString() } } } isInstanceFiltersEnabled = false } override fun createRequestForPreparedClass(debugProcess: DebugProcessImpl?, refType: ReferenceType?) { if (debugProcess == null || refType == null) return val property = getProperty(sourcePosition) ?: return breakpointType = (computeBreakpointType(property) ?: return) val vm = debugProcess.virtualMachineProxy try { if (properties.watchInitialization) { val sourcePosition = sourcePosition if (sourcePosition != null) { debugProcess.positionManager .locationsOfLine(refType, sourcePosition) .filter { it.method().isConstructor || it.method().isStaticInitializer } .forEach { val request = debugProcess.requestsManager.createBreakpointRequest(this, it) debugProcess.requestsManager.enableRequest(request) if (LOG.isDebugEnabled) { LOG.debug("Breakpoint request added") } } } } when (breakpointType) { BreakpointType.FIELD -> { val field = refType.fieldByName(getFieldName()) if (field != null) { val manager = debugProcess.requestsManager if (properties.watchModification && vm.canWatchFieldModification()) { val request = manager.createModificationWatchpointRequest(this, field) debugProcess.requestsManager.enableRequest(request) if (LOG.isDebugEnabled) { LOG.debug("Modification request added") } } if (properties.watchAccess && vm.canWatchFieldAccess()) { val request = manager.createAccessWatchpointRequest(this, field) debugProcess.requestsManager.enableRequest(request) if (LOG.isDebugEnabled) { LOG.debug("Field access request added (field = ${field.name()}; refType = ${refType.name()})") } } } } BreakpointType.METHOD -> { val fieldName = getFieldName() if (properties.watchAccess) { val getter = refType.methodsByName(JvmAbi.getterName(fieldName)).firstOrNull() if (getter != null) { createMethodBreakpoint(debugProcess, refType, getter) } } if (properties.watchModification) { val setter = refType.methodsByName(JvmAbi.setterName(fieldName)).firstOrNull() if (setter != null) { createMethodBreakpoint(debugProcess, refType, setter) } } } } } catch (ex: Exception) { LOG.debug(ex) } } private fun computeBreakpointType(property: KtCallableDeclaration): BreakpointType? { return runReadAction { val bindingContext = property.analyze() var descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, property) if (descriptor is ValueParameterDescriptor) { descriptor = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, descriptor) } if (descriptor is PropertyDescriptor) { if (bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor)!!) { BreakpointType.FIELD } else { BreakpointType.METHOD } } else { null } } } private fun createMethodBreakpoint(debugProcess: DebugProcessImpl, refType: ReferenceType, accessor: Method) { val manager = debugProcess.requestsManager val line = accessor.safeAllLineLocations().firstOrNull() if (line != null) { val request = manager.createBreakpointRequest(this, line) debugProcess.requestsManager.enableRequest(request) if (LOG.isDebugEnabled) { LOG.debug("Breakpoint request added") } } else { var entryRequest: MethodEntryRequest? = findRequest(debugProcess, MethodEntryRequest::class.java, this) if (entryRequest == null) { entryRequest = manager.createMethodEntryRequest(this)!! if (LOG.isDebugEnabled) { LOG.debug("Method entry request added (method = ${accessor.name()}; refType = ${refType.name()})") } } else { entryRequest.disable() } entryRequest.addClassFilter(refType) manager.enableRequest(entryRequest) } } private inline fun <reified T : EventRequest> findRequest( debugProcess: DebugProcessImpl, requestClass: Class<T>, requestor: Requestor ): T? { val requests = debugProcess.requestsManager.findRequests(requestor) for (eventRequest in requests) { if (eventRequest::class.java == requestClass) { return eventRequest as T } } return null } override fun evaluateCondition(context: EvaluationContextImpl, event: LocatableEvent): Boolean { if (breakpointType == BreakpointType.METHOD && !matchesEvent(event)) { return false } return super.evaluateCondition(context, event) } fun matchesEvent(event: LocatableEvent): Boolean { val method = event.location()?.method() // TODO check property type return method != null && method.name() in getMethodsName() } private fun getMethodsName(): List<String> { val fieldName = getFieldName() return listOf(JvmAbi.getterName(fieldName), JvmAbi.setterName(fieldName)) } override fun getEventMessage(event: LocatableEvent): String { val location = event.location()!! val locationQName = location.declaringType().name() + "." + location.method().name() val locationFileName = try { location.sourceName() } catch (e: AbsentInformationException) { fileName } catch (e: InternalError) { fileName } val locationLine = location.lineNumber() when (event) { is ModificationWatchpointEvent -> { val field = event.field() return JavaDebuggerBundle.message( "status.static.field.watchpoint.reached.access", field.declaringType().name(), field.name(), locationQName, locationFileName, locationLine ) } is AccessWatchpointEvent -> { val field = event.field() return JavaDebuggerBundle.message( "status.static.field.watchpoint.reached.access", field.declaringType().name(), field.name(), locationQName, locationFileName, locationLine ) } is MethodEntryEvent -> { val method = event.method() return JavaDebuggerBundle.message( "status.method.entry.breakpoint.reached", method.declaringType().name() + "." + method.name() + "()", locationQName, locationFileName, locationLine ) } is MethodExitEvent -> { val method = event.method() return JavaDebuggerBundle.message( "status.method.exit.breakpoint.reached", method.declaringType().name() + "." + method.name() + "()", locationQName, locationFileName, locationLine ) } } return JavaDebuggerBundle.message( "status.line.breakpoint.reached", locationQName, locationFileName, locationLine ) } fun setFieldName(fieldName: String) { properties.myFieldName = fieldName } @TestOnly fun setWatchAccess(value: Boolean) { properties.watchAccess = value } @TestOnly fun setWatchModification(value: Boolean) { properties.watchModification = value } @TestOnly fun setWatchInitialization(value: Boolean) { properties.watchInitialization = value } override fun getDisabledIcon(isMuted: Boolean): Icon { val master = DebuggerManagerEx.getInstanceEx(myProject).breakpointManager.findMasterBreakpoint(this) return when { isMuted && master == null -> AllIcons.Debugger.Db_muted_disabled_field_breakpoint isMuted && master != null -> AllIcons.Debugger.Db_muted_dep_field_breakpoint master != null -> AllIcons.Debugger.Db_dep_field_breakpoint else -> AllIcons.Debugger.Db_disabled_field_breakpoint } } override fun getSetIcon(isMuted: Boolean): Icon { return when { isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint else -> AllIcons.Debugger.Db_field_breakpoint } } override fun getVerifiedIcon(isMuted: Boolean): Icon { return when { isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint else -> AllIcons.Debugger.Db_verified_field_breakpoint } } override fun getVerifiedWarningsIcon(isMuted: Boolean): Icon = AllIcons.Debugger.Db_exception_breakpoint override fun getCategory() = CATEGORY override fun getDisplayName(): String { if (!isValid) { return JavaDebuggerBundle.message("status.breakpoint.invalid") } val className = className @Suppress("HardCodedStringLiteral") return if (!className.isNullOrEmpty()) className + "." + getFieldName() else getFieldName() } private fun getFieldName(): String { val declaration = getField() return runReadAction { declaration?.name } ?: "unknown" } override fun getEvaluationElement(): PsiElement? { return getField() } }
apache-2.0
c976612b1a93c7b92f74b701b1752560
38.605263
158
0.603721
5.615672
false
false
false
false
dahlstrom-g/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/PlatformModules.kt
3
14573
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build.impl import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.ProductModulesLayout import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.w3c.dom.Element import java.nio.file.Files import java.util.* import javax.xml.parsers.DocumentBuilderFactory private const val UTIL_JAR = "util.jar" private const val UTIL_RT_JAR = "util_rt.jar" private val PLATFORM_API_MODULES: List<String> = java.util.List.of( "intellij.platform.analysis", "intellij.platform.builtInServer", "intellij.platform.core", "intellij.platform.diff", "intellij.platform.vcs.dvcs", "intellij.platform.editor", "intellij.platform.externalSystem", "intellij.platform.externalSystem.dependencyUpdater", "intellij.platform.codeStyle", "intellij.platform.indexing", "intellij.platform.jps.model", "intellij.platform.lang.core", "intellij.platform.lang", "intellij.platform.lvcs", "intellij.platform.ide", "intellij.platform.ide.core", "intellij.platform.projectModel", "intellij.platform.remote.core", "intellij.platform.remoteServers.agent.rt", "intellij.platform.remoteServers", "intellij.platform.tasks", "intellij.platform.usageView", "intellij.platform.vcs.core", "intellij.platform.vcs", "intellij.platform.vcs.log", "intellij.platform.vcs.log.graph", "intellij.platform.execution", "intellij.platform.debugger", "intellij.xml.analysis", "intellij.xml", "intellij.xml.psi", "intellij.xml.structureView", "intellij.platform.concurrency", ) /** * List of modules which are included into lib/app.jar in all IntelliJ based IDEs. */ private val PLATFORM_IMPLEMENTATION_MODULES: List<String> = java.util.List.of( "intellij.platform.analysis.impl", "intellij.platform.builtInServer.impl", "intellij.platform.core.impl", "intellij.platform.ide.core.impl", "intellij.platform.diff.impl", "intellij.platform.editor.ex", "intellij.platform.codeStyle.impl", "intellij.platform.indexing.impl", "intellij.platform.elevation", "intellij.platform.elevation.client", "intellij.platform.elevation.common", "intellij.platform.elevation.daemon", "intellij.platform.externalProcessAuthHelper", "intellij.platform.refactoring", "intellij.platform.inspect", "intellij.platform.lang.impl", "intellij.platform.workspaceModel.storage", "intellij.platform.workspaceModel.jps", "intellij.platform.lvcs.impl", "intellij.platform.vfs.impl", "intellij.platform.ide.impl", "intellij.platform.projectModel.impl", "intellij.platform.macro", "intellij.platform.execution.impl", "intellij.platform.wsl.impl", "intellij.platform.externalSystem.impl", "intellij.platform.scriptDebugger.protocolReaderRuntime", "intellij.regexp", "intellij.platform.remoteServers.impl", "intellij.platform.scriptDebugger.backend", "intellij.platform.scriptDebugger.ui", "intellij.platform.smRunner", "intellij.platform.smRunner.vcs", "intellij.platform.structureView.impl", "intellij.platform.tasks.impl", "intellij.platform.testRunner", "intellij.platform.debugger.impl", "intellij.platform.configurationStore.impl", "intellij.platform.serviceContainer", "intellij.platform.objectSerializer", "intellij.platform.diagnostic", "intellij.platform.diagnostic.telemetry", "intellij.platform.core.ui", "intellij.platform.credentialStore", "intellij.platform.credentialStore.ui", "intellij.platform.rd.community", "intellij.platform.ml.impl", "intellij.remoteDev.util", "intellij.platform.feedback", "intellij.platform.warmup", "intellij.platform.buildScripts.downloader", "intellij.idea.community.build.dependencies", "intellij.platform.usageView.impl", ) object PlatformModules { const val PRODUCT_JAR = "product.jar" val CUSTOM_PACK_MODE: Map<String, LibraryPackMode> = linkedMapOf( // jna uses native lib "jna" to LibraryPackMode.STANDALONE_MERGED, "lz4-java" to LibraryPackMode.STANDALONE_MERGED, "jetbrains-annotations-java5" to LibraryPackMode.STANDALONE_SEPARATE_WITHOUT_VERSION_NAME, "intellij-coverage" to LibraryPackMode.STANDALONE_SEPARATE, "github.jnr.ffi" to LibraryPackMode.STANDALONE_SEPARATE, ) fun collectPlatformModules(to: MutableCollection<String>) { to.addAll(PLATFORM_API_MODULES) to.addAll(PLATFORM_IMPLEMENTATION_MODULES) } fun hasPlatformCoverage(productLayout: ProductModulesLayout, enabledPluginModules: Set<String>, context: BuildContext): Boolean { val modules = LinkedHashSet<String>() modules.addAll(productLayout.getIncludedPluginModules(enabledPluginModules)) modules.addAll(PLATFORM_API_MODULES) modules.addAll(PLATFORM_IMPLEMENTATION_MODULES) modules.addAll(productLayout.productApiModules) modules.addAll(productLayout.productImplementationModules) modules.addAll(productLayout.additionalPlatformJars.values()) val coverageModuleName = "intellij.platform.coverage" if (modules.contains(coverageModuleName)) { return true } for (moduleName in modules) { var contains = false JpsJavaExtensionService.dependencies(context.findRequiredModule(moduleName)) .productionOnly() .processModules { module -> if (!contains && module.name == coverageModuleName) { contains = true } } if (contains) { return true } } return false } fun jar(relativeJarPath: String, moduleNames: Collection<String>, productLayout: ProductModulesLayout, layout: PlatformLayout) { for (moduleName in moduleNames) { if (!productLayout.excludedModuleNames.contains(moduleName)) { layout.withModule(moduleName, relativeJarPath) } } } private fun addModule(moduleName: String, productLayout: ProductModulesLayout, layout: PlatformLayout) { if (!productLayout.excludedModuleNames.contains(moduleName)) { layout.withModule(moduleName) } } private fun addModule(moduleName: String, relativeJarPath: String, productLayout: ProductModulesLayout, layout: PlatformLayout) { if (!productLayout.excludedModuleNames.contains(moduleName)) { layout.withModule(moduleName, relativeJarPath) } } @JvmStatic fun createPlatformLayout(productLayout: ProductModulesLayout, hasPlatformCoverage: Boolean, additionalProjectLevelLibraries: SortedSet<ProjectLibraryData>, context: BuildContext): PlatformLayout { val layout = PlatformLayout() // used only in modules that packed into Java layout.withoutProjectLibrary("jps-javac-extension") layout.withoutProjectLibrary("Eclipse") for (platformLayoutCustomizer in productLayout.platformLayoutCustomizers) { platformLayoutCustomizer.accept(layout, context) } val alreadyPackedModules = HashSet<String>() for (entry in productLayout.additionalPlatformJars.entrySet()) { jar(entry.key, entry.value, productLayout, layout) alreadyPackedModules.addAll(entry.value) } for (moduleName in PLATFORM_API_MODULES) { // intellij.platform.core is used in Kotlin and Scala JPS plugins (PathUtil) https://youtrack.jetbrains.com/issue/IDEA-292483 if (!productLayout.excludedModuleNames.contains(moduleName) && moduleName != "intellij.platform.core") { layout.withModule(moduleName, if (moduleName == "intellij.platform.jps.model") "jps-model.jar" else BaseLayout.APP_JAR) } } jar(BaseLayout.APP_JAR, productLayout.productApiModules, productLayout, layout) for (module in productLayout.productImplementationModules) { if (!productLayout.excludedModuleNames.contains(module) && !alreadyPackedModules.contains(module)) { val isRelocated = module == "intellij.xml.dom.impl" || module == "intellij.platform.structuralSearch" || // todo why intellij.tools.testsBootstrap is included to RM? module == "intellij.tools.testsBootstrap" || module == "intellij.platform.duplicates.analysis" if (isRelocated) { layout.withModule(module, BaseLayout.APP_JAR) } else if (!context.productProperties.useProductJar || module.startsWith("intellij.platform.commercial")) { layout.withModule(module, productLayout.mainJarName) } else { layout.withModule(module, PRODUCT_JAR) } } } for (entry in productLayout.moduleExcludes.entrySet()) { layout.moduleExcludes.putValues(entry.key, entry.value) } jar(UTIL_RT_JAR, listOf( "intellij.platform.util.rt", ), productLayout, layout) jar(UTIL_JAR, listOf( "intellij.platform.util.rt.java8", "intellij.platform.util.zip", "intellij.platform.util.classLoader", "intellij.platform.bootstrap", "intellij.platform.util", "intellij.platform.util.text.matching", "intellij.platform.util.base", "intellij.platform.util.diff", "intellij.platform.util.xmlDom", "intellij.platform.util.jdom", "intellij.platform.extensions", "intellij.platform.tracing.rt", "intellij.platform.core", // GeneralCommandLine is used by Scala in JPS plugin "intellij.platform.ide.util.io", "intellij.platform.boot", ), productLayout, layout) jar("externalProcess-rt.jar", listOf( "intellij.platform.externalProcessAuthHelper.rt" ), productLayout, layout) jar(BaseLayout.APP_JAR, PLATFORM_IMPLEMENTATION_MODULES, productLayout, layout) // util.jar is loaded by JVM classloader as part of loading our custom PathClassLoader class - reduce file size jar(BaseLayout.APP_JAR, listOf( "intellij.platform.util.ui", "intellij.platform.util.ex", "intellij.platform.ide.util.io.impl", "intellij.platform.ide.util.netty", ), productLayout, layout) jar(BaseLayout.APP_JAR, listOf( "intellij.relaxng", "intellij.json", "intellij.spellchecker", "intellij.xml.analysis.impl", "intellij.xml.psi.impl", "intellij.xml.structureView.impl", "intellij.xml.impl", "intellij.platform.vcs.impl", "intellij.platform.vcs.dvcs.impl", "intellij.platform.vcs.log.graph.impl", "intellij.platform.vcs.log.impl", "intellij.platform.collaborationTools", "intellij.platform.collaborationTools.auth", "intellij.platform.markdown.utils", "intellij.platform.icons", "intellij.platform.resources", "intellij.platform.resources.en", "intellij.platform.colorSchemes", ), productLayout, layout) jar("stats.jar", listOf( "intellij.platform.statistics", "intellij.platform.statistics.uploader", "intellij.platform.statistics.config", ), productLayout, layout) layout.excludedModuleLibraries.putValue("intellij.platform.credentialStore", "dbus-java") addModule("intellij.platform.statistics.devkit", productLayout, layout) addModule("intellij.platform.objectSerializer.annotations", productLayout, layout) addModule("intellij.java.guiForms.rt", productLayout, layout) addModule("intellij.platform.jps.model.serialization", "jps-model.jar", productLayout, layout) addModule("intellij.platform.jps.model.impl", "jps-model.jar", productLayout, layout) addModule("intellij.platform.externalSystem.rt", "external-system-rt.jar", productLayout, layout) addModule("intellij.platform.cdsAgent", "cds/classesLogAgent.jar", productLayout, layout) if (hasPlatformCoverage) { addModule("intellij.platform.coverage", BaseLayout.APP_JAR, productLayout, layout) } for (libraryName in productLayout.projectLibrariesToUnpackIntoMainJar) { layout.withProjectLibraryUnpackedIntoJar(libraryName, productLayout.mainJarName) } val productPluginSourceModuleName = context.productProperties.applicationInfoModule for (name in getProductPluginContentModules(context, productPluginSourceModuleName)) { layout.withModule(name, BaseLayout.APP_JAR) } layout.projectLibrariesToUnpack.putValue(UTIL_JAR, "Trove4j") for (item in additionalProjectLevelLibraries) { val name = item.libraryName if (!productLayout.projectLibrariesToUnpackIntoMainJar.contains(name) && !layout.projectLibrariesToUnpack.values().contains(name) && !layout.excludedProjectLibraries.contains(name)) { layout.includedProjectLibraries.add(item) } } layout.collectProjectLibrariesFromIncludedModules(context) { lib, module -> val name = lib.name if (module.name == "intellij.platform.buildScripts.downloader" && name == "zstd-jni") { return@collectProjectLibrariesFromIncludedModules } layout.includedProjectLibraries .addOrGet(ProjectLibraryData(name, CUSTOM_PACK_MODE.getOrDefault(name, LibraryPackMode.MERGED))) .dependentModules.computeIfAbsent("core") { mutableListOf() }.add(module.name) } return layout } // result _must_ consistent, do not use Set.of or HashSet here fun getProductPluginContentModules(buildContext: BuildContext, productPluginSourceModuleName: String): Set<String> { var file = buildContext.findFileInModuleSources(productPluginSourceModuleName, "META-INF/plugin.xml") if (file == null) { file = buildContext.findFileInModuleSources(productPluginSourceModuleName, "META-INF/${buildContext.productProperties.platformPrefix}Plugin.xml") if (file == null) { buildContext.messages.warning("Cannot find product plugin descriptor in '$productPluginSourceModuleName' module") return emptySet() } } Files.newInputStream(file).use { val contentList = DocumentBuilderFactory.newDefaultInstance() .newDocumentBuilder() .parse(it, file.toString()) .documentElement .getElementsByTagName("content") if (contentList.length == 0) { return emptySet() } val modules = (contentList.item(0) as Element).getElementsByTagName("module") val result = LinkedHashSet<String>(modules.length) for (i in 0 until modules.length) { result.add((modules.item(i) as Element).getAttribute("name")) } return result } } }
apache-2.0
08635fccb8db08f6cdeda9bffa469114
37.657825
131
0.716874
4.437576
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/input/TextInputService.kt
3
9566
/* * 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.ui.text.input import androidx.compose.ui.geometry.Rect import androidx.compose.ui.text.AtomicReference /** * Handles communication with the IME. Informs about the IME changes via [EditCommand]s and * provides utilities for working with software keyboard. * * This class is responsible for ensuring there is only one open [TextInputSession] which will * interact with software keyboards. Start new a TextInputSession by calling [startInput] and * close it with [stopInput]. */ // Open for testing purposes. open class TextInputService(private val platformTextInputService: PlatformTextInputService) { private val _currentInputSession: AtomicReference<TextInputSession?> = AtomicReference(null) internal val currentInputSession: TextInputSession? get() = _currentInputSession.get() /** * Start text input session for given client. * * If there is a previous [TextInputSession] open, it will immediately be closed by this call * to [startInput]. * * @param value initial [TextFieldValue] * @param imeOptions IME configuration * @param onEditCommand callback to inform about changes requested by IME * @param onImeActionPerformed callback to inform if an IME action such as [ImeAction.Done] * etc occurred. */ open fun startInput( value: TextFieldValue, imeOptions: ImeOptions, onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit ): TextInputSession { platformTextInputService.startInput( value, imeOptions, onEditCommand, onImeActionPerformed ) val nextSession = TextInputSession(this, platformTextInputService) _currentInputSession.set(nextSession) return nextSession } /** * Stop text input session. * * If the [session] is not the currently open session, no action will occur. * * @param session the session returned by [startInput] call. */ open fun stopInput(session: TextInputSession) { if (_currentInputSession.compareAndSet(session, null)) { platformTextInputService.stopInput() } } /** * Request showing onscreen keyboard. * * This call will be ignored if there is not an open [TextInputSession], as it means there is * nothing that will accept typed input. The most common way to open a TextInputSession is to * set the focus to an editable text composable. * * There is no guarantee that the keyboard will be shown. The software keyboard or * system service may silently ignore this request. */ @Deprecated( message = "Use SoftwareKeyboardController.show or " + "TextInputSession.showSoftwareKeyboard instead.", replaceWith = ReplaceWith("textInputSession.showSoftwareKeyboard()") ) // TODO(b/183448615) @InternalTextApi fun showSoftwareKeyboard() { if (_currentInputSession.get() != null) { platformTextInputService.showSoftwareKeyboard() } } /** * Hide onscreen keyboard. */ @Deprecated( message = "Use SoftwareKeyboardController.hide or " + "TextInputSession.hideSoftwareKeyboard instead.", replaceWith = ReplaceWith("textInputSession.hideSoftwareKeyboard()") ) // TODO(b/183448615) @InternalTextApi fun hideSoftwareKeyboard(): Unit = platformTextInputService.hideSoftwareKeyboard() } /** * Represents a input session for interactions between a soft keyboard and editable text. * * This session may be closed at any time by [TextInputService] or by calling [dispose], after * which [isOpen] will return false and all further calls will have no effect. */ class TextInputSession( private val textInputService: TextInputService, private val platformTextInputService: PlatformTextInputService ) { /** * If this session is currently open. * * A session may be closed at any time by [TextInputService] or by calling [dispose]. */ val isOpen: Boolean get() = textInputService.currentInputSession == this /** * Close this input session. * * All further calls to this object will have no effect, and [isOpen] will return false. * * Note, [TextInputService] may also close this input session at any time without calling * dispose. Calling dispose after this session has been closed has no effect. */ fun dispose() { textInputService.stopInput(this) } /** * Execute [block] if [isOpen] is true. * * This function will only check [isOpen] once, and may execute the action after the input * session closes in the case of concurrent execution. * * @param block action to take if isOpen * @return true if an action was performed */ private inline fun ensureOpenSession(block: () -> Unit): Boolean { return isOpen.also { applying -> if (applying) { block() } } } @Suppress("DeprecatedCallableAddReplaceWith", "DEPRECATION") @Deprecated("This method should not be called, used BringIntoViewRequester instead.") fun notifyFocusedRect(rect: Rect): Boolean = ensureOpenSession { platformTextInputService.notifyFocusedRect(rect) } /** * Notify IME about the new [TextFieldValue] and latest state of the editing buffer. [oldValue] * is the state of the buffer before the changes applied by the [newValue]. * * [oldValue] represents the changes that was requested by IME on the buffer, and [newValue] * is the final state of the editing buffer that was requested by the application. In cases * where [oldValue] is not equal to [newValue], it would mean the IME suggested value is * rejected, and the IME connection will be restarted with the newValue. * * If the session is not open, action will be performed. * * @param oldValue the value that was requested by IME on the buffer * @param newValue final state of the editing buffer that was requested by the application * @return false if this session expired and no action was performed */ fun updateState( oldValue: TextFieldValue?, newValue: TextFieldValue ): Boolean = ensureOpenSession { platformTextInputService.updateState(oldValue, newValue) } /** * Request showing onscreen keyboard. * * This call will have no effect if this session is not open. * * This should be used instead of [TextInputService.showSoftwareKeyboard] when implementing a * new editable text composable to show the keyboard in response to events related to that * composable. * * There is no guarantee that the keyboard will be shown. The software keyboard or * system service may silently ignore this request. * * @return false if this session expired and no action was performed */ fun showSoftwareKeyboard(): Boolean = ensureOpenSession { platformTextInputService.showSoftwareKeyboard() } /** * Hide onscreen keyboard for a specific [TextInputSession]. * * This call will have no effect if this session is not open. * * This should be used instead of [TextInputService.showSoftwareKeyboard] when implementing a * new editable text composable to hide the keyboard in response to events related to that * composable. * * @return false if this session expired and no action was performed */ fun hideSoftwareKeyboard(): Boolean = ensureOpenSession { platformTextInputService.hideSoftwareKeyboard() } } /** * Platform specific text input service. */ interface PlatformTextInputService { /** * Start text input session for given client. * * @see TextInputService.startInput */ fun startInput( value: TextFieldValue, imeOptions: ImeOptions, onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit ) /** * Stop text input session. * * @see TextInputService.stopInput */ fun stopInput() /** * Request showing onscreen keyboard * * There is no guarantee nor callback of the result of this API. * * @see TextInputService.showSoftwareKeyboard */ fun showSoftwareKeyboard() /** * Hide software keyboard * * @see TextInputService.hideSoftwareKeyboard */ fun hideSoftwareKeyboard() /* * Notify the new editor model to IME. * * @see TextInputService.updateState */ fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) @Deprecated("This method should not be called, used BringIntoViewRequester instead.") fun notifyFocusedRect(rect: Rect) { } }
apache-2.0
b8b2ed267238812cd00a1079bbada9ea
34.298893
99
0.679385
4.938565
false
false
false
false
GunoH/intellij-community
plugins/maven/src/test/java/org/jetbrains/idea/maven/utils/MavenWslUtilTestCase.kt
7
4130
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.utils import com.intellij.execution.wsl.WSLDistribution import com.intellij.execution.wsl.WslDistributionManager import com.intellij.maven.testFramework.MavenTestCase import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.IoTestUtil import com.intellij.testFramework.RunAll import junit.framework.TestCase import org.jetbrains.idea.maven.utils.MavenWslUtil.getWindowsFile import org.jetbrains.idea.maven.utils.MavenWslUtil.getWslFile import org.jetbrains.idea.maven.utils.MavenWslUtil.resolveLocalRepository import org.jetbrains.idea.maven.utils.MavenWslUtil.resolveM2Dir import org.jetbrains.idea.maven.utils.MavenWslUtil.resolveUserSettingsFile import org.junit.Assume import org.junit.Test import java.io.File import java.io.IOException class MavenWslUtilTestCase : MavenTestCase() { private lateinit var ourWslTempDir: File private lateinit var myDistribution: WSLDistribution private lateinit var myWslDir: File private lateinit var myUserHome: File @Throws(Exception::class) public override fun setUp() { super.setUp() IoTestUtil.assumeWindows() Assume.assumeFalse("WSL should be installed", WslDistributionManager.getInstance().installedDistributions.isEmpty()) myDistribution = WslDistributionManager.getInstance().installedDistributions[0] val user = myDistribution.environment?.get("USER") if (user == null){ fail("Cannot retrieve env variables from WSL") } myUserHome = File("\\\\wsl$\\${myDistribution.msId}\\home\\${user}") ensureWslTempDirCreated() } @Throws(IOException::class) private fun ensureWslTempDirCreated() { ourWslTempDir = File(myDistribution!!.getWindowsPath("/tmp"), "mavenTests") myWslDir = File(ourWslTempDir, getTestName(false)) FileUtil.delete(ourWslTempDir!!) FileUtil.ensureExists(myWslDir!!) } @Throws(Exception::class) public override fun tearDown() { RunAll( { deleteDirOnTearDown(ourWslTempDir) }, { super.tearDown() } ).run() } @Test fun testShouldReturnMavenLocalDirOnWsl() { TestCase.assertEquals( File(File(myUserHome, ".m2"), "repository"), myDistribution.resolveLocalRepository(null, null, null)) } @Test fun testShouldReturnMavenLocalSettings() { TestCase.assertEquals( File(File(myUserHome, ".m2"), "settings.xml"), myDistribution.resolveUserSettingsFile(null)) } @Test fun testShouldReturnMavenRepoForOverloadedSettings() { val subFile = createProjectSubFile("settings.xml", "<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd\">\n" + " <localRepository>/tmp/path/to/repo</localRepository>\n" + "</settings>") TestCase.assertEquals( File(myDistribution.getWindowsPath("/tmp/path/to/repo")!!), myDistribution.resolveLocalRepository(null, null, subFile.path)) } @Test fun testShouldReturnCorrectM2Dir() { TestCase.assertEquals( File(myUserHome, ".m2"), myDistribution.resolveM2Dir()) } @Test fun testWindowFileMapInMnt() { TestCase.assertEquals(File("c:\\somefile"), myDistribution.getWindowsFile(File("/mnt/c/somefile"))) } @Test fun testWindowFileMapInternalWsl() { TestCase.assertEquals(File("\\\\wsl$\\${myDistribution.msId}\\somefile"), myDistribution.getWindowsFile(File("/somefile"))) } @Test fun testWslFileMapInMnt() { TestCase.assertEquals(File("/mnt/c/somefile"), myDistribution.getWslFile(File("c:\\somefile"))) } @Test fun testWslFileMapInternalWsl() { TestCase.assertEquals(File("/somefile"), myDistribution.getWslFile(File("\\\\wsl$\\${myDistribution.msId}\\somefile"))) } }
apache-2.0
4af729977a2e0e6a55040ce59da5e751
36.216216
161
0.713317
4.134134
false
true
false
false
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/main/kotlin/entities/relationship/HasInvalidToMany.kt
1
670
package entities.relationship import com.onyx.persistence.IManagedEntity import com.onyx.persistence.annotations.* import com.onyx.persistence.annotations.values.CascadePolicy import com.onyx.persistence.annotations.values.RelationshipType import entities.AbstractEntity /** * Created by timothy.osborn on 11/4/14. */ @Entity class HasInvalidToMany : AbstractEntity(), IManagedEntity { @Attribute @Identifier var identifier: String? = null @Attribute var correlation: Int = 0 @Relationship(type = RelationshipType.ONE_TO_MANY, cascadePolicy = CascadePolicy.SAVE, inverseClass = OneToOneChild::class) var child: OneToOneChild? = null }
agpl-3.0
d7088842a9d8af305da77bd97bc022f4
26.916667
127
0.773134
4.294872
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OptionalOneToOneParentEntityImpl.kt
2
8056
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OptionalOneToOneParentEntityImpl(val dataSource: OptionalOneToOneParentEntityData) : OptionalOneToOneParentEntity, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(OptionalOneToOneParentEntity::class.java, OptionalOneToOneChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, true) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ) } override val child: OptionalOneToOneChildEntity? get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: OptionalOneToOneParentEntityData?) : ModifiableWorkspaceEntityBase<OptionalOneToOneParentEntity, OptionalOneToOneParentEntityData>( result), OptionalOneToOneParentEntity.Builder { constructor() : this(OptionalOneToOneParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OptionalOneToOneParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as OptionalOneToOneParentEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var child: OptionalOneToOneChildEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? OptionalOneToOneChildEntity } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? OptionalOneToOneChildEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override fun getEntityClass(): Class<OptionalOneToOneParentEntity> = OptionalOneToOneParentEntity::class.java } } class OptionalOneToOneParentEntityData : WorkspaceEntityData<OptionalOneToOneParentEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<OptionalOneToOneParentEntity> { val modifiable = OptionalOneToOneParentEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): OptionalOneToOneParentEntity { return getCached(snapshot) { val entity = OptionalOneToOneParentEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OptionalOneToOneParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return OptionalOneToOneParentEntity(entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as OptionalOneToOneParentEntityData if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as OptionalOneToOneParentEntityData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
e4d8607081ee091f7bd483243e9927eb
36.124424
155
0.709906
5.443243
false
false
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/util/text/DateFormatUtilTest.kt
12
3737
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.text import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.openapi.util.Clock import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.IoTestUtil.assumeMacOS import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import java.io.File import java.time.Duration import java.time.LocalDateTime import java.time.ZoneId import java.time.temporal.ChronoUnit class DateFormatUtilTest { @Before fun setUp() { Clock.reset() } @Test fun system() { assumeMacOS() val testDate = LocalDateTime.of(2019, 5, 22, 13, 45).toMillis() val helper = File(DateFormatUtilTest::class.java.getResource("DateFormatUtilTest_macOS")!!.toURI()) FileUtil.setExecutable(helper) val expected = ExecUtil.execAndGetOutput(GeneralCommandLine(helper.path, "${testDate / 1000}")).stdoutLines[0] assertEquals(expected, DateFormatUtil.formatDateTime(testDate)) } @Test fun prettyDate() { val now = LocalDateTime.now() assertPrettyDate("Today", now) assertPrettyDate("Today", now.truncatedTo(ChronoUnit.DAYS)) assertPrettyDate("Yesterday", now.minus(Duration.ofDays(1))) val d1 = LocalDateTime.parse("2003-12-10T17:00:00") assertPrettyDate(DateFormatUtil.formatDate(d1.toMillis()), d1) val d2 = LocalDateTime.parse("2004-12-08T23:59:59") assertPrettyDate(DateFormatUtil.formatDate(d2.toMillis()), d2) } @Test fun prettyDateTime() { val now = LocalDateTime.now() assertPrettyDateTime("Moments ago", now.minus(Duration.ofSeconds(1))) assertPrettyDateTime("A minute ago", now.minus(Duration.ofMinutes(1))) assertPrettyDateTime("5 minutes ago", now.minus(Duration.ofMinutes(5))) assertPrettyDateTime("1 hour ago", now.minus(Duration.ofHours(1))) val d1 = now.plus(Duration.ofMinutes(65)) if (d1.dayOfYear == now.dayOfYear) { assertPrettyDateTime("Today " + DateFormatUtil.formatTime(d1.toMillis()), d1) } val d2 = now.minus(Duration.ofMinutes(65)) if (d2.dayOfYear == now.dayOfYear) { assertPrettyDateTime("Today " + DateFormatUtil.formatTime(d2.toMillis()), d2) } val d3 = now.minus(Duration.ofDays(1)) assertPrettyDateTime("Yesterday " + DateFormatUtil.formatTime(d3.toMillis()), d3) } @Test fun time() { val t = LocalDateTime.parse("1970-01-01T09:28:15") assertThat(DateFormatUtil.formatTime(t.toMillis())).contains("9").contains("28").doesNotContain("15") assertThat(DateFormatUtil.formatTimeWithSeconds(t.toMillis())).contains("9").contains("28").contains("15") } @Test fun aboutDialogDate() { assertEquals("January 1, 1999", DateFormatUtil.formatAboutDialogDate(LocalDateTime.parse("1999-01-01T00:00:00").toMillis())) assertEquals("December 12, 2012", DateFormatUtil.formatAboutDialogDate(LocalDateTime.parse("2012-12-12T15:35:12").toMillis())) } @Test fun frequency() { assertEquals("Once in 2 minutes", DateFormatUtil.formatFrequency(2L * 60 * 1000)) assertEquals("Once in a few moments", DateFormatUtil.formatFrequency(1000L)) } private fun assertPrettyDate(expected: String, now: LocalDateTime) { assertEquals(expected, DateFormatUtil.formatPrettyDate(now.toMillis())) } private fun assertPrettyDateTime(expected: String, now: LocalDateTime) { assertEquals(expected, DateFormatUtil.formatPrettyDateTime(now.toMillis())) } private fun LocalDateTime.toMillis() = atZone(ZoneId.systemDefault()).toEpochSecond() * 1000L }
apache-2.0
0496328645364b0a94f1670def5308e4
40.988764
140
0.741236
4.061957
false
true
false
false
smmribeiro/intellij-community
plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.kt
10
3254
/* * 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.cherrypick import com.intellij.openapi.vcs.VcsApplicationSettings import com.intellij.vcs.log.impl.HashImpl import git4idea.i18n.GitBundle import git4idea.test.* abstract class GitCherryPickTest : GitSingleRepoTest() { protected lateinit var vcsAppSettings: VcsApplicationSettings override fun setUp() { super.setUp() vcsAppSettings = VcsApplicationSettings.getInstance() } protected fun `check dirty tree conflicting with commit`() { val file = file("c.txt") file.create("initial\n").addCommit("initial") branch("feature") val commit = file.append("master\n").addCommit("fix #1").hash() checkout("feature") file.append("local\n") cherryPick(commit) assertErrorNotification("Cherry-pick failed", """ ${shortHash(commit)} fix #1 """ + GitBundle.message("apply.changes.would.be.overwritten", "cherry-pick")) } protected fun `check untracked file conflicting with commit`() { branch("feature") val file = file("untracked.txt") val commit = file.create("master\n").addCommit("fix #1").hash() checkout("feature") file.create("untracked\n") cherryPick(commit) assertErrorNotification("Untracked Files Prevent Cherry-pick", """ Move or commit them before cherry-pick""") } protected fun `check conflict with cherry-picked commit should show merge dialog`() { val initial = tac("c.txt", "base\n") val commit = repo.appendAndCommit("c.txt", "master") repo.checkoutNew("feature", initial) repo.appendAndCommit("c.txt", "feature") `do nothing on merge`() cherryPick(commit) `assert merge dialog was shown`() } protected fun `check resolve conflicts and commit`() { val commit = repo.prepareConflict() `mark as resolved on merge`() vcsHelper.onCommit { msg -> git("commit -am '$msg'") true } cherryPick(commit) `assert commit dialog was shown`() assertLastMessage("on_master") repo.assertCommitted { modified("c.txt") } assertSuccessfulNotification("Cherry-pick successful", "${shortHash(commit)} on_master") changeListManager.assertNoChanges() changeListManager.waitScheduledChangelistDeletions() changeListManager.assertOnlyDefaultChangelist() } protected fun cherryPick(hashes: List<String>) { updateChangeListManager() val details = readDetails(hashes) GitCherryPicker(project).cherryPick(details) } protected fun cherryPick(vararg hashes: String) { cherryPick(hashes.asList()) } protected fun shortHash(hash: String) = HashImpl.build(hash).toShortString() }
apache-2.0
9f6137f99101df07ef2fd076996fdb32
29.990476
87
0.698218
4.344459
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/debugger-ui/src/com/intellij/javascript/debugger/NameMapper.kt
4
6710
// 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.javascript.debugger import com.google.common.base.CharMatcher import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.SyntaxTraverser import org.jetbrains.debugger.sourcemap.MappingEntry import org.jetbrains.debugger.sourcemap.Mappings import org.jetbrains.debugger.sourcemap.MappingsProcessorInLine import org.jetbrains.debugger.sourcemap.SourceMap import org.jetbrains.rpc.LOG import java.util.concurrent.atomic.AtomicInteger private const val S1 = ",()[]{}=" // don't trim trailing .&: - could be part of expression private val OPERATOR_TRIMMER = CharMatcher.invisible().or(CharMatcher.anyOf(S1)) val NAME_TRIMMER: CharMatcher = CharMatcher.invisible().or(CharMatcher.anyOf("$S1.&:")) // generateVirtualFile only for debug purposes open class NameMapper(private val document: Document, private val transpiledDocument: Document, private val sourceMappings: Mappings, protected val sourceMap: SourceMap, private val transpiledFile: VirtualFile? = null) { var rawNameToSource: MutableMap<String, String>? = null private set // PsiNamedElement, JSVariable for example // returns generated name @JvmOverloads open fun map(identifierOrNamedElement: PsiElement, saveMapping: Boolean = true): String? { return doMap(identifierOrNamedElement, false, saveMapping) } protected fun doMap(identifierOrNamedElement: PsiElement, mapBySourceCode: Boolean, saveMapping: Boolean = true): String? { val mappings = getMappingsForElement(identifierOrNamedElement) if (mappings == null || mappings.isEmpty()) return null val sourceEntry = mappings[0] val generatedName: String? try { generatedName = extractName(getGeneratedName(identifierOrNamedElement, transpiledDocument, sourceMap, mappings), identifierOrNamedElement) } catch (e: IndexOutOfBoundsException) { LOG.warn("Cannot get generated name: source entry (${sourceEntry.generatedLine}, ${sourceEntry.generatedColumn}). Transpiled File: " + transpiledFile?.path) return null } if (generatedName == null || generatedName.isEmpty()) { return null } var sourceName = sourceEntry.name if (sourceName == null || mapBySourceCode) { sourceName = (identifierOrNamedElement as? PsiNamedElement)?.name ?: identifierOrNamedElement.text ?: sourceName ?: return null } if (saveMapping) { addMapping(generatedName, sourceName) } return generatedName } protected open fun getMappingsForElement(element: PsiElement): List<MappingEntry>? { val mappings = mutableListOf<MappingEntry>() val offset = element.textOffset val line = document.getLineNumber(offset) val elementColumn = offset - document.getLineStartOffset(line) val elementEndColumn = elementColumn + element.textLength - 1 val sourceEntryIndex = sourceMappings.indexOf(line, elementColumn) if (sourceEntryIndex == -1) { return null } val sourceEntry = sourceMappings.getByIndex(sourceEntryIndex) val next = sourceMappings.getNextOnTheSameLine(sourceEntryIndex, false) if (next != null && sourceMappings.getColumn(next) == sourceMappings.getColumn(sourceEntry)) { warnSeveralMapping(element) return null } val file = element.containingFile val namedElementsCounter = AtomicInteger(0) val processor = object : MappingsProcessorInLine { override fun process(entry: MappingEntry, nextEntry: MappingEntry?): Boolean { val entryColumn = entry.sourceColumn // next entry column could be equal to prev, see https://code.google.com/p/google-web-toolkit/issues/detail?id=9103 val isSuitable = if (nextEntry == null || (entryColumn == 0 && nextEntry.sourceColumn == 0)) { entryColumn <= elementColumn } else { entryColumn in elementColumn..elementEndColumn } if (isSuitable) { val startOffset = document.getLineStartOffset(line) + entryColumn val endOffset = if (nextEntry != null) document.getLineStartOffset(line) + nextEntry.sourceColumn else document.getLineEndOffset(line) if (collectNamedElementsInRange(TextRange(startOffset, endOffset))) { return false } mappings.add(entry) } return true } private fun collectNamedElementsInRange(range: TextRange): Boolean { return SyntaxTraverser.psiTraverser(file) .onRange(range) .filter { it is PsiNamedElement && range.contains(it.textRange) && namedElementsCounter.incrementAndGet() > 1 } .traverse() .isNotEmpty } } if (!sourceMap.processSourceMappingsInLine(sourceEntry.source, sourceEntry.sourceLine, processor)) { return null } return mappings } fun addMapping(generatedName: String, sourceName: String) { if (rawNameToSource == null) { rawNameToSource = HashMap<String, String>() } rawNameToSource!!.put(generatedName, sourceName) } protected open fun extractName(rawGeneratedName: CharSequence?, context: PsiElement? = null):String? = rawGeneratedName?.let { NAME_TRIMMER.trimFrom(it) } companion object { fun trimName(rawGeneratedName: CharSequence, isLastToken: Boolean): String? = (if (isLastToken) NAME_TRIMMER else OPERATOR_TRIMMER).trimFrom(rawGeneratedName) } protected open fun getGeneratedName(element: PsiElement, document: Document, sourceMap: SourceMap, mappings: List<MappingEntry>): CharSequence? { val sourceEntry = mappings[0] val lineStartOffset = document.getLineStartOffset(sourceEntry.generatedLine) val nextGeneratedMapping = sourceMap.generatedMappings.getNextOnTheSameLine(sourceEntry) val endOffset: Int if (nextGeneratedMapping == null) { endOffset = document.getLineEndOffset(sourceEntry.generatedLine) } else { endOffset = lineStartOffset + nextGeneratedMapping.generatedColumn } return document.immutableCharSequence.subSequence(lineStartOffset + sourceEntry.generatedColumn, endOffset) } } fun warnSeveralMapping(element: PsiElement) { // see https://dl.dropboxusercontent.com/u/43511007/s/Screen%20Shot%202015-01-21%20at%2020.33.44.png // var1 mapped to the whole "var c, notes, templates, ..." expression text + unrelated text " ;" LOG.warn("incorrect sourcemap, several mappings for named element ${element.text}") }
apache-2.0
24f7eb909666f09c691b26557fcbd064
41.468354
220
0.730551
4.54607
false
false
false
false
bigown/SOpt
Kotlin/ReadFile.kt
2
1200
import java.io.File import java.io.InputStream fun main(args: Array<String>) { val inputStream: InputStream = File("kotlination.txt").inputStream() val inputString = inputStream.bufferedReader().use { it.readText() } println(inputString) } import java.io.File import java.io.InputStream fun main(args: Array<String>) { val inputStream: InputStream = File("kotlination.txt").inputStream() val lineList = mutableListOf<String>() inputStream.bufferedReader().useLines { lines -> lines.forEach { lineList.add(it)} } lineList.forEach{println("> " + it)} } import java.io.File import java.io.BufferedReader fun main(args: Array<String>) { val bufferedReader: BufferedReader = File("kotlination.txt").bufferedReader() val inputString = bufferedReader.use { it.readText() } println(inputString) } import java.io.File import java.io.BufferedReader fun main(args: Array<String>) { val bufferedReader = File("kotlination.txt").bufferedReader() val lineList = mutableListOf<String>() bufferedReader.useLines { lines -> lines.forEach { lineList.add(it) } } lineList.forEach { println("> " + it) } } //https://pt.stackoverflow.com/q/227393/101
mit
fcf85be1698276af967e198fe86d1bd0
26.906977
88
0.7125
3.896104
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/PetalList/PetalListFragment.kt
1
7273
package stan.androiddemo.project.petal.Module.PetalList import android.content.Context import android.os.Bundle import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.view.View import android.widget.FrameLayout import android.widget.ImageButton import android.widget.LinearLayout import android.widget.TextView import com.chad.library.adapter.base.BaseViewHolder import com.facebook.drawee.view.SimpleDraweeView import org.greenrobot.eventbus.EventBus import rx.Observable import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import stan.androiddemo.R import stan.androiddemo.UI.BasePetalRecyclerFragment import stan.androiddemo.project.petal.API.ListPinsBean import stan.androiddemo.project.petal.API.PetalAPI import stan.androiddemo.project.petal.Config.Config import stan.androiddemo.project.petal.Event.OnPinsFragmentInteractionListener import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient import stan.androiddemo.project.petal.Model.PinsMainInfo import stan.androiddemo.tool.CompatUtils import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder import stan.androiddemo.tool.Logger class PetalListFragment : BasePetalRecyclerFragment<PinsMainInfo>() { var mLimit = Config.LIMIT var maxId = 0 private var mListener: OnPinsFragmentInteractionListener? = null override fun getTheTAG(): String { return this.toString() } companion object { fun createListFragment(type:String,title:String):PetalListFragment{ val fragment = PetalListFragment() val bundle = Bundle() bundle.putString("key",type) bundle.putString("title",title) fragment.arguments = bundle return fragment } } override fun onAttach(context: Context?) { super.onAttach(context) Logger.d(context.toString()) if (context is OnPinsFragmentInteractionListener){ mListener = context } } override fun getLayoutManager(): RecyclerView.LayoutManager { return StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL) } override fun getItemLayoutId(): Int { return R.layout.petal_cardview_image_item } override fun itemLayoutConvert(helper: BaseViewHolder, t: PinsMainInfo) { val img = helper.getView<SimpleDraweeView>(R.id.img_card_main) val txtGather = helper.getView<TextView>(R.id.txt_card_gather) var txtLike = helper.getView<TextView>(R.id.txt_card_like) val linearlayoutTitleInfo = helper.getView<LinearLayout>(R.id.linearLayout_image_title_info) //只能在这里设置TextView的drawable了 txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_favorite_black_18dp,R.color.tint_list_grey),null,null,null) txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_camera_black_18dp,R.color.tint_list_grey),null,null,null) val imgUrl = String.format(mUrlGeneralFormat,t.file!!.key) img.aspectRatio = t.imgRatio helper.getView<FrameLayout>(R.id.frame_layout_card_image).setOnClickListener { EventBus.getDefault().postSticky(t) mListener?.onClickPinsItemImage(t,it) } linearlayoutTitleInfo.setOnClickListener { EventBus.getDefault().postSticky(t) mListener?.onClickPinsItemText(t,it) } txtGather.setOnClickListener { if (!isLogin){ toast("请先登录再操作") return@setOnClickListener } //不做like操作了, t.repin_count ++ txtGather.text = t.repin_count.toString() txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_favorite_black_18dp,R.color.tint_list_pink),null,null,null) } txtLike.setOnClickListener { if (!isLogin){ toast("请先登录再操作") return@setOnClickListener } //不做like操作了, t.like_count ++ helper.setText(R.id.txt_card_like,t.like_count.toString()) txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_camera_black_18dp,R.color.tint_list_pink),null,null,null) } if (t.raw_text.isNullOrEmpty() && t.like_count <= 0 && t.repin_count <= 0){ linearlayoutTitleInfo.visibility = View.GONE } else{ linearlayoutTitleInfo.visibility = View.VISIBLE if (!t.raw_text.isNullOrEmpty()){ helper.getView<TextView>(R.id.txt_card_title).text = t.raw_text!! helper.getView<TextView>(R.id.txt_card_title).visibility = View.VISIBLE } else{ helper.getView<TextView>(R.id.txt_card_title).visibility = View.GONE } helper.setText(R.id.txt_card_gather,t.repin_count.toString()) helper.setText(R.id.txt_card_like,t.like_count.toString()) } var imgType = t.file?.type if (!imgType.isNullOrEmpty()){ if (imgType!!.toLowerCase().contains("gif") ) { helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.VISIBLE } else{ helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.INVISIBLE } } ImageLoadBuilder.Start(context,img,imgUrl).setProgressBarImage(progressLoading).build() } override fun requestListData(page: Int): Subscription { val request = RetrofitClient.createService(PetalAPI::class.java) var result : Observable<ListPinsBean> if (page == 0){ result = request.httpsTypeLimitRx(mAuthorization!!,mKey,mLimit) } else{ result = request.httpsTypeMaxLimitRx(mAuthorization!!,mKey,maxId, mLimit) } return result.map { it.pins }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object:Subscriber<List<PinsMainInfo>>(){ override fun onCompleted() { } override fun onError(e: Throwable?) { e?.printStackTrace() loadError() checkException(e) } override fun onNext(t: List<PinsMainInfo>?) { if (t == null){ loadError() return } if( t!!.size > 0 ){ maxId = t!!.last()!!.pin_id } loadSuccess(t!!) if (t!!.size < mLimit){ setNoMoreData() } } }) } }
mit
f017d4ec829239f1e207262954fc8cb9
36.128866
110
0.626406
4.632154
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/usecases/GetToolbarTitleChangeDialogUseCase.kt
1
820
package ch.rmy.android.http_shortcuts.usecases import androidx.annotation.CheckResult import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.extensions.createDialogState import javax.inject.Inject class GetToolbarTitleChangeDialogUseCase @Inject constructor() { @CheckResult operator fun invoke(onToolbarTitleChangeSubmitted: (String) -> Unit, oldTitle: String) = createDialogState { title(R.string.title_set_title) .textInput( prefill = oldTitle, allowEmpty = true, maxLength = TITLE_MAX_LENGTH, callback = onToolbarTitleChangeSubmitted, ) .build() } companion object { private const val TITLE_MAX_LENGTH = 50 } }
mit
7028c1311fda774b48c83b3993009b41
28.285714
92
0.629268
4.739884
false
false
false
false
android/midi-samples
MidiTools/src/main/java/com/example/android/miditools/MidiPortSelector.kt
1
6268
/* * Copyright (C) 2022 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.miditools import com.example.android.miditools.MidiDeviceMonitor.Companion.getInstance import android.media.midi.MidiManager import android.media.midi.MidiManager.DeviceCallback import android.media.midi.MidiDeviceInfo import android.widget.ArrayAdapter import android.widget.Spinner import android.media.midi.MidiDeviceStatus import android.widget.AdapterView.OnItemSelectedListener import android.widget.AdapterView import android.util.Log import android.view.View import java.lang.Integer.min import java.util.HashSet /** * Base class that uses a Spinner to select available MIDI ports. */ abstract class MidiPortSelector( protected var mMidiManager: MidiManager, spinner: Spinner, type: Int ) : DeviceCallback() { private var mType = MidiConstants.MIDI_INPUT_PORT protected var mAdapter: ArrayAdapter<MidiPortWrapper> private var mBusyPorts = HashSet<MidiPortWrapper>() private val mSpinner: Spinner private var mCurrentWrapper: MidiPortWrapper? = null /** * Set to no port selected. */ private fun clearSelection() { mSpinner.setSelection(0) } private fun getInfoPortCount(info: MidiDeviceInfo): Int { return when (mType) { MidiConstants.MIDI_INPUT_PORT -> { info.inputPortCount } MidiConstants.MIDI_OUTPUT_PORT -> { info.outputPortCount } else -> { min(info.inputPortCount, info.outputPortCount) } } } final override fun onDeviceAdded(info: MidiDeviceInfo) { val portCount = getInfoPortCount(info) for (i in 0 until portCount) { val wrapper = MidiPortWrapper(info, mType, i) mAdapter.add(wrapper) Log.i(MidiConstants.TAG, "$wrapper was added to $this") mAdapter.notifyDataSetChanged() } } override fun onDeviceRemoved(info: MidiDeviceInfo) { val portCount = getInfoPortCount(info) for (i in 0 until portCount) { val wrapper = MidiPortWrapper(info, mType, i) val currentWrapper = mCurrentWrapper mAdapter.remove(wrapper) // If the currently selected port was removed then select no port. if (wrapper == currentWrapper) { clearSelection() } mAdapter.notifyDataSetChanged() Log.i(MidiConstants.TAG, "$wrapper was removed") } } override fun onDeviceStatusChanged(status: MidiDeviceStatus) { // If an input port becomes busy then remove it from the menu. // If it becomes free then add it back to the menu. if ((mType == MidiConstants.MIDI_INPUT_PORT) || (mType == MidiConstants.MIDI_INPUT_OUTPUT_PORT)) { val info = status.deviceInfo Log.i( MidiConstants.TAG, "MidiPortSelector.onDeviceStatusChanged status = " + status + ", mType = " + mType + ", info = " + info ) // Look for transitions from free to busy. val portCount = info.inputPortCount for (i in 0 until portCount) { val wrapper = MidiPortWrapper(info, mType, i) if (wrapper != mCurrentWrapper) { if (status.isInputPortOpen(i)) { // busy? if (!mBusyPorts.contains(wrapper)) { // was free, now busy mBusyPorts.add(wrapper) mAdapter.remove(wrapper) mAdapter.notifyDataSetChanged() } } else { if (mBusyPorts.remove(wrapper)) { // was busy, now free mAdapter.add(wrapper) mAdapter.notifyDataSetChanged() } } } } } } /** * Implement this method to handle the user selecting a port on a device. * * @param wrapper */ abstract fun onPortSelected(wrapper: MidiPortWrapper?) /** * Implement this method to clean up any open resources. */ open fun onClose() {} /** * Implement this method to clean up any open resources. */ fun onDestroy() { getInstance(mMidiManager)!!.unregisterDeviceCallback(this) } /** * */ fun close() { onClose() } init { mType = type mSpinner = spinner mAdapter = ArrayAdapter( mSpinner.context, android.R.layout.simple_spinner_item ) mAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item ) mAdapter.add(MidiPortWrapper(null, 0, 0)) mSpinner.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, pos: Int, id: Long ) { mCurrentWrapper = mAdapter.getItem(pos) onPortSelected(mCurrentWrapper) } override fun onNothingSelected(parent: AdapterView<*>?) { onPortSelected(null) mCurrentWrapper = null } } mSpinner.adapter = mAdapter val infoSet = mMidiManager.getDevicesForTransport(MidiManager.TRANSPORT_UNIVERSAL_MIDI_PACKETS) for (info in infoSet) { onDeviceAdded(info) } } }
apache-2.0
7c40a46d50b46565486afa497aee61db
33.256831
94
0.588864
4.862684
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/tools/security/BrdUserManager.kt
1
23686
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 8/12/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.tools.security import android.app.Activity import android.app.KeyguardManager import android.content.Context import android.content.SharedPreferences import android.os.Build import android.security.keystore.KeyPermanentlyInvalidatedException import android.security.keystore.UserNotAuthenticatedException import android.text.format.DateUtils import androidx.annotation.VisibleForTesting import androidx.core.content.edit import androidx.core.content.getSystemService import androidx.lifecycle.Lifecycle import com.breadwallet.app.ApplicationLifecycleObserver import com.breadwallet.app.BreadApp import com.breadwallet.crypto.Account import com.breadwallet.crypto.Key import com.breadwallet.logger.logInfo import com.breadwallet.tools.crypto.CryptoHelper.hexDecode import com.breadwallet.tools.crypto.CryptoHelper.hexEncode import com.breadwallet.tools.manager.BRReportsManager import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.platform.interfaces.AccountMetaDataProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.Default import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.CONFLATED import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.flow.transformLatest import kotlinx.coroutines.invoke import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import java.security.KeyStore import java.security.UnrecoverableKeyException import java.util.Date import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import javax.crypto.Cipher import kotlin.math.pow const val PIN_LENGTH = 6 const val LEGACY_PIN_LENGTH = 4 private const val MAX_UNLOCK_ATTEMPTS = 3 private const val JWT_EXP_PADDING_MS = 10_000L private const val ANDROID_KEY_STORE = "AndroidKeyStore" private const val NEW_CIPHER_ALGORITHM = "AES/GCM/NoPadding" private const val POLL_ATTEMPTS_MAX = 15 private const val POLL_TIMEOUT_MS = 1000L private const val PUT_PHRASE_RC = 400 private const val GET_PHRASE_RC = 401 private const val KEY_ACCOUNT = "account" private const val KEY_PHRASE = "phrase" private const val KEY_AUTH_KEY = "authKey" private const val KEY_CREATION_TIME = "creationTimeSeconds" private const val KEY_TOKEN = "token" private const val KEY_BDB_JWT = "bdbJwt" private const val KEY_BDB_JWT_EXP = "bdbJwtExp" private const val KEY_PIN_CODE = "pinCode" private const val KEY_FAIL_COUNT = "failCount" private const val KEY_FAIL_TIMESTAMP = "failTimestamp" private const val KEY_ETH_PUB_KEY = "ethPublicKey" private const val MANUFACTURER_GOOGLE = "Google" @Suppress("TooManyFunctions") class CryptoUserManager( context: Context, private val createStore: () -> SharedPreferences?, private val metaDataProvider: AccountMetaDataProvider ) : BrdUserManager { private var store: SharedPreferences? = null private val keyguard = checkNotNull(context.getSystemService<KeyguardManager>()) private val mutex = Mutex() private val resultChannel = Channel<Int>() private val stateChangeChannel = BroadcastChannel<Unit>(CONFLATED) private val accountInvalidated = AtomicBoolean() private val locked = AtomicBoolean(true) private val disabledSeconds = AtomicInteger(0) private var token: String? = null private var jwt: String? = null private var jwtExp: Long? = null init { store = createStore() if (store != null && isPhraseKeyValid()) { startDisabledTimer(getFailTimestamp()) } stateChangeChannel.offer(Unit) ApplicationLifecycleObserver.addApplicationLifecycleListener { event -> if (event == Lifecycle.Event.ON_START) { if (getState() is BrdUserState.KeyStoreInvalid) { stateChangeChannel.offer(Unit) } } } } override suspend fun setupWithGeneratedPhrase(): SetupResult { val creationDate = Date() val phrase = try { generatePhrase() } catch (e: Exception) { return SetupResult.FailedToGeneratePhrase(e) } return initAccount(phrase, creationDate).also { withContext(Dispatchers.IO) { metaDataProvider.create(creationDate) } } } override suspend fun setupWithPhrase(phrase: ByteArray): SetupResult { val apiKey = Key.createForBIP32ApiAuth( phrase, Key.getDefaultWordList() ).orNull() ?: return SetupResult.FailedToCreateApiKey checkNotNull(store).edit { putBytes(KEY_AUTH_KEY, apiKey.encodeAsPrivate()) } val creationDate = metaDataProvider.walletInfo() .first() .creationDate .run(::Date) BreadApp.applicationScope.launch { metaDataProvider.recoverAll(true) } return initAccount(phrase, creationDate, apiKey) } override suspend fun migrateKeystoreData() = mutex.withLock { // Migrate fields required for Account val phrase = getPhrase() ?: return@withLock false try { val creationDate = Date(BRKeyStore.getWalletCreationTime()) val account = Account.createFromPhrase(phrase, creationDate, BRSharedPrefs.getDeviceId()).get() val apiKey = Key.createForBIP32ApiAuth( phrase, Key.getDefaultWordList() ).orNull() checkNotNull(apiKey) { "Migration failed, failed to create Api Key." } writeAccount(account, apiKey, creationDate) } catch (e: Exception) { wipeAccount() return@withLock false } // Migrate other fields BRKeyStore.getToken()?.let { putToken(String(it)) } BRKeyStore.getEthPublicKey()?.let { putEthPublicKey(it) } putPinCode(BRKeyStore.getPinCode()) putFailCount(BRKeyStore.getFailCount()) putFailTimestamp(BRKeyStore.getFailTimeStamp()) BreadApp.applicationScope.launch(Dispatchers.IO) { BRKeyStore.wipeAfterMigration() } true } override suspend fun checkAccountInvalidated() { val deviceId = BRSharedPrefs.getDeviceId() val invalidated = checkNotNull(store).getBytes(KEY_ACCOUNT, null)?.let { Account.createFromSerialization(it, deviceId).orNull() == null } ?: false if (!invalidated) return val phrase = getPhrase() if (phrase == null) { accountInvalidated.set(true) stateChangeChannel.offer(Unit) return } logInfo("Account needs to be re-created from phrase.") val account = Account.createFromPhrase( phrase, Date(getWalletCreationTime()), deviceId ).orNull() if (account == null) { accountInvalidated.set(true) stateChangeChannel.offer(Unit) } else { logInfo("Account re-created.") checkNotNull(store).edit { putBytes(KEY_ACCOUNT, account.serialize()) } } } override fun isInitialized() = getState() != BrdUserState.Uninitialized override fun isMigrationRequired() = !isInitialized() && (BRKeyStore.getMasterPublicKey() != null || BRKeyStore.hasAccountBytes()) override fun getState(): BrdUserState = when { // Account invalidated and phrase not provided or phrase Key invalidated, recovery required accountInvalidated.get() || !isPhraseKeyValid() -> if (requiresUninstall()) { BrdUserState.KeyStoreInvalid.Uninstall } else { BrdUserState.KeyStoreInvalid.Wipe } // User must create/restore a wallet getAccount() == null -> BrdUserState.Uninitialized // Too many failed unauthorized access attempts, user must wait disabledSeconds.get() > 0 -> BrdUserState.Disabled(disabledSeconds.get()) // State is valid, request authentication locked.get() -> BrdUserState.Locked // State is valid else -> BrdUserState.Enabled } override fun stateChanges(disabledUpdates: Boolean): Flow<BrdUserState> = stateChangeChannel.asFlow() .onStart { emit(Unit) } .map { getState() } .transformLatest { state -> if (state is BrdUserState.Disabled && disabledUpdates) { emit(state) while (disabledSeconds.get() > 0) { delay(1000) emit(state.copy(seconds = disabledSeconds.get())) } } else emit(state) } .distinctUntilChanged() .flowOn(Default) override suspend fun getPhrase(): ByteArray? = store?.getBytes(KEY_PHRASE, null) ?: executeWithAuth { BRKeyStore.getPhrase(it, GET_PHRASE_RC) } ?.also { bytes -> store?.edit { putBytes(KEY_PHRASE, bytes) } } override fun getAccount(): Account? = store?.getBytes(KEY_ACCOUNT, null)?.run { Account.createFromSerialization( this, BRSharedPrefs.getDeviceId() ).orNull() } override fun updateAccount(accountBytes: ByteArray) { checkNotNull( Account.createFromSerialization( accountBytes, BRSharedPrefs.getDeviceId() ).orNull() ) checkNotNull(store).edit { putBytes(KEY_ACCOUNT, accountBytes) } } override fun getAuthKey() = checkNotNull(store).getBytes(KEY_AUTH_KEY, null) override suspend fun configurePinCode(pinCode: String) { checkNotNull(getPhrase()) { "Phrase is null, cannot set pin code." } check(pinCode.length == PIN_LENGTH && pinCode.toIntOrNull() != null) { "Invalid pin code." } putPinCode(pinCode) putFailCount(0) } override suspend fun clearPinCode(phrase: ByteArray) { val storedPhrase = checkNotNull(getPhrase()) { "Phrase is null, cannot clear pin code." } check(phrase.contentEquals(storedPhrase)) { "Phrase does not match." } putPinCode("") putFailCount(0) putFailTimestamp(0) disabledSeconds.set(0) locked.set(false) stateChangeChannel.offer(Unit) } override fun verifyPinCode(pinCode: String) = if (pinCode == getPinCode()) { putFailCount(0) putFailTimestamp(0) locked.set(false) stateChangeChannel.offer(Unit) true } else { val failCount = getFailCount() + 1 putFailCount(failCount) if (failCount >= MAX_UNLOCK_ATTEMPTS) { BRSharedPrefs.getSecureTime() .also(::putFailTimestamp) .also(::startDisabledTimer) stateChangeChannel.offer(Unit) } false } override fun hasPinCode() = getPinCode().isNotBlank() override fun pinCodeNeedsUpgrade() = getPinCode().let { it.isNotBlank() && it.length != PIN_LENGTH } override fun lock() { if (!locked.getAndSet(true)) { stateChangeChannel.offer(Unit) } } override fun unlock() { if (locked.getAndSet(false)) { stateChangeChannel.offer(Unit) } } @Synchronized override fun getToken() = token ?: checkNotNull(store).getString(KEY_TOKEN, null) @Synchronized override fun putToken(token: String) { checkNotNull(store).edit { putString(KEY_TOKEN, token) } this.token = token } @Synchronized override fun removeToken() { checkNotNull(store).edit { remove(KEY_TOKEN) } token = null } @Synchronized override fun getBdbJwt() = if ((getBdbJwtExp() - JWT_EXP_PADDING_MS) <= System.currentTimeMillis()) { null } else { jwt ?: checkNotNull(store).getString(KEY_BDB_JWT, null) } @Synchronized override fun putBdbJwt(jwt: String, exp: Long) { checkNotNull(store).edit { putString(KEY_BDB_JWT, jwt) putLong(KEY_BDB_JWT_EXP, exp) } this.jwt = jwt this.jwtExp = exp } @Synchronized private fun getBdbJwtExp() = jwtExp ?: checkNotNull(store).getLong(KEY_BDB_JWT_EXP, 0) /** * Used to determine address mismatch cases for tracking purposes, therefore exposed * as part of the implementation rather than the [BrdUserManager] interface. */ fun getEthPublicKey(): ByteArray? = checkNotNull(store).getBytes(KEY_ETH_PUB_KEY, null) private fun generatePhrase(): ByteArray { val words = Key.getDefaultWordList() return Account.generatePhrase(words).also { phrase -> check(Account.validatePhrase(phrase, words)) { "Invalid phrase generated." } } } private suspend fun initAccount(phrase: ByteArray, creationDate: Date, apiKey: Key? = null) = mutex.withLock { check(getPhrase() == null) { "Phrase already exists." } try { val storedPhrase = checkNotNull(store).run { edit { putBytes(KEY_PHRASE, phrase) } getBytes(KEY_PHRASE, null) } ?: return@withLock SetupResult.FailedToPersistPhrase val account = Account.createFromPhrase( storedPhrase, creationDate, BRSharedPrefs.getDeviceId() ).get() ?: return@withLock SetupResult.FailedToCreateAccount val apiAuthKey = apiKey ?: Key.createForBIP32ApiAuth( phrase, Key.getDefaultWordList() ).orNull() ?: return@withLock SetupResult.FailedToCreateApiKey writeAccount(account, apiAuthKey, creationDate) if ( !validateAccount( storedPhrase, account, apiAuthKey, creationDate.time ) ) return@withLock SetupResult.FailedToCreateValidWallet locked.set(false) stateChangeChannel.offer(Unit) logInfo("Account created.") SetupResult.Success } catch (e: Exception) { wipeAccount() SetupResult.UnknownFailure(e) } } private fun getPinCode() = checkNotNull(store).getString(KEY_PIN_CODE, "") ?: "" private fun putEthPublicKey(ethPubKey: ByteArray) = checkNotNull(store).edit { putBytes(KEY_ETH_PUB_KEY, ethPubKey) } private fun getWalletCreationTime() = checkNotNull(store).getLong(KEY_CREATION_TIME, 0L) private fun disabledUntil(failCount: Int, failTimestamp: Long): Long { val pow = PIN_LENGTH.toDouble() .pow((failCount - MAX_UNLOCK_ATTEMPTS).toDouble()) * DateUtils.MINUTE_IN_MILLIS return (failTimestamp + pow).toLong() } private fun putPinCode(pinCode: String) { checkNotNull(store).edit { putString(KEY_PIN_CODE, pinCode) } } private fun getFailCount() = checkNotNull(store).getInt(KEY_FAIL_COUNT, 0) private fun putFailCount(count: Int) = checkNotNull(store).edit { putInt(KEY_FAIL_COUNT, count) } private fun getFailTimestamp(): Long = checkNotNull(store).getLong(KEY_FAIL_TIMESTAMP, 0) private fun putFailTimestamp(timestamp: Long) = checkNotNull(store).edit { putLong(KEY_FAIL_TIMESTAMP, timestamp) } private fun startDisabledTimer(failTimestamp: Long) { if (failTimestamp > 0) { BRSharedPrefs.secureTimeFlow() .map { secureTime -> val disableUntil = disabledUntil(getFailCount(), failTimestamp) ((disableUntil - secureTime) / 1000).toInt() } .takeWhile { it > 0 } .onEach { initialDelay -> disabledSeconds.set(initialDelay) while (disabledSeconds.get() > 0) { delay(1000) disabledSeconds.getAndDecrement() } putFailTimestamp(0) disabledSeconds.set(0) stateChangeChannel.offer(Unit) } .launchIn(BreadApp.applicationScope) } } /** * Invokes [action], catching [UserNotAuthenticatedException]. * If authentication is required, it will be attempted and upon * success will invoke [action] again. If authentication fails, * null is returned. */ private suspend fun <T> executeWithAuth(action: (context: Activity) -> T): T { val activity = getActivity() return try { Main { runCatching { action(activity) } }.getOrThrow() } catch (e: UserNotAuthenticatedException) { logInfo("Attempting authentication") when (resultChannel.receive()) { Activity.RESULT_OK -> Main { runCatching { action(activity) } }.getOrThrow() else -> throw e } } } override fun onActivityResult(requestCode: Int, resultCode: Int) { check(!resultChannel.isClosedForSend) resultChannel.offer( when (requestCode) { PUT_PHRASE_RC -> resultCode GET_PHRASE_RC -> resultCode else -> return } ) } private fun writeAccount( account: Account, apiKey: Key, creationDate: Date ) { checkNotNull(store).edit { putBytes(KEY_ACCOUNT, account.serialize()) putBytes(KEY_AUTH_KEY, apiKey.encodeAsPrivate()) putLong(KEY_CREATION_TIME, creationDate.time) } } private suspend fun validateAccount( phrase: ByteArray, account: Account, apiKey: Key, creationTime: Long ) = withContext(Dispatchers.IO) { Account.validatePhrase(phrase, Key.getDefaultWordList()) && getAccount()?.serialize()?.contentEquals(account.serialize()) == true && getAuthKey()?.contentEquals(apiKey.encodeAsPrivate()) == true && getWalletCreationTime() == creationTime } @VisibleForTesting fun wipeAccount() { checkNotNull(store).edit { putString(KEY_PHRASE, null) putString(KEY_ACCOUNT, null) putString(KEY_AUTH_KEY, null) putString(KEY_PIN_CODE, null) putLong(KEY_CREATION_TIME, 0) } BRKeyStore.wipeKeyStore(true) } private suspend fun getActivity(): Activity { var context = BreadApp.getBreadContext() while (context !is Activity) { context = BreadApp.getBreadContext() delay(1_000) } return context } private fun isPhraseKeyValid(): Boolean { if (store?.getBytes(KEY_PHRASE, null) != null) { // BRKeyStore is not required anymore, phrase key is ignored. return true } return runCatching { // Attempt to retrieve the key that protects the paper key and initialize an encryption cipher. val key = KeyStore.getInstance(ANDROID_KEY_STORE) .apply { load(null) } .getKey(BRKeyStore.PHRASE_ALIAS, null) when { key != null -> { val cipher = Cipher.getInstance(NEW_CIPHER_ALGORITHM) cipher.init(Cipher.ENCRYPT_MODE, key) true } store?.getBytes(KEY_ACCOUNT, null) != null -> false // key is null when it should not be else -> true // key has not been initialized, the key store is still considered valid } }.recoverCatching { e -> // If KeyPermanentlyInvalidatedException // -> with no cause happens, then the password was disabled. See DROID-1019. // If UnrecoverableKeyException // -> with cause "Key blob corrupted" happens then the password was disabled & re-enabled. See DROID-1207. // -> with cause "Key blob corrupted" happens then after DROID-1019 the app was opened again while password is on. // -> with cause "Key not found" happens then after DROID-1019 the app was opened again while password is off. // -> with cause "System error" (KeyStoreException) after app wipe on devices that need uninstall to recover. // Note: These exceptions would happen before a UserNotAuthenticatedException, so we don't need to handle that. (e !is KeyPermanentlyInvalidatedException && e !is UnrecoverableKeyException).also { isValid -> if (!isValid) BRReportsManager.error("Phrase key permanently invalidated", e) } }.getOrDefault(false) } private fun requiresUninstall(): Boolean { val isGoogleDevice = MANUFACTURER_GOOGLE == Build.MANUFACTURER val isOmr1 = Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1 val isOorAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O return isGoogleDevice && isOmr1 || !isGoogleDevice && isOorAbove } } fun SharedPreferences.getBytes(key: String, defaultValue: ByteArray?): ByteArray? { val valStr = getString(key, null) ?: return defaultValue return hexDecode(valStr) } fun SharedPreferences.Editor.putBytes(key: String, value: ByteArray) { putString(key, hexEncode(value)) }
mit
17eb07fe42114511e4c6b0206b86d23b
35.44
127
0.628219
4.77733
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/search/SearchPagedListAdapter.kt
1
1435
package org.fossasia.openevent.general.search import org.fossasia.openevent.general.favorite.FavoriteEventViewHolder import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagedListAdapter import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.common.EventClickListener import org.fossasia.openevent.general.common.EventsDiffCallback import org.fossasia.openevent.general.common.FavoriteFabClickListener import org.fossasia.openevent.general.databinding.ItemCardFavoriteEventBinding class SearchPagedListAdapter : PagedListAdapter<Event, FavoriteEventViewHolder>(EventsDiffCallback()) { var onEventClick: EventClickListener? = null var onFavFabClick: FavoriteFabClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteEventViewHolder { val binding = ItemCardFavoriteEventBinding.inflate(LayoutInflater.from(parent.context), parent, false) return FavoriteEventViewHolder(binding) } override fun onBindViewHolder(holder: FavoriteEventViewHolder, position: Int) { val event = getItem(position) if (event != null) { holder.apply { bind(event, position, "") eventClickListener = onEventClick favFabClickListener = onFavFabClick } } } fun clear() { this.submitList(null) } }
apache-2.0
d9eb33453f824fd818c1bfd7d44e4f6a
36.763158
110
0.750523
4.880952
false
false
false
false
seventhroot/elysium
bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/listener/PlayerInteractListener.kt
1
6144
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.auctions.bukkit.listener import com.rpkit.auctions.bukkit.RPKAuctionsBukkit import com.rpkit.auctions.bukkit.auction.RPKAuctionProvider import com.rpkit.auctions.bukkit.bid.RPKBid import com.rpkit.auctions.bukkit.bid.RPKBidImpl import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.economy.bukkit.economy.RPKEconomyProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.ChatColor.GREEN import org.bukkit.Material.AIR import org.bukkit.block.Sign import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerInteractEvent /** * Player interact listener for auction signs. */ class PlayerInteractListener(private val plugin: RPKAuctionsBukkit): Listener { @EventHandler fun onPlayerInteract(event: PlayerInteractEvent) { if (!event.hasBlock()) return val sign = event.clickedBlock?.state as? Sign ?: return if (sign.getLine(0) != "$GREEN[auction]") return if (!event.player.hasPermission("rpkit.auctions.sign.auction.bid")) { event.player.sendMessage(plugin.messages["no-permission-bid"]) return } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val economyProvider = plugin.core.serviceManager.getServiceProvider(RPKEconomyProvider::class) val auctionProvider = plugin.core.serviceManager.getServiceProvider(RPKAuctionProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(event.player) if (minecraftProfile == null) { event.player.sendMessage(plugin.messages["no-minecraft-profile"]) return } val character = characterProvider.getActiveCharacter(minecraftProfile) val auction = auctionProvider.getAuction(sign.getLine(1).toInt()) if (auction == null) { event.player.sendMessage(plugin.messages["bid-invalid-auction-not-existent"]) return } if (System.currentTimeMillis() >= auction.endTime) { auction.closeBidding() } if (!auction.isBiddingOpen) { event.player.sendMessage(plugin.messages["bid-invalid-auction-not-open"]) return } val bidAmount = (auction.bids.sortedByDescending(RPKBid::amount).firstOrNull()?.amount?:auction.startPrice) + auction.minimumBidIncrement if (character == null) { event.player.sendMessage(plugin.messages["no-character"]) return } if (bidAmount >= economyProvider.getBalance(character, auction.currency)) { event.player.sendMessage(plugin.messages["bid-invalid-not-enough-money"]) return } val radius = plugin.config.getInt("auctions.radius") val auctionLocation = auction.location if (radius >= 0 && auctionLocation != null && event.player.location.distanceSquared(auctionLocation) > radius * radius) { event.player.sendMessage(plugin.messages["bid-invalid-too-far-away"]) return } val bid = RPKBidImpl( auction = auction, character = character, amount = bidAmount ) if (!auction.addBid(bid)) { event.player.sendMessage(plugin.messages["bid-create-failed"]) return } if (!auctionProvider.updateAuction(auction)) { event.player.sendMessage(plugin.messages["auction-update-failed"]) return } event.player.sendMessage(plugin.messages["bid-valid", mapOf( Pair("amount", bid.amount.toString()), Pair("currency", if (bid.amount == 1) auction.currency.nameSingular else auction.currency.namePlural), Pair("item", auction.item.amount.toString() + " " + auction.item.type.toString().toLowerCase().replace("_", " ") + if (auction.item.amount != 1) "s" else "") )]) auction.bids .asSequence() .map(RPKBid::character) .toSet() .asSequence() .filter { character -> character != bid.character } .map(RPKCharacter::minecraftProfile) .filterNotNull() .filter(RPKMinecraftProfile::isOnline) .toList() .forEach { minecraftProfile -> minecraftProfile.sendMessage(plugin.messages["bid-created", mapOf( Pair("auction_id", bid.auction.id.toString()), Pair("character", bid.character.name), Pair("amount", bid.amount.toString()), Pair("currency", if (bid.amount == 1) auction.currency.nameSingular else auction.currency.namePlural), Pair("item", auction.item.amount.toString() + " " + auction.item.type.toString().toLowerCase().replace("_", " ") + if (auction.item.amount != 1) "s" else "") )]) } sign.setLine(3, (bid.amount + auction.minimumBidIncrement).toString()) sign.update() if (!auction.isBiddingOpen) { event.clickedBlock?.type = AIR } } }
apache-2.0
a65ac3e90f614bdda3a634658eed3cf2
46.261538
185
0.648275
4.755418
false
false
false
false
rethumb/rethumb-examples
examples-resize-by-width/example-kotlin.kt
1
689
import java.io.FileOutputStream import java.net.URL import java.nio.channels.Channels object KotlinRethumbWidthExample { @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val paramOperation = "width" val paramValue = 100 // New width in pixels. val imageURL = "http://images.rethumb.com/image_coimbra_600x300.jpg" val imageFilename = "resized-image.jpg" val url = URL(String.format("http://api.rethumb.com/v1/%s/%s/%s", paramOperation, paramValue, imageURL)) val fos = FileOutputStream(imageFilename) fos.channel.transferFrom(Channels.newChannel(url.openStream()), 0, java.lang.Long.MAX_VALUE) } }
unlicense
4c061e84a6e491cca8a79873dc203964
33.5
112
0.692308
3.569948
false
false
false
false
android/user-interface-samples
WindowInsetsAnimation/app/src/main/java/com/google/android/samples/insetsanimation/ControlFocusInsetsAnimationCallback.kt
1
2833
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.samples.insetsanimation import android.view.View import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsAnimationCompat import androidx.core.view.WindowInsetsCompat /** * A [WindowInsetsAnimationCompat.Callback] which will request and clear focus on the given view, * depending on the [WindowInsetsCompat.Type.ime] visibility state when an IME * [WindowInsetsAnimationCompat] has finished. * * This is primarily used when animating the [WindowInsetsCompat.Type.ime], so that the * appropriate view is focused for accepting input from the IME. * * @param view the view to request/clear focus * @param dispatchMode The dispatch mode for this callback. * * @see WindowInsetsAnimationCompat.Callback.getDispatchMode */ class ControlFocusInsetsAnimationCallback( private val view: View, dispatchMode: Int = DISPATCH_MODE_STOP ) : WindowInsetsAnimationCompat.Callback(dispatchMode) { override fun onProgress( insets: WindowInsetsCompat, runningAnimations: List<WindowInsetsAnimationCompat> ): WindowInsetsCompat { // no-op and return the insets return insets } override fun onEnd(animation: WindowInsetsAnimationCompat) { if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) { // The animation has now finished, so we can check the view's focus state. // We post the check because the rootWindowInsets has not yet been updated, but will // be in the next message traversal view.post { checkFocus() } } } private fun checkFocus() { val imeVisible = ViewCompat.getRootWindowInsets(view) ?.isVisible(WindowInsetsCompat.Type.ime()) == true if (imeVisible && view.rootView.findFocus() == null) { // If the IME will be visible, and there is not a currently focused view in // the hierarchy, request focus on our view view.requestFocus() } else if (!imeVisible && view.isFocused) { // If the IME will not be visible and our view is currently focused, clear the focus view.clearFocus() } } }
apache-2.0
c3fdb72deed2cec52cf0e16c3ed28188
37.808219
97
0.699612
4.70598
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/misc/DiscordBotListTopCommand.kt
1
2611
package net.perfectdreams.loritta.morenitta.commands.vanilla.misc import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.utils.image.JVMImage import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase import net.perfectdreams.loritta.morenitta.tables.BotVotes import net.perfectdreams.loritta.morenitta.utils.RankingGenerator import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.count import org.jetbrains.exposed.sql.selectAll class DiscordBotListTopCommand(loritta: LorittaBot): DiscordAbstractCommandBase(loritta, listOf("dbl top"), net.perfectdreams.loritta.common.commands.CommandCategory.MISC) { companion object { private const val LOCALE_PREFIX = "commands.command.dbltop" } override fun command() = create { localizedDescription("$LOCALE_PREFIX.description") executesDiscord { var page = args.getOrNull(0)?.toLongOrNull() if (page != null && !RankingGenerator.isValidRankingPage(page)) { reply( LorittaReply( locale["commands.invalidRankingPage"], Constants.ERROR ) ) return@executesDiscord } if (page != null) page -= 1 if (page == null) page = 0 val userId = BotVotes.userId val userIdCount = BotVotes.userId.count() val userData = loritta.newSuspendedTransaction { BotVotes.slice(userId, userIdCount) .selectAll() .groupBy(userId) .orderBy(userIdCount, SortOrder.DESC) .limit(5, page * 5) .toList() } sendImage( JVMImage( RankingGenerator.generateRanking( loritta, "Ranking Global", null, userData.map { RankingGenerator.UserRankInformation( it[userId], locale["$LOCALE_PREFIX.votes", it[userIdCount]] ) } ) ), "rank.png", getUserMention(true) ) } } }
agpl-3.0
8b789696cca6bceaae2f5b57ce4676f2
35.277778
173
0.555726
5.520085
false
false
false
false
allen-garvey/photog-spark
src/main/kotlin/main/export.kt
1
5712
/* * * Exports Apple Photos database in format suitable for https://github.com/allen-garvey/photog-phoenix * */ package main import controllers.SqliteController import models.Folder import models.Import import java.sql.Timestamp val IMAGES_TABLE_NAME = "images" val ALBUMS_TABLE_NAME = "albums" val PEOPLE_TABLE_NAME = "persons" val TAGS_TABLE_NAME = "tags" val ALBUM_TAGS_TABLE_NAME = "album_tags" val IMPORTS_TABLE_NAME = "imports" val TIMESTAMPS_COLUMN_NAMES = ",inserted_at, updated_at" val TIMESTAMPS_COLUMN_VALUES = ",now(), now()" fun sqlEscapeOptionalString(s: String?): String{ if(s == null){ return "null" } return sqlEscapeString(s) } fun sqlEscapeString(s: String): String{ return "'${s.replace("'", "''")}'" } fun sqlOptionalInt(d: Int?): String{ if(d == null){ return "null" } return d.toString() } fun sqlBool(b: Boolean = false): String{ if(b){ return "true" } return "false" } fun sqlOptionalInt(s: String?): String{ if(s == null){ return "null" } return s } //postgresql to timestamp https://www.postgresql.org/docs/8.2/static/functions-formatting.html fun sqlTimestamp(t: Timestamp): String{ // return "to_timestamp('${t.toInstant().toString()}', 'YYYY-MM-DD HH:MI:SS')" return "to_timestamp('${t.toString().replace(Regex("\\.0$"), "")}', 'YYYY-MM-DD HH24:MI:SS')" } fun sqlDate(t: Timestamp): String{ return "to_date('${t.toString().replace(Regex(" .*$"), "")}', 'YYYY-MM-DD')" } fun relatedImageId(imageId: String): String{ return "(SELECT ${IMAGES_TABLE_NAME}.id FROM ${IMAGES_TABLE_NAME} WHERE ${IMAGES_TABLE_NAME}.apple_photos_id = ${imageId} LIMIT 1)" } fun relatedPersonId(personId: String): String{ return "(SELECT ${PEOPLE_TABLE_NAME}.id FROM ${PEOPLE_TABLE_NAME} WHERE ${PEOPLE_TABLE_NAME}.apple_photos_id = ${personId} LIMIT 1)" } fun relatedAlbumId(albumId: String): String{ return "(SELECT ${ALBUMS_TABLE_NAME}.id FROM ${ALBUMS_TABLE_NAME} WHERE ${ALBUMS_TABLE_NAME}.apple_photos_id = ${albumId} LIMIT 1)" } fun relatedFolderUuid(folderUuid: String): String{ return "(SELECT ${TAGS_TABLE_NAME}.id FROM ${TAGS_TABLE_NAME} WHERE ${TAGS_TABLE_NAME}.apple_photos_uuid = ${folderUuid} LIMIT 1)" } fun relatedImportUuid(importUuid: String): String{ return "(SELECT ${IMPORTS_TABLE_NAME}.id FROM ${IMPORTS_TABLE_NAME} WHERE ${IMPORTS_TABLE_NAME}.apple_photos_uuid = ${importUuid} LIMIT 1)" } fun main(args: Array<String>) { if(args.size >= 1){ SqliteController.databaseRoot = args[0] } //create import resources println("\n\n--Imports\n") val imports = SqliteController.selectAllImports() imports.forEach { println("INSERT INTO ${IMPORTS_TABLE_NAME} (apple_photos_uuid, import_time ${TIMESTAMPS_COLUMN_NAMES} ) VALUES (${sqlEscapeString(it.uuid)}, ${sqlTimestamp(it.timestamp)} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--Tags (called Folders in Apple Photos)\n") var folders = SqliteController.selectAllFolders() //have to add library folder since it is an implicit folder not contained in table folders.add(Folder("LibraryFolder", "Library")) folders.reverse() folders.forEach{ println("INSERT INTO ${TAGS_TABLE_NAME} (apple_photos_uuid, name ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${sqlEscapeString(it.uuid)}, ${sqlEscapeString(it.name)} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--Images\n") SqliteController.selectAllImages().forEach{ println("INSERT INTO ${IMAGES_TABLE_NAME} (import_id, apple_photos_id, creation_time, master_path, thumbnail_path, mini_thumbnail_path, is_favorite ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${relatedImportUuid(sqlEscapeString(it.importUuid!!))}, ${it.id}, ${sqlTimestamp(it.creation!!)}, ${sqlEscapeString(it.path)}, ${sqlEscapeString(it.thumbnail!!.thumbnailPath)}, ${sqlEscapeString(it.thumbnail!!.miniThumbnailPath)}, ${sqlBool(it.isFavorite)} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--Albums\n") var albums = SqliteController.selectAllAlbums() albums.sortBy({it.id.toInt()}) albums.forEach{ println("INSERT INTO ${ALBUMS_TABLE_NAME} (apple_photos_id, name, cover_image_id, creation_date ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${it.id}, ${sqlEscapeString(it.name)}, ${relatedImageId(it.coverImage!!.id)}, ${sqlDate(it.creation!!)} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--Album Tags\n") albums.forEach{ println("INSERT INTO ${ALBUM_TAGS_TABLE_NAME} (album_id, tag_id, album_order ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${relatedAlbumId(it.id)}, ${relatedFolderUuid(sqlEscapeString(it.folderUuid))}, ${it.folderOrder!!} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--People\n") var people = SqliteController.selectAllPeople() people.sortBy({it.id.toInt()}) people.forEach{ println("INSERT INTO ${PEOPLE_TABLE_NAME} (apple_photos_id, name, cover_image_id ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${it.id}, ${sqlEscapeString(it.name)}, ${relatedImageId(it.coverImageId!!)} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--Person Images\n") SqliteController.selectAllPersonImages().forEach{ println("INSERT INTO person_images (person_id, image_id ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${relatedPersonId(it.personId)}, ${relatedImageId(it.imageId)} ${TIMESTAMPS_COLUMN_VALUES});") } println("\n\n--Album Images\n") SqliteController.selectAllAlbumImages().forEach{ println("INSERT INTO album_images (album_id, image_id, image_order ${TIMESTAMPS_COLUMN_NAMES}) VALUES (${relatedAlbumId(it.albumId)}, ${relatedImageId(it.imageId)}, ${it.order} ${TIMESTAMPS_COLUMN_VALUES});") } }
mit
4adec0f0786edf8b0b75cf9b45fb7c11
38.130137
480
0.681723
3.530284
false
false
false
false
pixis/TraktTV
app/src/main/java/com/pixis/traktTV/screen_main_old/MainActivity.kt
2
2971
package com.pixis.traktTV.screen_main_old /* import android.content.Intent import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.widget.SwipeRefreshLayout import android.view.Menu import android.view.MenuItem import butterknife.BindView import com.pixis.traktTV.BuildConfig import com.pixis.traktTV.R import com.pixis.traktTV.adapters.RecyclerListAdapter import com.pixis.traktTV.base.BaseRxActivity import com.pixis.traktTV.screen_login.LoginActivity import com.pixis.traktTV.screen_main_old.presenters.PresenterMainActivity import com.pixis.traktTV.views.AdvancedRecyclerView import com.pixis.trakt_api.utils.Token.TokenDatabase import nucleus5.factory.RequiresPresenter import timber.log.Timber import javax.inject.Inject //List of tracked movies and tv shows @RequiresPresenter(PresenterMainActivity::class) class MainActivity : BaseRxActivity<PresenterMainActivity>() { override val layoutId: Int = R.layout.activity_main @BindView(R.id.recyclerView) lateinit var recyclerView: AdvancedRecyclerView @BindView(R.id.fabMainAction) lateinit var fabMainAction: FloatingActionButton lateinit var trackedItemAdapter: RecyclerListAdapter<TrackedItem> @Inject lateinit var tokenDatabase: TokenDatabase override fun injectPresenter(presenter: PresenterMainActivity) { getComponent().inject(presenter) } override fun init(savedInstanceState: Bundle?) { getComponent().inject(this) if (!tokenDatabase.isAuthenticated()) { startActivity(Intent(this, LoginActivity::class.java)) finish() return } trackedItemAdapter = RecyclerListAdapter(this, TrackedItemHolder()) recyclerView.setMAdapter(trackedItemAdapter) recyclerView.setRefreshing(true) if (BuildConfig.DEBUG) { Timber.d("ACCESS TOKEN %s", tokenDatabase.getAccessToken()) } recyclerView.setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener { loadData(fromSwipe = true) }) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.menu_refresh) { loadData() return true } return super.onOptionsItemSelected(item) } private fun loadData(fromSwipe: Boolean = false) { if (!fromSwipe) recyclerView.setRefreshing(true) presenter.loadCalendar() } fun setData(it: List<TrackedItem>) { trackedItemAdapter.setItems(it)//TODO recyclerView.setRefreshing(false) } fun showError(s: String) { Snackbar.make(recyclerView, s, Snackbar.LENGTH_SHORT).show() recyclerView.setRefreshing(false) } } */
apache-2.0
96b67a5813980ea88c6bcecc8b2b5e5d
29.958333
110
0.725008
4.563748
false
false
false
false
actions-on-google/appactions-fitness-kotlin
app/src/main/java/com/devrel/android/fitactions/tracking/FitTrackingService.kt
1
4092
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.devrel.android.fitactions.tracking import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.Observer import com.devrel.android.fitactions.FitMainActivity import com.devrel.android.fitactions.R import com.devrel.android.fitactions.model.FitActivity import com.devrel.android.fitactions.model.FitRepository /** * Foreground Android Service that starts an activity and keep tracks of the status showing * a notification. */ class FitTrackingService : Service() { private companion object { private const val ONGOING_NOTIFICATION_ID = 999 private const val CHANNEL_ID = "TrackingChannel" } private val fitRepository: FitRepository by lazy { FitRepository.getInstance(this) } /** * Create a notification builder that will be used to create and update the stats notification */ private val notificationBuilder: NotificationCompat.Builder by lazy { val pendingIntent = Intent(this, FitMainActivity::class.java).let { notificationIntent -> PendingIntent.getActivity(this, 0, notificationIntent, 0) } NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(getText(R.string.tracking_notification_title)) .setSmallIcon(R.drawable.ic_run) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_MAX) } /** * Observer that will update the notification with the ongoing activity status. */ private val trackingObserver: Observer<FitActivity> = Observer { fitActivity -> fitActivity?.let { val km = String.format("%.2f", it.distanceMeters / 1000) val notification = notificationBuilder .setContentText(getString(R.string.stat_distance, km)) .build() NotificationManagerCompat.from(this).notify(ONGOING_NOTIFICATION_ID, notification) } } override fun onBind(intent: Intent): IBinder? = null override fun onCreate() { super.onCreate() createNotificationChannel() startForeground(ONGOING_NOTIFICATION_ID, notificationBuilder.build()) // Start a new activity and attach the observer fitRepository.startActivity() fitRepository.getOnGoingActivity().observeForever(trackingObserver) } override fun onDestroy() { super.onDestroy() // Stop the ongoing activity and detach the observer fitRepository.stopActivity() fitRepository.getOnGoingActivity().removeObserver(trackingObserver) } /** * Creates a Notification channel needed for new version of Android */ private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.app_name) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance) val notificationManager = getSystemService( Context.NOTIFICATION_SERVICE ) as NotificationManager notificationManager.createNotificationChannel(channel) } } }
apache-2.0
5464b6978cad7dbd97de800b2f9b7d49
35.535714
98
0.707967
4.93012
false
false
false
false
google/horologist
media-data/src/main/java/com/google/android/horologist/media/data/database/dao/PlaylistDao.kt
1
2882
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.media.data.database.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi import com.google.android.horologist.media.data.database.model.MediaEntity import com.google.android.horologist.media.data.database.model.PlaylistEntity import com.google.android.horologist.media.data.database.model.PlaylistMediaEntity import com.google.android.horologist.media.data.database.model.PopulatedPlaylist import kotlinx.coroutines.flow.Flow /** * DAO for [PlaylistEntity]. */ @ExperimentalHorologistMediaDataApi @Dao public interface PlaylistDao { @Insert(onConflict = OnConflictStrategy.REPLACE) public suspend fun upsert( playlistEntity: PlaylistEntity, mediaEntityList: List<MediaEntity>, playlistMediaEntityList: List<PlaylistMediaEntity> ) @Transaction @Query( value = """ SELECT * FROM PlaylistEntity WHERE playlistId = :playlistId """ ) public suspend fun getPopulated(playlistId: String): PopulatedPlaylist? @Transaction @Query( value = """ SELECT * FROM playlistentity WHERE playlistId = :playlistId """ ) public fun getPopulatedStream(playlistId: String): Flow<PopulatedPlaylist?> @Transaction @Query( value = """ SELECT * FROM PlaylistEntity """ ) public fun getAllPopulated(): Flow<List<PopulatedPlaylist>> @Transaction @Query( value = """ SELECT * FROM PlaylistEntity WHERE EXISTS ( SELECT 1 FROM PlaylistMediaEntity WHERE PlaylistMediaEntity.playlistId = PlaylistEntity.playlistId AND EXISTS ( SELECT 1 FROM MediaDownloadEntity WHERE MediaDownloadEntity.mediaId = PlaylistMediaEntity.mediaId ) ) """ ) public fun getAllDownloaded(): Flow<List<PopulatedPlaylist>> @Query( value = """ DELETE FROM PlaylistEntity WHERE playlistId in (:playlistIds) """ ) public fun delete(playlistIds: List<String>) }
apache-2.0
7e135e695c7f740ab75c8b2368a03795
29.659574
82
0.701943
4.716858
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/interests/InterestsScreen.kt
1
16902
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui.interests import androidx.compose.foundation.Box import androidx.compose.foundation.Icon import androidx.compose.foundation.Image import androidx.compose.foundation.ScrollableColumn import androidx.compose.foundation.Text import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.preferredSize import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider import androidx.compose.material.DrawerValue import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.material.Tab import androidx.compose.material.TabRow import androidx.compose.material.TopAppBar import androidx.compose.material.rememberDrawerState import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.savedinstancestate.savedInstanceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.imageResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import androidx.ui.tooling.preview.Preview import com.example.jetnews.R import com.example.jetnews.data.Result import com.example.jetnews.data.interests.InterestsRepository import com.example.jetnews.data.interests.TopicSelection import com.example.jetnews.data.interests.TopicsMap import com.example.jetnews.data.interests.impl.FakeInterestsRepository import com.example.jetnews.ui.AppDrawer import com.example.jetnews.ui.Screen import com.example.jetnews.ui.ThemedPreview import com.example.jetnews.utils.launchUiStateProducer import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking enum class Sections(val title: String) { Topics("Topics"), People("People"), Publications("Publications") } /** * TabContent for a single tab of the screen. * * This is intended to encapsulate a tab & it's content as a single object. It was added to avoid * passing several parameters per-tab from the stateful composable to the composable that displays * the current tab. * * @param section the tab that this content is for * @param section content of the tab, a composable that describes the content */ class TabContent(val section: Sections, val content: @Composable () -> Unit) /** * Stateful InterestsScreen manages state using [launchUiStateProducer] * * @param navigateTo (event) request navigation to [Screen] * @param scaffoldState (state) state for screen Scaffold * @param interestsRepository data source for this screen */ @Composable fun InterestsScreen( navigateTo: (Screen) -> Unit, interestsRepository: InterestsRepository, scaffoldState: ScaffoldState = rememberScaffoldState() ) { // Returns a [CoroutineScope] that is scoped to the lifecycle of [InterestsScreen]. When this // screen is removed from composition, the scope will be cancelled. val coroutineScope = rememberCoroutineScope() // Describe the screen sections here since each section needs 2 states and 1 event. // Pass them to the stateless InterestsScreen using a tabContent. val topicsSection = TabContent(Sections.Topics) { val (topics) = launchUiStateProducer(interestsRepository) { getTopics() } // collectAsState will read a [Flow] in Compose val selectedTopics by interestsRepository.observeTopicsSelected().collectAsState(setOf()) val onTopicSelect: (TopicSelection) -> Unit = { coroutineScope.launch { interestsRepository.toggleTopicSelection(it) } } val data = topics.value.data ?: return@TabContent TopicList(data, selectedTopics, onTopicSelect) } val peopleSection = TabContent(Sections.People) { val (people) = launchUiStateProducer(interestsRepository) { getPeople() } val selectedPeople by interestsRepository.observePeopleSelected().collectAsState(setOf()) val onPeopleSelect: (String) -> Unit = { coroutineScope.launch { interestsRepository.togglePersonSelected(it) } } val data = people.value.data ?: return@TabContent PeopleList(data, selectedPeople, onPeopleSelect) } val publicationSection = TabContent(Sections.Publications) { val (publications) = launchUiStateProducer(interestsRepository) { getPublications() } val selectedPublications by interestsRepository.observePublicationSelected().collectAsState(setOf()) val onPublicationSelect: (String) -> Unit = { coroutineScope.launch { interestsRepository.togglePublicationSelected(it) } } val data = publications.value.data ?: return@TabContent PublicationList(data, selectedPublications, onPublicationSelect) } val tabContent = listOf(topicsSection, peopleSection, publicationSection) val (currentSection, updateSection) = savedInstanceState { tabContent.first().section } InterestsScreen( tabContent = tabContent, tab = currentSection, onTabChange = updateSection, navigateTo = navigateTo, scaffoldState = scaffoldState ) } /** * Stateless interest screen displays the tabs specified in [tabContent] * * @param tabContent (slot) the tabs and their content to display on this screen, must be a non-empty * list, tabs are displayed in the order specified by this list * @param tab (state) the current tab to display, must be in [tabContent] * @param onTabChange (event) request a change in [tab] to another tab from [tabContent] * @param navigateTo (event) request navigation to [Screen] * @param scaffoldState (state) the state for the screen's [Scaffold] */ @Composable fun InterestsScreen( tabContent: List<TabContent>, tab: Sections, onTabChange: (Sections) -> Unit, navigateTo: (Screen) -> Unit, scaffoldState: ScaffoldState, ) { Scaffold( scaffoldState = scaffoldState, drawerContent = { AppDrawer( currentScreen = Screen.Interests, closeDrawer = { scaffoldState.drawerState.close() }, navigateTo = navigateTo ) }, topBar = { TopAppBar( title = { Text("Interests") }, navigationIcon = { IconButton(onClick = { scaffoldState.drawerState.open() }) { Icon(vectorResource(R.drawable.ic_jetnews_logo)) } } ) }, bodyContent = { TabContent(tab, onTabChange, tabContent) } ) } /** * Displays a tab row with [currentSection] selected and the body of the corresponding [tabContent]. * * @param currentSection (state) the tab that is currently selected * @param updateSection (event) request a change in tab selection * @param tabContent (slot) tabs and their content to display, must be a non-empty list, tabs are * displayed in the order of this list */ @Composable private fun TabContent( currentSection: Sections, updateSection: (Sections) -> Unit, tabContent: List<TabContent> ) { val selectedTabIndex = tabContent.indexOfFirst { it.section == currentSection } Column { TabRow( selectedTabIndex = selectedTabIndex ) { tabContent.forEachIndexed { index, tabContent -> Tab( text = { Text(tabContent.section.title) }, selected = selectedTabIndex == index, onClick = { updateSection(tabContent.section) } ) } } Box(modifier = Modifier.weight(1f)) { // display the current tab content which is a @Composable () -> Unit tabContent[selectedTabIndex].content() } } } /** * Display the list for the topic tab * * @param topics (state) topics to display, mapped by section * @param selectedTopics (state) currently selected topics * @param onTopicSelect (event) request a topic selection be changed */ @Composable private fun TopicList( topics: TopicsMap, selectedTopics: Set<TopicSelection>, onTopicSelect: (TopicSelection) -> Unit ) { TabWithSections(topics, selectedTopics, onTopicSelect) } /** * Display the list for people tab * * @param people (state) people to display * @param selectedPeople (state) currently selected people * @param onPersonSelect (event) request a person selection be changed */ @Composable private fun PeopleList( people: List<String>, selectedPeople: Set<String>, onPersonSelect: (String) -> Unit ) { TabWithTopics(people, selectedPeople, onPersonSelect) } /** * Display a list for publications tab * * @param publications (state) publications to display * @param selectedPublications (state) currently selected publications * @param onPublicationSelect (event) request a publication selection be changed */ @Composable private fun PublicationList( publications: List<String>, selectedPublications: Set<String>, onPublicationSelect: (String) -> Unit ) { TabWithTopics(publications, selectedPublications, onPublicationSelect) } /** * Display a simple list of topics * * @param topics (state) topics to display * @param selectedTopics (state) currently selected topics * @param onTopicSelect (event) request a topic selection be changed */ @Composable private fun TabWithTopics( topics: List<String>, selectedTopics: Set<String>, onTopicSelect: (String) -> Unit ) { ScrollableColumn(modifier = Modifier.padding(top = 16.dp)) { topics.forEach { topic -> TopicItem( topic, selected = selectedTopics.contains(topic) ) { onTopicSelect(topic) } TopicDivider() } } } /** * Display a sectioned list of topics * * @param sections (state) topics to display, grouped by sections * @param selectedTopics (state) currently selected topics * @param onTopicSelect (event) request a topic+section selection be changed */ @Composable private fun TabWithSections( sections: TopicsMap, selectedTopics: Set<TopicSelection>, onTopicSelect: (TopicSelection) -> Unit ) { ScrollableColumn { sections.forEach { (section, topics) -> Text( text = section, modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.subtitle1 ) topics.forEach { topic -> TopicItem( itemTitle = topic, selected = selectedTopics.contains(TopicSelection(section, topic)) ) { onTopicSelect(TopicSelection(section, topic)) } TopicDivider() } } } } /** * Display a full-width topic item * * @param itemTitle (state) topic title * @param selected (state) is topic currently selected * @param onToggle (event) toggle selection for topic */ @Composable private fun TopicItem(itemTitle: String, selected: Boolean, onToggle: () -> Unit) { val image = imageResource(R.drawable.placeholder_1_1) Row( modifier = Modifier .toggleable( value = selected, onValueChange = { onToggle() } ) .padding(horizontal = 16.dp) ) { Image( image, Modifier .align(Alignment.CenterVertically) .preferredSize(56.dp, 56.dp) .clip(RoundedCornerShape(4.dp)) ) Text( text = itemTitle, modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) .padding(16.dp), style = MaterialTheme.typography.subtitle1 ) SelectTopicButton( modifier = Modifier.align(Alignment.CenterVertically), selected = selected ) } } /** * Full-width divider for topics */ @Composable private fun TopicDivider() { Divider( modifier = Modifier.padding(start = 72.dp, top = 8.dp, bottom = 8.dp), color = MaterialTheme.colors.surface.copy(alpha = 0.08f) ) } @Preview("Interests screen") @Composable fun PreviewInterestsScreen() { ThemedPreview { InterestsScreen( navigateTo = {}, interestsRepository = FakeInterestsRepository() ) } } @Preview("Interests screen dark theme") @Composable fun PreviewInterestsScreenDark() { ThemedPreview(darkTheme = true) { val scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(DrawerValue.Open) ) InterestsScreen( navigateTo = {}, scaffoldState = scaffoldState, interestsRepository = FakeInterestsRepository() ) } } @Preview("Interests screen drawer open") @Composable private fun PreviewDrawerOpen() { ThemedPreview { val scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(DrawerValue.Open) ) InterestsScreen( navigateTo = {}, scaffoldState = scaffoldState, interestsRepository = FakeInterestsRepository() ) } } @Preview("Interests screen drawer open dark theme") @Composable private fun PreviewDrawerOpenDark() { ThemedPreview(darkTheme = true) { val scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(DrawerValue.Open) ) InterestsScreen( navigateTo = {}, scaffoldState = scaffoldState, interestsRepository = FakeInterestsRepository() ) } } @Preview("Interests screen topics tab") @Composable fun PreviewTopicsTab() { ThemedPreview { TopicList(loadFakeTopics(), setOf(), {}) } } @Preview("Interests screen topics tab dark theme") @Composable fun PreviewTopicsTabDark() { ThemedPreview(darkTheme = true) { TopicList(loadFakeTopics(), setOf(), {}) } } @Composable private fun loadFakeTopics(): TopicsMap { val topics = runBlocking { FakeInterestsRepository().getTopics() } return (topics as Result.Success).data } @Preview("Interests screen people tab") @Composable fun PreviewPeopleTab() { ThemedPreview { PeopleList(loadFakePeople(), setOf(), { }) } } @Preview("Interests screen people tab dark theme") @Composable fun PreviewPeopleTabDark() { ThemedPreview(darkTheme = true) { PeopleList(loadFakePeople(), setOf(), { }) } } @Composable private fun loadFakePeople(): List<String> { val people = runBlocking { FakeInterestsRepository().getPeople() } return (people as Result.Success).data } @Preview("Interests screen publications tab") @Composable fun PreviewPublicationsTab() { ThemedPreview { PublicationList(loadFakePublications(), setOf(), { }) } } @Preview("Interests screen publications tab dark theme") @Composable fun PreviewPublicationsTabDark() { ThemedPreview(darkTheme = true) { PublicationList(loadFakePublications(), setOf(), { }) } } @Composable private fun loadFakePublications(): List<String> { val publications = runBlocking { FakeInterestsRepository().getPublications() } return (publications as Result.Success).data } @Preview("Interests screen tab with topics") @Composable fun PreviewTabWithTopics() { ThemedPreview { TabWithTopics(topics = listOf("Hello", "Compose"), selectedTopics = setOf()) {} } } @Preview("Interests screen tab with topics dark theme") @Composable fun PreviewTabWithTopicsDark() { ThemedPreview(darkTheme = true) { TabWithTopics(topics = listOf("Hello", "Compose"), selectedTopics = setOf()) {} } }
apache-2.0
47039c303b5da184fe74e9412ac44ee7
31.255725
108
0.682582
4.581729
false
false
false
false
zensum/franz
src/main/kotlin/WorkerResult.kt
1
624
package franz class WorkerResult<out L> ( val value: L? = null, val status: WorkerStatus ) { companion object { fun <L> success(result: L) = WorkerResult(result, WorkerStatus.Success) val retry = WorkerResult(null, WorkerStatus.Retry) val failure = WorkerResult(null, WorkerStatus.Failure) } fun toJobStatus(): JobStatus = when(status){ WorkerStatus.Success -> JobStatus.Incomplete WorkerStatus.Retry -> JobStatus.TransientFailure WorkerStatus.Failure -> JobStatus.PermanentFailure } } enum class WorkerStatus { Success, Retry, Failure }
mit
42a82fe9f3d32e995c2db38bd3fa7d42
25.041667
79
0.673077
4.244898
false
false
false
false
HendraAnggrian/kota
kota-support-v4/src/resources/ConfigurationsV4.kt
1
1281
@file:JvmMultifileClass @file:JvmName("ResourcesV4Kt") @file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.support.v4.app.Fragment inline val Fragment.screenSize: Int get() = context!!.screenSize inline fun Fragment.isScreenSizeAtLeast(size: Int): Boolean = context!!.isScreenSizeAtLeast(size) inline val Fragment.isScreenLong: Boolean get() = context!!.isScreenLong inline val Fragment.isRtl: Boolean get() = context!!.isRtl inline val Fragment.hasTouchscreen: Boolean get() = context!!.hasTouchscreen inline val Fragment.hasKeyboard: Boolean get() = context!!.hasKeyboard inline val Fragment.isKeyboardHidden: Boolean get() = context!!.isKeyboardHidden inline val Fragment.isHardKeyboardHidden: Boolean get() = context!!.isHardKeyboardHidden inline val Fragment.hasNavigation: Boolean get() = context!!.hasNavigation inline val Fragment.isNavigationHidden: Boolean get() = context!!.isNavigationHidden inline val Fragment.isLandscape: Boolean get() = context!!.isLandscape inline val Fragment.typeMode: Int get() = context!!.typeMode inline val Fragment.isTypeNormal: Boolean get() = context!!.isTypeNormal inline val Fragment.nightMode: Int get() = context!!.nightMode inline val Fragment.isNightMode: Boolean get() = context!!.isNightMode
apache-2.0
32ada080e78e73157f15d613b2623917
33.648649
97
0.785324
4.092652
false
false
false
false
reime005/splintersweets
core/src/de/reimerm/splintersweets/utils/Resources.kt
1
2252
/* * Copyright (c) 2017. Marius Reimer * * 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 de.reimerm.splintersweets.utils /** * All resources listed in an enum class. * * Created by Marius Reimer on 12-Jun-16. */ object Resources { val SPRITES_ATLAS_PATH = "sprites.atlas" val SPLASH_IMAGE_PATH = "splash.png" val BACKGROUND_MUSIC = "background.mp3" val FONT_PATH = "font.fnt" val GAME_OVER_FONT_PATH = "gameover.fnt" val GAME_OVER_SCORE_FONT_PATH = "gameoverscore.fnt" val SOUND_BLOP = "blop.mp3" val SOUND_BUZZ = "buzz.mp3" enum class RegionNames(val str: String) { BACKGROUND_NAME("background"), BUTTON_LEADERBOARD("button_leaderboard"), BUTTON_AUDIO_ON("button_audio_on"), BUTTON_AUDIO_OFF("button_audio_off"), CIRCLE_RED("jellybig_red"), CIRCLE_BROWN("mmstroke_brown"), CIRCLE_PINK("swirl_pink"), BUTTON_PAUSE_NAME("button_pause"), BUTTON_RESUME_NAME("button_resume"), BUTTON_AGAIN_NAME("button_again"), HIGHSCORE_PANE("pane"), BUTTON_QUIT_NAME("button_quit"); } enum class AnimationNames(val array: Array<String>) { CIRCLE_RED_START_ANIMATIONS(Array(4, { i -> "jellybig_red_anim_" + i })), CIRCLE_BROWN_START_ANIMATIONS(Array(4, { i -> "mmstroke_brown_anim_" + i })), CIRCLE_PINK_START_ANIMATIONS(Array(4, { i -> "swirl_pink_anim_" + i })), CIRCLE_RED_START_ANIMATIONS_REVERSE(Array(4, { i -> "jellybig_red_anim_" + +(4 - i - 1) })), CIRCLE_BROWN_START_ANIMATIONS_REVERSE(Array(4, { i -> "mmstroke_brown_anim_" + +(4 - i - 1) })), CIRCLE_PINK_START_ANIMATIONS_REVERSE(Array(4, { i -> "swirl_pink_anim_" + +(4 - i - 1) })), } }
apache-2.0
176c5832a769b9e1fbd1758cb7701e4d
38.526316
104
0.645204
3.376312
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/bookmark/model/Bookmark.kt
1
1917
package jp.toastkid.yobidashi.browser.bookmark.model import android.content.Context import androidx.core.net.toUri import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import jp.toastkid.lib.storage.FilesDir import jp.toastkid.yobidashi.browser.UrlItem /** * Bookmark model. * * @author toastkidjp */ @Entity(indices = [Index(value = ["parent", "folder"])]) class Bookmark : UrlItem { @PrimaryKey(autoGenerate = true) var _id: Long = 0 var title: String = "" var url: String = "" var favicon: String = "" var parent: String = getRootFolderName() var folder: Boolean = false var viewCount: Int = 0 var lastViewed: Long = 0 override fun urlString() = url override fun itemId() = _id override fun toString(): String { return "Bookmark(_id=$_id, title='$title', url='$url', favicon='$favicon', " + "parent='$parent', folder=$folder, viewCount=$viewCount, lastViewed=$lastViewed)" } companion object { private const val ROOT_FOLDER_NAME: String = "root" fun getRootFolderName() = ROOT_FOLDER_NAME fun makeFaviconUrl(context: Context, url: String): String { val host = url.toUri().host ?: url return FilesDir(context, "favicons").assignNewFile("$host.png").absolutePath } fun make( title: String, url: String = "", faviconPath: String = "", parent: String = "parent", folder: Boolean = false ): Bookmark { val bookmark = Bookmark() bookmark.title = title bookmark.url = url bookmark.favicon = faviconPath bookmark.lastViewed = System.currentTimeMillis() bookmark.parent = parent bookmark.folder = folder return bookmark } } }
epl-1.0
799f14c6d5425f459227c9059c817fa4
24.905405
97
0.599896
4.468531
false
false
false
false
square/curtains
curtains/src/androidTest/java/curtains/test/utilities/TestUtils.kt
1
4244
package curtains.test.utilities import android.app.Activity import android.app.Application import android.app.Application.ActivityLifecycleCallbacks import android.os.Build import android.os.ParcelFileDescriptor import android.view.View import android.view.View.OnAttachStateChangeListener import androidx.test.core.app.ActivityScenario import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiSelector import curtains.OnWindowFocusChangedListener import curtains.onWindowFocusChangedListeners import org.junit.Assume import java.io.Closeable import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import kotlin.reflect.KClass fun <T> getOnMain(runOnMainSync: () -> T): T { val result = AtomicReference<T>() InstrumentationRegistry.getInstrumentation().runOnMainSync { result.set(runOnMainSync()) } return result.get() } fun <T> MutableList<T>.addUntilClosed(element: T): Closeable { this += element return Closeable { this -= element } } fun Application.registerUntilClosed(callbacks: ActivityLifecycleCallbacks): Closeable { registerActivityLifecycleCallbacks(callbacks) return Closeable { unregisterActivityLifecycleCallbacks(callbacks) } } fun assumeSdkAtMost( sdkInt: Int, reason: String ) { val currentVersion = Build.VERSION.SDK_INT Assume.assumeTrue( "SDK Int $currentVersion > max $sdkInt: $reason", currentVersion <= sdkInt ) } fun assumeSdkAtLeast( sdkInt: Int, reason: String ) { val currentVersion = Build.VERSION.SDK_INT Assume.assumeTrue( "SDK Int $currentVersion < min $sdkInt: $reason", currentVersion >= sdkInt ) } fun CountDownLatch.checkAwait() { check(await(30, TimeUnit.SECONDS)) { "30 seconds elapsed without count coming down" } } val application: Application get() = InstrumentationRegistry.getInstrumentation().context.applicationContext as Application fun <T : Activity, R> ActivityScenario<T>.getOnActivity(getOnActivity: (T) -> R): R { val result = AtomicReference<R>() onActivity { activity -> result.set(getOnActivity(activity)) } return result.get() } fun Closeable.useWith(other: Closeable): Closeable { return Closeable { close() other.close() } } fun View.onAttachedToWindow(onAttachedToWindow: () -> Unit) { addOnAttachStateChangeListener(object : OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) = onAttachedToWindow() override fun onViewDetachedFromWindow(v: View) = Unit }) } fun <T : Activity> launchWaitingForFocus(activityClass: KClass<T>): ActivityScenario<T> { val scenario = ActivityScenario.launch(activityClass.java) var hasFocus = scenario.waitForFocus() if (hasFocus == null) { resolveAnr() } hasFocus = scenario.waitForFocus() if (hasFocus == null) { dumpWindowService() } check(hasFocus) { "expected activity to become focused" } return scenario } private fun <T : Activity> ActivityScenario<T>.waitForFocus(): Boolean? { val activityHasWindowFocus = ArrayBlockingQueue<Boolean>(1) onActivity { activity -> if (activity.hasWindowFocus()) { activityHasWindowFocus.put(true) } else { activity.window.onWindowFocusChangedListeners += object : OnWindowFocusChangedListener { override fun onWindowFocusChanged(hasFocus: Boolean) { activity.window.onWindowFocusChangedListeners -= this activityHasWindowFocus.put(hasFocus) } } } } return activityHasWindowFocus.poll(10, TimeUnit.SECONDS) } private fun resolveAnr() { val instrumentation = InstrumentationRegistry.getInstrumentation() val uiDevice = UiDevice.getInstance(instrumentation) uiDevice.findObject(UiSelector().resourceId("android:id/aerr_wait"))?.click() } private fun dumpWindowService(): Nothing { val dump = InstrumentationRegistry.getInstrumentation() .uiAutomation .executeShellCommand("dumpsys window") .let(ParcelFileDescriptor::AutoCloseInputStream) .bufferedReader().useLines { it.joinToString("\n|") } throw RuntimeException(dump) }
apache-2.0
e0c5e347fd7cb06198eadb0cdfa82d63
28.075342
96
0.754006
4.439331
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/graph/processing/PropagationGraphProcessor.kt
1
3100
package com.openlattice.graph.processing import com.openlattice.datastore.services.EdmManager import com.openlattice.graph.processing.processors.AssociationProcessor import com.openlattice.graph.processing.processors.GraphProcessor import com.openlattice.graph.processing.processors.SelfProcessor import org.apache.olingo.commons.api.edm.FullQualifiedName class PropagationGraphProcessor(private val edm: EdmManager) { val singleForwardPropagationGraph: MutableMap<Propagation, MutableSet<Propagation>> = mutableMapOf() val selfPropagationGraph: MutableMap<Propagation, MutableSet<Propagation>> = mutableMapOf() val rootInputPropagations: MutableSet<Propagation> = mutableSetOf() private val outputPropagations: MutableSet<Propagation> = mutableSetOf() private val graphHandler = BaseGraphHandler<Propagation>() fun register(processor: GraphProcessor) { val inputs = when(processor) { is AssociationProcessor -> { val allInputs = mutableMapOf<FullQualifiedName, Set<FullQualifiedName>>() allInputs.putAll(processor.getSrcInputs()) allInputs.putAll(processor.getDstInputs()) allInputs.putAll(processor.getEdgeInputs()) allInputs } is SelfProcessor -> { processor.getInputs() } else -> { mapOf() } } val outputEntityTypeId = edm.getEntityType(processor.getOutput().first).id val outputPropertyTypeId = edm.getPropertyTypeId(processor.getOutput().second) inputs.map { val inputEntityTypeId = edm.getEntityType(it.key).id it.value .map { edm.getPropertyTypeId(it) } // List<PropertyType UUID> .map { Propagation(inputEntityTypeId, it) } .toSet() }.forEach { val outputProp = Propagation( outputEntityTypeId, outputPropertyTypeId) it.forEach { // Input propagations inputProp -> // Add to root propagations, if its not contained in any propagation graph yet if(!(outputPropagations.contains(inputProp))) { rootInputPropagations.add(inputProp) } outputPropagations.add(outputProp) // Remove from root propagations if propagation is an output too rootInputPropagations.remove(outputProp) if(inputProp.entityTypeId == outputEntityTypeId) { selfPropagationGraph.getOrPut(inputProp) { mutableSetOf() }.add(outputProp) } else { singleForwardPropagationGraph.getOrPut(inputProp) { mutableSetOf() }.add(outputProp) } } } } fun hasCycle():Boolean { val remain = singleForwardPropagationGraph.toMutableMap() remain.putAll(selfPropagationGraph) val roots = rootInputPropagations.toMutableSet() return graphHandler.hasCycle(remain, roots) } }
gpl-3.0
0db84b5c23cf713d3236da1128691a17
41.479452
104
0.639032
5.123967
false
false
false
false
yichen0831/RobotM
core/src/game/robotm/ecs/systems/InteractionSystem.kt
1
2069
package game.robotm.ecs.systems import com.badlogic.ashley.core.ComponentMapper import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import game.robotm.ecs.components.AnimationComponent import game.robotm.ecs.components.InteractionComponent import game.robotm.ecs.components.InteractionType import game.robotm.ecs.components.PhysicsComponent import game.robotm.gamesys.SoundPlayer class InteractionSystem : IteratingSystem(Family.all(InteractionComponent::class.java, PhysicsComponent::class.java, AnimationComponent::class.java).get()) { val interactionM = ComponentMapper.getFor(InteractionComponent::class.java) val physicsM = ComponentMapper.getFor(PhysicsComponent::class.java) val animM = ComponentMapper.getFor(AnimationComponent::class.java) override fun processEntity(entity: Entity, deltaTime: Float) { val interactionComponent = interactionM.get(entity) val body = physicsM.get(entity).body val animationComponent = animM.get(entity) when (interactionComponent.type) { InteractionType.SPRING -> { when (interactionComponent.status) { "normal" -> { animationComponent.currentAnim = "normal" } "hit" -> { animationComponent.currentAnim = "hit" if (animationComponent.animations["hit"]!!.isAnimationFinished(animationComponent.animTime)) { interactionComponent.status = "normal" } } } } InteractionType.ENEMY -> {} InteractionType.ITEM -> { when (interactionComponent.status) { "normal" -> {} "hit" -> { body.world.destroyBody(body) engine.removeEntity(entity) SoundPlayer.play("power_up") } } } } } }
apache-2.0
75c7e055eec5c43804b0b4244eb06cd8
38.807692
157
0.617206
4.949761
false
false
false
false
pdvrieze/ProcessManager
java-common/src/javaMain/kotlin/net/devrieze/util/Streams.kt
1
1747
/* * 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/>. */ @file:JvmName("Streams") package net.devrieze.util import java.io.* import java.nio.charset.Charset @Deprecated("Compatibility with Java interface", ReplaceWith("inputStream.readString(charset)")) @Throws(IOException::class) fun toString(inputStream: InputStream, charset: Charset):String = inputStream.readString(charset) fun InputStream.readString(charset: Charset): String { return InputStreamReader(this, charset).readString() } @Deprecated("Compatibility with Java interface", ReplaceWith("reader.readString()")) @Throws(IOException::class) fun toString(reader: Reader):String = reader.readString() fun Reader.readString(): String { val result = StringBuilder() val buffer = CharArray(0x8ff) var count = read(buffer) while (count >= 0) { result.append(buffer, 0, count) count = read(buffer) } return result.toString() } fun StringBuilder.writer(): Writer = object : Writer() { override fun write(cbuf: CharArray, off: Int, len: Int) { append(cbuf, off, len) } override fun flush() = Unit override fun close() = Unit }
lgpl-3.0
7a90d9d97042ef18690f55825e492761
30.781818
112
0.738409
4.100939
false
false
false
false
Waboodoo/Status-Bar-Tachometer
StatusBarSpeedometer/app/src/main/kotlin/ch/rmy/android/statusbar_tacho/notifications/NotificationProvider.kt
1
2768
package ch.rmy.android.statusbar_tacho.notifications import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import ch.rmy.android.statusbar_tacho.R import ch.rmy.android.statusbar_tacho.activities.SettingsActivity class NotificationProvider(context: Context) { private val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private val builder: Notification.Builder init { val intent = Intent(context, SettingsActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE } else { 0 }) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationManager.createNotificationChannel(createChannel(context)) } builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Notification.Builder(context, CHANNEL_ID) } else { @Suppress("DEPRECATION") Notification.Builder(context) } .setSmallIcon(R.drawable.icon_unknown) .setContentTitle(context.getString(R.string.current_speed)) .setContentText(context.getString(R.string.unknown)) .setContentIntent(pendingIntent) } fun initializeNotification(service: Service) { service.startForeground(NOTIFICATION_ID, builder.build()) } fun updateNotification(message: String, @DrawableRes smallIcon: Int) { val notification = builder .setContentText(message) .setSmallIcon(smallIcon) .setOnlyAlertOnce(true) .build() notificationManager.notify(NOTIFICATION_ID, notification) } companion object { private const val NOTIFICATION_ID = 1 private const val CHANNEL_ID = "notification" @RequiresApi(Build.VERSION_CODES.O) private fun createChannel(context: Context): NotificationChannel = NotificationChannel( CHANNEL_ID, context.getString(R.string.notification_channel), NotificationManager.IMPORTANCE_LOW ) .apply { enableLights(false) enableVibration(false) setShowBadge(false) } } }
mit
dffc9134cccb8ef8cfcf2c68f1dc60a5
32.756098
148
0.659682
5.023593
false
false
false
false
lavenderx/foliage
foliage-api/src/main/kotlin/io/foliage/api/ApiBootstrap.kt
1
785
package io.foliage.api import io.foliage.api.web.WebServer import io.foliage.utils.loggerFor class ApiBootstrap { companion object { private val SERVER_PORT = "foliage.server.port" private val logger = loggerFor<ApiBootstrap>() @JvmStatic fun main(args: Array<String>) { val port = if (System.getProperty(SERVER_PORT) == null) 8080 else System.getProperty(SERVER_PORT).toInt() val webServer = WebServer("FoliageServer", port).start() Runtime.getRuntime().addShutdownHook(Thread { try { webServer.destroy() } catch (e: Exception) { logger.error("An exception occurred when destroying server", e) } }) } } }
mit
6448090bb23a5f0e99143f9847dcb6bf
31.75
117
0.587261
4.672619
false
false
false
false
songzhw/Hello-kotlin
AdvancedJ/src/main/kotlin/algorithm/sort/MInSwap.kt
1
990
package algorithm.sort import utils.swap // unsorted array consisting of consecutive integers fun minSwaps(ary: Array<Int>): Int { // 若第零位是3, 那我就要把第零位和第三位互换 -- 因为数字就代表我的位置, 所以我先移动一下, 至少先把第零位上的数字放到正确的位置 // 现在再对新的第零位, 重复一样的动作. var swapTimes = 0 val size = ary.size var i = 0 while (i < size) { if (ary[i] == i) { i++ continue } ary.swap(i, ary[i]) swapTimes++ //这里就不再 i++ 了, 因为我还要比较第i位的数字是不是i, 所以i仍是原样进入下一循环单次 } return swapTimes } fun main(args: Array<String>) { val ary1 = intArrayOf(3, 2, 0, 1).toTypedArray() println("min01 = ${minSwaps(ary1)}") //=> 3 val ary2 = intArrayOf(1, 2, 3, 0, 4).toTypedArray() println("min02 = ${minSwaps(ary2)}") //=> 3 }
apache-2.0
0b3a6eea323e14b0a4ee4bb09a8d379a
20
74
0.578608
2.561056
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/inventory/LanternItemStackBuilder.kt
1
3940
/* * 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.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.data.DataManipulator import org.spongepowered.api.data.Key import org.spongepowered.api.data.persistence.AbstractDataBuilder import org.spongepowered.api.data.persistence.DataView import org.spongepowered.api.data.value.MergeFunction import org.spongepowered.api.data.value.Value import org.spongepowered.api.entity.attribute.AttributeModifier import org.spongepowered.api.entity.attribute.type.AttributeType import org.spongepowered.api.item.ItemType import org.spongepowered.api.item.ItemTypes import org.spongepowered.api.item.inventory.ItemStack import org.spongepowered.api.item.inventory.ItemStackSnapshot import org.spongepowered.api.item.inventory.equipment.EquipmentType import java.util.Optional class LanternItemStackBuilder : AbstractDataBuilder<ItemStack>(ItemStack::class.java, 1), ItemStack.Builder { private var itemStack: LanternItemStack? = null private var itemTypeSet: Boolean = false private fun itemStack(itemType: ItemType?): LanternItemStack { var itemStack = this.itemStack if (itemType != null) { if (itemStack == null) { itemStack = LanternItemStack(itemType) } else if (itemStack.type !== itemType) { val oldItemStack = itemStack itemStack = LanternItemStack(itemType) itemStack.quantity = oldItemStack.quantity itemStack.copyFromNoEvents(oldItemStack, MergeFunction.REPLACEMENT_PREFERRED) } this.itemTypeSet = true } else if (itemStack == null) { itemStack = LanternItemStack(ItemTypes.APPLE.get()) } this.itemStack = itemStack return itemStack } override fun itemType(itemType: ItemType) = apply { itemStack(itemType) } override fun getCurrentItem(): ItemType = if (this.itemTypeSet) itemStack(null).type else ItemTypes.AIR.get() override fun quantity(quantity: Int) = apply { itemStack(null).quantity = quantity } override fun add(itemData: DataManipulator) = apply { val itemStack = itemStack(null) itemData.values.forEach { itemStack.offerFastNoEvents(it) } } override fun add(value: Value<*>) = apply { itemStack(null).offerFastNoEvents(value) } override fun <V : Any> add(key: Key<out Value<V>>, value: V) = apply { itemStack(null).offerFastNoEvents(key, value) } override fun attributeModifier(attributeType: AttributeType, modifier: AttributeModifier, equipmentType: EquipmentType): ItemStack.Builder { TODO("Not yet implemented") } override fun from(value: ItemStack) = apply { this.itemStack = value.copy() as LanternItemStack } override fun fromSnapshot(snapshot: ItemStackSnapshot) = apply { from((snapshot as LanternItemStackSnapshot).asStack()) } override fun fromItemStack(itemStack: ItemStack) = apply { from(itemStack) } override fun fromContainer(container: DataView): ItemStack.Builder { TODO() } override fun fromBlockSnapshot(blockSnapshot: BlockSnapshot): ItemStack.Builder { TODO() } override fun reset() = apply { this.itemTypeSet = false this.itemStack = null } override fun build(): ItemStack { check(this.itemTypeSet) { "The item type must be set" } return itemStack(null).copy() } override fun buildContent(container: DataView): Optional<ItemStack> { TODO() } }
mit
b38fe71e3fcaac870ee3212e2c0eba05
33.867257
144
0.696447
4.533947
false
false
false
false
LISTEN-moe/android-app
app/src/main/kotlin/me/echeung/moemoekyun/ui/activity/MainActivity.kt
1
12526
package me.echeung.moemoekyun.ui.activity import android.content.Intent import android.media.AudioManager import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.annotation.NonNull import androidx.appcompat.widget.ActionMenuView import androidx.databinding.DataBindingUtil import androidx.databinding.Observable import com.google.android.material.bottomsheet.BottomSheetBehavior import me.echeung.moemoekyun.App import me.echeung.moemoekyun.BR import me.echeung.moemoekyun.R import me.echeung.moemoekyun.client.RadioClient import me.echeung.moemoekyun.client.api.Library import me.echeung.moemoekyun.client.auth.AuthUtil import me.echeung.moemoekyun.databinding.ActivityMainBinding import me.echeung.moemoekyun.databinding.RadioControlsBinding import me.echeung.moemoekyun.service.RadioService import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil.broadcastAuthEvent import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil.handleAuthActivityResult import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil.showLoginActivity import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil.showLogoutDialog import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil.showRegisterActivity import me.echeung.moemoekyun.ui.base.BaseActivity import me.echeung.moemoekyun.ui.dialog.SleepTimerDialog import me.echeung.moemoekyun.ui.view.PlayPauseView import me.echeung.moemoekyun.util.PreferenceUtil import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.ext.openUrl import me.echeung.moemoekyun.util.ext.startActivity import me.echeung.moemoekyun.util.system.NetworkUtil import me.echeung.moemoekyun.viewmodel.RadioViewModel import me.echeung.moemoekyun.viewmodel.UserViewModel import org.koin.android.ext.android.inject class MainActivity : BaseActivity() { private val radioViewModel: RadioViewModel by inject() private val userViewModel: UserViewModel by inject() private val radioClient: RadioClient by inject() private val authUtil: AuthUtil by inject() private val preferenceUtil: PreferenceUtil by inject() private val songActionsUtil: SongActionsUtil by inject() private lateinit var binding: ActivityMainBinding private var searchMenu: ActionMenuView? = null private var nowPlayingSheet: BottomSheetBehavior<*>? = null private var nowPlayingSheetMenu: Menu? = null private var playPauseCallback: Observable.OnPropertyChangedCallback? = null private var playPauseView: PlayPauseView? = null private var miniPlayPauseView: PlayPauseView? = null override fun onCreate(savedInstanceState: Bundle?) { // Replace splash screen theme setTheme(R.style.Theme_App) super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.vm = radioViewModel binding.btnRetry.setOnClickListener { retry() } binding.btnLogin.setOnClickListener { showLoginActivity() } binding.btnRegister.setOnClickListener { showRegisterActivity() } // Check network connectivity if (!NetworkUtil.isNetworkAvailable(this)) { return } // Sets audio type to media (volume button control) volumeControlStream = AudioManager.STREAM_MUSIC initAppbar() initNowPlaying() initSecondaryMenus() // Invalidate token if needed val isAuthed = authUtil.checkAuthTokenValidity() radioViewModel.isAuthed = isAuthed if (!isAuthed) { userViewModel.reset() } } override fun onDestroy() { // Kill service/notification if killing activity and not playing val service = App.service if (service != null && !service.isPlaying) { sendBroadcast( Intent(RadioService.STOP).apply { setPackage(packageName) }, ) } binding.unbind() if (playPauseCallback != null) { radioViewModel.removeOnPropertyChangedCallback(playPauseCallback!!) } super.onDestroy() } override fun onBackPressed() { // Collapse now playing if (nowPlayingSheet?.state == BottomSheetBehavior.STATE_EXPANDED) { nowPlayingSheet?.state = BottomSheetBehavior.STATE_COLLAPSED return } super.onBackPressed() } /** * For retry button in no internet view. */ private fun retry() { if (NetworkUtil.isNetworkAvailable(this)) { recreate() sendBroadcast( Intent(RadioService.UPDATE).apply { setPackage(packageName) }, ) } } override fun initAppbar() { super.initAppbar() supportActionBar?.apply { setDisplayHomeAsUpEnabled(false) setDisplayShowTitleEnabled(false) } searchMenu = appbar?.findViewById(R.id.appbar_search_menu) searchMenu?.setOnMenuItemClickListener { menuItem -> onOptionsItemSelected(menuItem) } } private fun initNowPlaying() { nowPlayingSheet = BottomSheetBehavior.from(binding.nowPlaying.nowPlayingSheet) // Restore previous expanded state if (preferenceUtil.isNowPlayingExpanded().get()) { nowPlayingSheet?.setState(BottomSheetBehavior.STATE_EXPANDED) } else { radioViewModel.miniPlayerAlpha = 1f } nowPlayingSheet?.setBottomSheetCallback( object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(@NonNull bottomSheet: View, newState: Int) { preferenceUtil.isNowPlayingExpanded().set(newState == BottomSheetBehavior.STATE_EXPANDED) } override fun onSlide(@NonNull bottomSheet: View, slideOffset: Float) { // Shows/hides mini player [email protected] = 1f - slideOffset } }, ) // Expand when tap mini player binding.nowPlaying.miniPlayer.root.setOnClickListener { nowPlayingSheet!!.setState(BottomSheetBehavior.STATE_EXPANDED) } // Collapse button / when toolbar is tapped binding.nowPlaying.collapseBtn.setOnClickListener { nowPlayingSheet!!.setState(BottomSheetBehavior.STATE_COLLAPSED) } binding.nowPlaying.toolbar.setOnClickListener { nowPlayingSheet!!.setState(BottomSheetBehavior.STATE_COLLAPSED) } initPlayPause() val radioControls: RadioControlsBinding = binding.nowPlaying.fullPlayer.radioControls radioControls.historyBtn.setOnClickListener { showHistory() } radioControls.favoriteBtn.setOnClickListener { favorite() } // Press song info to show history val vCurrentSong = binding.nowPlaying.fullPlayer.radioSongs.currentSong vCurrentSong.setOnClickListener { if (radioViewModel.currentSong != null) { showHistory() } } // Long press song info to copy to clipboard vCurrentSong.setOnLongClickListener { songActionsUtil.copyToClipboard(this, radioViewModel.currentSong) true } // Long press album art to open in browser binding.nowPlaying.fullPlayer.radioAlbumArt.root.setOnLongClickListener { val currentSong = radioViewModel.currentSong ?: return@setOnLongClickListener false val albumArtUrl = currentSong.albumArtUrl ?: return@setOnLongClickListener false openUrl(albumArtUrl) true } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) updateMenuOptions(menu) return true } override fun invalidateOptionsMenu() { super.invalidateOptionsMenu() nowPlayingSheetMenu?.let { updateMenuOptions(it) } } private fun initSecondaryMenus() { // Duplicate menu in now playing sheet val toolbar = binding.nowPlaying.toolbar toolbar.inflateMenu(R.menu.menu_main) nowPlayingSheetMenu = toolbar.menu toolbar.setOnMenuItemClickListener { this.onOptionsItemSelected(it) } updateMenuOptions(nowPlayingSheetMenu!!) // Secondary menu with search menuInflater.inflate(R.menu.menu_search, searchMenu?.menu) } private fun updateMenuOptions(menu: Menu) { // Toggle visibility of logout option based on authentication status menu.findItem(R.id.action_logout).isVisible = authUtil.isAuthenticated // Pre-check the library mode when (preferenceUtil.libraryMode().get()) { Library.JPOP -> menu.findItem(R.id.action_library_jpop).isChecked = true Library.KPOP -> menu.findItem(R.id.action_library_kpop).isChecked = true } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_library_jpop -> { item.isChecked = true setLibraryMode(Library.JPOP) return true } R.id.action_library_kpop -> { item.isChecked = true setLibraryMode(Library.KPOP) return true } R.id.action_logout -> { showLogoutDialog() return true } R.id.action_search -> { startActivity<SearchActivity>() return true } R.id.action_settings -> { startActivity<SettingsActivity>() return true } R.id.action_about -> { startActivity<AboutActivity>() return true } R.id.action_sleep_timer -> { SleepTimerDialog(this) return true } else -> return super.onOptionsItemSelected(item) } } // Auth stuff // ============================================================================================= override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { handleAuthActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data) } // Now playing stuff // ============================================================================================= private fun initPlayPause() { val playPauseBtn = binding.nowPlaying.fullPlayer.radioControls.playPauseBtn playPauseBtn.setOnClickListener { togglePlayPause() } playPauseView = PlayPauseView(this, playPauseBtn) val miniPlayPauseBtn = binding.nowPlaying.miniPlayer.miniPlayPause miniPlayPauseBtn.setOnClickListener { togglePlayPause() } miniPlayPauseView = PlayPauseView(this, miniPlayPauseBtn) setPlayPauseDrawable() playPauseCallback = object : Observable.OnPropertyChangedCallback() { override fun onPropertyChanged(sender: Observable, propertyId: Int) { if (propertyId == BR.playing) { setPlayPauseDrawable() } } } radioViewModel.addOnPropertyChangedCallback(playPauseCallback!!) } private fun setPlayPauseDrawable() { val isPlaying = radioViewModel.isPlaying playPauseView?.toggle(isPlaying) miniPlayPauseView?.toggle(isPlaying) } private fun togglePlayPause() { sendBroadcast( Intent(RadioService.PLAY_PAUSE).apply { setPackage(packageName) }, ) } private fun favorite() { if (!authUtil.isAuthenticated) { showLoginActivity(AuthActivityUtil.LOGIN_FAVORITE_REQUEST) return } sendBroadcast( Intent(RadioService.TOGGLE_FAVORITE).apply { setPackage(packageName) }, ) } private fun showHistory() { songActionsUtil.showSongsDialog(this, getString(R.string.last_played), radioViewModel.history) } private fun setLibraryMode(libraryMode: Library) { radioClient.changeLibrary(libraryMode) broadcastAuthEvent() invalidateOptionsMenu() } }
mit
bac98d9bbcbc8a45a78623d1e390b2a8
33.506887
128
0.653601
5.289696
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/search/ResultViewHolder.kt
1
1702
package net.simonvt.cathode.ui.search import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView.ViewHolder import net.simonvt.cathode.R.id import net.simonvt.cathode.api.enumeration.ItemType import net.simonvt.cathode.common.widget.CircularProgressIndicator import net.simonvt.cathode.common.widget.RemoteImageView import net.simonvt.cathode.common.widget.find import net.simonvt.cathode.images.ImageType import net.simonvt.cathode.images.ImageUri import net.simonvt.cathode.search.SearchHandler.SearchItem import net.simonvt.cathode.ui.search.SearchAdapter.OnResultClickListener class ResultViewHolder(view: View, listener: OnResultClickListener) : ViewHolder(view) { val poster: RemoteImageView = view.find(id.poster) val title: TextView = view.find(id.title) val overview: TextView = view.find(id.overview) val rating: CircularProgressIndicator = view.find(id.rating) var item: SearchItem? = null init { view.setOnClickListener { val item = this.item if (item != null) { if (item.itemType == ItemType.SHOW) { listener.onShowClicked(item.itemId, item.title, item.overview) } else { listener.onMovieClicked(item.itemId, item.title, item.overview) } } } } fun update(item: SearchItem) { this.item = item val posterUri = when (item.itemType) { ItemType.SHOW -> ImageUri.create(ImageUri.ITEM_SHOW, ImageType.POSTER, item.itemId) else -> ImageUri.create(ImageUri.ITEM_MOVIE, ImageType.POSTER, item.itemId) } poster.setImage(posterUri) title.text = item.title overview.text = item.overview rating.setValue(item.rating) } }
apache-2.0
f325c0e4e91b7f04f6a8322e7145b255
32.372549
89
0.741481
3.885845
false
false
false
false
RoverPlatform/rover-android
location/src/main/kotlin/io/rover/sdk/location/GoogleGeofenceService.kt
1
13378
package io.rover.sdk.location import android.Manifest import android.annotation.SuppressLint import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofenceStatusCodes import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.GeofencingEvent import com.google.android.gms.location.GeofencingRequest import io.rover.sdk.core.Rover import io.rover.sdk.core.data.domain.Location import io.rover.sdk.core.data.graphql.getStringIterable import io.rover.sdk.core.logging.log import io.rover.sdk.core.permissions.PermissionsNotifierInterface import io.rover.sdk.core.platform.LocalStorage import io.rover.sdk.core.platform.whenNotNull import io.rover.sdk.core.streams.PublishSubject import io.rover.sdk.core.streams.Publishers import io.rover.sdk.core.streams.Scheduler import io.rover.sdk.core.streams.blockForResult import io.rover.sdk.core.streams.doOnNext import io.rover.sdk.core.streams.map import io.rover.sdk.core.streams.observeOn import io.rover.sdk.core.streams.share import io.rover.sdk.core.streams.subscribe import io.rover.sdk.location.domain.asLocation import io.rover.sdk.location.sync.GeofencesRepository import org.json.JSONArray import org.reactivestreams.Publisher /** * Monitors for Geofence events using the Google Location Geofence API. * * Monitors the list of appropriate geofences to subscribe to as defined by the Rover API * via the [RegionObserver] interface. * * Google documentation: https://developer.android.com/training/location/geofencing.html */ class GoogleGeofenceService( private val applicationContext: Context, private val localStorage: LocalStorage, private val geofencingClient: GeofencingClient, mainScheduler: Scheduler, ioScheduler: Scheduler, private val locationReportingService: LocationReportingServiceInterface, permissionsNotifier: PermissionsNotifierInterface, private val geofencesRepository: GeofencesRepository, googleBackgroundLocationService: GoogleBackgroundLocationServiceInterface, private val geofenceMonitorLimit: Int = 50 ) : GoogleGeofenceServiceInterface { private val store = localStorage.getKeyValueStorageFor(STORAGE_CONTEXT_IDENTIFIER) private val geofenceSubject = PublishSubject<GeofenceServiceInterface.GeofenceEvent>() override val geofenceEvents: Publisher<GeofenceServiceInterface.GeofenceEvent> = geofenceSubject .observeOn(mainScheduler) .share() override val currentGeofences: List<io.rover.sdk.location.domain.Geofence> get() = enclosingGeofences override val enclosingGeofences: MutableList<io.rover.sdk.location.domain.Geofence> = mutableListOf() override fun newGoogleGeofenceEvent(geofencingEvent: GeofencingEvent) { // have to do processing here because we need to know what the regions are. if (!geofencingEvent.hasError()) { val triggeringGeofences = geofencingEvent.triggeringGeofences if (triggeringGeofences == null) { log.w("Unable to obtain list of geofences that triggered a GeofencingEvent from Google.") return } val transitioningGeofences = triggeringGeofences.mapNotNull { fence -> val geofence = geofencesRepository.geofenceByIdentifier( fence.requestId ).blockForResult().firstOrNull() if (geofence == null) { val verb = when (geofencingEvent.geofenceTransition) { Geofence.GEOFENCE_TRANSITION_ENTER -> "enter" Geofence.GEOFENCE_TRANSITION_EXIT -> "exit" else -> "unknown (${geofencingEvent.geofenceTransition})" } log.w("Received an $verb event for Geofence with request-id/identifier '${fence.requestId}', but not currently tracking that one. Ignoring.") } geofence } transitioningGeofences.forEach { geofence -> when (geofencingEvent.geofenceTransition) { Geofence.GEOFENCE_TRANSITION_ENTER -> { locationReportingService.trackEnterGeofence( geofence ) enclosingGeofences.add(geofence) geofenceSubject.onNext( GeofenceServiceInterface.GeofenceEvent( false, geofence ) ) } Geofence.GEOFENCE_TRANSITION_EXIT -> { locationReportingService.trackExitGeofence( geofence ) enclosingGeofences.remove(geofence) geofenceSubject.onNext( GeofenceServiceInterface.GeofenceEvent( true, geofence ) ) } } } } else { val errorMessage = GeofenceStatusCodes.getStatusCodeString( geofencingEvent.errorCode ) log.w("Unable to capture Geofence message because: $errorMessage") } } @SuppressLint("MissingPermission") private fun startMonitoringGeofences(updatedFencesList: List<io.rover.sdk.location.domain.Geofence>) { log.v("Updating geofences.") // the fences we ultimately want to be monitoring once the following operation is complete. val targetFenceIds = updatedFencesList.map { it.identifier }.toSet() val alreadyInGoogle = if (activeFences == null || activeFences?.isEmpty() == true) { // if I don't have any persisted "previously set" fences, then I should do a full // clear from our pending intent, because I don't know what fences could be left from a // prior SDK that wasn't tracking the state. geofencingClient.removeGeofences( pendingIntentForReceiverService() ) emptySet() } else { // remove any geofences that are active but no longer in our list of target geofence ids. val staleGeofences = (activeFences!! - targetFenceIds).toList() if (staleGeofences.isNotEmpty()) { geofencingClient.removeGeofences( staleGeofences ) } else { log.v("No removals from currently monitored geofences on Google needed.") } // now google's state is that it has all target fences that were ALREADY being monitored. activeFences!!.intersect(targetFenceIds) } val toAdd = targetFenceIds - alreadyInGoogle val fencesByIdentifier = updatedFencesList.associateBy { it.identifier } val geofences = toAdd.map { geofenceIdentifier -> val geofence = fencesByIdentifier[geofenceIdentifier] ?: throw RuntimeException( "Logic error in Rover's GoogleGeofenceService, identifier missing in indexed geofences mapping." ) Geofence.Builder() .setRequestId(geofence.identifier) .setCircularRegion( geofence.center.latitude, geofence.center.longitude, geofence.radius.toFloat() ) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build() } if (geofences.isNotEmpty()) { val request = GeofencingRequest.Builder() .addGeofences(geofences) .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER or GeofencingRequest.INITIAL_TRIGGER_DWELL) .build() geofencingClient.addGeofences(request, pendingIntentForReceiverService()).addOnFailureListener { error -> log.w("Unable to configure Rover Geofence receiver because: $error") }.addOnSuccessListener { log.v("Now monitoring ${geofences.count()} Rover geofences.") } } else { log.v("No additions to currently monitored geofences on Google needed.") } activeFences = targetFenceIds } /** * A Pending Intent for activating the receiver service, [GeofenceBroadcastReceiver]. */ private fun pendingIntentForReceiverService(): PendingIntent { return PendingIntent.getBroadcast( applicationContext, 0, Intent(applicationContext, GeofenceBroadcastReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { FLAG_IMMUTABLE } else { 0 } ) } /** * A list of the IDs of all the Geofences that have already been pushed into Google, by * requestId. */ private var activeFences: Set<String>? = try { val currentFencesJson = store[ACTIVE_FENCES_KEY] when (currentFencesJson) { null -> null else -> JSONArray(currentFencesJson).getStringIterable().toSet() } } catch (throwable: Throwable) { log.w("Corrupted list of active geofences, ignoring and starting fresh. Cause: ${throwable.message}") null } set(value) { field = value store[ACTIVE_FENCES_KEY] = value.whenNotNull { JSONArray(it.toList()).toString() } } init { Publishers.combineLatest( // observeOn(mainScheduler) used on each because combineLatest() is not thread safe. permissionsNotifier.notifyForPermission(Manifest.permission.ACCESS_FINE_LOCATION).observeOn(mainScheduler).doOnNext { log.v("Permission obtained.") }, geofencesRepository.allGeofences().observeOn(mainScheduler).doOnNext { log.v("Full geofences list obtained from sync.") }, googleBackgroundLocationService.locationUpdates.observeOn(mainScheduler).doOnNext { log.v("Location update obtained so that distant geofences can be filtered out.") } ) { permission, fences, location -> Triple(permission, fences, location) }.observeOn(ioScheduler).map { (_, fences, location) -> log.v("Determining $geofenceMonitorLimit closest geofences for monitoring.") fences.iterator().use { it.asSequence().sortedBy { it.center.asLocation().distanceTo(location) }.take(geofenceMonitorLimit).toList() } }.observeOn(mainScheduler).subscribe { fences -> log.v("Got location permission, geofences, and current location. Ready to start monitoring for ${fences.count()} geofence(s).") startMonitoringGeofences(fences) } } companion object { private const val ACTIVE_FENCES_KEY = "active-fences" private const val STORAGE_CONTEXT_IDENTIFIER = "google-geofence-service" } } class GeofenceBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val rover = Rover.shared if (rover == null) { log.e("Received a geofence result from Google, but Rover is not initialized. Ignoring.") return } val geofenceService = rover.resolve(GoogleGeofenceServiceInterface::class.java) if (geofenceService == null) { log.e("Received a geofence result from Google, but GoogleGeofenceServiceInterface is not registered in the Rover container. Ensure LocationAssembler() is in Rover.initialize(). Ignoring.") return } val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent == null) { log.w("Unable to hydrate a GeofencingEvent from an incoming broadcast receive intent.") return } geofenceService.newGoogleGeofenceEvent( geofencingEvent ) } } /** * Returns distance in meters. * * Assumes coordinates on Planet Earth. */ fun Location.distanceTo(other: Location): Double { val earthRadius = 6371000 val lat1 = degreesToRadians(coordinate.latitude) val lon1 = degreesToRadians(coordinate.longitude) val lat2 = degreesToRadians(other.coordinate.latitude) val lon2 = degreesToRadians(other.coordinate.longitude) return earthRadius * ahaversine( haversine(lat2 - lat1) + Math.cos(lat1) * Math.cos(lat2) * haversine(lon2 - lon1) ) } private fun haversine(value: Double): Double { return (1 - Math.cos(value)) / 2 } private fun ahaversine(value: Double): Double { return 2 * Math.asin(Math.sqrt(value)) } private fun degreesToRadians(degrees: Double): Double { return (degrees / 360.0) * 2 * Math.PI }
apache-2.0
fc9f9aab41d8c74e101ae9162fd4592a
42.576547
200
0.64038
5.108057
false
false
false
false
jeffgbutler/mybatis-qbe
src/test/kotlin/examples/kotlin/mybatis3/joins/OrderDetailDynamicSQLSupport.kt
1
1460
/* * Copyright 2016-2021 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 examples.kotlin.mybatis3.joins import org.mybatis.dynamic.sql.SqlTable import org.mybatis.dynamic.sql.util.kotlin.elements.column import java.sql.JDBCType object OrderDetailDynamicSQLSupport { val orderDetail = OrderDetail() val orderId = orderDetail.orderId val lineNumber = orderDetail.lineNumber val description = orderDetail.description val quantity = orderDetail.quantity class OrderDetail : SqlTable("OrderDetail") { val orderId = column<Int>(name = "order_id", jdbcType = JDBCType.INTEGER) val lineNumber = column<Int>(name = "line_number", jdbcType = JDBCType.INTEGER) val description = column<String>(name = "description", jdbcType = JDBCType.VARCHAR) val quantity = column<Int>(name = "quantity", jdbcType = JDBCType.INTEGER) } }
apache-2.0
8c8d969f41d324105b05588fb51ae08b
40.714286
91
0.719863
4.183381
false
false
false
false
prt2121/json2pojo
src/main/kotlin/com/prt2121/pojo/MainController.kt
1
4530
package com.prt2121.pojo import com.prt2121.pojo.rx.JavaFxObservable import com.sun.codemodel.JCodeModel import javafx.application.Platform import javafx.fxml.FXML import javafx.fxml.Initializable import javafx.scene.control.Button import javafx.scene.control.ProgressIndicator import javafx.scene.control.TextArea import javafx.scene.control.TextField import javafx.scene.input.MouseEvent import org.jsonschema2pojo.* import org.jsonschema2pojo.rules.RuleFactory import java.io.* import java.net.URL import java.util.* import java.util.concurrent.TimeUnit /** * Created by pt2121 on 11/7/15. */ public class MainController : Initializable { @FXML var jsonTextArea: TextArea? = null @FXML var packageNameField: TextField? = null @FXML var generateButton: Button? = null @FXML var classNameField: TextField? = null @FXML var progressIndicator: ProgressIndicator? = null override fun initialize(url: URL?, bundle: ResourceBundle?) { // for logging after packaging System.setOut(PrintStream(object : OutputStream() { override fun write(b: Int) { appendText(b.toChar().toString()) } }, true)) val jsonObservable = JavaFxObservable .fromObservableValue(jsonTextArea!!.textProperty()) .throttleLast(1, TimeUnit.SECONDS) val classNameObservable = JavaFxObservable .fromObservableValue(classNameField!!.textProperty()) .throttleLast(1, TimeUnit.SECONDS) val packageNameObservable = JavaFxObservable .fromObservableValue(packageNameField!!.textProperty()) .throttleLast(1, TimeUnit.SECONDS) val clicks = JavaFxObservable .fromNodeEvents(generateButton!!, MouseEvent.MOUSE_CLICKED) .throttleLast(1, TimeUnit.SECONDS) rx.Observable.combineLatest(jsonObservable, packageNameObservable, classNameObservable) { json, packageName, className -> Input(json, packageName, className) }.doOnNext { Platform.runLater { generateButton?.setDisable(it.json.isBlank() || it.className.isBlank()) } }.subscribe() clicks.doOnNext { Platform.runLater { progressIndicator!!.isVisible = true } }.map { val dir = File("json2pojoOutput") val success = if(dir.exists()) dir.deleteRecursively() else true dir to success }.filter { it.second }.map { it.first }.map { dir -> dir.mkdir() val packageName = packageNameField?.textProperty()?.value ?: "" val input = Input(jsonTextArea!!.textProperty().value, packageName, classNameField!!.textProperty().value) val inputFile = createInputFile(input.json) val codeModel = JCodeModel() val mapper = SchemaMapper(RuleFactory(object : DefaultGenerationConfig() { public override fun getSourceType(): SourceType { return SourceType.JSON } }, GsonAnnotator(), SchemaStore()), SchemaGenerator()) mapper.generate(codeModel, input.className, input.packageName, inputFile.toURI().toURL()) codeModel.build(dir) inputFile.delete() println("\n") dir }.subscribe({ file -> println("\n") println(file.name) println(file.absolutePath) Platform.runLater { progressIndicator!!.isVisible = false } }, { t -> println(t.message) Platform.runLater { progressIndicator!!.isVisible = false } }, { Platform.runLater { progressIndicator!!.isVisible = false } }) } // https://github.com/joelittlejohn/jsonschema2pojo/issues/255 private fun createInputFile(json: String): File { val inputFile = File("json2pojoOutput/tmp.json") inputFile.createNewFile() val out = PrintWriter(inputFile) out.print(json) out.close() return inputFile } class Input(val json: String, val packageName: String, val className: String) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Input if (json != other.json) return false if (packageName != other.packageName) return false if (className != other.className) return false return true } override fun hashCode(): Int { var result = json.hashCode() result += 31 * result + packageName.hashCode() result += 31 * result + className.hashCode() return result } } fun appendText(str: String) { Platform.runLater { jsonTextArea!!.appendText(str) } } }
apache-2.0
eacc2eba4194876de4e809c559c45d3a
29.614865
112
0.675717
4.480712
false
false
false
false
jamieadkins95/Roach
app/src/main/java/com/jamieadkins/gwent/update/UpdateService.kt
1
3798
package com.jamieadkins.gwent.update import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import com.jamieadkins.gwent.R import com.jamieadkins.gwent.base.GwentApplication.Companion.coreComponent import javax.inject.Inject class UpdateService : Service(), UpdateContract.View { @Inject lateinit var presenter: UpdateContract.Presenter override fun onBind(intent: Intent): IBinder? { // We don't provide binding, so return null return null } override fun onCreate() { DaggerUpdateComponent.builder() .core(coreComponent) .service(this) .build() .inject(this) super.onCreate() setupNotificationChannel() NotificationManagerCompat.from(this).cancel(COMPLETE_NOTIFICATION_ID) val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(this, R.color.gwentGreen)) .setContentTitle(getString(R.string.update_notification_progress_title)) .setProgress(0, 0, true) .setPriority(NotificationCompat.PRIORITY_LOW) .build() startForeground(IN_PROGRESS_NOTIFICATION_ID, notification) presenter.onAttach() } override fun onDestroy() { presenter.onDetach() super.onDestroy() } override fun finish() { val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(this, R.color.gwentGreen)) .setContentTitle(getString(R.string.update_notification_complete_title)) .setPriority(NotificationCompat.PRIORITY_LOW) .build() NotificationManagerCompat.from(this).notify(COMPLETE_NOTIFICATION_ID, notification) stopSelf() } override fun showError() { val retryIntent = Intent(this, UpdateService::class.java) val retryPendingIntent: PendingIntent = PendingIntent.getService(this, 0, retryIntent, 0) val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(this, R.color.gwentGreen)) .setContentTitle(getString(R.string.update_notification_error_title)) .addAction(R.drawable.ic_notification, getString(R.string.retry), retryPendingIntent) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_LOW) .build() NotificationManagerCompat.from(this).notify(COMPLETE_NOTIFICATION_ID, notification) stopSelf() } private fun setupNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, getString(R.string.update_notification_channel_name), NotificationManager.IMPORTANCE_LOW ) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } companion object { private const val CHANNEL_ID = "com.jamieadkins.gwent.update.notifications" private const val IN_PROGRESS_NOTIFICATION_ID = 31413 private const val COMPLETE_NOTIFICATION_ID = 31414 } }
apache-2.0
9a83d3f2a679980586675fb1b210333a
35.171429
107
0.685624
4.913325
false
false
false
false
verhoevenv/kotlin-koans
src/i_introduction/_7_Nullable_Types/NullableTypes.kt
1
1111
package i_introduction._7_Nullable_Types import util.TODO import util.doc7 fun test() { val s: String = "this variable cannot store null references" val q: String? = null if (q != null) q.length // you have to check to dereference val i: Int? = q?.length // null val j: Int = q?.length ?: 0 // 0 } fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO( """ Task 7. Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression. Declarations of Client, PersonalInfo and Mailer are given below. """, documentation = doc7(), references = { JavaCode7().sendMessageToClient(client, message, mailer) } ) fun sendMessageToClient( client: Client?, message: String?, mailer: Mailer ) { val email: String? = client?.personalInfo?.email if (email == null || message == null) return mailer.sendMessage(email, message) } class Client (val personalInfo: PersonalInfo?) class PersonalInfo (val email: String?) interface Mailer { fun sendMessage(email: String, message: String) }
mit
c2b72272904c1dcc03c3e65360e312a9
28.236842
88
0.666067
3.996403
false
false
false
false
mgolokhov/dodroid
app/src/main/java/doit/study/droid/quiz/mappers/Extentions.kt
1
611
package doit.study.droid.quiz.mappers import doit.study.droid.data.local.entity.Question import doit.study.droid.quiz.AnswerVariantItem import doit.study.droid.quiz.QuizItem fun Question.toQuizItem(tagName: String): QuizItem { val answerVariants = right.map { AnswerVariantItem(text = it, isRight = true) } + wrong.map { AnswerVariantItem(text = it, isRight = false) } return QuizItem( questionId = id, questionText = text, answerVariants = answerVariants.toMutableList(), title = tagName, docLink = docLink ) }
mit
11bd0f363943c3af2769b3b26910dcee
31.157895
72
0.656301
4.073333
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/screens/playlist/dialog/M3uPlaylistDialog.kt
1
5914
package com.simplecity.amp_library.ui.screens.playlist.dialog import android.app.Dialog import android.app.ProgressDialog import android.content.Context import android.os.Bundle import android.os.Environment import android.support.v4.app.DialogFragment import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.util.Log import android.widget.Toast import com.simplecity.amp_library.R import com.simplecity.amp_library.data.SongsRepository import com.simplecity.amp_library.di.app.activity.fragment.FragmentModule import com.simplecity.amp_library.di.app.activity.fragment.FragmentScope import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.model.Song import com.simplecity.amp_library.utils.LogUtils import dagger.Binds import dagger.Module import dagger.android.support.AndroidSupportInjection import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.functions.Function import io.reactivex.schedulers.Schedulers import java.io.File import java.io.FileWriter import java.io.IOException import javax.inject.Inject import javax.inject.Named class M3uPlaylistDialog : DialogFragment() { private lateinit var playlist: Playlist @Inject lateinit var songsRepository: SongsRepository private var disposable: Disposable? = null override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { playlist = arguments!!.getSerializable(ARG_PLAYLIST) as Playlist val progressDialog = ProgressDialog(context) progressDialog.isIndeterminate = true progressDialog.setTitle(R.string.saving_playlist) disposable = songsRepository.getSongs(playlist) .first(emptyList()) .map(Function<List<Song>, File> { songs -> if (!songs.isEmpty()) { var playlistFile: File? = null if (Environment.getExternalStorageDirectory().canWrite()) { val root = File(Environment.getExternalStorageDirectory(), "Playlists/Export/") if (!root.exists()) { root.mkdirs() } val noMedia = File(root, ".nomedia") if (!noMedia.exists()) { try { noMedia.createNewFile() } catch (e: IOException) { e.printStackTrace() } } val name = playlist.name.replace("[^a-zA-Z0-9.-]".toRegex(), "_") playlistFile = File(root, "$name.m3u") var i = 0 while (playlistFile!!.exists()) { i++ playlistFile = File(root, "$name$i.m3u") } try { val fileWriter = FileWriter(playlistFile) val body = StringBuilder() body.append("#EXTM3U\n") for (song in songs) { body.append("#EXTINF:") .append(song.duration / 1000) .append(",") .append(song.name) .append(" - ") .append(song.artistName) .append("\n") //Todo: Use relative paths instead of absolute .append(song.path) .append("\n") } fileWriter.append(body) fileWriter.flush() fileWriter.close() } catch (e: IOException) { Log.e(TAG, "Failed to write file: $e") } } return@Function playlistFile } null }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { file -> progressDialog.dismiss() if (file != null) { Toast.makeText(context, String.format(context!!.getString(R.string.playlist_saved), file.path), Toast.LENGTH_LONG).show() } else { Toast.makeText(context, R.string.playlist_save_failed, Toast.LENGTH_SHORT).show() } }, { error -> LogUtils.logException(TAG, "Error saving m3u playlist", error) } ) return progressDialog } override fun onDestroyView() { disposable!!.dispose() super.onDestroyView() } fun show(fragmentManager: FragmentManager) { show(fragmentManager, TAG) } companion object { private const val TAG = "M3uPlaylistDialog" private const val ARG_PLAYLIST = "playlist" fun newInstance(playlist: Playlist): M3uPlaylistDialog { val args = Bundle() args.putSerializable(ARG_PLAYLIST, playlist) val fragment = M3uPlaylistDialog() fragment.arguments = args return fragment } } } @Module(includes = arrayOf(FragmentModule::class)) abstract class M3uDialogFragmentModule { @Binds @Named(FragmentModule.FRAGMENT) @FragmentScope internal abstract fun fragment(m3uPlaylistDialog: M3uPlaylistDialog): Fragment }
gpl-3.0
04f66c5ef86ed94f67db188e416859a0
35.067073
145
0.54092
5.381256
false
false
false
false
Ray-Eldath/Avalon
src/main/kotlin/avalon/tool/pool/AvalonPluginPool.kt
1
1623
package avalon.tool.pool import avalon.tool.pool.Constants.Address.DATA_PATH import avalon.util.Plugin import avalon.util.PluginInfo import org.json.JSONObject import org.json.JSONTokener import org.slf4j.LoggerFactory import java.io.File import java.net.URL import java.net.URLClassLoader import java.nio.file.Files import java.nio.file.Paths object AvalonPluginPool { private val setting = Paths.get("$DATA_PATH${File.separator}plugin${File.separator}plugins.json") private val infoList = arrayListOf<PluginInfo>() private val pluginList = arrayListOf<Plugin>() private val logger = LoggerFactory.getLogger(AvalonPluginPool.javaClass) private val main = (JSONTokener(Files.newBufferedReader(setting)).nextValue() as JSONObject).getJSONObject("plugins") init { val keySet = main.keySet() keySet.forEach { val o = main.getJSONObject(it) infoList += PluginInfo( it, o.getString("copyright"), o.getString("website"), o.getString("class"), o.getString("file"), o.getBoolean("enable") ) } } fun load() { infoList.filter { it.isEnabled }.forEach { try { load(it) } catch (exception: Exception) { logger.warn("plugin ${it.name} load failed: `${exception.localizedMessage}`") } } } private fun load(info: PluginInfo) { val plugin = URLClassLoader( Array(1) { URL("file:$DATA_PATH${File.separator}plugin${File.separator}${info.fileName}") }, Thread.currentThread().contextClassLoader) .loadClass(info.classString) as Plugin pluginList.add(plugin) plugin.main() } fun getInfoList() = infoList fun getPluginList() = pluginList }
agpl-3.0
5dd1ea5fda3dcf1a98234b3318105687
26.066667
118
0.722736
3.512987
false
false
false
false
renyuneyun/Easer
app/src/main/java/ryey/easer/core/RemotePluginRegistryService.kt
1
11755
/* * Copyright (c) 2016 - 2019 Rui Zhao <[email protected]> * * This file is part of Easer. * * Easer 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. * * Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>. */ package ryey.easer.core import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.* import android.util.Log import androidx.collection.ArrayMap import com.orhanobut.logger.Logger import ryey.easer.core.RemotePluginCommunicationHelper.C import ryey.easer.plugin.operation.Category import ryey.easer.remote_plugin.RemoteOperationData import ryey.easer.remote_plugin.RemotePlugin /** * This service performs the actual communication with remote plugins. It executes in a separate process. * Use [RemotePluginCommunicationHelper] to interact with this service. * * TODO: Support more remote plugin types */ class RemotePluginRegistryService : Service() { private val callbackStore: AsyncHelper.CallbackStore<OnOperationLoadResultCallback> = AsyncHelper.CallbackStore(ArrayMap()) private val mReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Logger.d("[RemotePluginRegistryService][onReceive] %s", intent) if (RemotePlugin.ACTION_RESPONSE_PLUGIN_INFO == intent.action) { val packageName = intent.getStringExtra(RemotePlugin.EXTRA_PACKAGE_NAME)!! val pluginId = intent.getStringExtra(RemotePlugin.EXTRA_PLUGIN_ID)!! val pluginName = intent.getStringExtra(RemotePlugin.EXTRA_PLUGIN_NAME)!! val activityEditData = intent.getStringExtra(RemotePlugin.EXTRA_ACTIVITY_EDIT_DATA) val pluginType = intent.getStringExtra(RemotePlugin.EXTRA_PLUGIN_TYPE) //TODO: More types assert(pluginType == RemotePlugin.TYPE_OPERATION_PLUGIN) val categoryString = intent.getStringExtra(RemotePlugin.OperationPlugin.EXTRA_PLUGIN_CATEGORY) val category = try { if (categoryString != null) Category.valueOf(categoryString) else Category.unknown } catch (e: RuntimeException) { Category.unknown } val info = RemoteOperationPluginInfo(packageName, pluginId, pluginName, activityEditData, category) operationPluginInfos.add(info) } else if (RemotePlugin.OperationPlugin.ACTION_TRIGGER_RESULT == intent.action) { val jobId: ParcelUuid = intent.getParcelableExtra(RemotePlugin.EXTRA_MESSAGE_ID)!! if (!intent.hasExtra(RemotePlugin.OperationPlugin.EXTRA_SUCCESS)) { Logger.w("Remote Operation Plugin load Operation returned WITHOUT success value. Using `false` instead.") } val success: Boolean = intent.getBooleanExtra(RemotePlugin.OperationPlugin.EXTRA_SUCCESS, false) callbackStore.extractCallBack(jobId)?.onResult(success) } } } private val mFilter = IntentFilter() init { mFilter.addAction(RemotePlugin.ACTION_RESPONSE_PLUGIN_INFO) mFilter.addAction(RemotePlugin.OperationPlugin.ACTION_TRIGGER_RESULT) } private val operationPluginInfos = androidx.collection.ArraySet<RemoteOperationPluginInfo>() fun infoForId(id: String): RemoteOperationPluginInfo? { for (info in operationPluginInfos) { if (info.pluginId == id) return info } return null } private val handlerThread = HandlerThread("RemotePluginRegistryService_HandlerThread") private lateinit var incomingHandler: Handler private lateinit var incomingMessenger: Messenger override fun onCreate() { ServiceUtils.startNotification(this) handlerThread.start() incomingHandler = IncomingHandler(this, handlerThread) incomingMessenger = Messenger(incomingHandler) registerReceiver(mReceiver, mFilter) queryPlugins() } override fun onDestroy() { ServiceUtils.stopNotification(this) unregisterReceiver(mReceiver) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { handlerThread.quitSafely() } else { handlerThread.quit() } } override fun onBind(intent: Intent): IBinder { return incomingMessenger.binder } private fun queryPlugins() { operationPluginInfos.clear() val resolved = this.packageManager.queryBroadcastReceivers(Intent(RemotePlugin.TYPE_OPERATION_PLUGIN), 0) Logger.d("queryPlugin size %d", resolved.size) for (ri in resolved) { Logger.d("%s %s", ri, ri.activityInfo.packageName) val intent = Intent(RemotePlugin.ACTION_REQUEST_PLUGIN_INFO) intent.setPackage(ri.activityInfo.packageName) intent.putExtra(RemotePlugin.EXTRA_REPLY_PACKAGE, packageName) sendBroadcast(intent) } } /** * FIXME: Fix possible memory leak using WeakReference? */ internal class IncomingHandler(val service: RemotePluginRegistryService, handlerThread: HandlerThread) : Handler(handlerThread.looper) { override fun handleMessage(message: Message) { Logger.d("[RemotePluginRegistryService][handleMessage] %s", message) val rMessenger = message.replyTo if (message.what == C.MSG_FIND_PLUGIN) { val id = message.data.getString(C.EXTRA_PLUGIN_ID)!! val jobId: ParcelUuid = message.data.getParcelable(C.EXTRA_MESSAGE_ID)!! val reply = Message.obtain() reply.what = C.MSG_FIND_PLUGIN_RESPONSE reply.data.putParcelable(C.EXTRA_MESSAGE_ID, jobId) reply.data.putParcelable(C.EXTRA_PLUGIN_INFO, service.infoForId(id)) rMessenger.send(reply) } else if (message.what == C.MSG_CURRENT_OPERATION_PLUGIN_LIST) { val jobId: ParcelUuid = message.data.getParcelable(C.EXTRA_MESSAGE_ID)!! val reply = Message.obtain() reply.what = C.MSG_CURRENT_OPERATION_PLUGIN_LIST_RESPONSE reply.data.putParcelable(C.EXTRA_MESSAGE_ID, jobId) reply.data.putParcelableArrayList(C.EXTRA_PLUGIN_LIST, ArrayList<RemoteOperationPluginInfo>(service.operationPluginInfos)) rMessenger.send(reply) // } else if (message.what == C.MSG_PARSE_OPERATION_DATA) { // // FIXME: This branch seems not to be necessary nor possible. Remove when adding Event and Condition. // throw IllegalAccessError("This message is not yet in use") // Logger.d("[RemotePluginRegistryService] MSG_PARSE_OPERATION_DATA") // val id = message.data.getString(C.EXTRA_PLUGIN_ID) // val pluginInfo = service.infoForId(id) // val reply = Message.obtain() // reply.what = C.MSG_PARSE_OPERATION_DATA_RESPONSE // if (pluginInfo == null) { // rMessenger.send(reply) // } else { // val data = message.data.getString(C.EXTRA_RAW_DATA) // val receiver: BroadcastReceiver = object : BroadcastReceiver() { // override fun onReceive(p0: Context?, p1: Intent?) { // if (RemotePlugin.ACTION_RESPONSE_PARSE_DATA == p1?.action) { // val operationData: OperationData = p1.getParcelableExtra(RemotePlugin.EXTRA_DATA) // reply.data.putParcelable(C.EXTRA_PLUGIN_DATA, operationData) // rMessenger.send(reply) // service.unregisterReceiver(this) // } // } // } // val uri: Uri = Uri.parse("re_ser://%d".format(receiver.hashCode())) // val filter = IntentFilter() // filter.addAction(RemotePlugin.ACTION_RESPONSE_PARSE_DATA) // filter.addDataScheme(uri.scheme) // filter.addDataAuthority(uri.authority, null) // filter.addDataPath(uri.path, PatternMatcher.PATTERN_LITERAL) // service.registerReceiver(receiver, filter) // val intent = Intent(RemotePlugin.ACTION_REQUEST_PARSE_DATA) //// intent.data = uri // intent.`package` = pluginInfo.packageName // intent.putExtra(RemotePlugin.EXTRA_DATA, data) // service.sendBroadcast(intent) // } } else if (message.what == C.MSG_TRIGGER_OPERATION) { Log.d("RemoPlRegistry", "MSG_TRIGGER_OPERATION") message.data.classLoader = String::class.java.classLoader val id = message.data.getString(C.EXTRA_PLUGIN_ID)!! message.data.classLoader = RemoteOperationData::class.java.classLoader val data: RemoteOperationData = message.data.getParcelable(C.EXTRA_PLUGIN_DATA)!! val jobId: ParcelUuid = message.data.getParcelable(C.EXTRA_MESSAGE_ID)!! service.callbackStore.putCallback(jobId, OnOperationLoadResultCallback(jobId, rMessenger)) val pluginInfo = service.infoForId(id)!! val intent = Intent(RemotePlugin.OperationPlugin.ACTION_TRIGGER) intent.`package` = pluginInfo.packageName intent.putExtra(RemotePlugin.EXTRA_REPLY_PACKAGE, service.packageName) intent.putExtra(RemotePlugin.EXTRA_DATA, data) intent.putExtra(RemotePlugin.EXTRA_MESSAGE_ID, jobId) service.sendBroadcast(intent) } else if (message.what == C.MSG_EDIT_OPERATION_DATA) { val id = message.data.getString(C.EXTRA_PLUGIN_ID)!! val pluginInfo = service.infoForId(id)!! val jobId: ParcelUuid = message.data.getParcelable(C.EXTRA_MESSAGE_ID)!! val bundle = Bundle() bundle.putString(C.EXTRA_PLUGIN_PACKAGE, pluginInfo.packageName) bundle.putString(C.EXTRA_PLUGIN_EDIT_DATA_ACTIVITY, pluginInfo.activityEditData) bundle.putParcelable(C.EXTRA_MESSAGE_ID, jobId) val reply = Message.obtain() reply.what = C.MSG_EDIT_OPERATION_DATA_RESPONSE reply.data = bundle rMessenger.send(reply) } } } private class OnOperationLoadResultCallback(val jobId: ParcelUuid, val messenger: Messenger) { fun onResult(success: Boolean) { val reply = Message.obtain() reply.what = C.MSG_TRIGGER_OPERATION_RESPONSE reply.data.putParcelable(C.EXTRA_MESSAGE_ID, jobId) reply.data.putBoolean(C.EXTRA_SUCCESS, success) messenger.send(reply) } } }
gpl-3.0
9efe55866f852376818410be7ec1da3d
49.450644
138
0.627988
4.690742
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/media/PlaylistManager.kt
1
33870
package org.videolan.vlc.media import android.content.Intent import android.net.Uri import android.support.v4.media.session.PlaybackStateCompat import android.text.TextUtils import android.util.Log import android.widget.Toast import androidx.annotation.MainThread import androidx.lifecycle.MutableLiveData import androidx.localbroadcastmanager.content.LocalBroadcastManager import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.actor import org.videolan.libvlc.FactoryManager import org.videolan.libvlc.MediaPlayer import org.videolan.libvlc.RendererItem import org.videolan.libvlc.interfaces.IMedia import org.videolan.libvlc.interfaces.IMediaFactory import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.resources.* import org.videolan.tools.* import org.videolan.vlc.BuildConfig import org.videolan.vlc.PlaybackService import org.videolan.vlc.R import org.videolan.vlc.gui.video.VideoPlayerActivity import org.videolan.vlc.util.* import org.videolan.vlc.util.FileUtils import java.util.* import kotlin.math.max private const val TAG = "VLC/PlaylistManager" private const val PREVIOUS_LIMIT_DELAY = 5000L private const val PLAYLIST_REPEAT_MODE_KEY = "audio_repeat_mode" //we keep the old string for migration reasons @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class PlaylistManager(val service: PlaybackService) : MediaWrapperList.EventListener, IMedia.EventListener, CoroutineScope { override val coroutineContext = Dispatchers.Main.immediate + SupervisorJob() companion object { val showAudioPlayer = MutableLiveData<Boolean>().apply { value = false } private val mediaList = MediaWrapperList() fun hasMedia() = mediaList.size() != 0 } private val medialibrary by lazy(LazyThreadSafetyMode.NONE) { Medialibrary.getInstance() } val player by lazy(LazyThreadSafetyMode.NONE) { PlayerController(service.applicationContext) } private val settings by lazy(LazyThreadSafetyMode.NONE) { Settings.getInstance(service) } private val ctx by lazy(LazyThreadSafetyMode.NONE) { service.applicationContext } var currentIndex = -1 private var nextIndex = -1 private var prevIndex = -1 private var previous = Stack<Int>() var stopAfter = -1 var repeating = PlaybackStateCompat.REPEAT_MODE_NONE var shuffling = false var videoBackground = false private set var isBenchmark = false var isHardware = false private var parsed = false var savedTime = 0L private var random = Random(System.currentTimeMillis()) private var newMedia = false @Volatile private var expanding = false private var entryUrl : String? = null val abRepeat by lazy(LazyThreadSafetyMode.NONE) { MutableLiveData<ABRepeat>().apply { value = ABRepeat() } } val abRepeatOn by lazy(LazyThreadSafetyMode.NONE) { MutableLiveData<Boolean>().apply { value = false } } val videoStatsOn by lazy(LazyThreadSafetyMode.NONE) { MutableLiveData<Boolean>().apply { value = false } } val delayValue by lazy(LazyThreadSafetyMode.NONE) { MutableLiveData<DelayValues>().apply { value = DelayValues() } } private val mediaFactory = FactoryManager.getFactory(IMediaFactory.factoryId) as IMediaFactory fun hasCurrentMedia() = isValidPosition(currentIndex) fun hasPlaylist() = mediaList.size() > 1 fun canShuffle() = mediaList.size() > 2 fun isValidPosition(position: Int) = position in 0 until mediaList.size() init { repeating = settings.getInt(PLAYLIST_REPEAT_MODE_KEY, PlaybackStateCompat.REPEAT_MODE_NONE) } /** * Loads a selection of files (a non-user-supplied collection of media) * into the primary or "currently playing" playlist. * * @param mediaPathList A list of locations to load * @param position The position to start playing at */ @MainThread fun loadLocations(mediaPathList: List<String>, position: Int) { launch { val mediaList = ArrayList<MediaWrapper>() withContext(Dispatchers.IO) { for (location in mediaPathList) { var mediaWrapper = medialibrary.getMedia(location) if (mediaWrapper === null) { if (!location.validateLocation()) { Log.w(TAG, "Invalid location $location") service.showToast(service.resources.getString(R.string.invalid_location, location), Toast.LENGTH_SHORT) continue } Log.v(TAG, "Creating on-the-fly Media object for $location") mediaWrapper = MLServiceLocator.getAbstractMediaWrapper(Uri.parse(location)) mediaList.add(mediaWrapper) } else mediaList.add(mediaWrapper) } } load(mediaList, position) } } @MainThread suspend fun load(list: List<MediaWrapper>, position: Int, mlUpdate: Boolean = false) { saveMediaList() savePosition() mediaList.removeEventListener(this@PlaylistManager) previous.clear() videoBackground = false mediaList.replaceWith(list) if (!hasMedia()) { Log.w(TAG, "Warning: empty media list, nothing to play !") return } currentIndex = if (isValidPosition(position)) position else 0 // Add handler after loading the list mediaList.addEventListener(this@PlaylistManager) stopAfter = -1 clearABRepeat() player.setRate(1.0f, false) playIndex(currentIndex) service.onPlaylistLoaded() if (mlUpdate) { service.awaitMedialibraryStarted() mediaList.replaceWith(withContext(Dispatchers.IO) { mediaList.copy.updateWithMLMeta() }) executeUpdate() service.showNotification() } } @Volatile private var loadingLastPlaylist = false fun loadLastPlaylist(type: Int = PLAYLIST_TYPE_AUDIO) : Boolean { if (loadingLastPlaylist) return true loadingLastPlaylist = true val audio = type == PLAYLIST_TYPE_AUDIO val currentMedia = settings.getString(if (audio) KEY_CURRENT_AUDIO else KEY_CURRENT_MEDIA, "") if (currentMedia.isNullOrEmpty()) { loadingLastPlaylist = false return false } val locations = settings.getString(if (audio) KEY_AUDIO_LAST_PLAYLIST else KEY_MEDIA_LAST_PLAYLIST, null) ?.split(" ".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray() if (locations.isNullOrEmpty()) { loadingLastPlaylist = false return false } launch { val playList = withContext(Dispatchers.Default) { locations.asSequence().mapTo(ArrayList(locations.size)) { MLServiceLocator.getAbstractMediaWrapper(Uri.parse(it)) } } // load playlist shuffling = settings.getBoolean(if (audio) "audio_shuffling" else "media_shuffling", false) val position = max(0, settings.getInt(if (audio) "position_in_audio_list" else "position_in_media_list", 0)) savedTime = settings.getLong(if (audio) "position_in_song" else "position_in_media", -1) if (!audio && position < playList.size && settings.getBoolean(VIDEO_PAUSED, false)) { playList[position].addFlags(MediaWrapper.MEDIA_PAUSED) } if (audio && position < playList.size) playList[position].addFlags(MediaWrapper.MEDIA_FORCE_AUDIO) load(playList, position, true) loadingLastPlaylist = false if (!audio) { val rate = settings.getFloat(VIDEO_SPEED, player.getRate()) if (rate != 1.0f) player.setRate(rate, false) } } return true } fun play() { if (hasMedia()) player.play() } fun pause() { if (player.pause()) { savePosition() if (getCurrentMedia()?.isPodcast == true) saveMediaMeta() } } @MainThread fun next(force : Boolean = false) { val size = mediaList.size() if (force || repeating != PlaybackStateCompat.REPEAT_MODE_ONE) { previous.push(currentIndex) currentIndex = nextIndex if (size == 0 || currentIndex < 0 || currentIndex >= size) { Log.w(TAG, "Warning: invalid next index, aborted !") stop() return } videoBackground = videoBackground || (!player.isVideoPlaying() && player.canSwitchToVideo()) } launch { playIndex(currentIndex) } } fun stop(systemExit: Boolean = false, video: Boolean = false) { clearABRepeat() stopAfter = -1 videoBackground = false val job = getCurrentMedia()?.let { savePosition(video = video) val audio = isAudioList() // check before dispatching in saveMediaMeta() launch(start = CoroutineStart.UNDISPATCHED) { saveMediaMeta().join() if (AndroidDevices.isAndroidTv && AndroidUtil.isOOrLater && !audio) setResumeProgram(service.applicationContext, it) } } mediaList.removeEventListener(this) previous.clear() currentIndex = -1 if (systemExit) player.release() else player.restart() mediaList.clear() showAudioPlayer.value = false service.onPlaybackStopped(systemExit) //Close video player if started LocalBroadcastManager.getInstance(ctx).sendBroadcast(Intent(EXIT_PLAYER)) if (systemExit) launch(start = CoroutineStart.UNDISPATCHED) { job?.join() cancel() player.cancel() } } @MainThread fun previous(force : Boolean) { if (hasPrevious() && currentIndex > 0 && (force || !player.seekable || player.getCurrentTime() < PREVIOUS_LIMIT_DELAY)) { val size = mediaList.size() currentIndex = prevIndex if (previous.size > 0) previous.pop() if (size == 0 || prevIndex < 0 || currentIndex >= size) { Log.w(TAG, "Warning: invalid previous index, aborted !") player.stop() return } launch { playIndex(currentIndex) } } else player.setPosition(0F) } @MainThread fun shuffle() { if (shuffling) previous.clear() shuffling = !shuffling savePosition() launch { determinePrevAndNextIndices() } } @MainThread fun setRepeatType(repeatType: Int) { repeating = repeatType settings.putSingle(PLAYLIST_REPEAT_MODE_KEY, repeating) savePosition() launch { determinePrevAndNextIndices() } } fun setRenderer(item: RendererItem?) { player.setRenderer(item) showAudioPlayer.value = PlayerController.playbackState != PlaybackStateCompat.STATE_STOPPED && (item !== null || !player.isVideoPlaying()) } suspend fun playIndex(index: Int, flags: Int = 0) { videoBackground = videoBackground || (!player.isVideoPlaying() && player.canSwitchToVideo()) if (mediaList.size() == 0) { Log.w(TAG, "Warning: empty media list, nothing to play !") return } currentIndex = if (isValidPosition(index)) { index } else { Log.w(TAG, "Warning: index $index out of bounds") 0 } val mw = mediaList.getMedia(index) ?: return val isVideoPlaying = mw.type == MediaWrapper.TYPE_VIDEO && player.isVideoPlaying() if (!videoBackground && isVideoPlaying) mw.addFlags(MediaWrapper.MEDIA_VIDEO) if (videoBackground) mw.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO) if (isBenchmark) mw.addFlags(MediaWrapper.MEDIA_BENCHMARK) parsed = false player.switchToVideo = false if (TextUtils.equals(mw.uri.scheme, "content")) withContext(Dispatchers.IO) { MediaUtils.retrieveMediaTitle(mw) } if (mw.type != MediaWrapper.TYPE_VIDEO || isVideoPlaying || player.hasRenderer || mw.hasFlag(MediaWrapper.MEDIA_FORCE_AUDIO)) { var uri = withContext(Dispatchers.IO) { FileUtils.getUri(mw.uri) } if (uri == null) { skipMedia() return } val title = mw.getMetaLong(MediaWrapper.META_TITLE) if (title > 0) uri = Uri.parse("$uri#$title") val start = getStartTime(mw) val media = mediaFactory.getFromUri(VLCInstance.get(service), uri) media.addOption(":start-time=${start/1000L}") VLCOptions.setMediaOptions(media, ctx, flags or mw.flags, PlaybackService.hasRenderer()) /* keeping only video during benchmark */ if (isBenchmark) { media.addOption(":no-audio") media.addOption(":no-spu") if (isHardware) { media.addOption(":codec=mediacodec_ndk,mediacodec_jni,none") isHardware = false } } media.setEventListener(this@PlaylistManager) player.startPlayback(media, mediaplayerEventListener, start) player.setSlaves(media, mw) newMedia = true determinePrevAndNextIndices() service.onNewPlayback() } else { //Start VideoPlayer for first video, it will trigger playIndex when ready. if (player.isPlaying()) player.stop() VideoPlayerActivity.startOpened(ctx, mw.uri, currentIndex) } } private fun skipMedia() { if (currentIndex != nextIndex) next() else stop() } fun onServiceDestroyed() { player.release() } @MainThread fun switchToVideo(): Boolean { val media = getCurrentMedia() if (media === null || media.hasFlag(MediaWrapper.MEDIA_FORCE_AUDIO) || !player.canSwitchToVideo()) return false val hasRenderer = player.hasRenderer videoBackground = false if (player.isVideoPlaying() && !hasRenderer) {//Player is already running, just send it an intent player.setVideoTrackEnabled(true) LocalBroadcastManager.getInstance(service).sendBroadcast( VideoPlayerActivity.getIntent(PLAY_FROM_SERVICE, media, false, currentIndex)) } else if (!player.switchToVideo) { //Start the video player VideoPlayerActivity.startOpened(AppContextProvider.appContext, media.uri, currentIndex) if (!hasRenderer) player.switchToVideo = true } return true } fun setVideoTrackEnabled(enabled: Boolean) { if (!hasMedia() || !player.isPlaying()) return if (enabled) getCurrentMedia()?.addFlags(MediaWrapper.MEDIA_VIDEO) else getCurrentMedia()?.removeFlags(MediaWrapper.MEDIA_VIDEO) player.setVideoTrackEnabled(enabled) } fun hasPrevious() = prevIndex != -1 fun hasNext() = nextIndex != -1 @MainThread override fun onItemAdded(index: Int, mrl: String) { if (BuildConfig.DEBUG) Log.i(TAG, "CustomMediaListItemAdded") if (currentIndex >= index && !expanding) ++currentIndex addUpdateActor.offer(Unit) } private val addUpdateActor = actor<Unit>(capacity = Channel.CONFLATED) { for (update in channel) { determinePrevAndNextIndices() executeUpdate() saveMediaList() } } @MainThread override fun onItemRemoved(index: Int, mrl: String) { if (BuildConfig.DEBUG) Log.i(TAG, "CustomMediaListItemDeleted") val currentRemoved = currentIndex == index if (currentIndex >= index && !expanding) --currentIndex launch { determinePrevAndNextIndices() if (currentRemoved && !expanding) { when { nextIndex != -1 -> next() currentIndex != -1 -> playIndex(currentIndex, 0) else -> stop() } } executeUpdate() saveMediaList() } } private fun executeUpdate() { service.executeUpdate() } fun saveMediaMeta() = launch(start = CoroutineStart.UNDISPATCHED) { val titleIdx = player.getTitleIdx() val chapterIdx = player.getChapterIdx() val currentMedia = getCurrentMedia() ?: return@launch if (currentMedia.uri.scheme == "fd") return@launch //Save progress val time = player.getCurrentTime() val length = player.getLength() val canSwitchToVideo = player.canSwitchToVideo() val rate = player.getRate() launch(Dispatchers.IO) { val media = medialibrary.findMedia(currentMedia) ?: return@launch if (media.id == 0L) return@launch if (titleIdx > 0) media.setLongMeta(MediaWrapper.META_TITLE, titleIdx.toLong()) if (media.type == MediaWrapper.TYPE_VIDEO || canSwitchToVideo || media.isPodcast) { var progress = time / length.toFloat() if (progress > 0.95f || length - time < 10000) { //increase seen counter if more than 95% of the media have been seen //and reset progress to 0 media.setLongMeta(MediaWrapper.META_SEEN, media.seen+1) progress = 0f } media.time = if (progress == 0f) 0L else time media.setLongMeta(MediaWrapper.META_PROGRESS, media.time) } media.setStringMeta(MediaWrapper.META_SPEED, rate.toString()) } } fun setSpuTrack(index: Int) { if (!player.setSpuTrack(index)) return val media = getCurrentMedia() ?: return if (media.id != 0L) launch(Dispatchers.IO) { media.setLongMeta(MediaWrapper.META_SUBTITLE_TRACK, index.toLong()) } } fun setAudioDelay(delay: Long) { if (!player.setAudioDelay(delay)) return val media = getCurrentMedia() ?: return if (media.id != 0L && settings.getBoolean("save_individual_audio_delay", true)) { launch(Dispatchers.IO) { media.setLongMeta(MediaWrapper.META_AUDIODELAY, player.getAudioDelay()) } } } fun setSpuDelay(delay: Long) { if (!player.setSpuDelay(delay)) return val media = getCurrentMedia() ?: return if (media.id != 0L) launch(Dispatchers.IO) { media.setLongMeta(MediaWrapper.META_SUBTITLE_DELAY, player.getSpuDelay()) } } private fun loadMediaMeta(media: MediaWrapper) { if (media.id == 0L) return if (player.canSwitchToVideo()) { if (settings.getBoolean("save_individual_audio_delay", true)) player.setAudioDelay(media.getMetaLong(MediaWrapper.META_AUDIODELAY)) player.setSpuTrack(media.getMetaLong(MediaWrapper.META_SUBTITLE_TRACK).toInt()) player.setSpuDelay(media.getMetaLong(MediaWrapper.META_SUBTITLE_DELAY)) val rateString = media.getMetaString(MediaWrapper.META_SPEED) if (!rateString.isNullOrEmpty()) { player.setRate(rateString.toFloat(), false) } } } @Synchronized private fun saveCurrentMedia() { val media = getCurrentMedia() ?: return val isAudio = isAudioList() settings.putSingle(if (isAudio) KEY_CURRENT_AUDIO else KEY_CURRENT_MEDIA, media.location) } private suspend fun saveMediaList() { if (getCurrentMedia() === null) return val locations = StringBuilder() withContext(Dispatchers.Default) { val list = mediaList.copy.takeIf { it.isNotEmpty() } ?: return@withContext for (mw in list) locations.append(" ").append(mw.uri.toString()) //We save a concatenated String because putStringSet is APIv11. settings.putSingle(if (isAudioList()) KEY_AUDIO_LAST_PLAYLIST else KEY_MEDIA_LAST_PLAYLIST, locations.toString().trim()) } } override fun onItemMoved(indexBefore: Int, indexAfter: Int, mrl: String) { if (BuildConfig.DEBUG) Log.i(TAG, "CustomMediaListItemMoved") when (currentIndex) { indexBefore -> { currentIndex = indexAfter if (indexAfter > indexBefore) --currentIndex } in indexAfter until indexBefore -> ++currentIndex in (indexBefore + 1) until indexAfter -> --currentIndex } // If we are in random mode, we completely reset the stored previous track // as their indices changed. previous.clear() addUpdateActor.safeOffer(Unit) } private suspend fun determinePrevAndNextIndices(expand: Boolean = false) { val media = getCurrentMedia() if (expand && media !== null) { expanding = true nextIndex = expand(media.type == MediaWrapper.TYPE_STREAM) expanding = false } else { nextIndex = -1 } prevIndex = -1 if (nextIndex == -1) { // No subitems; play the next item. val size = mediaList.size() shuffling = shuffling and (size > 2) if (shuffling) { if (!previous.isEmpty()) { prevIndex = previous.peek() while (!isValidPosition(prevIndex)) { previous.removeAt(previous.size - 1) if (previous.isEmpty()) { prevIndex = -1 break } prevIndex = previous.peek() } } // If we've played all songs already in shuffle, then either // reshuffle or stop (depending on RepeatType). if (previous.size + 1 == size) { if (repeating == PlaybackStateCompat.REPEAT_MODE_NONE) { nextIndex = -1 return } else { previous.clear() random = Random(System.currentTimeMillis()) } } random = Random(System.currentTimeMillis()) // Find a new index not in previous. do { nextIndex = random.nextInt(size) } while (nextIndex == currentIndex || previous.contains(nextIndex)) } else { // normal playback if (currentIndex > 0) prevIndex = currentIndex - 1 nextIndex = when { currentIndex + 1 < size -> currentIndex + 1 repeating == PlaybackStateCompat.REPEAT_MODE_NONE -> -1 else -> 0 } } } } /** * Expand the current media. * @return the index of the media was expanded, and -1 if no media was expanded */ @MainThread private suspend fun expand(updateHistory: Boolean): Int { val index = currentIndex val expandedMedia = getCurrentMedia() val stream = expandedMedia?.type == MediaWrapper.TYPE_STREAM val ml = player.expand() var ret = -1 if (ml != null && ml.count > 0) { val mrl = if (updateHistory) expandedMedia?.location else null mediaList.removeEventListener(this) mediaList.remove(index) for (i in 0 until ml.count) { val child = ml.getMediaAt(i) withContext(Dispatchers.IO) { child.parse() } mediaList.insert(index+i, MLServiceLocator.getAbstractMediaWrapper(child)) child.release() } mediaList.addEventListener(this) addUpdateActor.offer(Unit) service.onMediaListChanged() if (mrl !== null && ml.count == 1) { getCurrentMedia()?.apply { AppScope.launch(Dispatchers.IO) { if (stream) { type = MediaWrapper.TYPE_STREAM entryUrl = mrl medialibrary.getMedia(mrl)?.run { if (id > 0) medialibrary.removeExternalMedia(id) } } else if (uri.scheme != "fd") { medialibrary.addToHistory(mrl, title) } } } } ret = index } ml?.release() return ret } fun getCurrentMedia() = mediaList.getMedia(currentIndex) fun getPrevMedia() = if (isValidPosition(prevIndex)) mediaList.getMedia(prevIndex) else null fun getNextMedia() = if (isValidPosition(nextIndex)) mediaList.getMedia(nextIndex) else null fun getMedia(position: Int) = mediaList.getMedia(position) private suspend fun getStartTime(mw: MediaWrapper) : Long { val start = when { mw.hasFlag(MediaWrapper.MEDIA_FROM_START) -> { mw.removeFlags(MediaWrapper.MEDIA_FROM_START) 0L } savedTime <= 0L -> when { mw.time > 0L -> mw.time mw.type == MediaWrapper.TYPE_VIDEO || mw.isPodcast -> withContext(Dispatchers.IO) { medialibrary.findMedia(mw).getMetaLong(MediaWrapper.META_PROGRESS) } else -> 0L } else -> savedTime } savedTime = 0L return start } @Synchronized private fun savePosition(reset: Boolean = false, video: Boolean = false) { if (!hasMedia()) return val editor = settings.edit() val audio = !video && isAudioList() editor.putBoolean(if (audio) "audio_shuffling" else "media_shuffling", shuffling) editor.putInt(if (audio) "position_in_audio_list" else "position_in_media_list", if (reset) 0 else currentIndex) editor.putLong(if (audio) "position_in_song" else "position_in_media", if (reset) 0L else player.getCurrentTime()) if (!audio) { editor.putFloat(VIDEO_SPEED, player.getRate()) } editor.apply() } /** * Append to the current existing playlist */ @MainThread suspend fun append(list: List<MediaWrapper>) { if (!hasCurrentMedia()) { launch { load(list, 0, mlUpdate = true) } return } val list = withContext(Dispatchers.IO) { list.updateWithMLMeta() } mediaList.removeEventListener(this) for (media in list) mediaList.add(media) mediaList.addEventListener(this) addUpdateActor.offer(Unit) } /** * Insert into the current existing playlist */ @MainThread fun insertNext(list: List<MediaWrapper>) { if (!hasCurrentMedia()) { launch { load(list, 0) } return } val startIndex = currentIndex + 1 for ((index, mw) in list.withIndex()) mediaList.insert(startIndex + index, mw) } /** * Move an item inside the playlist. */ @MainThread fun moveItem(positionStart: Int, positionEnd: Int) = mediaList.move(positionStart, positionEnd) @MainThread fun insertItem(position: Int, mw: MediaWrapper) = mediaList.insert(position, mw) @MainThread fun remove(position: Int) = mediaList.remove(position) @MainThread fun removeLocation(location: String) = mediaList.remove(location) fun getMediaListSize()= mediaList.size() fun getMediaList(): List<MediaWrapper> = mediaList.copy fun setABRepeatValue(time: Long) { val value = abRepeat.value ?: ABRepeat() when { value.start == -1L -> value.start = time value.start > time -> { value.stop = value.start value.start = time } else -> value.stop = time } abRepeat.value = value } fun setDelayValue(time: Long, start: Boolean) { val value = delayValue.value ?: DelayValues() if (start) value.start = time else value.stop = time delayValue.value = value } fun resetDelayValues() { delayValue.postValue(DelayValues()) } fun resetABRepeatValues() { abRepeat.value = ABRepeat() } fun toggleABRepeat() { abRepeatOn.value = !abRepeatOn.value!! if (abRepeatOn.value == false) { abRepeat.value = ABRepeat() } } fun toggleStats() { videoStatsOn.value = !videoStatsOn.value!! } fun clearABRepeat() { abRepeat.value = abRepeat.value?.apply { start = -1L stop = -1L } abRepeatOn.value = false } override fun onEvent(event: IMedia.Event) { var update = true when (event.type) { IMedia.Event.MetaChanged -> { /* Update Meta if file is already parsed */ if (parsed && player.updateCurrentMeta(event.metaId, getCurrentMedia())) service.executeUpdate() if (BuildConfig.DEBUG) Log.i(TAG, "Media.Event.MetaChanged: " + event.metaId) } IMedia.Event.ParsedChanged -> { if (BuildConfig.DEBUG) Log.i(TAG, "Media.Event.ParsedChanged") player.updateCurrentMeta(-1, getCurrentMedia()) parsed = true } else -> update = false } if (update) { service.onMediaEvent(event) if (parsed) service.showNotification() } } private val mediaplayerEventListener = object : MediaPlayerEventListener { override suspend fun onEvent(event: MediaPlayer.Event) { when (event.type) { MediaPlayer.Event.Playing -> { val mw = withContext(Dispatchers.IO) { getCurrentMedia()?.let { medialibrary.findMedia(it).apply { if (type == -1) type = it.type } } } ?: return if (newMedia) { loadMediaMeta(mw) saveMediaList() savePosition(reset = true) saveCurrentMedia() newMedia = false if (player.hasRenderer || !player.isVideoPlaying()) showAudioPlayer.value = true savePlaycount(mw) } } MediaPlayer.Event.EndReached -> { clearABRepeat() if (currentIndex != nextIndex) { saveMediaMeta() if (isBenchmark) player.setPreviousStats() if (nextIndex == -1) savePosition(reset = true) } if (stopAfter == currentIndex) { stop() } else { determinePrevAndNextIndices(true) if (!hasNext()) getCurrentMedia()?.let { if (AndroidDevices.isAndroidTv && AndroidUtil.isOOrLater && !isAudioList()) setResumeProgram(service.applicationContext, it) } next() } } MediaPlayer.Event.EncounteredError -> { service.showToast(service.getString( R.string.invalid_location, getCurrentMedia()?.location ?: ""), Toast.LENGTH_SHORT, true) if (currentIndex != nextIndex) next() else stop() } MediaPlayer.Event.TimeChanged -> { abRepeat.value?.let { if (it.stop != -1L && player.getCurrentTime() > it.stop) player.seek(it.start) } } MediaPlayer.Event.SeekableChanged -> if (event.seekable && settings.getBoolean(KEY_PLAYBACK_SPEED_PERSIST, false)) { player.setRate(settings.getFloat(KEY_PLAYBACK_RATE, 1.0f), false) } } service.onMediaPlayerEvent(event) } } private suspend fun savePlaycount(mw: MediaWrapper) { if (settings.getBoolean(PLAYBACK_HISTORY, true)) withContext(Dispatchers.IO) { var id = mw.id if (id == 0L) { var internalMedia = medialibrary.findMedia(mw) if (internalMedia != null && internalMedia.id != 0L) id = internalMedia.id else { internalMedia = if (mw.type == MediaWrapper.TYPE_STREAM) { medialibrary.addStream(Uri.decode(entryUrl ?: mw.uri.toString()), mw.title).also { entryUrl = null } } else medialibrary.addMedia(Uri.decode(mw.uri.toString())) if (internalMedia != null) id = internalMedia.id } } if (id != 0L) medialibrary.increasePlayCount(id) } } internal fun isAudioList() = !player.isVideoPlaying() && mediaList.isAudioList } class ABRepeat(var start: Long = -1L, var stop: Long = -1L) class DelayValues(var start: Long = -1L, var stop: Long = -1L)
gpl-2.0
0551ea63e01e9c83fcb84befaece9804
38.660422
168
0.580691
4.768408
false
false
false
false
Ahmed-Abdelmeged/Android-BluetoothMCLibrary
bluetoothmc/src/main/java/com/ahmedabdelmeged/bluetoothmc/BluetoothMC.kt
1
10015
package com.ahmedabdelmeged.bluetoothmc import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothSocket import android.content.Intent import android.os.AsyncTask import android.os.Handler import com.ahmedabdelmeged.bluetoothmc.util.BluetoothStates import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.* /** * @author Ahmed Abd-Elmeged */ class BluetoothMC(val bufferSize: Int = 1024) { /** * the MAC address for the chosen device */ private var devicesAddress: String? = null private var myBluetoothAdapter: BluetoothAdapter? = null private var btSocket: BluetoothSocket? = null private var isBtConnected = false private var mOnDataReceivedListener: onDataReceivedListener? = null private var mBluetoothConnectionListener: BluetoothConnectionListener? = null private var mBluetoothErrorsListener: BluetoothErrorsListener? = null private var newConnectionFlag = 0 init { if (bufferSize == 0) { throw IllegalStateException("Buffer size can't be zero") } newConnectionFlag++ //get the mobile bluetooth device myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter() HandleBluetoothStates() } /** * Interface for listen to the incoming data */ interface onDataReceivedListener { fun onDataReceived(data: String) } /** * Interface for track the connection states */ interface BluetoothConnectionListener { fun onDeviceConnecting() fun onDeviceConnected() fun onDeviceDisconnected() fun onDeviceConnectionFailed() } /** * Interface for track the errors */ interface BluetoothErrorsListener { fun onSendingFailed() fun onReceivingFailed() fun onDisconnectingFailed() fun onCommunicationFailed() } fun setOnDataReceivedListener(onDataReceivedListener: onDataReceivedListener) { mOnDataReceivedListener = onDataReceivedListener } fun setOnBluetoothConnectionListener(bluetoothConnectionListener: BluetoothConnectionListener) { mBluetoothConnectionListener = bluetoothConnectionListener } fun setOnBluetoothErrorsListener(bluetoothErrorsListener: BluetoothErrorsListener) { mBluetoothErrorsListener = bluetoothErrorsListener } fun isBluetoothEnabled(): Boolean { return myBluetoothAdapter != null && myBluetoothAdapter?.isEnabled ?: false } fun isBluetoothAvailable(): Boolean { return myBluetoothAdapter != null } fun getBluetoothAdapter(): BluetoothAdapter? { return myBluetoothAdapter } fun enableBluetooth() { if (myBluetoothAdapter != null) { myBluetoothAdapter?.enable() } } /** * used to connect the the bluetooth device with it's address * * @param intent */ fun connect(intent: Intent) { devicesAddress = intent.getStringExtra(BluetoothStates.EXTRA_DEVICE_ADDRESS) if (devicesAddress != null) { //call the class to connect to bluetooth if (newConnectionFlag == 1) { ConnectBT().execute() } } } /** * Helper method to handle bluetooth states */ private fun HandleBluetoothStates() { bluetoothHandler = object : Handler() { override fun handleMessage(msg: android.os.Message) { //handle messages when (msg.what) { BluetoothStates.BLUETOOTH_CONNECTING -> mBluetoothConnectionListener?.onDeviceConnecting() BluetoothStates.BLUETOOTH_CONNECTED -> mBluetoothConnectionListener?.onDeviceConnected() BluetoothStates.BLUETOOTH_CONNECTION_FAILED -> mBluetoothConnectionListener?.onDeviceConnectionFailed() BluetoothStates.BLUETOOTH_CONNECTION_LOST -> mBluetoothConnectionListener?.onDeviceDisconnected() BluetoothStates.BLUETOOTH_LISTENING -> { // msg.arg1 = bytes from connect thread val readBuf = msg.obj as ByteArray val readMessage = String(readBuf, 0, msg.arg1) mOnDataReceivedListener?.onDataReceived(readMessage) } BluetoothStates.ERROR_DISCONNECT -> mBluetoothErrorsListener?.onDisconnectingFailed() BluetoothStates.ERROR_LISTEN -> mBluetoothErrorsListener?.onReceivingFailed() BluetoothStates.ERROR_SEND -> mBluetoothErrorsListener?.onSendingFailed() BluetoothStates.ERROR_COMMUNICATION -> mBluetoothErrorsListener?.onCommunicationFailed() } } } } /** * An AysncTask to connect to Bluetooth socket */ private inner class ConnectBT : AsyncTask<Void, Void, Void>() { private var connectSuccess = true override fun onPreExecute() {} //while the progress dialog is shown, the connection is done in background override fun doInBackground(vararg params: Void): Void? { try { if (btSocket == null || !isBtConnected) { bluetoothHandler?.obtainMessage(BluetoothStates.BLUETOOTH_CONNECTING)?.sendToTarget() //connects to the device's address and checks if it's available val bluetoothDevice = myBluetoothAdapter?.getRemoteDevice(devicesAddress) //create a RFCOMM (SPP) connection btSocket = bluetoothDevice?.createInsecureRfcommSocketToServiceRecord(myUUID) BluetoothAdapter.getDefaultAdapter().cancelDiscovery() //start connection btSocket?.connect() } } catch (e: IOException) { //if the try failed, you can check the exception here connectSuccess = false } return null } //after the doInBackground, it checks if everything went fine override fun onPostExecute(aVoid: Void) { super.onPostExecute(aVoid) if (!connectSuccess) { bluetoothHandler?.obtainMessage(BluetoothStates.BLUETOOTH_CONNECTION_FAILED)?.sendToTarget() } else { isBtConnected = true bluetoothHandler?.obtainMessage(BluetoothStates.BLUETOOTH_CONNECTED)?.sendToTarget() mConnectedThread = ConnectedThread(btSocket!!) mConnectedThread?.start() } } } /** * to disconnect the bluetooth connection */ fun disconnect() { if (btSocket != null) //If the btSocket is busy { try { btSocket!!.close() //close connection isBtConnected = false bluetoothHandler?.obtainMessage(BluetoothStates.BLUETOOTH_CONNECTION_LOST)?.sendToTarget() } catch (e: IOException) { bluetoothHandler?.obtainMessage(BluetoothStates.ERROR_DISCONNECT)?.sendToTarget() } } } /** * create a new class for connect thread * to send and read DataSend from the microcontroller */ private inner class ConnectedThread//Create the connect thread internal constructor(socket: BluetoothSocket) : Thread() { private val mmInputStream: InputStream? private val mmOutputStream: OutputStream? init { var tmpIn: InputStream? = null var tmpOut: OutputStream? = null try { //create I/O stream for the connection tmpIn = socket.inputStream tmpOut = socket.outputStream } catch (e: IOException) { bluetoothHandler?.obtainMessage(BluetoothStates.ERROR_COMMUNICATION)?.sendToTarget() } mmInputStream = tmpIn mmOutputStream = tmpOut } override fun run() { val buffer = ByteArray(bufferSize) var bytes: Int //keep looping for listen for received message while (true) { try { //read bytes from input buffer bytes = mmInputStream!!.read(buffer) // Send the obtained bytes to the UI Activity via handler bluetoothHandler?.obtainMessage(BluetoothStates.BLUETOOTH_LISTENING, bytes, -1, buffer) ?.sendToTarget() } catch (e: IOException) { bluetoothHandler?.obtainMessage(BluetoothStates.ERROR_LISTEN)?.sendToTarget() break } } } //write method internal fun write(input: String) { //converted entered string into bytes val msgBuffer = input.toByteArray() //write bytes over bluetooth connection via outstream try { mmOutputStream!!.write(msgBuffer) } catch (e: IOException) { bluetoothHandler?.obtainMessage(BluetoothStates.ERROR_SEND)?.sendToTarget() } } } /** * used to send data to the micro controller * * @param data the data that will send prefer to be one char */ fun send(data: String) { if (btSocket != null && mConnectedThread != null) { mConnectedThread?.write(data) } } companion object { //SPP UUID. Look for it' //This the SPP for the arduino(AVR) private val myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") private var mConnectedThread: ConnectedThread? = null /** * Handler to get the DataSend from thr thread and drive it to the UI */ private var bluetoothHandler: Handler? = null } }
mit
40ca169f1cf0b7a4599bc294810c26ef
31.839344
123
0.610984
5.47567
false
false
false
false
GeoffreyMetais/vlc-android
application/tools/src/main/java/org/videolan/tools/DependencyProvider.kt
1
1066
package org.videolan.tools import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap @Suppress("UNCHECKED_CAST") open class DependencyProvider<A> { val objectMap: ConcurrentMap<String, Any> = ConcurrentHashMap() val creatorMap: ConcurrentMap<String, (A) -> Any> = ConcurrentHashMap() var overrideCreator = true inline fun <T> getKey(clazz: Class<T>): String = clazz.name inline fun <X : Any, reified T : X> registerCreator(clazz: Class<X>? = null, noinline creator: (A) -> T) { val key = getKey(clazz ?: T::class.java) if (overrideCreator || !creatorMap.containsKey(key)) creatorMap[key] = creator if (objectMap.containsKey(key) && overrideCreator) { objectMap.remove(key) } } inline fun <X : Any, reified T : X> get(arg: A, clazz: Class<X>? = null): T { val key = getKey(clazz ?: T::class.java) if (!objectMap.containsKey(key)) objectMap[key] = creatorMap[key]?.invoke(arg) return objectMap[key] as T } }
gpl-2.0
8e7ac4fbf42fb04f4a073ca1e26b311e
33.419355
110
0.642589
3.876364
false
false
false
false
tasks/tasks
app/src/test/java/com/todoroo/astrid/repeats/RepeatMonthlyTests.kt
1
2921
package com.todoroo.astrid.repeats import com.natpryce.makeiteasy.MakeItEasy.with import org.junit.Assert.assertEquals import org.junit.Test import org.tasks.makers.TaskMaker.COMPLETION_TIME import org.tasks.time.DateTime class RepeatMonthlyTests : RepeatTests() { @Test fun testRepeatMonthlyFromDueDate() { val task = newFromDue("FREQ=MONTHLY;INTERVAL=3", newDayTime(2016, 8, 28, 1, 44)) val next = calculateNextDueDate(task) assertEquals(newDayTime(2016, 11, 28, 1, 44), next) } @Test fun testRepeatMonthlyFromCompleteDateCompleteBefore() { val task = newFromDue( "FREQ=MONTHLY;INTERVAL=1", newDayTime(2016, 8, 30, 0, 25), with(COMPLETION_TIME, DateTime(2016, 8, 29, 0, 14, 13, 451)), afterComplete = true ) val next = calculateNextDueDate(task) assertEquals(newDayTime(2016, 9, 29, 0, 25), next) } @Test fun testRepeatMonthlyFromCompleteDateCompleteAfter() { val task = newFromDue( "FREQ=MONTHLY;INTERVAL=1", newDayTime(2016, 8, 28, 0, 4), with(COMPLETION_TIME, DateTime(2016, 8, 29, 0, 14, 13, 451)), afterComplete = true ) val next = calculateNextDueDate(task) assertEquals(newDayTime(2016, 9, 29, 0, 4), next) } @Test fun repeatAtEndOfJanuary() { val task = newFromDue( "FREQ=MONTHLY;INTERVAL=1", newDayTime(2017, 1, 31, 13, 30) ) val next = calculateNextDueDate(task) assertEquals(newDayTime(2017, 2, 28, 13, 30), next) } @Test fun repeatMonthlyNoInterval() { val task = newFromDue( "FREQ=MONTHLY", newDayTime(2017, 11, 1, 13, 30) ) val next = calculateNextDueDate(task) assertEquals(newDayTime(2017, 12, 1, 13, 30), next) } @Test fun repeatMonthlyEndOfMonthNoInterval() { val task = newFromDue( "FREQ=MONTHLY", newDayTime(2017, 11, 30, 13, 30) ) val next = calculateNextDueDate(task) assertEquals(newDayTime(2017, 12, 31, 13, 30), next) } /* https://tools.ietf.org/html/rfc5545#section-3.3.10 * Recurrence rules may generate recurrence instances with an invalid * date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM * on a day where the local time is moved forward by an hour at 1:00 * AM). Such recurrence instances MUST be ignored and MUST NOT be * counted as part of the recurrence set. */ @Test fun repeatJanuary30th() { val task = newFromDue( "FREQ=MONTHLY;INTERVAL=1", newDayTime(2017, 1, 30, 13, 30) ) val next = calculateNextDueDate(task) assertEquals(newDayTime(2017, 3, 30, 13, 30), next) } }
gpl-3.0
312524389e59dc6e920d5a3d3fc83eef
27.930693
88
0.593975
3.721019
false
true
false
false
lambdasoup/watchlater
app/src/test/java/com/lambdasoup/watchlater/viewmodel/AddViewModelTest.kt
1
11771
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.watchlater.viewmodel import android.accounts.Account import android.content.Intent import android.net.Uri import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.google.common.truth.Truth.assertThat import com.lambdasoup.tea.testing.TeaTestEngineRule import com.lambdasoup.watchlater.data.AccountRepository import com.lambdasoup.watchlater.data.YoutubeRepository import com.lambdasoup.watchlater.data.YoutubeRepository.AddVideoResult import com.lambdasoup.watchlater.data.YoutubeRepository.ErrorType import com.lambdasoup.watchlater.data.YoutubeRepository.Playlists.Playlist import com.lambdasoup.watchlater.data.YoutubeRepository.VideoInfoResult import com.lambdasoup.watchlater.data.YoutubeRepository.Videos import com.lambdasoup.watchlater.util.VideoIdParser import com.lambdasoup.watchlater.viewmodel.AddViewModel.Event import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoAdd import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import org.junit.runner.RunWith import org.mockito.MockitoAnnotations.initMocks import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class AddViewModelTest { @get:Rule var aacRule: TestRule = InstantTaskExecutorRule() @get:Rule var teaRule: TestRule = TeaTestEngineRule() private val accountRepository: AccountRepository = mock() private val videoIdParser: VideoIdParser = mock() private val youtubeRepository: YoutubeRepository = mock() private lateinit var vm: AddViewModel private lateinit var accountLiveData: MutableLiveData<Account> private val playlistLiveData = MutableLiveData<Playlist?>() private val token = "token" private val uri: Uri = mock() private val videoId = "video-id" private val item: Videos.Item = mock() private val observedEvents = mutableListOf<Event>() private val playlist: Playlist = mock() @Before fun setup() { initMocks(this) accountLiveData = MutableLiveData() whenever(accountRepository.get()).thenReturn(accountLiveData) whenever(youtubeRepository.targetPlaylist).thenReturn(playlistLiveData) playlistLiveData.value = playlist vm = AddViewModel(accountRepository, youtubeRepository, videoIdParser) whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.AuthToken(token)) accountLiveData.value = mock() whenever(videoIdParser.parseVideoId(uri)).thenReturn(videoId) whenever(youtubeRepository.getVideoInfo(videoId, token)) .thenReturn(VideoInfoResult.VideoInfo(item)) whenever(youtubeRepository.addVideo(videoId, playlist, token)) .thenReturn(AddVideoResult.Success) observedEvents.clear() vm.setVideoUri(uri) vm.setPermissionNeeded(false) } @Test fun `should set account`() { val account: Account = mock() vm.setAccount(account) verify(accountRepository).put(account) } @Test fun `should get account`() { val account: Account = mock() accountLiveData.value = account assertThat(vm.model.value!!.account).isEqualTo(account) } @Test fun `should set permission needed`() { vm.setPermissionNeeded(true) assertThat(vm.model.value!!.permissionNeeded).isEqualTo(true) } @Test fun `should set add progress when permission to true`() { vm.setPermissionNeeded(true) vm.setPermissionNeeded(false) val videoAdd = vm.model.value?.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isEqualTo(VideoAdd.Idle) } @Test fun `should error when watchlater without account`() { accountLiveData.value = null vm.watchLater(videoId) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isInstanceOf(VideoAdd.Error::class.java) assertThat((videoAdd as VideoAdd.Error).error).isEqualTo(VideoAdd.ErrorType.NoAccount) } @Test fun `should error when watchlater without permissions`() { accountLiveData.value = mock() vm.setPermissionNeeded(true) vm.watchLater(videoId) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isInstanceOf(VideoAdd.Error::class.java) assertThat((videoAdd as VideoAdd.Error).error).isEqualTo(VideoAdd.ErrorType.NoPermission) } @Test fun `should add to watchlater`() { vm.watchLater(videoId) val videoAdd = vm.model.value?.videoAdd assertThat(videoAdd).isEqualTo(VideoAdd.Success) } @Test fun `should error when token result has error`() { whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.Error(AccountRepository.ErrorType.AccountRemoved)) accountLiveData.value = mock() vm.watchLater(videoId) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isInstanceOf(VideoAdd.Error::class.java) assertThat((videoAdd as VideoAdd.Error).error).isEqualTo(VideoAdd.ErrorType.NoAccount) } @Test fun `should network error when token result has network error`() { whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.Error(AccountRepository.ErrorType.Network)) accountLiveData.value = mock() vm.watchLater(videoId) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isInstanceOf(VideoAdd.Error::class.java) assertThat((videoAdd as VideoAdd.Error).error).isEqualTo(VideoAdd.ErrorType.Network) } @Test fun `should intent when token result has intent`() { val intent: Intent = mock() whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.HasIntent(intent)) accountLiveData.value = mock() vm.watchLater(videoId) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isInstanceOf(VideoAdd.HasIntent::class.java) assertThat((videoAdd as VideoAdd.HasIntent).intent).isEqualTo(intent) assertTrue(vm.events.contains(Event.OpenAuthIntent(intent))) } @Test fun `should refresh token transparently`() { val token2 = "token2" whenever(youtubeRepository.addVideo(videoId, playlist, token)) .thenReturn(AddVideoResult.Error(ErrorType.InvalidToken, token)) whenever(youtubeRepository.addVideo(videoId, playlist, token2)) .thenReturn(AddVideoResult.Success) whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.AuthToken(token)) .thenReturn(AccountRepository.AuthTokenResult.AuthToken(token2)) vm.watchLater(videoId) verify(accountRepository).invalidateToken(token) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isEqualTo(VideoAdd.Success) } @Test fun `should error when token refresh fails`() { val token2 = "token2" whenever(youtubeRepository.addVideo(videoId, playlist, token)) .thenReturn(AddVideoResult.Error(ErrorType.InvalidToken, token)) whenever(youtubeRepository.addVideo(videoId, playlist, token2)) .thenReturn(AddVideoResult.Error(ErrorType.InvalidToken, token2)) whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.AuthToken(token)) .thenReturn(AccountRepository.AuthTokenResult.AuthToken(token2)) vm.watchLater(videoId) verify(accountRepository).invalidateToken(token) val videoAdd = vm.model.value!!.videoAdd assertThat(videoAdd).isNotNull() assertThat(videoAdd).isEqualTo(VideoAdd.Error(VideoAdd.ErrorType.Other("InvalidToken"))) } @Test fun `should handle generic error`() { whenever(youtubeRepository.addVideo(videoId, playlist, token)) .thenReturn(AddVideoResult.Error(ErrorType.Other, token)) vm.watchLater(videoId) val videoAdd = vm.model.value!!.videoAdd assertThat((videoAdd as VideoAdd.Error).error).isEqualTo(VideoAdd.ErrorType.Other("Other")) } @Test fun `should set videoid and get videoinfo`() { val uri: Uri = mock() val item: Videos.Item = mock() val videoId = "video-id" whenever(videoIdParser.parseVideoId(uri)).thenReturn(videoId) whenever(youtubeRepository.getVideoInfo(videoId, token)) .thenReturn(VideoInfoResult.VideoInfo(item)) vm.setVideoUri(uri) assertThat(vm.model.value!!.videoId).isEqualTo(videoId) assertThat(vm.model.value!!.videoInfo).isEqualTo(VideoInfo.Loaded(item)) } @Test fun `should set videoinfo error`() { val uri: Uri = mock() val videoId = "video-id" whenever(videoIdParser.parseVideoId(uri)).thenReturn(videoId) whenever(youtubeRepository.getVideoInfo(videoId, token)) .thenReturn(VideoInfoResult.Error(ErrorType.VideoNotFound)) vm.setVideoUri(uri) assertThat(vm.model.value!!.videoId).isEqualTo(videoId) assertThat(vm.model.value!!.videoInfo) .isEqualTo(VideoInfo.Error(VideoInfo.ErrorType.Youtube(ErrorType.VideoNotFound))) } @Test fun `should reload videoinfo after error when new account is added`() { accountLiveData.value = null whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.Error(AccountRepository.ErrorType.Network)) vm.setVideoUri(uri) whenever(accountRepository.getAuthToken()) .thenReturn(AccountRepository.AuthTokenResult.AuthToken(token)) accountLiveData.value = mock() assertThat(vm.model.value!!.videoInfo) .isInstanceOf(VideoInfo.Loaded::class.java) } @Test fun `should remove videoAdd error when playlist gets changed`() { vm.selectPlaylist(mock()) assertThat(vm.model.value!!.videoAdd) .isInstanceOf(VideoAdd.Idle::class.java) } @Test fun `should unset playlist when account is changed`() { val account: Account = mock() vm.setAccount(account) verify(youtubeRepository).setPlaylist(null) } }
gpl-3.0
f4fdcd3ee7cbca5d1cd79232497dbd49
34.561934
108
0.707332
4.52209
false
true
false
false
SeunAdelekan/Kanary
examples/HelloWorld - Gradle/src/hello/world/app.kt
1
1913
package hello.world import com.fasterxml.jackson.databind.ObjectMapper import com.iyanuadelekan.kanary.app.KanaryApp import com.iyanuadelekan.kanary.core.KanaryController import com.iyanuadelekan.kanary.core.KanaryRouter import com.iyanuadelekan.kanary.handlers.AppHandler import com.iyanuadelekan.kanary.helpers.http.request.done import com.iyanuadelekan.kanary.helpers.http.response.sendJson import com.iyanuadelekan.kanary.helpers.http.response.withStatus import com.iyanuadelekan.kanary.server.Server import org.eclipse.jetty.server.Request import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse val requestLogger: (HttpServletRequest?) -> Unit = { if(it != null && it.method != null && it.pathInfo != null) { println("Started ${it.scheme} ${it.method} request to: '${it.pathInfo}'") } } class HelloWorldController : KanaryController() { fun hello(baseRequest: Request, request: HttpServletRequest, response: HttpServletResponse) { // Create json object mapper val mapper = ObjectMapper() val responseRootNode = mapper.createObjectNode() with(responseRootNode) { put("hello", "world") } response withStatus 201 sendJson responseRootNode baseRequest.done() } } fun main(args: Array<String>) { println("Visit http://localhost:8080/hello/world to see the output") val app = KanaryApp() val server = Server() val helloWorldRouter = KanaryRouter() val helloWorldController = HelloWorldController() helloWorldRouter on "hello/" use helloWorldController helloWorldRouter.get("world/", helloWorldController::hello) app.mount(helloWorldRouter) app.use(requestLogger) server.handler = AppHandler(app) //server.listen(Integer.valueOf(System.getenv("PORT"))) // for Heroku deployment server.listen(8080) // for local development }
apache-2.0
dc78309e33e19663facc255f33226e5a
31.440678
97
0.73863
4.222958
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/main/ProfileFragment.kt
1
3248
package de.xikolo.controllers.main import android.os.Bundle import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import butterknife.BindView import de.xikolo.App import de.xikolo.R import de.xikolo.config.Config import de.xikolo.config.GlideApp import de.xikolo.controllers.webview.WebViewActivityAutoBundle import de.xikolo.extensions.observe import de.xikolo.models.User import de.xikolo.viewmodels.main.ProfileViewModel class ProfileFragment : MainFragment<ProfileViewModel>() { companion object { val TAG: String = ProfileFragment::class.java.simpleName } @BindView(R.id.textFullName) lateinit var textFullName: TextView @BindView(R.id.textName) lateinit var textName: TextView @BindView(R.id.imageProfile) lateinit var imageProfile: ImageView @BindView(R.id.textEnrollCount) lateinit var textEnrollCounts: TextView @BindView(R.id.textEmail) lateinit var textEmail: TextView @BindView(R.id.buttonEditProfile) lateinit var buttonEditProfile: Button override val layoutResource = R.layout.fragment_profile override fun createViewModel(): ProfileViewModel { return ProfileViewModel() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.user .observe(viewLifecycleOwner) { showUser(it) showContent() } viewModel.enrollments .observe(viewLifecycleOwner) { updateEnrollmentCount(viewModel.enrollmentCount) } } private fun showUser(user: User) { activityCallback?.onFragmentAttached( R.id.navigation_login, getString(R.string.title_section_profile) ) if (user.name == user.profile.fullName) { textFullName.text = user.name textName.visibility = View.GONE } else { textFullName.text = user.profile.fullName textName.text = user.name } textEmail.text = user.profile.email buttonEditProfile.setOnClickListener { activity?.let { val url = Config.HOST_URL + Config.PROFILE val intent = WebViewActivityAutoBundle .builder(getString(R.string.btn_edit_profile), url) .inAppLinksEnabled(false) .externalLinksEnabled(false) .build(it) startActivity(intent) } } GlideApp.with(App.instance) .load(user.avatarUrl) .circleCrop() .allPlaceholders(R.drawable.avatar_placeholder) .into(imageProfile) } private fun updateEnrollmentCount(count: Long) { textEnrollCounts.text = count.toString() } override fun onLoginStateChange(isLoggedIn: Boolean) { if (!isLoggedIn) { viewModel.user.removeObservers(viewLifecycleOwner) viewModel.enrollments.removeObservers(viewLifecycleOwner) if (isAdded) { parentFragmentManager.popBackStack() } } } }
bsd-3-clause
0e1a6fb1d5f231c03a0d0e3222ea3edf
27.743363
73
0.644704
4.797637
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge3d/animation/Animator3D.kt
1
4821
package com.soywiz.korge3d.animation import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.korge3d.* import com.soywiz.korma.geom.* import com.soywiz.korma.interpolation.* /** * @param playbackPattern: A function that takes normalized time (from 0 to 1) as argument and returns normalized * animation progress (from 0 to 1). Allows defining complex behaviors of an object which range * of movement is defined by an animation, and concrete position is defined by game's logic. * Normalized time means that as the time flows, it's counted in the number of this animation's * periods. For example, if animation is 5 seconds long, after 5 seconds this argument will be * equal to 1, and after 7.5 seconds - 1.5. * Normalized progress means that the function specifies what frame of the animation should be * shown in terms of its defined timeframe. For example, if the function returns 0.25 and the * animation is 10 seconds long, it means that the engine should present the animation as if it * was at 0.25 * 10 = 2.5 seconds of its regular playback. * Thanks to this, it's possible to define normalized, reusable playback patterns, not tied to * any specific animation's length. */ @Korge3DExperimental class Animator3D(val animation: Animation3D, val rootView: View3D, var playbackPattern: (Double) -> Double = repeatInfinitely) { companion object { val repeatInfinitely: (Double) -> Double = { it % 1.0 } } var currentTime = 0.milliseconds val elapsedTimeInAnimation: TimeSpan get() = animation.totalTime * playbackPattern(currentTime/animation.totalTime) fun update(dt: TimeSpan) { //currentTime += ms.ms * 0.1 currentTime += dt val keyFrames = animation.keyFrames val fseconds = keyFrames.seconds val ftransforms = keyFrames.transforms val ffloats = keyFrames.floats val aproperty = animation.property //genericBinarySearch(0, animation.keys.size) { animation.keys[it] } val n = keyFrames.findIndex(elapsedTimeInAnimation) if (n < 0) return val startTime = fseconds[n].toDouble().seconds val endTime = fseconds.getOrNull(n + 1)?.let { it.toDouble().seconds } ?: startTime val fragmentTime = (endTime - startTime) if (fragmentTime <= 0.milliseconds) return val ratio = (elapsedTimeInAnimation - startTime) / fragmentTime val aview = rootView[animation.target] //println("ratio: $ratio, startTime=$startTime, endTime=$endTime, elapsedTimeInAnimation=$elapsedTimeInAnimation") if (aview != null) { when (aproperty) { "transform" -> { if (ftransforms != null) { if (n >= ftransforms.size) { error("Unexpected") } aview.transform.setToInterpolated( ftransforms[n], ftransforms.getCyclic(n + 1), ratio.toDouble() ) } } "location.X", "location.Y", "location.Z", "scale.X", "scale.Y", "scale.Z", "rotationX.ANGLE", "rotationY.ANGLE", "rotationZ.ANGLE" -> { if (ffloats != null) { val value = ratio.interpolate(ffloats[n], ffloats[n % ffloats.size]).toDouble() when (aproperty) { "location.X" -> aview.x = value "location.Y" -> aview.y = value "location.Z" -> aview.z = value "scale.X" -> aview.scaleX = value "scale.Y" -> aview.scaleY = value "scale.Z" -> aview.scaleZ = value "rotationX.ANGLE" -> aview.rotationX = value.degrees "rotationY.ANGLE" -> aview.rotationY = value.degrees "rotationZ.ANGLE" -> aview.rotationZ = value.degrees } } } else -> { println("WARNING: animation.property=${animation.property} not implemented") } } } //animation.keyFrames.binarySearch { it.time.millisecondsInt } //println(animation) } } @Korge3DExperimental data class Animation3D(val id: String, val target: String, val property: String, val keyFrames: Frames) : Library3D.Def() { val totalTime = keyFrames.totalTime class Frames( var seconds: FloatArray = floatArrayOf(), var interpolations: Array<String> = arrayOf(), var floats: FloatArray? = null, var matrices: Array<Matrix3D>? = null ) { val transforms = matrices?.map { Transform3D().setMatrix(it) }?.toTypedArray() val totalFrames = seconds.size val totalTime = seconds.maxOrNull()?.let { it.toDouble().seconds } ?: 0.seconds // @TODO: Binary Search fun findIndex(time: TimeSpan): Int { val elapsedSeconds = time.seconds for (n in 0 until totalFrames - 1) { if (elapsedSeconds >= seconds[n] && elapsedSeconds < seconds[n + 1]) { return n } } return totalFrames - 1 } } }
apache-2.0
48a456c1ee696a150af0c44615b55eb9
38.195122
139
0.651525
3.778213
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/util/extensions/String.kt
2
2719
package chat.rocket.android.util.extensions import android.graphics.Color import android.util.Patterns import chat.rocket.common.model.Token import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import timber.log.Timber fun String.removeTrailingSlash(): String { var removed = this while (removed.isNotEmpty() && removed[removed.length - 1] == '/') { removed = removed.substring(0, removed.length - 1) } return removed } fun String.sanitize(): String { val tmp = this.trim() return tmp.removeTrailingSlash() } fun String.avatarUrl( avatar: String, userId: String?, token: String?, isGroupOrChannel: Boolean = false, format: String = "jpeg" ): String { return if (isGroupOrChannel) { "${removeTrailingSlash()}/avatar/%23${avatar.removeTrailingSlash()}?format=$format&rc_uid=$userId&rc_token=$token" } else { "${removeTrailingSlash()}/avatar/${avatar.removeTrailingSlash()}?format=$format&rc_uid=$userId&rc_token=$token" } } fun String.fileUrl(path: String, token: Token): String { return (this + path + "?rc_uid=${token.userId}" + "&rc_token=${token.authToken}").safeUrl() } fun String.safeUrl(): String { return this.replace(" ", "%20").replace("\\", "") } fun String.serverLogoUrl(favicon: String) = "${removeTrailingSlash()}/$favicon" fun String.casUrl(serverUrl: String, casToken: String) = "${removeTrailingSlash()}?service=${serverUrl.removeTrailingSlash()}/_cas/$casToken" fun String.samlUrl(provider: String, samlToken: String) = "${removeTrailingSlash()}/_saml/authorize/$provider/$samlToken" fun String.termsOfServiceUrl() = "${removeTrailingSlash()}/terms-of-service" fun String.privacyPolicyUrl() = "${removeTrailingSlash()}/privacy-policy" fun String.adminPanelUrl() = "${removeTrailingSlash()}/admin/info?layout=embedded" fun String.isValidUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches() fun String.parseColor(): Int { return try { Color.parseColor(this) } catch (exception: IllegalArgumentException) { // Log the exception and get the white color. Timber.e(exception) Color.parseColor("white") } } fun String.userId(userId: String?): String? { return userId?.let { this.replace(it, "") } } fun String.lowercaseUrl(): String? = this.toHttpUrlOrNull()?.run { newBuilder().scheme(scheme.toLowerCase()).build().toString() } fun String?.isNotNullNorEmpty(): Boolean = this != null && this.isNotEmpty() fun String?.isNotNullNorBlank(): Boolean = this != null && this.isNotBlank() inline fun String?.ifNotNullNotEmpty(block: (String) -> Unit) { if (this != null && this.isNotEmpty()) { block(this) } }
mit
d3b2f45024be402197885107b949665d
30.264368
122
0.687753
3.878745
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/extension/StaggeredGridLayoutManagerExtensions.kt
1
1675
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.extension import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager val StaggeredGridLayoutManager.reachingStart: Boolean get() { var visiblePos = findFirstCompletelyVisibleItemPositions(null) if (visiblePos.all { it == RecyclerView.NO_POSITION }) { visiblePos = findFirstVisibleItemPositions(null) } return visiblePos.contains(0) } val StaggeredGridLayoutManager.reachingEnd: Boolean get() { var visiblePos = findLastCompletelyVisibleItemPositions(null) if (visiblePos.all { it == RecyclerView.NO_POSITION }) { visiblePos = findLastVisibleItemPositions(null) } return visiblePos.contains(itemCount - 1) }
gpl-3.0
d977fb130c5471c9518335abcdad4bae
36.244444
72
0.726567
4.328165
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/protocol/ProtocolConnection.kt
1
3969
package pl.wendigo.chrome.protocol import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import kotlinx.serialization.KSerializer import kotlinx.serialization.json.JsonElement import okhttp3.OkHttpClient import pl.wendigo.chrome.api.target.SessionID import pl.wendigo.chrome.protocol.websocket.FrameMapper import pl.wendigo.chrome.protocol.websocket.RequestFrame import pl.wendigo.chrome.protocol.websocket.WebSocketFramesStream import java.io.Closeable import java.util.concurrent.atomic.AtomicLong /** * ProtocolConnection represents connection to chrome's debugger via [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). * * It depends on [WebSocketFramesStream] which is responsible for providing stream of WebSocket frames (both events and responses) and allows for sending request frames. * * [EventMapper] is responsible for mapping [pl.wendigo.chrome.protocol.websocket.EventResponseFrame]s to concrete [Event] representations. * * @see WebSocketFramesStream * @see FrameMapper * @see EventMapper */ class ProtocolConnection constructor( private val frames: WebSocketFramesStream, private val eventMapper: EventMapper = ProtocolConnection.eventMapper, private val sessionId: SessionID? = null ) : Closeable, AutoCloseable { private val nextRequestId = AtomicLong(0) /** * Closes connection to remote debugger. */ override fun close() { frames.close() } /** * Sends request and captures response from the stream. */ fun <T> request(methodName: String, request: JsonElement?, responseSerializer: KSerializer<T>): Single<T> { val requestFrame = RequestFrame( id = nextRequestId.incrementAndGet(), method = methodName, params = request, sessionId = sessionId ) return frames.send(requestFrame).flatMap { sent -> if (sent) { frames.getResponse(requestFrame, responseSerializer) } else { Single.error(RequestFailed(requestFrame, "Could not enqueue message $request")) } } } /** * Captures events by given name and casts received messages to specified class. */ fun <T> events(eventName: String, serializer: KSerializer<T>): Flowable<T> where T : Event { return frames.eventFrames() .filter { frame -> frame.matches(eventName, sessionId) } .map { frame -> eventMapper.deserialize(frame, serializer) } .subscribeOn(Schedulers.io()) } /** * Captures all events as generated by remote debugger */ fun events(): Flowable<Event> { return frames.eventFrames() .filter { frame -> frame.matches(sessionId) } .map { frame -> eventMapper.deserialize(frame) } .subscribeOn(Schedulers.io()) } /** * Reuse existing debugger connection but for new sessionID sharing underlying WebSocket connection. */ internal fun cloneForSessionId(sessionID: SessionID): ProtocolConnection = ProtocolConnection( frames, eventMapper, sessionID ) /** * Factory is responsible for opening debugger WebSocket connections to a given debugger uri. */ companion object Factory { /** * Creates new ChromeDebuggerConnection session for given WebSocket uri and frames buffer size. */ @JvmStatic fun open(webSocketUri: String, framesBufferSize: Int = 128): ProtocolConnection { return ProtocolConnection( WebSocketFramesStream(webSocketUri, framesBufferSize, frameMapper, OkHttpClient()), eventMapper ) } private val frameMapper by lazy { FrameMapper() } private val eventMapper by lazy { EventMapper() } } }
apache-2.0
3cadbcfce4b1483e1a6823c8a40f8219
34.123894
169
0.672714
4.846154
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/params/DeleteTeamPermissionParams.kt
1
675
package com.vimeo.networking2.params import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.TeamEntity import com.vimeo.networking2.enums.TeamEntityType /** * Body for the request which removes a permission policy association with a resource for a specific [TeamEntity]. * * @property teamEntityType the type of a [TeamEntity] * @property teamEntityUri the uri of a specific [TeamEntity] */ @JsonClass(generateAdapter = true) data class DeleteTeamPermissionParams( @Json(name = "team_entity_type") val teamEntityType: TeamEntityType? = null, @Json(name = "team_entity_uri") val teamEntityUri: String? = null )
mit
154b01cc37d3c73e1ce0b3de25ad6dcb
31.142857
114
0.765926
3.813559
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/hints/type/RsInlayTypeHintsTestBase.kt
3
1770
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints.type import com.intellij.codeInsight.hints.InlayHintsProvider import com.intellij.codeInsight.hints.InlayHintsProviderExtension import com.intellij.codeInsight.hints.InlayHintsSettings import com.intellij.codeInsight.hints.LinearOrderInlayRenderer import org.intellij.lang.annotations.Language import org.rust.RsTestBase import org.rust.lang.RsLanguage import kotlin.reflect.KClass @Suppress("UnstableApiUsage") abstract class RsInlayTypeHintsTestBase( private val providerClass: KClass<out InlayHintsProvider<*>> ) : RsTestBase() { override fun setUp() { super.setUp() changeHintsProviderStatuses { it::class == providerClass } } override fun tearDown() { changeHintsProviderStatuses { true } super.tearDown() } protected fun checkByText(@Language("Rust") code: String) { InlineFile(code.replace(HINT_COMMENT_PATTERN, "<$1/>")) checkInlays() } private fun checkInlays() { myFixture.testInlays( { (it.renderer as LinearOrderInlayRenderer<*>).toString() }, { it.renderer is LinearOrderInlayRenderer<*> } ) } companion object { private val HINT_COMMENT_PATTERN = Regex("""/\*(hint.*?)\*/""") private fun changeHintsProviderStatuses(statusGetter: (InlayHintsProvider<*>) -> Boolean) { val settings = InlayHintsSettings.instance() InlayHintsProviderExtension.findProviders() .filter { it.language == RsLanguage } .forEach { settings.changeHintTypeStatus(it.provider.key, it.language, statusGetter(it.provider)) } } } }
mit
049753ea4786a65a7bc7e92e7cf17d1a
31.777778
115
0.687006
4.609375
false
true
false
false
mightyfrog/S4FD
app/src/main/java/org/mightyfrog/android/s4fd/data/LandingLag.kt
1
1152
package org.mightyfrog.android.s4fd.data import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel /** * @author Shigehiro Soejima */ @Table(database = AppDatabase::class) class LandingLag : BaseModel() { @Column @SerializedName("frames") @Expose var frames: Int? = null @PrimaryKey @Column @SerializedName("id") @Expose var id: Int = 0 @Column @SerializedName("ownerId") @Expose var ownerId: Int = 0 @Column @SerializedName("moveId") @Expose var moveId: Int = 0 @Column @SerializedName("moveName") @Expose var moveName: String? = null @Column @SerializedName("notes") @Expose var notes: String? = null @Column @SerializedName("rawValue") @Expose var rawValue: String? = null @Column @SerializedName("lastModified") @Expose var lastModified: String? = null }
apache-2.0
ef67ea76d3b6dbfd1bab45334ab0eaf2
19.963636
56
0.684028
4.013937
false
false
false
false
androidx/androidx
credentials/credentials/src/androidTest/java/androidx/credentials/PasswordCredentialTest.kt
3
2111
/* * Copyright 2022 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.credentials import android.os.Bundle import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.testutils.assertThrows import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @SmallTest class PasswordCredentialTest { @Test fun constructor_emptyPassword_throws() { assertThrows<IllegalArgumentException> { PasswordCredential("id", "") } } @Test fun getter_id() { val idExpected = "id" val credential = PasswordCredential(idExpected, "password") assertThat(credential.id).isEqualTo(idExpected) } @Test fun getter_password() { val passwordExpected = "pwd" val credential = PasswordCredential("id", passwordExpected) assertThat(credential.password).isEqualTo(passwordExpected) } @Test fun getter_frameworkProperties() { val idExpected = "id" val passwordExpected = "pwd" val expectedData = Bundle() expectedData.putString(PasswordCredential.BUNDLE_KEY_ID, idExpected) expectedData.putString(PasswordCredential.BUNDLE_KEY_PASSWORD, passwordExpected) val credential = PasswordCredential(idExpected, passwordExpected) assertThat(credential.type).isEqualTo(PasswordCredential.TYPE_PASSWORD_CREDENTIAL) assertThat(equals(credential.data, expectedData)).isTrue() } }
apache-2.0
537a55fc03a24e5c7d39e0463d0186af
32
90
0.721459
4.501066
false
true
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/lazy/grid/BaseLazyGridTestWithOrientation.kt
3
5341
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.grid import androidx.compose.animation.core.snap import androidx.compose.foundation.AutoTestFrameClock import androidx.compose.foundation.BaseLazyLayoutTestWithOrientation import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.ScrollableDefaults import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking open class BaseLazyGridTestWithOrientation( orientation: Orientation ) : BaseLazyLayoutTestWithOrientation(orientation) { fun LazyGridState.scrollBy(offset: Dp) { runBlocking(Dispatchers.Main + AutoTestFrameClock()) { animateScrollBy(with(rule.density) { offset.roundToPx().toFloat() }, snap()) } } fun LazyGridState.scrollTo(index: Int) { runBlocking(Dispatchers.Main + AutoTestFrameClock()) { scrollToItem(index) } } fun SemanticsNodeInteraction.scrollBy(offset: Dp) = scrollMainAxisBy(offset) @Composable fun LazyGrid( cells: Int, modifier: Modifier = Modifier, state: LazyGridState = rememberLazyGridState(), contentPadding: PaddingValues = PaddingValues(0.dp), reverseLayout: Boolean = false, reverseArrangement: Boolean = false, flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(), userScrollEnabled: Boolean = true, crossAxisSpacedBy: Dp = 0.dp, mainAxisSpacedBy: Dp = 0.dp, content: LazyGridScope.() -> Unit ) = LazyGrid( GridCells.Fixed(cells), modifier, state, contentPadding, reverseLayout, reverseArrangement, flingBehavior, userScrollEnabled, crossAxisSpacedBy, mainAxisSpacedBy, content ) @Composable fun LazyGrid( cells: GridCells, modifier: Modifier = Modifier, state: LazyGridState = rememberLazyGridState(), contentPadding: PaddingValues = PaddingValues(0.dp), reverseLayout: Boolean = false, reverseArrangement: Boolean = false, flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(), userScrollEnabled: Boolean = true, crossAxisSpacedBy: Dp = 0.dp, mainAxisSpacedBy: Dp = 0.dp, content: LazyGridScope.() -> Unit ) { if (vertical) { val verticalArrangement = when { mainAxisSpacedBy != 0.dp -> Arrangement.spacedBy(mainAxisSpacedBy) reverseLayout xor reverseArrangement -> Arrangement.Bottom else -> Arrangement.Top } val horizontalArrangement = when { crossAxisSpacedBy != 0.dp -> Arrangement.spacedBy(crossAxisSpacedBy) else -> Arrangement.Start } LazyVerticalGrid( columns = cells, modifier = modifier, state = state, contentPadding = contentPadding, reverseLayout = reverseLayout, flingBehavior = flingBehavior, userScrollEnabled = userScrollEnabled, verticalArrangement = verticalArrangement, horizontalArrangement = horizontalArrangement, content = content ) } else { val horizontalArrangement = when { mainAxisSpacedBy != 0.dp -> Arrangement.spacedBy(mainAxisSpacedBy) reverseLayout xor reverseArrangement -> Arrangement.End else -> Arrangement.Start } val verticalArrangement = when { crossAxisSpacedBy != 0.dp -> Arrangement.spacedBy(crossAxisSpacedBy) else -> Arrangement.Top } LazyHorizontalGrid( rows = cells, modifier = modifier, state = state, contentPadding = contentPadding, reverseLayout = reverseLayout, flingBehavior = flingBehavior, userScrollEnabled = userScrollEnabled, horizontalArrangement = horizontalArrangement, verticalArrangement = verticalArrangement, content = content ) } } }
apache-2.0
b6f8ac9d1d7878b93b78776eb7b144fd
36.886525
88
0.6525
5.575157
false
false
false
false
eyesniper2/skRayFall
src/main/java/net/rayfall/eyesniper2/skrayfall/crackshot/effects/EffGenerateExplosion.kt
1
2265
package net.rayfall.eyesniper2.skrayfall.crackshot.effects import ch.njol.skript.Skript import ch.njol.skript.doc.Description import ch.njol.skript.doc.Name import ch.njol.skript.lang.Effect import ch.njol.skript.lang.Expression import ch.njol.skript.lang.SkriptParser import ch.njol.util.Kleenean import com.shampaggon.crackshot.CSUtility import de.slikey.effectlib.effect.AtomEffect import de.slikey.effectlib.util.DynamicLocation import net.rayfall.eyesniper2.skrayfall.Core import org.bukkit.Location import org.bukkit.entity.Entity import org.bukkit.entity.Player import org.bukkit.event.Event @Name("Generate Crackshot Explosion") @Description("Generate an explosion through Crackshot.") class EffGenerateExplosion : Effect() { // (generate|create) an explosion for %player% at %location% for weapon %string% private var locationExpression: Expression<Location>? = null private var playerExpression: Expression<Player>? = null private var weaponStringExpression: Expression<String>? = null @Suppress("UNCHECKED_CAST") override fun init(exp: Array<Expression<*>?>, arg1: Int, arg2: Kleenean, arg3: SkriptParser.ParseResult): Boolean { playerExpression = exp[0] as Expression<Player>? locationExpression = exp[1] as Expression<Location>? weaponStringExpression = exp[2] as Expression<String>? return true } override fun toString(arg0: Event?, arg1: Boolean): String { return "" } override fun execute(evt: Event) { val location = locationExpression?.getSingle(evt) val player = playerExpression?.getSingle(evt) val weaponString = weaponStringExpression?.getSingle(evt)?.replace("\"", "") if (location == null) { Skript.warning("Location was null for Generate Crackshot Explosion") return } if (player == null) { Skript.warning("Player was null for Generate Crackshot Explosion") return } if (weaponString == null) { Skript.warning("The weapons string was null for Generate Crackshot Explosion") return } val cs = CSUtility(); cs.generateExplosion(player, location, weaponString) } }
gpl-3.0
3e53be719693323512cdc127365b0f4a
32.820896
119
0.694923
4.05914
false
false
false
false
bibaev/stream-debugger-plugin
src/main/java/com/intellij/debugger/streams/resolve/CollapseResolver.kt
1
1493
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.streams.resolve import com.intellij.debugger.streams.trace.TraceElement /** * @author Vitaliy.Bibaev */ class CollapseResolver : PartialReductionResolverBase() { override fun buildResult(mapping: Map<TraceElement, List<TraceElement>>): ValuesOrderResolver.Result { val direct = mutableMapOf<TraceElement, MutableList<TraceElement>>() val reverse = mutableMapOf<TraceElement, MutableList<TraceElement>>() for (valueAfter in mapping.keys.sortedBy { it.time }) { val valuesBefore = mapping[valueAfter]!!.sortedBy { it.time } val reverseMapping = mutableListOf<TraceElement>() for (valueBefore in valuesBefore) { direct[valueBefore] = mutableListOf(valueAfter) reverseMapping += valueBefore } reverse[valueAfter] = reverseMapping } return ValuesOrderResolver.Result.of(direct, reverse) } }
apache-2.0
2f9c7c693a0a3589b3ff7e54ecab25d7
35.439024
104
0.735432
4.456716
false
false
false
false
darkpaw/boss_roobot
src/org/darkpaw/ld33/Main.kt
1
1183
package org.darkpaw.ld33 import kotlin.browser.document import kotlin.browser.window import jquery.* import org.w3c.dom.HTMLCanvasElement import org.w3c.dom.CanvasRenderingContext2D import kotlin.test.assertNotNull val canvas = initalizeCanvas() fun initalizeCanvas(): HTMLCanvasElement { //val canvas = document.createElement("canvas") as HTMLCanvasElement val canvas = document.getElementById("main_canvas") as HTMLCanvasElement //canvas.width = window.innerWidth.toInt(); //canvas.height = window.innerHeight.toInt(); //val context = canvas.getContext("2d") as CanvasRenderingContext2D //document.body!!.appendChild(canvas) return canvas } fun v(x: Double, y: Double) = Vector(x, y) fun main(vararg args: String) { println("Startup!") try { document.getElementById("title")!!.innerHTML = "Kotlin Javascript and HTML5 Canvas Test" }catch(e : NullPointerException){ println("Whoops, the HTML is missing the title element?") } jq { val context = canvas.getContext("2d") as CanvasRenderingContext2D val world = GameWorld(context) CanvasEvents(canvas, world) world.run() } }
agpl-3.0
899be6569d4b83397616162a78b90c6c
27.190476
96
0.707523
3.983165
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/account/AccountData.kt
1
11667
/* * Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.account import android.accounts.Account import android.accounts.AccountManager import android.content.ContentResolver import android.os.Bundle import android.os.Parcel import android.os.Parcelable import io.vavr.control.Try import org.andstatus.app.context.MyContext import org.andstatus.app.context.MyContextEmpty import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyPreferences import org.andstatus.app.data.MatchedUri import org.andstatus.app.origin.Origin import org.andstatus.app.util.Identifiable import org.andstatus.app.util.InstanceId import org.andstatus.app.util.JsonUtils import org.andstatus.app.util.MyLog import org.andstatus.app.util.SharedPreferencesUtil import org.andstatus.app.util.TryUtils import org.json.JSONObject class AccountData : Parcelable, AccountDataWriter, Identifiable { override val instanceId = InstanceId.next() private val myContextIn: MyContext val accountName: AccountName @Volatile private var data: JSONObject @Volatile private var persistent = false private constructor(myContext: MyContext, jso: JSONObject, persistent: Boolean) { this.myContextIn = myContext data = jso this.persistent = persistent val origin = if (myContext.isEmpty) Origin.EMPTY else myContext.origins.fromName(getDataString(Origin.KEY_ORIGIN_NAME)) accountName = AccountName.fromOriginAndUniqueName(origin, getDataString(MyAccount.KEY_UNIQUE_NAME)) logMe("new " + accountName.name + " from jso") } private constructor(accountName: AccountName, jso: JSONObject) { myContextIn = accountName.myContext this.accountName = accountName data = jso updateFromAccountName() logMe("new from " + accountName.name + " and jso") } fun withAccountName(accountName: AccountName): AccountData { return AccountData(accountName, data) } fun updateFrom(myAccount: MyAccount): AccountData { setDataString(MyAccount.KEY_ACTOR_OID, myAccount.actor.oid) myAccount.credentialsVerified.put(this) setDataBoolean(MyAccount.KEY_OAUTH, myAccount.isOAuth()) setDataLong(MyAccount.KEY_ACTOR_ID, myAccount.actor.actorId) myAccount.connection.saveTo(this) setPersistent(true) setDataBoolean(MyAccount.KEY_IS_SYNCABLE, myAccount.isSyncable) setDataBoolean(MyAccount.KEY_IS_SYNCED_AUTOMATICALLY, myAccount.isSyncedAutomatically) setDataLong(MyPreferences.KEY_SYNC_FREQUENCY_SECONDS, myAccount.syncFrequencySeconds) // We don't create accounts of other versions setDataInt(AccountUtils.KEY_VERSION, AccountUtils.ACCOUNT_VERSION) setDataInt(MyAccount.KEY_ORDER, myAccount.order) logMe("updated from $myAccount") return this } private fun updateFromAccountName() { setDataString(AccountUtils.KEY_ACCOUNT, accountName.name) setDataString(MyAccount.KEY_USERNAME, accountName.username) setDataString(MyAccount.KEY_UNIQUE_NAME, accountName.getUniqueName()) setDataString(Origin.KEY_ORIGIN_NAME, accountName.getOriginName()) } val myContext: MyContext get() = myContextIn.takeIf { it.nonEmpty && !it.isExpired } ?: accountName.origin.myContext fun isPersistent(): Boolean { return persistent } fun setPersistent(persistent: Boolean) { this.persistent = persistent } /** @return changed (and successfully saved) or not */ fun saveIfChanged(androidAccount: Account): Try<Boolean> { val oldData = fromAndroidAccount(myContext, androidAccount) if (this == oldData) return Try.success(false) var syncFrequencySeconds = getDataLong(MyPreferences.KEY_SYNC_FREQUENCY_SECONDS, 0) if (syncFrequencySeconds <= 0) { syncFrequencySeconds = MyPreferences.getSyncFrequencySeconds() } AccountUtils.setSyncFrequencySeconds(androidAccount, syncFrequencySeconds) val isSyncable = getDataBoolean(MyAccount.KEY_IS_SYNCABLE, true) if (isSyncable != ContentResolver.getIsSyncable(androidAccount, MatchedUri.AUTHORITY) > 0) { ContentResolver.setIsSyncable(androidAccount, MatchedUri.AUTHORITY, if (isSyncable) 1 else 0) } val syncAutomatically = getDataBoolean(MyAccount.KEY_IS_SYNCED_AUTOMATICALLY, true) if (syncAutomatically != ContentResolver.getSyncAutomatically(androidAccount, MatchedUri.AUTHORITY)) { // We need to preserve sync on/off during backup/restore. // don't know about "network tickles"... See: // http://stackoverflow.com/questions/5013254/what-is-a-network-tickle-and-how-to-i-go-about-sending-one ContentResolver.setSyncAutomatically(androidAccount, MatchedUri.AUTHORITY, syncAutomatically) } val am = AccountManager.get(myContext.context) val jsonString = toJsonString() logMe("Saving to " + androidAccount.name) am.setUserData(androidAccount, AccountUtils.KEY_ACCOUNT, jsonString) return TryUtils.TRUE } fun isVersionCurrent(): Boolean { return AccountUtils.ACCOUNT_VERSION == getVersion() } fun getVersion(): Int { return getDataInt(AccountUtils.KEY_VERSION, 0) } override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is AccountData) return false return isPersistent() == other.isPersistent() && toJsonString() == other.toJsonString() } override fun hashCode(): Int { var text: String? = java.lang.Boolean.toString(isPersistent()) text += toJsonString() return text.hashCode() } override fun dataContains(key: String): Boolean { var contains = false try { val str = getDataString(key, "null") if (str.compareTo("null") != 0) { contains = true } } catch (e: Exception) { MyLog.v(this, e) } return contains } fun getDataBoolean(key: String, defValue: Boolean): Boolean { var value = defValue try { val str = getDataString(key, "null") if (str.compareTo("null") != 0) { value = SharedPreferencesUtil.isTrue(str) } } catch (e: Exception) { MyLog.v(this, e) } return value } override fun getDataString(key: String, defValue: String): String { return JsonUtils.optString(data, key, defValue) } override fun getDataInt(key: String, defValue: Int): Int { var value = defValue try { val str = getDataString(key, "null") if (str.compareTo("null") != 0) { value = str.toInt() } } catch (e: Exception) { MyLog.v(this, e) } return value } fun getDataLong(key: String, defValue: Long): Long { var value = defValue try { val str = getDataString(key, "null") if (str.compareTo("null") != 0) { value = str.toLong() } } catch (e: Exception) { MyLog.v(this, e) } return value } fun setDataBoolean(key: String, value: Boolean) { try { setDataString(key, java.lang.Boolean.toString(value)) } catch (e: Exception) { MyLog.v(this, e) } } override fun setDataLong(key: String, value: Long) { try { setDataString(key, java.lang.Long.toString(value)) } catch (e: Exception) { MyLog.v(this, e) } } override fun setDataInt(key: String, value: Int) { try { setDataString(key, Integer.toString(value)) } catch (e: Exception) { MyLog.v(this, e) } } override fun setDataString(key: String, value: String?) { data = if (value.isNullOrEmpty()) { JsonUtils.remove(data, key) } else { JsonUtils.put(data, key, value) } } private fun logMe(msg: String?): AccountData { MyLog.v(this) { "$msg: ${toJsonString()}" } return this } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(toJsonString()) } fun toJSon(): JSONObject { return data } fun toJsonString(): String { return JsonUtils.toString(data, 2) } override val classTag: String get() = TAG companion object { private val TAG: String = AccountData::class.simpleName!! val EMPTY: AccountData = AccountData(MyContextEmpty.EMPTY, JSONObject(), false) fun fromAndroidAccount(myContext: MyContext, androidAccount: Account?): AccountData { requireNotNull(androidAccount) { "$TAG account is null" } val am = AccountManager.get(myContext.context) val jsonString: String = am.getUserData(androidAccount, AccountUtils.KEY_ACCOUNT) ?: "" val accountData = fromJsonString(myContext, jsonString, true) accountData.setDataBoolean(MyAccount.KEY_IS_SYNCABLE, ContentResolver.getIsSyncable(androidAccount, MatchedUri.AUTHORITY) != 0) accountData.setDataBoolean(MyAccount.KEY_IS_SYNCED_AUTOMATICALLY, ContentResolver.getSyncAutomatically(androidAccount, MatchedUri.AUTHORITY)) accountData.logMe("Loaded from account " + androidAccount.name) return accountData } private fun fromJsonString(myContext: MyContext, userData: String, persistent: Boolean): AccountData { return JsonUtils.toJsonObject(userData).map { jso: JSONObject -> fromJson(myContext, jso, persistent) } .getOrElse(EMPTY) } fun fromJson(myContext: MyContext, jso: JSONObject, persistent: Boolean): AccountData { return AccountData(myContext, jso, persistent) } fun fromAccountName(accountName: AccountName): AccountData { return AccountData(accountName, JSONObject()) } @JvmField val CREATOR: Parcelable.Creator<AccountData> = object : Parcelable.Creator<AccountData> { override fun createFromParcel(source: Parcel): AccountData { return fromBundle( MyContextHolder.myContextHolder.getNow(), source.readBundle()) } override fun newArray(size: Int): Array<AccountData?> { return arrayOfNulls<AccountData>(size) } } fun fromBundle(myContext: MyContext, bundle: Bundle?): AccountData { var jsonString = "" if (bundle != null) { jsonString = bundle.getString(AccountUtils.KEY_ACCOUNT) ?: "" } return fromJsonString(myContext, jsonString, false).logMe("Loaded from bundle") } } }
apache-2.0
03c50010a6ef3b197fc4e74e64f27c0a
36.156051
127
0.649267
4.577089
false
false
false
false