repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
blindpirate/gradle
build-logic/performance-testing/src/main/kotlin/gradlebuild/performance/tasks/DetermineBaselines.kt
1
4569
/* * Copyright 2020 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 gradlebuild.performance.tasks import gradlebuild.basics.kotlindsl.execAndGetStdout import gradlebuild.identity.extension.ModuleIdentityExtension import org.gradle.api.DefaultTask import org.gradle.api.provider.Property import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.gradle.internal.os.OperatingSystem import org.gradle.kotlin.dsl.* import org.gradle.work.DisableCachingByDefault import javax.inject.Inject const val defaultBaseline = "defaults" const val forceDefaultBaseline = "force-defaults" const val flakinessDetectionCommitBaseline = "flakiness-detection-commit" @DisableCachingByDefault(because = "Not worth caching") abstract class DetermineBaselines @Inject constructor(@get:Internal val distributed: Boolean) : DefaultTask() { @get:Internal abstract val configuredBaselines: Property<String> @get:Internal abstract val determinedBaselines: Property<String> @TaskAction fun determineForkPointCommitBaseline() { if (configuredBaselines.getOrElse("") == forceDefaultBaseline) { determinedBaselines.set(defaultBaseline) } else if (configuredBaselines.getOrElse("") == flakinessDetectionCommitBaseline) { determinedBaselines.set(determineFlakinessDetectionBaseline()) } else if (!currentBranchIsMasterOrRelease() && !OperatingSystem.current().isWindows && configuredBaselines.isDefaultValue()) { // Windows git complains "long path" so we don't build commit distribution on Windows determinedBaselines.set(forkPointCommitBaseline()) } else { determinedBaselines.set(configuredBaselines) } } /** * Coordinator build doesn't resolve to real commit version, they just pass "flakiness-detection-commit" as it is to worker build * "flakiness-detection-commit" is resolved to real commit id in worker build to disable build cache. * * @see PerformanceTest#NON_CACHEABLE_VERSIONS */ private fun determineFlakinessDetectionBaseline() = if (distributed) flakinessDetectionCommitBaseline else currentCommitBaseline() private fun currentBranchIsMasterOrRelease() = project.the<ModuleIdentityExtension>().logicalBranch.get() in listOf("master", "release") private fun Property<String>.isDefaultValue() = !isPresent || get() in listOf("", defaultBaseline) private fun currentCommitBaseline() = commitBaseline(project.execAndGetStdout("git", "rev-parse", "HEAD")) private fun forkPointCommitBaseline(): String { val source = tryGetUpstream() ?: "origin" project.execAndGetStdout("git", "fetch", source, "master", "release") val masterForkPointCommit = project.execAndGetStdout("git", "merge-base", "origin/master", "HEAD") val releaseForkPointCommit = project.execAndGetStdout("git", "merge-base", "origin/release", "HEAD") val forkPointCommit = if (project.exec { isIgnoreExitValue = true; commandLine("git", "merge-base", "--is-ancestor", masterForkPointCommit, releaseForkPointCommit) }.exitValue == 0) releaseForkPointCommit else masterForkPointCommit return commitBaseline(forkPointCommit) } private fun tryGetUpstream(): String? = project.execAndGetStdout("git", "remote", "-v") .lines() .find { it.contains("[email protected]:gradle/gradle.git") || it.contains("https://github.com/gradle/gradle.git") } .let { val str = it?.replace(Regex("\\s+"), " ") return str?.substring(0, str.indexOf(' ')) } private fun commitBaseline(commit: String): String { val baseVersionOnForkPoint = project.execAndGetStdout("git", "show", "$commit:version.txt") val shortCommitId = project.execAndGetStdout("git", "rev-parse", "--short", commit) return "$baseVersionOnForkPoint-commit-$shortCommitId" } }
apache-2.0
79b19e5d453401cab67732b5e685d617
40.536364
171
0.713066
4.384837
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/vimscript/model/options/helpers/IdeaRefactorModeHelper.kt
1
3483
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.options.helpers import com.intellij.codeInsight.lookup.LookupEvent import com.intellij.codeInsight.lookup.LookupListener import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.helper.editorMode import com.maddyhome.idea.vim.helper.hasBlockOrUnderscoreCaret import com.maddyhome.idea.vim.helper.hasVisualSelection import com.maddyhome.idea.vim.helper.subMode import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService object IdeaRefactorModeHelper { fun keepMode(): Boolean = (VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, IjVimOptionService.idearefactormodeName) as VimString).value == IjVimOptionService.idearefactormode_keep fun selectMode(): Boolean = (VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, IjVimOptionService.idearefactormodeName) as VimString).value == IjVimOptionService.idearefactormode_select fun correctSelection(editor: Editor) { val action: () -> Unit = { if (!editor.editorMode.hasVisualSelection && editor.selectionModel.hasSelection()) { SelectionVimListenerSuppressor.lock().use { editor.selectionModel.removeSelection() } } if (editor.editorMode.hasVisualSelection && editor.selectionModel.hasSelection()) { val autodetectedSubmode = VimPlugin.getVisualMotion().autodetectVisualSubmode(editor.vim) if (editor.subMode != autodetectedSubmode) { // Update the submode editor.subMode = autodetectedSubmode } } if (editor.hasBlockOrUnderscoreCaret()) { TemplateManagerImpl.getTemplateState(editor)?.currentVariableRange?.let { segmentRange -> if (!segmentRange.isEmpty && segmentRange.endOffset == editor.caretModel.offset && editor.caretModel.offset != 0) { editor.caretModel.moveToOffset(editor.caretModel.offset - 1) } } } } val lookup = LookupManager.getActiveLookup(editor) as? LookupImpl if (lookup != null) { val selStart = editor.selectionModel.selectionStart val selEnd = editor.selectionModel.selectionEnd lookup.performGuardedChange(action) lookup.addLookupListener(object : LookupListener { override fun beforeItemSelected(event: LookupEvent): Boolean { // FIXME: 01.11.2019 Nasty workaround because of problems in IJ platform // Lookup replaces selected text and not the template itself. So, if there is no selection // in the template, lookup value will not replace the template, but just insert value on the caret position lookup.performGuardedChange { editor.selectionModel.setSelection(selStart, selEnd) } lookup.removeLookupListener(this) return true } }) } else { action() } } }
mit
2c6c67367bfca98d7ea17c12d135521f
44.828947
201
0.745909
4.494194
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/AnnualSiteStatsUseCase.kt
1
6483
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases import android.view.View import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.fluxc.model.stats.YearsInsightsModel import org.wordpress.android.fluxc.store.StatsStore.InsightType.ANNUAL_SITE_STATS import org.wordpress.android.fluxc.store.stats.insights.MostPopularInsightsStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.NavigationTarget import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.ANNUAL_STATS import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Link import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Title import org.wordpress.android.ui.stats.refresh.lists.sections.granular.SelectedDateProvider import org.wordpress.android.ui.stats.refresh.lists.sections.insights.InsightUseCaseFactory import org.wordpress.android.ui.stats.refresh.utils.ItemPopupMenuHandler import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider import org.wordpress.android.util.LocaleManagerWrapper import java.util.Calendar import java.util.Date import javax.inject.Inject import javax.inject.Named private const val VISIBLE_ITEMS = 1 @Suppress("LongParameterList") class AnnualSiteStatsUseCase( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val mostPopularStore: MostPopularInsightsStore, private val statsSiteProvider: StatsSiteProvider, private val selectedDateProvider: SelectedDateProvider, private val annualStatsMapper: AnnualStatsMapper, private val localeManagerWrapper: LocaleManagerWrapper, private val popupMenuHandler: ItemPopupMenuHandler, private val useCaseMode: UseCaseMode ) : StatelessUseCase<YearsInsightsModel>(ANNUAL_SITE_STATS, mainDispatcher, backgroundDispatcher) { override suspend fun loadCachedData(): YearsInsightsModel? { val dbModel = mostPopularStore.getYearsInsights(statsSiteProvider.siteModel) return if (dbModel?.years?.isNotEmpty() == true) dbModel else null } override suspend fun fetchRemoteData(forced: Boolean): State<YearsInsightsModel> { val response = mostPopularStore.fetchYearsInsights(statsSiteProvider.siteModel, forced) val model = response.model val error = response.error return when { error != null -> State.Error(error.message ?: error.type.name) model != null && model.years.isNotEmpty() -> State.Data(model) else -> State.Empty() } } override fun buildLoadingItem(): List<BlockListItem> = listOf(Title(R.string.stats_insights_this_year_site_stats)) override fun buildUiModel(domainModel: YearsInsightsModel): List<BlockListItem> { val periodFromProvider = selectedDateProvider.getSelectedDate(ANNUAL_STATS) val availablePeriods = domainModel.years val availableDates = availablePeriods.map { yearToDate(it.year) } val selectedPeriod = periodFromProvider ?: availableDates.last() val index = availableDates.indexOf(selectedPeriod) selectedDateProvider.selectDate(selectedPeriod, availableDates, ANNUAL_STATS) val items = mutableListOf<BlockListItem>() when (useCaseMode) { UseCaseMode.BLOCK -> { items.add(buildTitle()) items.addAll(annualStatsMapper.mapYearInBlock(domainModel.years.last())) if (domainModel.years.size > VISIBLE_ITEMS) { items.add( Link( text = R.string.stats_insights_view_more, navigateAction = ListItemInteraction.create(this::onViewMoreClicked) ) ) } } UseCaseMode.VIEW_ALL -> { items.addAll( annualStatsMapper.mapYearInViewAll( domainModel.years.getOrNull(index) ?: domainModel.years.last() ) ) } UseCaseMode.BLOCK_DETAIL -> Unit // Do nothing } return items } private fun onViewMoreClicked() { navigateTo(NavigationTarget.ViewAnnualStats) } private fun yearToDate(year: String): Date { val calendar = Calendar.getInstance(localeManagerWrapper.getLocale()) calendar.timeInMillis = 0 calendar.set(Calendar.YEAR, Integer.valueOf(year)) calendar.set(Calendar.MONTH, calendar.getMaximum(Calendar.MONTH)) calendar.set(Calendar.DAY_OF_MONTH, calendar.getMaximum(Calendar.DAY_OF_MONTH)) return calendar.time } private fun buildTitle() = Title(R.string.stats_insights_this_year_site_stats, menuAction = this::onMenuClick) private fun onMenuClick(view: View) { popupMenuHandler.onMenuClick(view, type) } class AnnualSiteStatsUseCaseFactory @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val mostPopularStore: MostPopularInsightsStore, private val statsSiteProvider: StatsSiteProvider, private val annualStatsMapper: AnnualStatsMapper, private val localeManagerWrapper: LocaleManagerWrapper, private val selectedDateProvider: SelectedDateProvider, private val popupMenuHandler: ItemPopupMenuHandler ) : InsightUseCaseFactory { override fun build(useCaseMode: UseCaseMode) = AnnualSiteStatsUseCase( mainDispatcher, backgroundDispatcher, mostPopularStore, statsSiteProvider, selectedDateProvider, annualStatsMapper, localeManagerWrapper, popupMenuHandler, useCaseMode ) } }
gpl-2.0
904c8f3ecbc09e8ea34a7f8f2f6f514f
45.307143
118
0.697054
4.845291
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/data/remote/api/attachments/AttachmentsApi.kt
1
5447
package forpdateam.ru.forpda.model.data.remote.api.attachments import forpdateam.ru.forpda.entity.remote.editpost.AttachmentItem import forpdateam.ru.forpda.model.data.remote.IWebClient import forpdateam.ru.forpda.model.data.remote.api.NetworkRequest import forpdateam.ru.forpda.model.data.remote.api.NetworkResponse import forpdateam.ru.forpda.model.data.remote.api.RequestFile import forpdateam.ru.forpda.model.data.remote.api.editpost.EditPostParser import forpdateam.ru.forpda.model.data.remote.api.theme.ThemeApi import forpdateam.ru.forpda.model.data.remote.api.theme.ThemeParser import java.io.ByteArrayInputStream import java.security.MessageDigest class AttachmentsApi( private val webClient: IWebClient, private val attachmentsParser: AttachmentsParser ) { fun uploadQmsFiles(files: List<RequestFile>, pending: List<AttachmentItem>) = uploadFiles(-1, "MSG", files, pending) fun uploadTopicFiles(postId: Int, files: List<RequestFile>, pending: List<AttachmentItem>) = uploadFiles(postId, null, files, pending) fun deleteQmsFiles(items: List<AttachmentItem>) = deleteFiles(-1, "MSG", items) fun deleteTopicFiles(postId: Int, items: List<AttachmentItem>) = deleteFiles(postId, null, items) private fun uploadFiles( postId: Int, relType: String?, files: List<RequestFile>, pending: List<AttachmentItem> ): List<AttachmentItem> { val builder = NetworkRequest.Builder() .url("https://4pda.to/forum/index.php?act=attach") .xhrHeader() .formHeader("index", "1") .formHeader("maxSize", "134217728") .formHeader("allowExt", "") .formHeader("forum-attach-files", "") .formHeader("code", "check") if (postId != -1) { builder.formHeader("relId", postId.toString()) } for (i in files.indices) { val file = files[i] val item = pending[i] file.requestName = "FILE_UPLOAD[]" val messageDigest = MessageDigest.getInstance("MD5") file.fileStream = file.fileStream.use { val targetArray = ByteArray(it.available()).apply { it.read(this) } messageDigest.update(targetArray) ByteArrayInputStream(targetArray) } val hash = messageDigest.digest() val md5 = byteArrayToHexString(hash) builder .formHeader("md5", md5) .formHeader("size", file.fileStream.available().toString()) .formHeader("name", file.fileName) var response = webClient.request(builder.build()) if (response.body == "0") { val uploadRequest = NetworkRequest.Builder() .url("https://4pda.to/forum/index.php?act=attach") .xhrHeader() .formHeader("index", "1") .formHeader("maxSize", "134217728") .formHeader("allowExt", "") .formHeader("forum-attach-files", "") .formHeader("code", "upload") .file(file) if (postId != -1) { uploadRequest.formHeader("relId", postId.toString()) } if (relType != null) { uploadRequest.formHeader("relType", relType) } response = webClient.request(uploadRequest.build(), item.progressListener) } attachmentsParser.parseAttachment(response.body, item) item.status = AttachmentItem.STATUS_UPLOADED } return pending } private fun deleteFiles( postId: Int, relType: String?, items: List<AttachmentItem> ): List<AttachmentItem> { var response: NetworkResponse for (item in items) { val builder = NetworkRequest.Builder() .url("https://4pda.to/forum/index.php?act=attach") .xhrHeader() .formHeader("index", "1") .formHeader("maxSize", "134217728") .formHeader("allowExt", "") .formHeader("code", "remove") .formHeader("id", Integer.toString(item.id)) if (postId != -1) { builder.formHeader("relId", postId.toString()) } if (relType != null) { builder.formHeader("relType", relType) } response = webClient.request(builder.build()) //todo проверка на ошибки, я хз че еще может быть кроме 0 if (response.body == "0") { item.status = AttachmentItem.STATUS_REMOVED item.isError = false } } return items } private fun byteArrayToHexString(bytes: ByteArray): String { val hexString = StringBuilder() for (aByte in bytes) { val hex = Integer.toHexString(aByte.toInt() and 0xFF) if (hex.length == 1) { hexString.append('0') } hexString.append(hex) } return hexString.toString() } }
gpl-3.0
fa61f72ccb798d09b8282c351beb352c
37.920863
96
0.554631
4.615188
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToPropertyAccessFix.kt
1
1954
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject class ChangeToPropertyAccessFix( element: KtCallExpression, private val isObjectCall: Boolean ) : KotlinQuickFixAction<KtCallExpression>(element) { override fun getFamilyName() = when { isObjectCall -> KotlinBundle.message("fix.change.to.property.access.family.remove") else -> KotlinBundle.message("fix.change.to.property.access.family.change") } override fun getText() = familyName public override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return element.replace(element.calleeExpression as KtExpression) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtCallExpression>? { val expression = diagnostic.psiElement.parent as? KtCallExpression ?: return null if (expression.valueArguments.isEmpty()) { val isObjectCall = expression.calleeExpression?.getCallableDescriptor() is FakeCallableDescriptorForObject return ChangeToPropertyAccessFix(expression, isObjectCall) } return null } } }
apache-2.0
ba40a4ca58b5c7fecf0f07804785169a
44.44186
158
0.759468
4.97201
false
false
false
false
mdaniel/intellij-community
platform/util-ex/src/com/intellij/util/containers/util.kt
2
9398
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.containers import com.intellij.openapi.diagnostic.Logger import com.intellij.util.SmartList import com.intellij.util.lang.CompoundRuntimeException import java.util.* import java.util.stream.Stream import kotlin.collections.ArrayDeque import kotlin.collections.HashSet fun <K, V> MutableMap<K, MutableList<V>>.remove(key: K, value: V) { val list = get(key) if (list != null && list.remove(value) && list.isEmpty()) { remove(key) } } fun <K, V> MutableMap<K, MutableList<V>>.putValue(key: K, value: V) { val list = get(key) if (list == null) { put(key, SmartList(value)) } else { list.add(value) } } @Deprecated( message = "Use 'isNullOrEmpty()' from Kotlin standard library.", level = DeprecationLevel.WARNING, replaceWith = ReplaceWith("isNullOrEmpty()", imports = ["kotlin.collections.isNullOrEmpty"]) ) fun Collection<*>?.isNullOrEmpty(): Boolean = this == null || isEmpty() @Deprecated("use tail()", ReplaceWith("tail()"), DeprecationLevel.ERROR) val <T> List<T>.tail: List<T> get() = tail() /** * @return all the elements of a non-empty list except the first one */ fun <T> List<T>.tail(): List<T> { require(isNotEmpty()) return subList(1, size) } /** * @return all the elements of a non-empty list except the first one or empty list */ fun <T> List<T>.tailOrEmpty(): List<T> { if (isEmpty()) return emptyList() return subList(1, size) } /** * @return pair of the first element and the rest of a non-empty list */ fun <T> List<T>.headTail(): Pair<T, List<T>> = Pair(first(), tail()) /** * @return pair of the first element and the rest of a non-empty list, or `null` if a list is empty */ fun <T> List<T>.headTailOrNull(): Pair<T, List<T>>? = if (isEmpty()) null else headTail() /** * @return all the elements of a non-empty list except the last one */ fun <T> List<T>.init(): List<T> { require(isNotEmpty()) return subList(0, size - 1) } fun <T> List<T>?.nullize(): List<T>? { return if (this == null || this.isEmpty()) null else this } inline fun <T> Array<out T>.forEachGuaranteed(operation: (T) -> Unit) { return iterator().forEachGuaranteed(operation) } inline fun <T> Collection<T>.forEachGuaranteed(operation: (T) -> Unit) { return iterator().forEachGuaranteed(operation) } inline fun <T> Iterator<T>.forEachGuaranteed(operation: (T) -> Unit) { var errors: MutableList<Throwable>? = null for (element in this) { try { operation(element) } catch (e: Throwable) { if (errors == null) { errors = SmartList() } errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } inline fun <T> Collection<T>.forEachLoggingErrors(logger: Logger, operation: (T) -> Unit) { asSequence().forEach { try { operation(it) } catch (e: Throwable) { logger.error(e) } } return } inline fun <T, R : Any> Collection<T>.mapNotNullLoggingErrors(logger: Logger, operation: (T) -> R?): List<R> { return mapNotNull { try { operation(it) } catch (e: Throwable) { logger.error(e) null } } } fun <T> Array<T>?.stream(): Stream<T> = if (this != null) Stream.of(*this) else Stream.empty() fun <T> Stream<T>?.isEmpty(): Boolean = this == null || !this.findAny().isPresent fun <T> Stream<T>?.notNullize(): Stream<T> = this ?: Stream.empty() fun <T> Stream<T>?.getIfSingle(): T? { return this?.limit(2) ?.map { Optional.ofNullable(it) } ?.reduce(Optional.empty()) { a, b -> if (a.isPresent xor b.isPresent) b else Optional.empty() } ?.orNull() } /** * There probably could be some performance issues if there is lots of streams to concat. See * http://mail.openjdk.org/pipermail/lambda-dev/2013-July/010659.html for some details. * * See also [Stream.concat] documentation for other possible issues of concatenating large number of streams. */ fun <T> concat(vararg streams: Stream<T>): Stream<T> = Stream.of(*streams).reduce(Stream.empty()) { a, b -> Stream.concat(a, b) } inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } fun <T> MutableList<T>.addIfNotNull(e: T?) { e?.let(::add) } fun <T> MutableList<T>.addAllIfNotNull(vararg elements: T?) { elements.forEach { e -> e?.let(::add) } } inline fun <T, R> Array<out T>.mapSmart(transform: (T) -> R): List<R> { return when (val size = size) { 1 -> SmartList(transform(this[0])) 0 -> SmartList() else -> mapTo(ArrayList(size), transform) } } inline fun <T, reified R> Array<out T>.map2Array(transform: (T) -> R): Array<R> = Array(this.size) { i -> transform(this[i]) } inline fun <T, reified R> Collection<T>.map2Array(transform: (T) -> R): Array<R> { @Suppress("UNCHECKED_CAST") return arrayOfNulls<R>(this.size).also { array -> this.forEachIndexed { index, t -> array[index] = transform(t) } } as Array<R> } inline fun <T, R> Collection<T>.mapSmart(transform: (T) -> R): List<R> { return when (val size = size) { 1 -> SmartList(transform(first())) 0 -> emptyList() else -> mapTo(ArrayList(size), transform) } } /** * Not mutable set will be returned. */ inline fun <T, R> Collection<T>.mapSmartSet(transform: (T) -> R): Set<R> { return when (val size = size) { 1 -> { Collections.singleton(transform(first())) } 0 -> emptySet() else -> mapTo(java.util.HashSet(size), transform) } } inline fun <T, R : Any> Collection<T>.mapSmartNotNull(transform: (T) -> R?): List<R> { val size = size return if (size == 1) { transform(first())?.let { SmartList(it) } ?: SmartList() } else { mapNotNullTo(ArrayList(size), transform) } } fun <T> List<T>.toMutableSmartList(): MutableList<T> { return when (size) { 1 -> SmartList(first()) 0 -> SmartList() else -> ArrayList(this) } } inline fun <T> Collection<T>.filterSmart(predicate: (T) -> Boolean): List<T> { val result: MutableList<T> = when (size) { 1 -> SmartList() 0 -> return emptyList() else -> ArrayList() } filterTo(result, predicate) return result } inline fun <T> Collection<T>.filterSmartMutable(predicate: (T) -> Boolean): MutableList<T> { return filterTo(if (size <= 1) SmartList() else ArrayList(), predicate) } inline fun <reified E : Enum<E>, V> enumMapOf(): MutableMap<E, V> = EnumMap(E::class.java) fun <E> Collection<E>.toArray(empty: Array<E>): Array<E> { @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") return (this as java.util.Collection<E>).toArray(empty) } /** * Given a collection of elements S returns collection of minimal elements M as ordered by [comparator]. * * Let S = M ∪ R; M ∩ R = ∅. Then: * - ∀ m1 ∈ M, ∀ m2 ∈ M : m1 = m2; * - ∀ m ∈ M, ∀ r ∈ R : m < r. */ fun <T> Collection<T>.minimalElements(comparator: Comparator<in T>): Collection<T> { if (isEmpty() || size == 1) return this val result = SmartList<T>() for (item in this) { if (result.isEmpty()) { result.add(item) } else { val comparison = comparator.compare(result[0], item) if (comparison > 0) { result.clear() result.add(item) } else if (comparison == 0) { result.add(item) } } } return result } /** * _Example_ * The following will print `1`, `2` and `3` when executed: * ``` * arrayOf(1, 2, 3, 4, 5) * .iterator() * .stopAfter { it == 3 } * .forEach(::println) * ``` * @return an iterator, which stops [this] Iterator after first element for which [predicate] returns `true` */ inline fun <T> Iterator<T>.stopAfter(crossinline predicate: (T) -> Boolean): Iterator<T> { return iterator { for (element in this@stopAfter) { yield(element) if (predicate(element)) { break } } } } fun <T> Optional<T>.orNull(): T? = orElse(null) fun <T> Iterable<T>?.asJBIterable(): JBIterable<T> = JBIterable.from(this) fun <T> Array<T>?.asJBIterable(): JBIterable<T> = if (this == null) JBIterable.empty() else JBIterable.of(*this) /** * Modify the elements of the array without creating a new array * * @return the array itself */ fun <T> Array<T>.mapInPlace(transform: (T) -> T): Array<T> { for (i in this.indices) { this[i] = transform(this[i]) } return this } /** * @return sequence of distinct nodes in breadth-first order */ fun <Node> generateRecursiveSequence(initialSequence: Sequence<Node>, children: (Node) -> Sequence<Node>): Sequence<Node> { return sequence { val initialIterator = initialSequence.iterator() if (!initialIterator.hasNext()) { return@sequence } val visited = HashSet<Node>() val sequences = ArrayDeque<Sequence<Node>>() sequences.addLast(initialIterator.asSequence()) while (sequences.isNotEmpty()) { val currentSequence = sequences.removeFirst() for (node in currentSequence) { if (visited.add(node)) { yield(node) sequences.addLast(children(node)) } } } } } /** * Returns a new sequence either of single given element, if it is not null, or empty sequence if the element is null. */ fun <T : Any> sequenceOfNotNull(element: T?): Sequence<T> = if (element == null) emptySequence() else sequenceOf(element)
apache-2.0
b67d48bcfdb7725df286637d38ec9d73
26.904762
129
0.637372
3.369026
false
false
false
false
android/play-billing-samples
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/SubRepository.kt
1
15674
/* * Copyright 2018 Google LLC. All rights reserved. * * 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.subscriptions.data import android.util.Log import com.android.billingclient.api.Purchase import com.example.subscriptions.Constants import com.example.subscriptions.billing.BillingClientLifecycle import com.example.subscriptions.data.disk.SubLocalDataSource import com.example.subscriptions.data.network.SubRemoteDataSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine /** * Repository handling the work with subscriptions. */ class SubRepository private constructor( private val localDataSource: SubLocalDataSource, private val remoteDataSource: SubRemoteDataSource, private val billingClientLifecycle: BillingClientLifecycle, private val externalScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) ) { /** * True when there are pending network requests. */ val loading: StateFlow<Boolean> = remoteDataSource.loading /** * [MutableStateFlow] to coordinate updates from the database and the network. * Intended to be collected by ViewModel */ val subscriptions: StateFlow<List<SubscriptionStatus>> = localDataSource.getSubscriptions() .stateIn(externalScope, SharingStarted.WhileSubscribed(), emptyList()) private val _basicContent = MutableStateFlow<ContentResource?>(null) private val _premiumContent = MutableStateFlow<ContentResource?>(null) /** * [StateFlow] with the basic content. * Intended to be collected by ViewModel */ val basicContent = _basicContent.asStateFlow() /** * [StateFlow] with the premium content. * Intended to be collected by ViewModel */ val premiumContent = _premiumContent.asStateFlow() init { // Update content from the remote server. // We are using a MutableStateFlow so that we can clear the data immediately // when the subscription changes. externalScope.launch { remoteDataSource.basicContent.collect { _basicContent.emit(it) } } externalScope.launch { remoteDataSource.premiumContent.collect { _premiumContent.emit(it) } } // When the list of purchases changes, we need to update the subscription status // to indicate whether the subscription is local or not. It is local if the // the Google Play Billing APIs return a Purchase record for the product. It is not // local if there is no record of the subscription on the device. externalScope.launch { billingClientLifecycle.purchases.collect { purchases -> Log.i(TAG, "Collected purchases...") val currentSubscriptions = subscriptions.value val hasChanged = updateLocalPurchaseTokens(currentSubscriptions, purchases) // We only need to update the database if [isLocalPurchase] field needs // to be changed. if (hasChanged) { localDataSource.updateSubscriptions(currentSubscriptions) } purchases.forEach { registerSubscription(it.products.first(), it.purchaseToken) } } } } suspend fun updateSubscriptionsFromNetwork(remoteSubscriptions: List<SubscriptionStatus>?) { Log.i(TAG, "Updating subscriptions from remote: ${remoteSubscriptions?.size}") val currentSubscriptions = subscriptions.value val purchases = billingClientLifecycle.purchases.value val mergedSubscriptions = mergeSubscriptionsAndPurchases(currentSubscriptions, remoteSubscriptions, purchases) // Acknowledge the subscription if it is not. remoteSubscriptions?.let { acknowledgeRegisteredPurchaseTokens(it) } // Store the subscription information when it changes. localDataSource.updateSubscriptions(mergedSubscriptions) // Update the content when the subscription changes. remoteSubscriptions?.let { // Figure out which content we need to fetch. var updateBasic = false var updatePremium = false for (subscription in it) { when (subscription.product) { Constants.BASIC_PRODUCT -> { updateBasic = true } Constants.PREMIUM_PRODUCT -> { updatePremium = true // Premium subscribers get access to basic content as well. updateBasic = true } } } if (updateBasic) { remoteDataSource.updateBasicContent() } else { // If we no longer own this content, clear it from the UI. _basicContent.emit(null) } if (updatePremium) { remoteDataSource.updatePremiumContent() } else { // If we no longer own this content, clear it from the UI. _premiumContent.emit(null) } } } /** * Acknowledge subscriptions that have been registered by the server. * Returns true if the param list was empty or all acknowledgement were succeeded */ /** * Acknowledge subscriptions that have been registered by the server * and update local data source. */ private suspend fun acknowledgeRegisteredPurchaseTokens( remoteSubscriptions: List<SubscriptionStatus> ) { remoteSubscriptions.forEach { sub -> if (!sub.isAcknowledged) { return withContext(externalScope.coroutineContext) { try { val acknowledgedSubs = sub.purchaseToken?.let { sub.product?.let { it1 -> acknowledgeSubscription( it1, it ) } } if (acknowledgedSubs != null) { localDataSource.updateSubscriptions(acknowledgedSubs) } else { localDataSource.updateSubscriptions(listOf()) } } catch (e: Exception) { throw e } } } } } /** * Merge the previous subscriptions and new subscriptions by looking at on-device purchases. * * We want to return the list of new subscriptions, possibly with some modifications * based on old subscriptions and the on-devices purchases from Google Play Billing. * Old subscriptions should be retained if they are owned by someone else (subAlreadyOwned) * and the purchase token for the subscription is still on this device. */ private fun mergeSubscriptionsAndPurchases( oldSubscriptions: List<SubscriptionStatus>?, newSubscriptions: List<SubscriptionStatus>?, purchases: List<Purchase>? ): List<SubscriptionStatus> { return ArrayList<SubscriptionStatus>().apply { if (purchases != null) { // Record which purchases are local and can be managed on this device. updateLocalPurchaseTokens(newSubscriptions, purchases) } if (newSubscriptions != null) { addAll(newSubscriptions) } // Find old subscriptions that are in purchases but not in new subscriptions. if (purchases != null && oldSubscriptions != null) { for (oldSubscription in oldSubscriptions) { if (oldSubscription.subAlreadyOwned && oldSubscription.isLocalPurchase) { // This old subscription was previously marked as "already owned" by // another user. It should be included in the output if the product // and purchase token match their previous value. for (purchase in purchases) { if (purchase.products[0] == oldSubscription.product && purchase.purchaseToken == oldSubscription.purchaseToken ) { // The old subscription that was already owned subscription should // be added to the new subscriptions. // Look through the new subscriptions to see if it is there. var foundNewSubscription = false newSubscriptions?.let { for (newSubscription in it) { if (newSubscription.product == oldSubscription.product) { foundNewSubscription = true } } } if (!foundNewSubscription) { // The old subscription should be added to the output. // It matches a local purchase. add(oldSubscription) } } } } } } } } /** * Modify the subscriptions isLocalPurchase field based on the list of local purchases. * Return true if any of the values changed. */ private fun updateLocalPurchaseTokens( subscriptions: List<SubscriptionStatus>?, purchases: List<Purchase>? ): Boolean { var hasChanged = false subscriptions?.forEach { subscription -> var isLocalPurchase = false var purchaseToken = subscription.purchaseToken purchases?.forEach { purchase -> if (subscription.product == purchase.products[0]) { isLocalPurchase = true purchaseToken = purchase.purchaseToken } } if (subscription.isLocalPurchase != isLocalPurchase) { subscription.isLocalPurchase = isLocalPurchase subscription.purchaseToken = purchaseToken hasChanged = true } } return hasChanged } /** * Fetch subscriptions from the server and update local data source. */ suspend fun fetchSubscriptions(): Result<Unit> = externalScope.async { try { val subscriptions = remoteDataSource.fetchSubscriptionStatus() localDataSource.updateSubscriptions(subscriptions) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } }.await() /** * Register subscription to this account and update local data source. */ suspend fun registerSubscription(product: String, purchaseToken: String): Result<Unit> { return externalScope.async { try { val subs = remoteDataSource.registerSubscription( product = product, purchaseToken = purchaseToken ) updateSubscriptionsFromNetwork(subs) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } }.await() } /** * Transfer subscription to this account and update local data source. */ suspend fun transferSubscription(product: String, purchaseToken: String) { externalScope.launch { remoteDataSource.postTransferSubscriptionSync( product = product, purchaseToken = purchaseToken ) }.join() } /** * Register Instance ID. */ fun registerInstanceId(instanceId: String) { externalScope.launch { try { remoteDataSource.postRegisterInstanceId(instanceId) } catch (e: Exception) { Log.e(TAG, "Failed to register the instance ID - ${e.localizedMessage}") } } } /** * Unregister Instance ID. */ fun unregisterInstanceId(instanceId: String) { externalScope.launch { try { remoteDataSource.postUnregisterInstanceId(instanceId) } catch (e: Exception) { // In general, this should trigger error event (eg. by using Result object), // then ViewModel should collect it and show appropriate error to user. Log.e(TAG, "Failed to register the instance ID - ${e.localizedMessage}") } } } /** * Acknowledge subscription to this account. */ private suspend fun acknowledgeSubscription(product: String, purchaseToken: String) : List<SubscriptionStatus>? { val result = remoteDataSource.postAcknowledgeSubscription( product = product, purchaseToken = purchaseToken ) return suspendCoroutine { continuation -> continuation.resume(result) } } /** * Delete local user data when the user signs out. */ suspend fun deleteLocalUserData() { withContext(externalScope.coroutineContext) { localDataSource.deleteLocalUserData() _basicContent.emit(null) _premiumContent.emit(null) } } companion object { private const val TAG = "SubRepository" @Volatile private var INSTANCE: SubRepository? = null fun getInstance( localDataSource: SubLocalDataSource, subRemoteDataSource: SubRemoteDataSource, billingClientLifecycle: BillingClientLifecycle, externalScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) ): SubRepository = INSTANCE ?: synchronized(this) { INSTANCE ?: SubRepository( localDataSource, subRemoteDataSource, billingClientLifecycle, externalScope ) .also { INSTANCE = it } } } }
apache-2.0
63b7b77a522916b3c3f9ff9288bba070
38.087282
98
0.581154
5.939371
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/ksx6924/KROCAPData.kt
1
2509
/* * KROCAPData.kt * * Copyright 2019 Michael Farrell <[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 au.id.micolous.metrodroid.card.ksx6924 import au.id.micolous.metrodroid.card.iso7816.HIDDEN_TAG import au.id.micolous.metrodroid.card.iso7816.ISO7816Data.TAG_DISCRETIONARY_DATA import au.id.micolous.metrodroid.card.iso7816.TagContents.DUMP_SHORT import au.id.micolous.metrodroid.card.iso7816.TagDesc import au.id.micolous.metrodroid.multi.R object KROCAPData { private const val TAG_BALANCE_COMMAND = "11" const val TAG_SERIAL_NUMBER = "12" private const val TAG_AGENCY_SERIAL_NUMBER = "13" private const val TAG_CARD_ISSUER = "43" private const val TAG_TICKET_TYPE = "45" private const val TAG_SUPPORTED_PROTOCOLS = "47" private const val TAG_ADF_AID = "4f" private const val TAG_CARDTYPE = "50" private const val TAG_EXPIRY_DATE = "5f24" private const val TAG_ADDITIONAL_FILE_REFERENCES = "9f10" val TAGMAP = mapOf( TAG_CARDTYPE to TagDesc(R.string.cardtype_header, DUMP_SHORT), TAG_SUPPORTED_PROTOCOLS to TagDesc(R.string.supported_protocols, DUMP_SHORT), TAG_CARD_ISSUER to TagDesc(R.string.card_issuer, DUMP_SHORT), TAG_BALANCE_COMMAND to TagDesc(R.string.balance_command, DUMP_SHORT), TAG_ADF_AID to TagDesc(R.string.adf_aid, DUMP_SHORT), TAG_ADDITIONAL_FILE_REFERENCES to TagDesc(R.string.additional_file_references, DUMP_SHORT), TAG_TICKET_TYPE to TagDesc(R.string.ticket_type, DUMP_SHORT), TAG_EXPIRY_DATE to TagDesc(R.string.expiry_date, DUMP_SHORT), TAG_SERIAL_NUMBER to HIDDEN_TAG, // Card serial number TAG_AGENCY_SERIAL_NUMBER to TagDesc(R.string.agency_card_serial_number, DUMP_SHORT), TAG_DISCRETIONARY_DATA to TagDesc(R.string.discretionary_data, DUMP_SHORT) ) }
gpl-3.0
54f8ac602ba2ae7253cd9b22a6158e35
47.269231
103
0.717417
3.533803
false
false
false
false
phicdy/toto-anticipation
android/api/src/main/java/com/phicdy/totoanticipation/api/RakutenTotoTopParser.kt
1
4689
package com.phicdy.totoanticipation.api import com.phicdy.totoanticipation.domain.Toto import org.jsoup.Jsoup import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import javax.inject.Inject class RakutenTotoTopParser @Inject constructor() { /** * * Parse rakuten top page and return latest toto number like "0923". * * e.g. 0922 and 0924 does not have toto, 0925 is not opened, 0923 is latest. * * * * * <dl> * <dt>[第922回](/toto/schedule/0922/)</dt> * <dd class="type"> * <img src="/toto/schedule/images/icon_toto2.gif" width="35" height="24" align="toto Goal2"></img> </dd> * * <dd class="span">2017年04月14日(金)~2017年04月21日(金)</dd> * <dd class="date">04月24日(月)</dd> * <dd class="status">[販売中](/toto/schedule/0922/)</dd> </dl> * * * * * <dl> * <dt>[第923回](/toto/schedule/0923/)</dt> * <dd class="type"> * <img src="/toto/schedule/images/icon_toto.gif" width="35" height="24" align="toto"></img> <img src="/toto/schedule/images/icon_minitoto.gif" width="35" height="24" align="mini toto"></img> <img src="/toto/schedule/images/icon_toto3.gif" width="35" height="24" align="toto Goal3"></img></dd> * <dd class="span">2017年04月15日(土)~2017年04月22日(土)</dd> * <dd class="date">04月24日(月)</dd> * <dd class="status">[販売中](/toto/schedule/0923/)</dd> </dl> * * * * * <dl> * <dt>[第924回](/toto/schedule/0924/)</dt> * <dd class="type"> * <img src="/toto/schedule/images/icon_minitoto.gif" width="35" height="24" align="mini toto"></img> <img src="/toto/schedule/images/icon_toto3.gif" width="35" height="24" align="toto Goal3"></img></dd> * <dd class="span">2017年04月19日(水)~2017年04月26日(水)</dd> * <dd class="date">04月27日(木)</dd> * <dd class="status">[販売中](/toto/schedule/0924/)</dd> </dl> * * * * * <dl> * <dt>[第925回](/toto/schedule/0925/)</dt> * <dd class="type"> * <img src="/toto/schedule/images/icon_toto.gif" width="35" height="24" align="toto"></img> <img src="/toto/schedule/images/icon_minitoto.gif" width="35" height="24" align="mini toto"></img> <img src="/toto/schedule/images/icon_toto3.gif" width="35" height="24" align="toto Goal3"></img></dd> * <dd class="span">2017年04月22日(土)~2017年04月29日(土)</dd> * <dd class="date">05月01日(月)</dd> * <dd class="status">販売前</dd> </dl> * * * ... * * * @param body HTML string of rakuten toto top page * @return Latest toto */ fun latestToto(body: String): Toto { if (body.isEmpty()) return Toto(Toto.DEFAULT_NUMBER, Date()) val bodyDoc = Jsoup.parse(body) val scheduleTable = bodyDoc.getElementsByClass("table") val lis = scheduleTable.select("li") var latestNumber = "" var deadline: Date for (i in lis.indices) { val li = lis[i] // Check hold on now or not val statusEl = li.getElementsByClass("status").first() ?: continue val totoStatus = statusEl.text() if (totoStatus != "販売中") continue // Toto icon gif indicates toto is held on val totoImages = li.getElementsByTag("img") for (totoImage in totoImages) { if (totoImage.attr("src").contains("icon_toto.gif")) { // Link is like "/toto/schedule/0923/", split number only val link = statusEl.select("a[href]").attr("href") latestNumber = link.replace("[^0-9]".toRegex(), "") break } } if (latestNumber == "") continue // Parse deadline date from "<dd class="span">2017年04月14日(金)~2017年04月21日(金)</dd>" val span = li.getElementsByClass("span").first() ?: continue // Cut "2017年04月14日(金)~" and "(金)" at last val indexDeadlineStart = 15 val indexDeadlineHi = 26 var deadlineDateStr = span.text().substring(indexDeadlineStart, indexDeadlineHi) deadlineDateStr += " 00:00:00" val format = SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.JAPAN) try { deadline = format.parse(deadlineDateStr) return Toto(latestNumber, deadline) } catch (e: ParseException) { e.printStackTrace() } } return Toto(Toto.DEFAULT_NUMBER, Date()) } }
apache-2.0
323f6ca62512180da5faed2b25a09b7a
39.63964
297
0.573487
3.178999
false
true
false
false
jk1/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/BinaryXmlWriter.kt
2
3044
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.util.containers.ObjectIntHashMap import com.intellij.util.io.IOUtil import org.jdom.* import java.io.DataOutputStream private fun String.isEmptySafe(): Boolean { return try { isEmpty() } catch (e: NullPointerException) { LOG.error(e) true } } internal class BinaryXmlWriter(private val out: DataOutputStream) { private val strings = ObjectIntHashMap<String>() fun write(element: Element) { writeElement(element) } private fun writeString(string: String) { if (string.isEmptySafe()) { out.write(1) return } val reference = strings.get(string) if (reference != -1) { writeUInt29(reference shl 1) return } strings.put(string, strings.size()) // don't write actual length, IOUtil does it out.write((1 shl 1) or 1) IOUtil.writeUTF(out, string) } private fun writeElement(element: Element) { writeString(element.name) writeAttributes(element.attributes) val content = element.content for (item in content) { when (item) { is Element -> { out.writeByte(TypeMarker.ELEMENT.ordinal) writeElement(item) } is CDATA -> { out.writeByte(TypeMarker.CDATA.ordinal) writeString(item.text) } is Text -> if (!isAllWhitespace(item)) { out.writeByte(TypeMarker.TEXT.ordinal) writeString(item.text) } } } out.writeByte(TypeMarker.ELEMENT_END.ordinal) } private fun writeAttributes(attributes: List<Attribute>?) { val size = attributes?.size ?: 0 out.write(size) if (size == 0) { return } if (size > 255) { throw UnsupportedOperationException("attributes size > 255") } else { for (attribute in attributes!!) { writeString(attribute.name) writeString(attribute.value) } } } // Represent smaller integers with fewer bytes using the most significant bit of each byte. The worst case uses 32-bits // to represent a 29-bit number, which is what we would have done with no compression. private fun writeUInt29(v: Int) { when { v < 0x80 -> out.write(v) v < 0x4000 -> { out.write((v shr 7 and 0x7F or 0x80)) out.write(v and 0x7F) } v < 0x200000 -> { out.write((v shr 14 and 0x7F or 0x80)) out.write(v shr 7 and 0x7F or 0x80) out.write(v and 0x7F) } v < 0x40000000 -> { out.write(v shr 22 and 0x7F or 0x80) out.write (v shr 15 and 0x7F or 0x80) out.write(v shr 8 and 0x7F or 0x80) out.write(v and 0xFF) } else -> throw IllegalArgumentException("Integer out of range: $v") } } private fun isAllWhitespace(obj: Text): Boolean { return obj.text?.all { Verifier.isXMLWhitespace(it) } ?: return true } }
apache-2.0
b890f88b118962299cb58c72835563d5
25.710526
140
0.628121
3.767327
false
true
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/badges/Badges.kt
2
4349
package org.thoughtcrime.securesms.badges import android.content.Context import android.net.Uri import androidx.recyclerview.widget.RecyclerView import com.google.android.flexbox.AlignItems import com.google.android.flexbox.FlexDirection import com.google.android.flexbox.FlexboxLayoutManager import com.google.android.flexbox.JustifyContent import org.signal.core.util.DimensionUnit import org.signal.core.util.logging.Log import org.signal.libsignal.protocol.util.Pair import org.thoughtcrime.securesms.BuildConfig import org.thoughtcrime.securesms.badges.models.Badge import org.thoughtcrime.securesms.badges.models.Badge.Category.Companion.fromCode import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.database.model.databaseprotos.BadgeList import org.thoughtcrime.securesms.util.ScreenDensity import org.whispersystems.signalservice.api.profiles.SignalServiceProfile import java.math.BigDecimal import java.sql.Timestamp import java.util.concurrent.TimeUnit object Badges { private val TAG: String = Log.tag(Badges::class.java) fun DSLConfiguration.displayBadges( context: Context, badges: List<Badge>, selectedBadge: Badge? = null, fadedBadgeId: String? = null ) { badges .map { Badge.Model( badge = it, isSelected = it == selectedBadge, isFaded = it.id == fadedBadgeId ) } .forEach { customPref(it) } val badgeSize = DimensionUnit.DP.toPixels(88f) val windowWidth = context.resources.displayMetrics.widthPixels val perRow = (windowWidth / badgeSize).toInt() val empties = ((perRow - (badges.size % perRow)) % perRow) repeat(empties) { customPref(Badge.EmptyModel()) } } fun createLayoutManagerForGridWithBadges(context: Context): RecyclerView.LayoutManager { val layoutManager = FlexboxLayoutManager(context) layoutManager.flexDirection = FlexDirection.ROW layoutManager.alignItems = AlignItems.CENTER layoutManager.justifyContent = JustifyContent.CENTER return layoutManager } private fun getBadgeImageUri(densityPath: String): Uri { return Uri.parse(BuildConfig.BADGE_STATIC_ROOT).buildUpon() .appendPath(densityPath) .build() } private fun getBestBadgeImageUriForDevice(serviceBadge: SignalServiceProfile.Badge): Pair<Uri, String> { return when (ScreenDensity.getBestDensityBucketForDevice()) { "ldpi" -> Pair(getBadgeImageUri(serviceBadge.sprites6[0]), "ldpi") "mdpi" -> Pair(getBadgeImageUri(serviceBadge.sprites6[1]), "mdpi") "hdpi" -> Pair(getBadgeImageUri(serviceBadge.sprites6[2]), "hdpi") "xxhdpi" -> Pair(getBadgeImageUri(serviceBadge.sprites6[4]), "xxhdpi") "xxxhdpi" -> Pair(getBadgeImageUri(serviceBadge.sprites6[5]), "xxxhdpi") else -> Pair(getBadgeImageUri(serviceBadge.sprites6[3]), "xhdpi") }.also { Log.d(TAG, "Selected badge density ${it.second()}") } } private fun getTimestamp(bigDecimal: BigDecimal): Long { return Timestamp(bigDecimal.toLong() * 1000).time } @JvmStatic fun fromDatabaseBadge(badge: BadgeList.Badge): Badge { return Badge( badge.id, fromCode(badge.category), badge.name, badge.description, Uri.parse(badge.imageUrl), badge.imageDensity, badge.expiration, badge.visible, 0L ) } @JvmStatic fun toDatabaseBadge(badge: Badge): BadgeList.Badge { return BadgeList.Badge.newBuilder() .setId(badge.id) .setCategory(badge.category.code) .setDescription(badge.description) .setExpiration(badge.expirationTimestamp) .setVisible(badge.visible) .setName(badge.name) .setImageUrl(badge.imageUrl.toString()) .setImageDensity(badge.imageDensity) .build() } @JvmStatic fun fromServiceBadge(serviceBadge: SignalServiceProfile.Badge): Badge { val uriAndDensity: Pair<Uri, String> = getBestBadgeImageUriForDevice(serviceBadge) return Badge( serviceBadge.id, fromCode(serviceBadge.category), serviceBadge.name, serviceBadge.description, uriAndDensity.first(), uriAndDensity.second(), serviceBadge.expiration?.let { getTimestamp(it) } ?: 0, serviceBadge.isVisible, TimeUnit.SECONDS.toMillis(serviceBadge.duration) ) } }
gpl-3.0
45f958c6a1be24e20d350a29923175cc
32.198473
106
0.725454
4.130104
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpConnect.kt
1
2183
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.winhttp.internal import io.ktor.http.* import io.ktor.utils.io.core.* import kotlinx.atomicfu.* import kotlinx.cinterop.* import ktor.cinterop.winhttp.* import platform.windows.* internal typealias WinHttpStatusHandler = (statusInfo: LPVOID?, statusInfoLength: DWORD) -> Unit internal class WinHttpConnect(private val hConnect: COpaquePointer) : Closeable { private val closed = atomic(false) val handlers = mutableMapOf<UInt, WinHttpStatusHandler>() val isClosed: Boolean get() = closed.value /** * Opens an HTTP request to the target server. * @param method is request method. * @param url is request URL. * @param chunkedMode is request body chunking mode. */ fun openRequest( method: HttpMethod, url: Url, httpVersion: String?, chunkedMode: WinHttpChunkedMode ): COpaquePointer? { var openFlags = WINHTTP_FLAG_ESCAPE_DISABLE or WINHTTP_FLAG_ESCAPE_DISABLE_QUERY or WINHTTP_FLAG_NULL_CODEPAGE if (url.protocol.isSecure()) { openFlags = openFlags or WINHTTP_FLAG_SECURE } if (chunkedMode == WinHttpChunkedMode.Automatic) { openFlags = openFlags or WINHTTP_FLAG_AUTOMATIC_CHUNKING } return WinHttpOpenRequest( hConnect, method.value, url.fullPath, httpVersion, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, openFlags.convert() ) } fun on(status: WinHttpCallbackStatus, handler: WinHttpStatusHandler) { handlers[status.value] = handler } override fun close() { if (!closed.compareAndSet(expect = false, update = true)) return handlers.clear() WinHttpCloseHandle(hConnect) } companion object { private const val WINHTTP_FLAG_AUTOMATIC_CHUNKING = 0x00000200 private val WINHTTP_NO_REFERER = null private val WINHTTP_DEFAULT_ACCEPT_TYPES = null } }
apache-2.0
93f88f17f7d9da810ee936c29a63fbe7
27.723684
119
0.648191
4.263672
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-cio/jvmAndNix/src/io/ktor/client/engine/cio/utils.kt
1
9356
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.cio import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.request.* import io.ktor.client.utils.* import io.ktor.http.* import io.ktor.http.cio.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.util.date.* import io.ktor.utils.io.* import io.ktor.utils.io.CancellationException import io.ktor.utils.io.core.* import io.ktor.utils.io.errors.* import io.ktor.utils.io.errors.EOFException import io.ktor.websocket.* import kotlinx.coroutines.* import kotlin.coroutines.* @OptIn(InternalAPI::class) internal suspend fun writeRequest( request: HttpRequestData, output: ByteWriteChannel, callContext: CoroutineContext, overProxy: Boolean, closeChannel: Boolean = true ) = withContext(callContext) { val builder = RequestResponseBuilder() val method = request.method val url = request.url val headers = request.headers val body = request.body val contentLength = headers[HttpHeaders.ContentLength] ?: body.contentLength?.toString() val contentEncoding = headers[HttpHeaders.TransferEncoding] val responseEncoding = body.headers[HttpHeaders.TransferEncoding] val chunked = contentLength == null || responseEncoding == "chunked" || contentEncoding == "chunked" try { val normalizedUrl = if (url.pathSegments.isEmpty()) URLBuilder(url).apply { encodedPath = "/" }.build() else url val urlString = if (overProxy) normalizedUrl.toString() else normalizedUrl.fullPath builder.requestLine(method, urlString, HttpProtocolVersion.HTTP_1_1.toString()) // this will only add the port to the host header if the port is non-standard for the protocol if (!headers.contains(HttpHeaders.Host)) { val host = if (url.protocol.defaultPort == url.port) { url.host } else { url.hostWithPort } builder.headerLine(HttpHeaders.Host, host) } if (contentLength != null) { if ((method != HttpMethod.Get && method != HttpMethod.Head) || body !is OutgoingContent.NoContent) { builder.headerLine(HttpHeaders.ContentLength, contentLength) } } mergeHeaders(headers, body) { key, value -> if (key == HttpHeaders.ContentLength) return@mergeHeaders builder.headerLine(key, value) } if (chunked && contentEncoding == null && responseEncoding == null && body !is OutgoingContent.NoContent) { builder.headerLine(HttpHeaders.TransferEncoding, "chunked") } builder.emptyLine() output.writePacket(builder.build()) output.flush() } catch (cause: Throwable) { if (closeChannel) { output.close() } throw cause } finally { builder.release() } if (body is OutgoingContent.NoContent) { if (closeChannel) output.close() return@withContext } val chunkedJob: EncoderJob? = if (chunked) encodeChunked(output, callContext) else null val channel = chunkedJob?.channel ?: output val scope = CoroutineScope(callContext + CoroutineName("Request body writer")) scope.launch { try { when (body) { is OutgoingContent.NoContent -> return@launch is OutgoingContent.ByteArrayContent -> channel.writeFully(body.bytes()) is OutgoingContent.ReadChannelContent -> body.readFrom().copyAndClose(channel) is OutgoingContent.WriteChannelContent -> body.writeTo(channel) is OutgoingContent.ProtocolUpgrade -> throw UnsupportedContentTypeException(body) } } catch (cause: Throwable) { channel.close(cause) throw cause } finally { channel.flush() chunkedJob?.channel?.close() chunkedJob?.join() output.closedCause?.unwrapCancellationException()?.takeIf { it !is CancellationException }?.let { throw it } if (closeChannel) { output.close() } } } } internal suspend fun readResponse( requestTime: GMTDate, request: HttpRequestData, input: ByteReadChannel, output: ByteWriteChannel, callContext: CoroutineContext ): HttpResponseData = withContext(callContext) { val rawResponse = parseResponse(input) ?: throw EOFException("Failed to parse HTTP response: unexpected EOF") rawResponse.use { val status = HttpStatusCode(rawResponse.status, rawResponse.statusText.toString()) val contentLength = rawResponse.headers[HttpHeaders.ContentLength]?.toString()?.toLong() ?: -1L val transferEncoding = rawResponse.headers[HttpHeaders.TransferEncoding]?.toString() val connectionType = ConnectionOptions.parse(rawResponse.headers[HttpHeaders.Connection]) val rawHeaders = rawResponse.headers val headers = HeadersImpl(rawHeaders.toMap()) val version = HttpProtocolVersion.parse(rawResponse.version) if (status == HttpStatusCode.SwitchingProtocols) { val session = RawWebSocket(input, output, masking = true, coroutineContext = callContext) return@withContext HttpResponseData(status, requestTime, headers, version, session, callContext) } val body = when { request.method == HttpMethod.Head || status in listOf(HttpStatusCode.NotModified, HttpStatusCode.NoContent) || status.isInformational() -> { ByteReadChannel.Empty } else -> { val coroutineScope = CoroutineScope(callContext + CoroutineName("Response")) val httpBodyParser = coroutineScope.writer(autoFlush = true) { parseHttpBody(contentLength, transferEncoding, connectionType, input, channel) } httpBodyParser.channel } } return@withContext HttpResponseData(status, requestTime, headers, version, body, callContext) } } internal suspend fun startTunnel( request: HttpRequestData, output: ByteWriteChannel, input: ByteReadChannel ) { val builder = RequestResponseBuilder() try { val hostWithPort = request.url.hostWithPort builder.requestLine(HttpMethod("CONNECT"), hostWithPort, HttpProtocolVersion.HTTP_1_1.toString()) builder.headerLine(HttpHeaders.Host, hostWithPort) builder.headerLine("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid. request.headers[HttpHeaders.UserAgent]?.let { builder.headerLine(HttpHeaders.UserAgent, it) } request.headers[HttpHeaders.ProxyAuthenticate]?.let { builder.headerLine(HttpHeaders.ProxyAuthenticate, it) } request.headers[HttpHeaders.ProxyAuthorization]?.let { builder.headerLine(HttpHeaders.ProxyAuthorization, it) } builder.emptyLine() output.writePacket(builder.build()) output.flush() val rawResponse = parseResponse(input) ?: throw EOFException("Failed to parse CONNECT response: unexpected EOF") rawResponse.use { if (rawResponse.status / 200 != 1) { throw IOException("Can not establish tunnel connection") } rawResponse.headers[HttpHeaders.ContentLength]?.let { input.discard(it.toString().toLong()) } } } finally { builder.release() } } internal fun HttpHeadersMap.toMap(): Map<String, List<String>> { val result = mutableMapOf<String, MutableList<String>>() for (index in 0 until size) { val key = nameAt(index).toString() val value = valueAt(index).toString() if (result[key]?.add(value) == null) { result[key] = mutableListOf(value) } } return result } internal fun HttpStatusCode.isInformational(): Boolean = (value / 100) == 1 /** * Wrap channel so that [ByteWriteChannel.close] of the resulting channel doesn't lead to closing of the base channel. */ @OptIn(DelicateCoroutinesApi::class) internal fun ByteWriteChannel.withoutClosePropagation( coroutineContext: CoroutineContext, closeOnCoroutineCompletion: Boolean = true ): ByteWriteChannel { if (closeOnCoroutineCompletion) { // Pure output represents a socket output channel that is closed when request fully processed or after // request sent in case TCP half-close is allowed. coroutineContext[Job]!!.invokeOnCompletion { close() } } return GlobalScope.reader(coroutineContext, autoFlush = true) { channel.copyTo(this@withoutClosePropagation, Long.MAX_VALUE) [email protected]() }.channel } /** * Wrap channel using [withoutClosePropagation] if [propagateClose] is false otherwise return the same channel. */ internal fun ByteWriteChannel.handleHalfClosed( coroutineContext: CoroutineContext, propagateClose: Boolean ): ByteWriteChannel = if (propagateClose) this else withoutClosePropagation(coroutineContext)
apache-2.0
66144d4792122569017aff00c0338a2b
35.834646
120
0.657867
4.877998
false
false
false
false
bigscreen/binary-game
app/src/main/java/com/bigscreen/binarygame/misc/SoundService.kt
1
1836
package com.bigscreen.binarygame.misc import android.content.Context import android.media.MediaPlayer import com.bigscreen.binarygame.storage.BGPreferences import javax.inject.Inject class SoundService @Inject constructor( private val context: Context, private val preferences: BGPreferences ) { private var mpSoundFX: MediaPlayer? = null private var mpBackSound: MediaPlayer? = null fun playEffect(soundResId: Int) { if (preferences.isSoundFxEnabled().not()) return releaseSoundFX() mpSoundFX = MediaPlayer.create(context, soundResId) mpSoundFX?.setOnCompletionListener { releaseSoundFX() } mpSoundFX?.start() } private fun releaseSoundFX() { mpSoundFX?.release() mpSoundFX = null } fun initBackSound(soundResId: Int) { releaseBackSound() mpBackSound = MediaPlayer.create(context, soundResId) mpBackSound?.isLooping = true } fun playBackSound() { if (preferences.isMusicEnabled().not() || mpBackSound == null) return if (mpBackSound?.isPlaying == false) mpBackSound?.start() } fun pauseBackSound() { if (preferences.isMusicEnabled().not() || mpBackSound == null) return if (mpBackSound?.isPlaying == true) mpBackSound?.pause() } fun stopBackSound() { if (preferences.isMusicEnabled().not() || mpBackSound == null) return if (mpBackSound?.isPlaying == true) mpBackSound?.stop() } fun stopAndReleaseBackSound() { mpBackSound?.let { if (it.isPlaying) { it.stop() releaseBackSound() } else { releaseBackSound() } } } private fun releaseBackSound() { mpBackSound?.release() mpBackSound = null } }
apache-2.0
e793fd3ce74b63f130d79d3e0b875bf7
26.833333
77
0.627451
4.309859
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/insight/MixinEntryPoint.kt
1
2125
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.intellij.codeInspection.reference.RefElement import com.intellij.codeInspection.visibility.EntryPointWithVisibilityLevel import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiUtil import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element class MixinEntryPoint : EntryPointWithVisibilityLevel() { @JvmField var MIXIN_ENTRY_POINT = true override fun getId() = "mixin" override fun getDisplayName() = "Mixin injectors" override fun getTitle() = "Suggest private visibility level for Mixin injectors" override fun getIgnoreAnnotations() = MixinConstants.Annotations.ENTRY_POINTS override fun isEntryPoint(element: PsiElement): Boolean { val modifierList = (element as? PsiMethod)?.modifierList ?: return false return MixinConstants.Annotations.ENTRY_POINTS.any { modifierList.findAnnotation(it) != null } } override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement) override fun getMinVisibilityLevel(member: PsiMember): Int { if (member !is PsiMethod) return -1 val modifierList = member.modifierList return if (MixinConstants.Annotations.METHOD_INJECTORS.any { modifierList.findAnnotation(it) != null }) { PsiUtil.ACCESS_LEVEL_PRIVATE } else { -1 } } override fun isSelected() = MIXIN_ENTRY_POINT override fun setSelected(selected: Boolean) { MIXIN_ENTRY_POINT = selected } override fun readExternal(element: Element) = XmlSerializer.serializeInto(this, element) override fun writeExternal(element: Element) = XmlSerializer.serializeInto(this, element, SkipDefaultValuesSerializationFilters()) }
mit
e0a576d85d967af2155ce17a9228282a
33.836066
134
0.740706
4.711752
false
false
false
false
mdanielwork/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/uastLiteralUtils.kt
1
4960
/* * 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. */ @file:JvmName("UastLiteralUtils") package org.jetbrains.uast import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.PsiReference import com.intellij.psi.util.PsiTreeUtil /** * Checks if the [UElement] is a null literal. * * @return true if the receiver is a null literal, false otherwise. */ fun UElement.isNullLiteral(): Boolean = this is ULiteralExpression && this.isNull /** * Checks if the [UElement] is a boolean literal. * * @return true if the receiver is a boolean literal, false otherwise. */ fun UElement.isBooleanLiteral(): Boolean = this is ULiteralExpression && this.isBoolean /** * Checks if the [UElement] is a `true` boolean literal. * * @return true if the receiver is a `true` boolean literal, false otherwise. */ fun UElement.isTrueLiteral(): Boolean = this is ULiteralExpression && this.isBoolean && this.value == true /** * Checks if the [UElement] is a `false` boolean literal. * * @return true if the receiver is a `false` boolean literal, false otherwise. */ fun UElement.isFalseLiteral(): Boolean = this is ULiteralExpression && this.isBoolean && this.value == false /** * Checks if the [UElement] is a [String] literal. * * @return true if the receiver is a [String] literal, false otherwise. */ fun UElement.isStringLiteral(): Boolean = this is ULiteralExpression && this.isString /** * Returns the [String] literal value. * * @return literal text if the receiver is a valid [String] literal, null otherwise. */ fun UElement.getValueIfStringLiteral(): String? = if (isStringLiteral()) (this as ULiteralExpression).value as String else null /** * Checks if the [UElement] is a [Number] literal (Integer, Long, Float, Double, etc.). * * @return true if the receiver is a [Number] literal, false otherwise. */ fun UElement.isNumberLiteral(): Boolean = this is ULiteralExpression && this.value is Number /** * Checks if the [UElement] is an integral literal (is an [Integer], [Long], [Short], [Char] or [Byte]). * * @return true if the receiver is an integral literal, false otherwise. */ fun UElement.isIntegralLiteral(): Boolean = this is ULiteralExpression && when (value) { is Int -> true is Long -> true is Short -> true is Char -> true is Byte -> true else -> false } /** * Returns the integral value of the literal. * * @return long representation of the literal expression value, * 0 if the receiver literal expression is not a integral one. */ fun ULiteralExpression.getLongValue(): Long = value.let { when (it) { is Long -> it is Int -> it.toLong() is Short -> it.toLong() is Char -> it.toLong() is Byte -> it.toLong() else -> 0 } } /** * @return corresponding [PsiLanguageInjectionHost] for this [UExpression] if it exists. * Tries to not return same [PsiLanguageInjectionHost] for different UElement-s, thus returns `null` if host could be obtained from * another [UExpression]. */ val UExpression.sourceInjectionHost: PsiLanguageInjectionHost? get() { (this.sourcePsi as? PsiLanguageInjectionHost)?.let { return it } // following is a handling of KT-27283 if (this !is ULiteralExpression) return null val parent = this.uastParent if (parent is UPolyadicExpression && parent.sourcePsi is PsiLanguageInjectionHost) return null (this.sourcePsi?.parent as? PsiLanguageInjectionHost)?.let { return it } return null } /** * @return a non-strict parent [PsiLanguageInjectionHost] for [sourcePsi] of given literal expression if it exists. * * NOTE: consider using [sourceInjectionHost] as more performant. Probably will be deprecated in future. */ val ULiteralExpression.psiLanguageInjectionHost: PsiLanguageInjectionHost? get() = this.psi?.let { PsiTreeUtil.getParentOfType(it, PsiLanguageInjectionHost::class.java, false) } /** * @return all references injected into this [ULiteralExpression] * * Note: getting references simply from the `sourcePsi` will not work for Kotlin polyadic strings for instance */ val ULiteralExpression.injectedReferences: Iterable<PsiReference> get() { val element = this.psiLanguageInjectionHost ?: return emptyList() val references = element.references.asSequence() val innerReferences = element.children.asSequence().flatMap { e -> e.references.asSequence() } return (references + innerReferences).asIterable() }
apache-2.0
6d6fcbdc38d21ca6c6131a83bb9aa10b
34.435714
131
0.724395
4.253859
false
false
false
false
McMoonLakeDev/MoonLake
Core/src/main/kotlin/com/mcmoonlake/impl/depend/DependVaultEconomyImpl.kt
1
5459
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.impl.depend import com.mcmoonlake.api.depend.DependPluginAbstract import com.mcmoonlake.api.depend.DependPluginException import com.mcmoonlake.api.depend.DependVaultEconomy import com.mcmoonlake.api.getPlugin import com.mcmoonlake.api.getServicesManager import net.milkbowl.vault.Vault import net.milkbowl.vault.economy.Economy import net.milkbowl.vault.economy.EconomyResponse import org.bukkit.OfflinePlayer import org.bukkit.plugin.RegisteredServiceProvider class DependVaultEconomyImpl : DependPluginAbstract<Vault>(getPlugin(DependVaultEconomy.NAME)), DependVaultEconomy { /** * Vault 插件存在不代表 Economy 功能是否拥有服务实现, 所以初始化的时候获取并判断是否不为 null 否之抛出异常 */ private val economy: Economy init { val registered: RegisteredServiceProvider<Economy>? = getServicesManager().getRegistration(Economy::class.java) if(registered == null || registered.provider == null) throw DependPluginException("依赖插件 Vault 未存在注册的 Economy 服务功能.") this.economy = registered.provider } private fun adapter(value: EconomyResponse?): com.mcmoonlake.api.wrapper.EconomyResponse { if(value?.type == null) return com.mcmoonlake.api.wrapper.EconomyResponse(.0, .0, com.mcmoonlake.api.wrapper.EconomyResponse.Type.NULL, null) val type = when(value.type) { EconomyResponse.ResponseType.FAILURE -> com.mcmoonlake.api.wrapper.EconomyResponse.Type.FAILURE EconomyResponse.ResponseType.SUCCESS -> com.mcmoonlake.api.wrapper.EconomyResponse.Type.SUCCESS EconomyResponse.ResponseType.NOT_IMPLEMENTED -> com.mcmoonlake.api.wrapper.EconomyResponse.Type.NOT_IMPLEMENTED else -> com.mcmoonlake.api.wrapper.EconomyResponse.Type.NULL } return com.mcmoonlake.api.wrapper.EconomyResponse(value.amount, value.balance, type, value.errorMessage) } override val implName: String get() = economy.name override fun fractionalDigits(): Int = economy.fractionalDigits() override fun currencyNamePlural(): String = economy.currencyNamePlural() override fun currencyNameSingular(): String = economy.currencyNameSingular() override fun format(value: Double): String = economy.format(value) override fun hasAccount(player: OfflinePlayer, world: String?): Boolean = economy.hasAccount(player, world) override fun createAccount(player: OfflinePlayer, world: String?): Boolean = economy.createPlayerAccount(player, world) override fun getBalance(player: OfflinePlayer, world: String?): Double = economy.getBalance(player, world) override fun hasBalance(player: OfflinePlayer, value: Double, world: String?): Boolean = economy.has(player, world, value) override fun withdraw(player: OfflinePlayer, value: Double, world: String?): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.withdrawPlayer(player, world, value)) override fun deposit(player: OfflinePlayer, value: Double, world: String?): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.depositPlayer(player, world, value)) override fun hasBankSupport(): Boolean = economy.hasBankSupport() override fun createBank(name: String, owner: OfflinePlayer): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.createBank(name, owner)) override fun deleteBank(name: String): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.deleteBank(name)) override fun getBankBalance(name: String): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.bankBalance(name)) override fun hasBankBalance(name: String, value: Double): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.bankHas(name, value)) override fun bankWithdraw(name: String, value: Double): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.bankWithdraw(name, value)) override fun bankDeposit(name: String, value: Double): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.bankDeposit(name, value)) override fun isBankOwner(name: String, player: OfflinePlayer): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.isBankOwner(name, player)) override fun isBankMember(name: String, player: OfflinePlayer): com.mcmoonlake.api.wrapper.EconomyResponse = adapter(economy.isBankMember(name, player)) override val banks: List<String> get() = economy.banks }
gpl-3.0
15ee90541ca02782d4c1545511daf782
42.860656
129
0.727154
4.301447
false
false
false
false
cascheberg/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorSelectionViewModel.kt
1
2502
package org.thoughtcrime.securesms.conversation.colors.ui import androidx.fragment.app.FragmentActivity import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import org.thoughtcrime.securesms.conversation.colors.ChatColors import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.SingleLiveEvent import org.thoughtcrime.securesms.util.livedata.Store class ChatColorSelectionViewModel(private val repository: ChatColorSelectionRepository) : ViewModel() { private val store = Store<ChatColorSelectionState>(ChatColorSelectionState()) private val chatColors = ChatColorsOptionsLiveData() private val internalEvents = SingleLiveEvent<Event>() val state: LiveData<ChatColorSelectionState> = store.stateLiveData val events: LiveData<Event> = internalEvents init { store.update(chatColors) { colors, state -> state.copy(chatColorOptions = colors) } } fun refresh() { repository.getWallpaper { wallpaper -> store.update { it.copy(wallpaper = wallpaper) } } repository.getChatColors { chatColors -> store.update { it.copy(chatColors = chatColors) } } } fun save(chatColors: ChatColors) { repository.save(chatColors, this::refresh) } fun duplicate(chatColors: ChatColors) { repository.duplicate(chatColors) } fun startDeletion(chatColors: ChatColors) { repository.getUsageCount(chatColors.id) { if (it > 0) { internalEvents.postValue(Event.ConfirmDeletion(it, chatColors)) } else { deleteNow(chatColors) } } } fun deleteNow(chatColors: ChatColors) { repository.delete(chatColors, this::refresh) } class Factory(private val repository: ChatColorSelectionRepository) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T = requireNotNull(modelClass.cast(ChatColorSelectionViewModel(repository))) } companion object { fun getOrCreate(activity: FragmentActivity, recipientId: RecipientId?): ChatColorSelectionViewModel { val repository = ChatColorSelectionRepository.create(activity, recipientId) val viewModelFactory = Factory(repository) return ViewModelProviders.of(activity, viewModelFactory).get(ChatColorSelectionViewModel::class.java) } } sealed class Event { class ConfirmDeletion(val usageCount: Int, val chatColors: ChatColors) : Event() } }
gpl-3.0
a3bab2d877aaad2dd738a0f61b8c3cab
32.810811
140
0.760592
4.607735
false
false
false
false
McMoonLakeDev/MoonLake
Core-v1.9-R2/src/main/kotlin/com/mcmoonlake/impl/anvil/AnvilWindowImpl_v1_9_R2.kt
1
2741
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.impl.anvil import net.minecraft.server.v1_9_R2.* import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer import org.bukkit.entity.Player import org.bukkit.inventory.Inventory import org.bukkit.plugin.Plugin open class AnvilWindowImpl_v1_9_R2( plugin: Plugin ) : AnvilWindowBase(plugin) { override fun open(player: Player) { super.open(player) val playerHandle = (player as CraftPlayer).handle val anvilTileContainer = AnvilWindowTileEntity(playerHandle.world) playerHandle.openTileEntity(anvilTileContainer) // add this anvil window id to list addWindowId(playerHandle.activeContainer.windowId) } override fun getInventory(): Inventory { val containerAnvil = handle as ContainerAnvil return containerAnvil.bukkitView.topInventory } private inner class AnvilWindowTileEntity(world: World) : BlockAnvil.TileEntityContainerAnvil(world, BlockPosition.ZERO) { override fun createContainer(playerInventory: PlayerInventory, opener: EntityHuman): Container? { val containerAnvil = object: ContainerAnvil(playerInventory, opener.world, BlockPosition.ZERO, opener) { override fun a(entityHuman: EntityHuman?): Boolean = true override fun a(value: String?) { if(inputHandler == null) { super.a(value) return } val event = callAnvilEvent(inputHandler, value) if(event != null && !event.isCancelled) super.a(event.input) } override fun b(entityHuman: EntityHuman?) { callAnvilEvent(closeHandler) release() super.b(entityHuman) } } handle = containerAnvil callAnvilEvent(openHandler) return containerAnvil } } }
gpl-3.0
89c0b18d5b6008425d21cf9c98929a4c
38.724638
126
0.645385
4.62226
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/diagnosticBased/HLRedundantVisibilityModifierInspection.kt
3
2370
// 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.fir.inspections.diagnosticBased import com.intellij.codeInspection.ProblemHighlightType import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.HLApplicator import org.jetbrains.kotlin.idea.api.applicator.with import org.jetbrains.kotlin.idea.fir.api.AbstractHLDiagnosticBasedInspection import org.jetbrains.kotlin.idea.fir.api.applicator.* import org.jetbrains.kotlin.idea.fir.api.inputByDiagnosticProvider import org.jetbrains.kotlin.idea.fir.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.fir.applicators.ModifierApplicators import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType class HLRedundantVisibilityModifierInspection : AbstractHLDiagnosticBasedInspection<KtModifierListOwner, KtFirDiagnostic.RedundantVisibilityModifier, ModifierApplicators.Modifier>( elementType = KtModifierListOwner::class, diagnosticType = KtFirDiagnostic.RedundantVisibilityModifier::class ) { override val inputByDiagnosticProvider = inputByDiagnosticProvider<KtModifierListOwner, KtFirDiagnostic.RedundantVisibilityModifier, ModifierApplicators.Modifier> { diagnostic -> val modifier = diagnostic.psi.visibilityModifierType() ?: return@inputByDiagnosticProvider null ModifierApplicators.Modifier(modifier) } override val presentation: HLPresentation<KtModifierListOwner> = presentation { highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) } override val applicabilityRange: HLApplicabilityRange<KtModifierListOwner> = ApplicabilityRanges.VISIBILITY_MODIFIER override val applicator: HLApplicator<KtModifierListOwner, ModifierApplicators.Modifier> = ModifierApplicators.removeModifierApplicator( KtTokens.VISIBILITY_MODIFIERS, KotlinBundle.lazyMessage("redundant.visibility.modifier") ).with { actionName { _, (modifier) -> KotlinBundle.message("remove.redundant.0.modifier", modifier.value) } } }
apache-2.0
86256f23fa74ca4b345f8e9397d35fa9
52.886364
158
0.803376
5.278396
false
false
false
false
ogarcia/ultrasonic
core/domain/src/main/kotlin/org/moire/ultrasonic/domain/Playlist.kt
2
424
package org.moire.ultrasonic.domain import java.io.Serializable data class Playlist @JvmOverloads constructor( val id: String, var name: String, val owner: String = "", val comment: String = "", val songCount: String = "", val created: String = "", val public: Boolean? = null ) : Serializable { companion object { private const val serialVersionUID = -4160515427075433798L } }
gpl-3.0
d2ae3c945bfae4b6a1275ba469a8b586
23.941176
66
0.662736
4.076923
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/facet/KotlinFacetType.kt
3
1245
// 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.facet import com.intellij.facet.FacetType import com.intellij.facet.FacetTypeId import com.intellij.facet.FacetTypeRegistry import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.ModuleType import com.intellij.openapi.util.NlsSafe import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.KotlinIcons import javax.swing.Icon abstract class KotlinFacetType<C : KotlinFacetConfiguration> : FacetType<KotlinFacet, C>(TYPE_ID, ID, NAME) { companion object { const val ID = "kotlin-language" val TYPE_ID = FacetTypeId<KotlinFacet>(ID) @NlsSafe const val NAME = "Kotlin" val INSTANCE get() = FacetTypeRegistry.getInstance().findFacetType(TYPE_ID) } override fun isSuitableModuleType(moduleType: ModuleType<*>): Boolean { return when { KotlinPlatformUtils.isCidr -> true else -> moduleType is JavaModuleType } } override fun getIcon(): Icon = KotlinIcons.SMALL_LOGO }
apache-2.0
bf9b0fe769f9483a8df92ca491fa250d
33.583333
158
0.727711
4.368421
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt
2
4625
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention import org.jetbrains.kotlin.idea.quickfix.SpecifyTypeExplicitlyFix import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.types.typeUtil.isNothing class FunctionWithLambdaExpressionBodyInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitNamedFunction(function: KtNamedFunction) { check(function) } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { if (accessor.isSetter) return if (accessor.returnTypeReference != null) return check(accessor) } private fun check(element: KtDeclarationWithBody) { val callableDeclaration = element.getNonStrictParentOfType<KtCallableDeclaration>() ?: return if (callableDeclaration.typeReference != null) return val lambda = element.bodyExpression as? KtLambdaExpression ?: return val functionLiteral = lambda.functionLiteral if (functionLiteral.arrow != null || functionLiteral.valueParameterList != null) return val lambdaBody = functionLiteral.bodyBlockExpression ?: return val used = ReferencesSearch.search(callableDeclaration).any() val fixes = listOfNotNull( IntentionWrapper(SpecifyTypeExplicitlyFix()), IntentionWrapper(AddArrowIntention()), if (!used && lambdaBody.statements.size == 1 && lambdaBody.allChildren.none { it is PsiComment } ) RemoveBracesFix() else null, if (!used) WrapRunFix() else null ) holder.registerProblem( lambda, KotlinBundle.message("inspection.function.with.lambda.expression.body.display.name"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixes.toTypedArray() ) } } private class AddArrowIntention : SpecifyExplicitLambdaSignatureIntention() { override fun skipProcessingFurtherElementsAfter(element: PsiElement): Boolean = false } private class RemoveBracesFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.braces.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val lambda = descriptor.psiElement as? KtLambdaExpression ?: return val singleStatement = lambda.functionLiteral.bodyExpression?.statements?.singleOrNull() ?: return val replaced = lambda.replaced(singleStatement) replaced.setTypeIfNeed() } } private class WrapRunFix : LocalQuickFix { override fun getName() = KotlinBundle.message("wrap.run.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val lambda = descriptor.psiElement as? KtLambdaExpression ?: return val body = lambda.functionLiteral.bodyExpression ?: return val replaced = lambda.replaced(KtPsiFactory(lambda).createExpressionByPattern("run { $0 }", body.allChildren)) replaced.setTypeIfNeed() } } } private fun KtExpression.setTypeIfNeed() { val declaration = getStrictParentOfType<KtCallableDeclaration>() ?: return val type = (declaration.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType if (type?.isNothing() == true) { declaration.setType(type) } }
apache-2.0
696a10404a5bc53efb8ac922163bc63a
43.902913
158
0.696216
5.499405
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ObsoleteExperimentalCoroutinesInspection.kt
3
8078
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.migration import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelFunctionFqnNameIndex import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull internal class ObsoleteExperimentalCoroutinesInspection : ObsoleteCodeMigrationInspection() { override val fromVersion: LanguageVersion = LanguageVersion.KOTLIN_1_2 override val toVersion: LanguageVersion = LanguageVersion.KOTLIN_1_3 override val problemReporters = listOf( ObsoleteTopLevelFunctionUsageReporter( "buildSequence", "kotlin.coroutines.experimental.buildSequence", "kotlin.sequences.sequence" ), ObsoleteTopLevelFunctionUsageReporter( "buildIterator", "kotlin.coroutines.experimental.buildIterator", "kotlin.sequences.iterator" ), ObsoleteExtensionFunctionUsageReporter( "resume", "kotlin.coroutines.experimental.Continuation.resume", "kotlin.coroutines.resume" ), ObsoleteExtensionFunctionUsageReporter( "resumeWithException", "kotlin.coroutines.experimental.Continuation.resumeWithException", "kotlin.coroutines.resumeWithException" ), ObsoleteCoroutinesImportsUsageReporter ) } private object ObsoleteCoroutinesUsageInWholeProjectFix : ObsoleteCodeInWholeProjectFix() { override val inspectionName = ObsoleteExperimentalCoroutinesInspection().shortName override fun getFamilyName(): String = KotlinBundle.message("obsolete.coroutine.usage.in.whole.fix.family.name") } private class ObsoleteCoroutinesDelegateQuickFix(delegate: ObsoleteCodeFix) : ObsoleteCodeFixDelegateQuickFix(delegate) { override fun getFamilyName(): String = KotlinBundle.message("obsolete.coroutine.usage.fix.family.name") } private fun isTopLevelCallForReplace(simpleNameExpression: KtSimpleNameExpression, oldFqName: String, newFqName: String): Boolean { if (simpleNameExpression.parent !is KtCallExpression) return false val descriptor = simpleNameExpression.resolveMainReferenceToDescriptors().firstOrNull() ?: return false val callableDescriptor = descriptor as? CallableDescriptor ?: return false val resolvedToFqName = callableDescriptor.fqNameOrNull()?.asString() ?: return false if (resolvedToFqName != oldFqName) return false val project = simpleNameExpression.project val isInIndex = KotlinTopLevelFunctionFqnNameIndex .get(newFqName, project, GlobalSearchScope.allScope(project)) .isEmpty() return !isInIndex } internal fun fixesWithWholeProject(isOnTheFly: Boolean, fix: LocalQuickFix, wholeProjectFix: LocalQuickFix): Array<LocalQuickFix> { if (!isOnTheFly) { return arrayOf(fix) } return arrayOf(fix, wholeProjectFix) } private class ObsoleteTopLevelFunctionUsageReporter( val textMarker: String, val oldFqName: String, val newFqName: String ) : ObsoleteCodeProblemReporter { override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean { if (simpleNameExpression.text != textMarker) return false if (!isTopLevelCallForReplace(simpleNameExpression, oldFqName, newFqName)) { return false } holder.registerProblem( simpleNameExpression, KotlinBundle.message("0.is.expected.to.be.used.since.kotlin.1.3", newFqName), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixesWithWholeProject(isOnTheFly, ObsoleteCoroutinesDelegateQuickFix(fix), ObsoleteCoroutinesUsageInWholeProjectFix) ) return true } private val fix = RebindReferenceFix(newFqName) companion object { private class RebindReferenceFix(val fqName: String) : ObsoleteCodeFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement if (element !is KtSimpleNameExpression) return element.mainReference.bindToFqName(FqName(fqName), KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING) } } } } private class ObsoleteExtensionFunctionUsageReporter( val textMarker: String, val oldFqName: String, val newFqName: String ) : ObsoleteCodeProblemReporter { override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean { if (simpleNameExpression.text != textMarker) return false if (!isTopLevelCallForReplace(simpleNameExpression, oldFqName, newFqName)) { return false } holder.registerProblem( simpleNameExpression, KotlinBundle.message("methods.are.absent.in.coroutines.class.since.1.3"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixesWithWholeProject(isOnTheFly, ObsoleteCoroutinesDelegateQuickFix(fix), ObsoleteCoroutinesUsageInWholeProjectFix) ) return true } private val fix = ImportExtensionFunctionFix(newFqName) companion object { private class ImportExtensionFunctionFix(val fqName: String) : ObsoleteCodeFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement if (element !is KtSimpleNameExpression) return val importFun = KotlinTopLevelFunctionFqnNameIndex .get(fqName, element.project, GlobalSearchScope.allScope(element.project)) .asSequence() .map { it.resolveToDescriptorIfAny() } .find { it != null && it.importableFqName?.asString() == fqName } ?: return ImportInsertHelper.getInstance(element.project).importDescriptor( element.containingKtFile, importFun, forceAllUnderImport = false ) } } } } private object ObsoleteCoroutinesImportsUsageReporter : ObsoleteImportsUsageReporter() { override val textMarker: String = "experimental" override val packageBindings: Map<String, String> = mapOf( "kotlinx.coroutines.experimental" to "kotlinx.coroutines", "kotlin.coroutines.experimental" to "kotlin.coroutines" ) override val importsToRemove: Set<String> = setOf( "kotlin.coroutines.experimental.buildSequence", "kotlin.coroutines.experimental.buildIterator" ) override val wholeProjectFix: LocalQuickFix = ObsoleteCoroutinesUsageInWholeProjectFix override fun problemMessage(): String = KotlinBundle.message("experimental.coroutines.usages.are.obsolete.since.1.3") override fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix = ObsoleteCoroutinesDelegateQuickFix(fix) }
apache-2.0
2a14799f8e3df348560ede4dba99b4ee
42.664865
158
0.732483
5.252276
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/graduate/design/pharmtech/GraduationDesignPharmtechController.kt
1
25778
package top.zbeboy.isy.web.graduate.design.pharmtech import org.apache.commons.lang.StringUtils import org.apache.commons.lang.math.NumberUtils import org.springframework.data.redis.core.ListOperations import org.springframework.data.redis.core.StringRedisTemplate import org.springframework.data.redis.core.ValueOperations import org.springframework.stereotype.Controller import org.springframework.ui.ModelMap import org.springframework.util.ObjectUtils import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import top.zbeboy.isy.config.Workbook import top.zbeboy.isy.domain.tables.pojos.GraduationDesignHopeTutor import top.zbeboy.isy.domain.tables.pojos.GraduationDesignRelease import top.zbeboy.isy.domain.tables.pojos.Student import top.zbeboy.isy.service.cache.CacheBook import top.zbeboy.isy.service.data.StudentService import top.zbeboy.isy.service.graduate.design.GraduationDesignHopeTutorService import top.zbeboy.isy.service.graduate.design.GraduationDesignTeacherService import top.zbeboy.isy.service.graduate.design.GraduationDesignTutorService import top.zbeboy.isy.service.platform.UsersService import top.zbeboy.isy.service.platform.UsersTypeService import top.zbeboy.isy.web.bean.error.ErrorBean import top.zbeboy.isy.web.bean.graduate.design.pharmtech.GraduationDesignTutorBean import top.zbeboy.isy.web.bean.graduate.design.release.GraduationDesignReleaseBean import top.zbeboy.isy.web.bean.graduate.design.teacher.GraduationDesignTeacherBean import top.zbeboy.isy.web.common.MethodControllerCommon import top.zbeboy.isy.web.graduate.design.common.GraduationDesignConditionCommon import top.zbeboy.isy.web.graduate.design.common.GraduationDesignMethodControllerCommon import top.zbeboy.isy.web.util.AjaxUtils import top.zbeboy.isy.web.util.PaginationUtils import java.util.ArrayList import java.util.HashMap import java.util.concurrent.TimeUnit import javax.annotation.Resource /** * Created by zbeboy 2018-01-19 . **/ @Controller open class GraduationDesignPharmtechController { @Resource open lateinit var graduationDesignTeacherService: GraduationDesignTeacherService @Resource open lateinit var graduationDesignHopeTutorService: GraduationDesignHopeTutorService @Resource open lateinit var usersService: UsersService @Resource open lateinit var studentService: StudentService @Resource open lateinit var methodControllerCommon: MethodControllerCommon @Resource open lateinit var graduationDesignTutorService: GraduationDesignTutorService @Resource open lateinit var usersTypeService: UsersTypeService @Resource open lateinit var template: StringRedisTemplate @Resource(name = "redisTemplate") open lateinit var stringValueOperations: ValueOperations<String, String> @Resource(name = "redisTemplate") open lateinit var stringListValueOperations: ValueOperations<String, List<GraduationDesignTeacherBean>> @Resource(name = "redisTemplate") open lateinit var listOperations: ListOperations<String, String> @Resource open lateinit var graduationDesignMethodControllerCommon: GraduationDesignMethodControllerCommon @Resource open lateinit var graduationDesignConditionCommon: GraduationDesignConditionCommon /** * 填报指导教师 * * @return 填报指导教师页面 */ @RequestMapping(value = ["/web/menu/graduate/design/pharmtech"], method = [(RequestMethod.GET)]) fun pharmtech(): String { return "web/graduate/design/pharmtech/design_pharmtech::#page-wrapper" } /** * 获取毕业设计发布数据 * * @param paginationUtils 分页工具 * @return 数据 */ @RequestMapping(value = ["/web/graduate/design/pharmtech/design/data"], method = [(RequestMethod.GET)]) @ResponseBody fun designDatas(paginationUtils: PaginationUtils): AjaxUtils<GraduationDesignReleaseBean> { return graduationDesignMethodControllerCommon.graduationDesignListDatas(paginationUtils) } /** * 志愿页面 * * @param graduationDesignReleaseId 发布id * @param modelMap 页面对象 * @return 页面 */ @RequestMapping(value = ["/web/graduate/design/pharmtech/wish"], method = [(RequestMethod.GET)]) fun pharmtechWish(@RequestParam("id") graduationDesignReleaseId: String, modelMap: ModelMap): String { return if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId) "web/graduate/design/pharmtech/design_pharmtech_wish::#page-wrapper" } else { methodControllerCommon.showTip(modelMap, "仅支持学生用户使用") } } /** * 填报页面 * * @param graduationDesignReleaseId 发布id * @param modelMap 页面对象 * @return 页面 */ @RequestMapping(value = ["/web/graduate/design/pharmtech/apply"], method = [(RequestMethod.GET)]) fun pharmtechApply(@RequestParam("id") graduationDesignReleaseId: String, modelMap: ModelMap): String { val errorBean = accessCondition(graduationDesignReleaseId) return if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student val count = graduationDesignHopeTutorService.countByStudentIdAndGraduationDesignReleaseId(student.studentId!!, graduationDesignReleaseId) if (count > 0) { modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId) "web/graduate/design/pharmtech/design_pharmtech_apply::#page-wrapper" } else { methodControllerCommon.showTip(modelMap, "请先填写志愿") } } else { methodControllerCommon.showTip(modelMap, errorBean.errorMsg!!) } } /** * 填报指导教师志愿数据 * * @param graduationDesignReleaseId 发布id * @return 数据 */ @RequestMapping(value = ["/web/graduate/design/pharmtech/wish/data"], method = [(RequestMethod.GET)]) @ResponseBody fun wishData(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<GraduationDesignTeacherBean> { val ajaxUtils = AjaxUtils.of<GraduationDesignTeacherBean>() if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { val users = usersService.getUserFromSession() val student = studentService.findByUsername(users!!.username) val designHopeTutorRecords = graduationDesignHopeTutorService.findByStudentIdAndGraduationDesignReleaseId(student.studentId!!, graduationDesignReleaseId) val graduationDesignTeachers = graduationDesignTeacherService.findByGraduationDesignReleaseIdRelationForStaff(graduationDesignReleaseId) for (designTeacherBean in graduationDesignTeachers) { var selectedTeacher = false if (designHopeTutorRecords.isNotEmpty) { val graduationDesignHopeTutors = designHopeTutorRecords.into(GraduationDesignHopeTutor::class.java) for (r in graduationDesignHopeTutors) { if (designTeacherBean.graduationDesignTeacherId == r.graduationDesignTeacherId) { selectedTeacher = true break } } } designTeacherBean.selected = selectedTeacher } ajaxUtils.success().msg("获取数据成功").listData(graduationDesignTeachers) } else { ajaxUtils.fail().msg("仅支持学生用户使用") } return ajaxUtils } /** * 填报指导教师数据 * * @param graduationDesignReleaseId 发布id * @return 数据 */ @RequestMapping(value = ["/web/graduate/design/pharmtech/apply/data"], method = [(RequestMethod.GET)]) @ResponseBody fun applyData(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<GraduationDesignTeacherBean> { val ajaxUtils = AjaxUtils.of<GraduationDesignTeacherBean>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student val graduationDesignTeacherBeens: List<GraduationDesignTeacherBean> val cacheKey = CacheBook.GRADUATION_DESIGN_TEACHER_STUDENT + graduationDesignReleaseId val studentKey = CacheBook.GRADUATION_DESIGN_PHARMTECH_STUDENT + student.studentId!! // 从缓存中得到列表 if (stringListValueOperations.operations.hasKey(cacheKey)!!) { graduationDesignTeacherBeens = stringListValueOperations.get(cacheKey)!! } else { graduationDesignTeacherBeens = ArrayList() } // 处理列表 if (!ObjectUtils.isEmpty(graduationDesignTeacherBeens) && graduationDesignTeacherBeens.size > 0) { var selectedTeacher = false for (designTeacherBean in graduationDesignTeacherBeens) { // 装填剩余人数 val studentCountKey = CacheBook.GRADUATION_DESIGN_TEACHER_STUDENT_COUNT + designTeacherBean.graduationDesignTeacherId if (template.hasKey(studentCountKey)) { val ops = this.template.opsForValue() designTeacherBean.residueCount = NumberUtils.toInt(ops.get(studentCountKey)) } // 选中当前用户已选择 if (!selectedTeacher && stringValueOperations.operations.hasKey(studentKey)!!) { // 解除逗号分隔的字符 指导教师id , 学生id val str = stringValueOperations.get(studentKey) if (StringUtils.isNotBlank(str)) { val arr = str!!.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (arr.size >= 2) { if (designTeacherBean.graduationDesignTeacherId == arr[0]) { selectedTeacher = true designTeacherBean.selected = true } } } } } } ajaxUtils.success().msg("获取数据成功").listData(graduationDesignTeacherBeens) } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 选择教师 * * @param graduationDesignTeacherId 指导老师id * @param graduationDesignReleaseId 发布id * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/wish/selected"], method = [(RequestMethod.POST)]) @ResponseBody fun wishSelected(@RequestParam("graduationDesignTeacherId") graduationDesignTeacherId: String, @RequestParam("graduationDesignReleaseId") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student // 是否已达到志愿数量 val count = graduationDesignHopeTutorService.countByStudentIdAndGraduationDesignReleaseId(student.studentId!!, graduationDesignReleaseId) if (count < 3) { val graduationDesignHopeTutor = GraduationDesignHopeTutor() graduationDesignHopeTutor.graduationDesignTeacherId = graduationDesignTeacherId graduationDesignHopeTutor.studentId = student.studentId graduationDesignHopeTutorService.save(graduationDesignHopeTutor) ajaxUtils.success().msg("保存成功") } else { ajaxUtils.fail().msg("最大支持志愿三位指导教师") } } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 填报选择教师 * * @param graduationDesignTeacherId 指导老师id * @param graduationDesignReleaseId 发布id * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/apply/selected"], method = [(RequestMethod.POST)]) @ResponseBody fun applySelected(@RequestParam("graduationDesignTeacherId") graduationDesignTeacherId: String, @RequestParam("graduationDesignReleaseId") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student // 判断是否已选择过教师 val canSelect: Boolean // 第一次选择 var isNewSelect = false val studentKey = CacheBook.GRADUATION_DESIGN_PHARMTECH_STUDENT + student.studentId!! if (stringValueOperations.operations.hasKey(studentKey)!!) { // 已选择过,不能重复选 val str = stringValueOperations.get(studentKey) if (StringUtils.isNotBlank(str)) { val arr = str!!.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() canSelect = arr.size >= 2 && arr[0] == "-1" } else { canSelect = false } } else { canSelect = true isNewSelect = true } if (canSelect) { // 计数器 val countKey = CacheBook.GRADUATION_DESIGN_TEACHER_STUDENT_COUNT + graduationDesignTeacherId if (template.hasKey(countKey)) { val ops = this.template.opsForValue() val count = NumberUtils.toInt(ops.get(countKey)) - 1 if (count >= 0) { ops.set(countKey, count.toString() + "") // 存储 指导教师id , 学生id if (isNewSelect) { stringValueOperations.set(studentKey, graduationDesignTeacherId + "," + student.studentId, CacheBook.EXPIRES_GRADUATION_DESIGN_TEACHER_STUDENT_DAYS, TimeUnit.DAYS) } else { stringValueOperations.set(studentKey, graduationDesignTeacherId + "," + student.studentId) } // 存储学生key // 是否已经存在当前学生key val listKey = CacheBook.GRADUATION_DESIGN_PHARMTECH_STUDENT_LIST + graduationDesignReleaseId val keys = listOperations.range(listKey, 0, listOperations.size(listKey)!!) val hasKey = !ObjectUtils.isEmpty(keys) && keys!!.contains(studentKey) // 不存在,需要添加 if (!hasKey) { listOperations.rightPush(listKey, studentKey) } ajaxUtils.success().msg("保存成功") } else { ajaxUtils.fail().msg("已达当前指导教师人数上限") } } else { ajaxUtils.fail().msg("未发现确认数据") } } else { ajaxUtils.fail().msg("仅可选择一位指导教师") } } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 取消教师 * * @param graduationDesignTeacherId 指导老师id * @param graduationDesignReleaseId 发布id * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/wish/cancel"], method = [(RequestMethod.POST)]) @ResponseBody fun wishCancel(@RequestParam("graduationDesignTeacherId") graduationDesignTeacherId: String, @RequestParam("graduationDesignReleaseId") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student val graduationDesignHopeTutor = GraduationDesignHopeTutor() graduationDesignHopeTutor.graduationDesignTeacherId = graduationDesignTeacherId graduationDesignHopeTutor.studentId = student.studentId graduationDesignHopeTutorService.delete(graduationDesignHopeTutor) ajaxUtils.success().msg("取消成功") } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 填报取消教师 * * @param graduationDesignTeacherId 指导老师id * @param graduationDesignReleaseId 发布id * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/apply/cancel"], method = [(RequestMethod.POST)]) @ResponseBody fun applyCancel(@RequestParam("graduationDesignTeacherId") graduationDesignTeacherId: String, @RequestParam("graduationDesignReleaseId") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student // 计数器 val countKey = CacheBook.GRADUATION_DESIGN_TEACHER_STUDENT_COUNT + graduationDesignTeacherId if (template.hasKey(countKey)) { val ops = this.template.opsForValue() ops.increment(countKey, 1L) // 存储 指导教师id , 学生id val studentKey = CacheBook.GRADUATION_DESIGN_PHARMTECH_STUDENT + student.studentId!! if (stringValueOperations.operations.hasKey(studentKey)!!) { stringValueOperations.set(studentKey, (-1).toString() + "," + student.studentId) } ajaxUtils.success().msg("取消成功") } else { ajaxUtils.fail().msg("未发现确认数据") } } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 进入志愿页面判断条件 * * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/wish/condition"], method = [(RequestMethod.POST)]) @ResponseBody fun canWish(): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { ajaxUtils.success().msg("在条件范围,允许使用") } else { ajaxUtils.fail().msg("仅支持学生用户使用") } return ajaxUtils } /** * 进入填报页面判断条件 * * @param graduationDesignReleaseId 毕业设计发布id * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/apply/condition"], method = [(RequestMethod.POST)]) @ResponseBody fun canApply(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { val student = errorBean.mapData!!["student"] as Student val count = graduationDesignHopeTutorService.countByStudentIdAndGraduationDesignReleaseId(student.studentId!!, graduationDesignReleaseId) if (count > 0) { ajaxUtils.success().msg("在条件范围,允许使用") } else { ajaxUtils.fail().msg("请先填写志愿") } } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 获取我的毕业指导教师信息 * * @param graduationDesignReleaseId 毕业发布id * @return 指导教师信息 */ @RequestMapping(value = ["/web/graduate/design/pharmtech/my/teacher"], method = [(RequestMethod.POST)]) @ResponseBody fun myTeacher(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = graduationDesignConditionCommon.isNotOkTeacherAdjust(graduationDesignReleaseId) if (!errorBean.isHasError()) { val graduationDesignRelease = errorBean.data if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // 查询学生 val users = usersService.getUserFromSession() val studentRecord = studentService.findByUsernameAndScienceIdAndGradeRelation(users!!.username, graduationDesignRelease!!.scienceId!!, graduationDesignRelease.allowGrade) if (studentRecord.isPresent) { val student = studentRecord.get().into(Student::class.java) val record = graduationDesignTutorService.findByStudentIdAndGraduationDesignReleaseIdRelationForStaff(student.studentId!!, graduationDesignReleaseId) if (record.isPresent) { val graduationDesignTutorBean = record.get().into(GraduationDesignTutorBean::class.java) ajaxUtils.success().msg("获取数据成功").obj(graduationDesignTutorBean) } else { ajaxUtils.fail().msg("未获取到任何信息") } } else { ajaxUtils.fail().msg("您的账号不符合此次毕业设计条件") } } else { ajaxUtils.fail().msg("仅支持学生用户使用") } } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 进入页面判断条件 * * @param graduationDesignReleaseId 毕业设计发布id * @return true or false */ @RequestMapping(value = ["/web/graduate/design/pharmtech/condition"], method = [(RequestMethod.POST)]) @ResponseBody fun canUse(@RequestParam("id") graduationDesignReleaseId: String): AjaxUtils<*> { val ajaxUtils = AjaxUtils.of<Any>() val errorBean = accessCondition(graduationDesignReleaseId) if (!errorBean.isHasError()) { ajaxUtils.success().msg("在条件范围,允许使用") } else { ajaxUtils.fail().msg(errorBean.errorMsg!!) } return ajaxUtils } /** * 进入填报教师入口条件 * * @param graduationDesignReleaseId 毕业设计发布id * @return true or false */ private fun accessCondition(graduationDesignReleaseId: String): ErrorBean<GraduationDesignRelease> { val errorBean = graduationDesignConditionCommon.isRangeFillTeacherDate(graduationDesignReleaseId) if (!errorBean.isHasError()) { val mapData = HashMap<String, Any>() val graduationDesignRelease = errorBean.data if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // 是否学生在该毕业设计专业下 val users = usersService.getUserFromSession() val studentRecord = studentService.findByUsernameAndScienceIdAndGradeRelation(users!!.username, graduationDesignRelease!!.scienceId!!, graduationDesignRelease.allowGrade) if (studentRecord.isPresent) { val student = studentRecord.get().into(Student::class.java) mapData.put("student", student) // 是否已确认 if (!ObjectUtils.isEmpty(graduationDesignRelease.isOkTeacher) && graduationDesignRelease.isOkTeacher == 1.toByte()) { // 是否已确认调整 if (!ObjectUtils.isEmpty(graduationDesignRelease.isOkTeacherAdjust) && graduationDesignRelease.isOkTeacherAdjust == 1.toByte()) { errorBean.hasError = true errorBean.errorMsg = "已确认毕业设计指导教师调整,无法进行操作" } else { errorBean.hasError = false } } else { errorBean.hasError = true errorBean.errorMsg = "未确认毕业设计指导教师,无法进行操作" } } else { errorBean.hasError = true errorBean.errorMsg = "您的账号不符合此次毕业设计条件" } } else { errorBean.hasError = true errorBean.errorMsg = "仅支持学生用户使用" } errorBean.mapData = mapData } return errorBean } }
mit
c1c14837205d4c86ad6189f3b546c716
43.622505
186
0.624908
4.986007
false
false
false
false
airbnb/epoxy
epoxy-integrationtest/src/test/java/com/airbnb/epoxy/utils/VisibilityAssertHelper.kt
1
6856
package com.airbnb.epoxy.utils import android.util.Log import com.airbnb.epoxy.EpoxyVisibilityTracker import com.airbnb.epoxy.VisibilityState import org.junit.Assert import kotlin.math.abs /** * Helper for asserting visibility. */ internal class VisibilityAssertHelper(val id: Int) { var visitedStates = mutableListOf<Int>() var visibleHeight = 0 var visibleWidth = 0 var percentVisibleHeight = 0.0f var percentVisibleWidth = 0.0f var visible = false var focused = false var partialImpression = false var fullImpression = false /** * Resets the attributes to the state where no visibility changes occurred. */ fun reset() { visitedStates = mutableListOf() visibleHeight = 0 visibleWidth = 0 percentVisibleHeight = 0.0f percentVisibleWidth = 0.0f visible = false focused = false partialImpression = false fullImpression = false } /** * Asserts that no visibility changes occurred. */ fun assertDefault() { assert( id = id, visibleHeight = 0, visibleWidth = 0, percentVisibleHeight = 0.0f, percentVisibleWidth = 0.0f, visible = false, partialImpression = false, fullImpression = false, visitedStates = IntArray(0) ) } /** * Asserts that the desired visibility changes occurred. Use null to omit an assertion for that * attribute. */ fun assert( id: Int? = null, visibleHeight: Int? = null, visibleWidth: Int? = null, percentVisibleHeight: Float? = null, percentVisibleWidth: Float? = null, visible: Boolean? = null, partialImpression: Boolean? = null, fullImpression: Boolean? = null, visitedStates: IntArray? = null ) { id?.let { Assert.assertEquals( "id expected $it got ${this.id}", it, this.id ) } visibleHeight?.let { // assert using tolerance, see TOLERANCE_PIXELS log("assert visibleHeight, got $it, expected ${this.visibleHeight}") Assert.assertTrue( "visibleHeight expected ${it}px got ${this.visibleHeight}px", abs(it - this.visibleHeight) <= TOLERANCE_PIXELS ) } visibleWidth?.let { // assert using tolerance, see TOLERANCE_PIXELS log("assert visibleWidth, got $it, expected ${this.visibleWidth}") Assert.assertTrue( "visibleWidth expected ${it}px got ${this.visibleWidth}px", abs(it - this.visibleWidth) <= TOLERANCE_PIXELS ) } percentVisibleHeight?.let { Assert.assertEquals( "percentVisibleHeight expected $it got ${this.percentVisibleHeight}", it, this.percentVisibleHeight, 0.05f ) } percentVisibleWidth?.let { Assert.assertEquals( "percentVisibleWidth expected $it got ${this.percentVisibleWidth}", it, this.percentVisibleWidth, 0.05f ) } visible?.let { Assert.assertEquals( "visible expected $it got ${this.visible}", it, this.visible ) } partialImpression?.let { Assert.assertEquals( "partialImpression expected $it got ${this.partialImpression}", it, this.partialImpression ) } fullImpression?.let { Assert.assertEquals( "fullImpression expected $it got ${this.fullImpression}", it, this.fullImpression ) } visitedStates?.let { assertVisited(it) } } private fun assertVisited(states: IntArray) { val expectedStates = mutableListOf<Int>() states.forEach { expectedStates.add(it) } for (state in expectedStates) { if (!visitedStates.contains(state)) { Assert.fail( "Expected visited ${expectedStates.description()}, " + "got ${visitedStates.description()}" ) } } for (state in ALL_STATES) { if (!expectedStates.contains(state) && visitedStates.contains(state)) { Assert.fail( "Expected ${state.description()} not visited, " + "got ${visitedStates.description()}" ) } } } /** * List of Int to VisibilityState constant names. */ private fun List<Int>.description(): String { val builder = StringBuilder("[") forEachIndexed { index, state -> builder.append(state.description()) builder.append(if (index < size - 1) "," else "") } builder.append("]") return builder.toString() } companion object { private const val TAG = "VisibilityAssertHelper" /** * Tolerance used for robolectric ui assertions when comparing data in pixels */ private const val TOLERANCE_PIXELS = 1 private val ALL_STATES = intArrayOf( VisibilityState.VISIBLE, VisibilityState.INVISIBLE, VisibilityState.FOCUSED_VISIBLE, VisibilityState.UNFOCUSED_VISIBLE, VisibilityState.PARTIAL_IMPRESSION_VISIBLE, VisibilityState.PARTIAL_IMPRESSION_INVISIBLE, VisibilityState.FULL_IMPRESSION_VISIBLE ) /** * Logs debug messages based on the flag in [EpoxyVisibilityTracker]. */ fun log(message: String) { if (EpoxyVisibilityTracker.DEBUG_LOG) { Log.d(TAG, message) } } /** * List of Int to VisibilityState constant names. */ fun Int.description(): String { return when (this) { VisibilityState.VISIBLE -> "VISIBLE" VisibilityState.INVISIBLE -> "INVISIBLE" VisibilityState.FOCUSED_VISIBLE -> "FOCUSED_VISIBLE" VisibilityState.UNFOCUSED_VISIBLE -> "UNFOCUSED_VISIBLE" VisibilityState.PARTIAL_IMPRESSION_VISIBLE -> "PARTIAL_IMPRESSION_VISIBLE" VisibilityState.PARTIAL_IMPRESSION_INVISIBLE -> "PARTIAL_IMPRESSION_INVISIBLE" VisibilityState.FULL_IMPRESSION_VISIBLE -> "FULL_IMPRESSION_VISIBLE" else -> throw IllegalStateException("Please declare new state here") } } } }
apache-2.0
9d342633377dd2b078e1167b0e877880
31.647619
99
0.549737
4.957339
false
false
false
false
flesire/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/RolesServiceImpl.kt
1
14704
package net.nemerosa.ontrack.service.security import net.nemerosa.ontrack.model.labels.LabelManagement import net.nemerosa.ontrack.model.labels.ProjectLabelManagement import net.nemerosa.ontrack.model.security.* import net.nemerosa.ontrack.model.support.StartupService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* /** * Management of the roles and functions. */ @Service @Transactional class RolesServiceImpl @Autowired constructor( /** * Role contributors */ private val roleContributors: List<RoleContributor> ) : RolesService, StartupService { /** * Index of global roles */ private val globalRoles = LinkedHashMap<String, GlobalRole>() /** * Index of project roles */ private val projectRoles = LinkedHashMap<String, ProjectRole>() override fun getGlobalRoles(): List<GlobalRole> { return ArrayList(globalRoles.values) } override fun getGlobalRole(id: String): Optional<GlobalRole> { return Optional.ofNullable(globalRoles[id]) } override fun getProjectRoles(): List<ProjectRole> { return ArrayList(projectRoles.values) } override fun getProjectRole(id: String): Optional<ProjectRole> { return Optional.ofNullable(projectRoles[id]) } override fun getGlobalFunctions(): List<Class<out GlobalFunction>> { return RolesService.defaultGlobalFunctions } override fun getProjectFunctions(): List<Class<out ProjectFunction>> { return RolesService.defaultProjectFunctions } override fun getProjectRoleAssociation(project: Int, roleId: String): Optional<ProjectRoleAssociation> { return getProjectRole(roleId).map { role -> ProjectRoleAssociation(project, role) } } override fun getName(): String { return "Roles" } override fun startupOrder(): Int { return 50 } override fun start() { // Global roles initGlobalRoles() // Project roles initProjectRoles() } private fun initProjectRoles() { // Owner register(Roles.PROJECT_OWNER, "Project owner", "The project owner is allowed to all functions in a project, but for its deletion.", projectFunctions .filter { t -> !ProjectDelete::class.java.isAssignableFrom(t) } ) // Participant register(Roles.PROJECT_PARTICIPANT, "Participant", "A participant in a project is allowed to change statuses in validation runs.", Arrays.asList( ProjectView::class.java, ValidationRunStatusChange::class.java, ValidationStampFilterCreate::class.java ) ) // Validation manager val validationManagerFunctions = Arrays.asList( ValidationStampCreate::class.java, ValidationStampEdit::class.java, ValidationStampDelete::class.java, ValidationRunCreate::class.java, ValidationRunStatusChange::class.java, ValidationStampFilterCreate::class.java, ValidationStampFilterShare::class.java, ValidationStampFilterMgt::class.java ) register(Roles.PROJECT_VALIDATION_MANAGER, "Validation manager", "The validation manager can manage the validation stamps.", validationManagerFunctions ) // Promoter val promoterFunctions = Arrays.asList( PromotionRunCreate::class.java, PromotionRunDelete::class.java, ValidationRunStatusChange::class.java ) register(Roles.PROJECT_PROMOTER, "Promoter", "The promoter can promote existing builds.", promoterFunctions ) // Project manager val projectManagerFunctions = ArrayList<Class<out ProjectFunction>>() projectManagerFunctions.addAll(validationManagerFunctions) projectManagerFunctions.addAll(promoterFunctions) projectManagerFunctions.add(BranchFilterMgt::class.java) projectManagerFunctions.add(BranchCreate::class.java) projectManagerFunctions.add(BranchEdit::class.java) projectManagerFunctions.add(BranchDelete::class.java) projectManagerFunctions.add(ProjectLabelManagement::class.java) register(Roles.PROJECT_MANAGER, "Project manager", "The project manager can promote existing builds, manage the validation stamps, " + "manage the shared build filters, manage the branches and edit some properties.", projectManagerFunctions ) // Read only on a project register(Roles.PROJECT_READ_ONLY, "Read Only", "This role grants a read-only access to all components of the projects", RolesService.readOnlyProjectFunctions ) // Project roles contributions roleContributors.forEach { roleContributor -> roleContributor.projectRoles.forEach { roleDefinition -> if (Roles.PROJECT_ROLES.contains(roleDefinition.id)) { // Totally illegal - stopping everything throw IllegalStateException("An existing project role cannot be overridden: " + roleDefinition.id) } else { register( roleDefinition.id, roleDefinition.name, roleDefinition.description, getProjectFunctionsFromProjectParent(roleDefinition.parent) ) } } } } private fun register(id: String, name: String, description: String, projectFunctions: List<Class<out ProjectFunction>>) { val functions = LinkedHashSet(projectFunctions) // Contributions roleContributors.forEach { roleContributor -> roleContributor.projectFunctionContributionsForProjectRoles[id]?.forEach { fn -> // Checks if the role is predefined if (Roles.PROJECT_ROLES.contains(id)) { // Checks the function as non core checkFunctionForContribution(fn) } // OK functions.add(fn) } } // OK register(ProjectRole( id, name, description, functions )) } private fun checkFunctionForContribution(fn: Class<*>) { val coreFunction = fn.getDeclaredAnnotation(CoreFunction::class.java) if (coreFunction != null) { // Totally illegal - stopping everything throw IllegalStateException("A core function cannot be added to an existing role.") } } private fun register(projectRole: ProjectRole) { projectRoles[projectRole.id] = projectRole } private fun initGlobalRoles() { // Administrator // This particular role must have ALL functions register(Roles.GLOBAL_ADMINISTRATOR, "Administrator", "An administrator is allowed to do everything in the application.", (globalFunctions + roleContributors.flatMap { it.globalFunctionContributionsForGlobalRoles.values.flatten() } ).distinct(), (projectFunctions + roleContributors.flatMap { it.projectFunctionContributionsForGlobalRoles.values.flatten() + it.projectFunctionContributionsForProjectRoles.values.flatten() } ).distinct() ) // Creator register(Roles.GLOBAL_CREATOR, "Creator", "A creator is allowed to create new projects and to configure it. Once done, its rights on the " + "project are revoked immediately.", listOf( ProjectCreation::class.java, LabelManagement::class.java ), listOf( // Structure creation functions only ProjectConfig::class.java, BranchCreate::class.java, BranchTemplateMgt::class.java, PromotionLevelCreate::class.java, ValidationStampCreate::class.java ) ) // Creator register(Roles.GLOBAL_AUTOMATION, "Automation", "This role can be assigned to users or groups which must automate Ontrack. It aggregates both the " + "Creator and the Controller roles into one.", Arrays.asList( ProjectCreation::class.java, AccountGroupManagement::class.java ), Arrays.asList( // Structure creation functions only ProjectConfig::class.java, ProjectAuthorisationMgt::class.java, BranchCreate::class.java, BranchTemplateMgt::class.java, PromotionLevelCreate::class.java, PromotionLevelEdit::class.java, ValidationStampCreate::class.java, ValidationStampEdit::class.java, ProjectView::class.java, BuildCreate::class.java, BuildConfig::class.java, PromotionRunCreate::class.java, ValidationRunCreate::class.java, BranchTemplateSync::class.java ) ) // Controller register(Roles.GLOBAL_CONTROLLER, "Controller", "A controller, is allowed to create builds, promotion runs and validation runs. He can also " + "synchronise templates. This role is typically granted to continuous integration tools.", emptyList(), Arrays.asList( ProjectView::class.java, BuildCreate::class.java, BuildConfig::class.java, PromotionRunCreate::class.java, ValidationRunCreate::class.java, BranchTemplateSync::class.java ) ) // Read only on all projects register(Roles.GLOBAL_READ_ONLY, "Read Only", "This role grants a read-only access to all projects", RolesService.readOnlyGlobalFunctions, RolesService.readOnlyProjectFunctions ) // Global roles contributions roleContributors.forEach { roleContributor -> roleContributor.globalRoles.forEach { roleDefinition -> if (Roles.GLOBAL_ROLES.contains(roleDefinition.id)) { // Totally illegal - stopping everything throw IllegalStateException("An existing global role cannot be overridden: " + roleDefinition.id) } else { register( roleDefinition.id, roleDefinition.name, roleDefinition.description, getGlobalFunctionsFromGlobalParent(roleDefinition.parent), getProjectFunctionsFromGlobalParent(roleDefinition.parent) ) } } } } private fun getProjectParentRole(parent: String?): ProjectRole? { if (parent == null) { return null } else if (Roles.PROJECT_ROLES.contains(parent)) { val parentRole = projectRoles[parent] if (parentRole != null) { return parentRole } } throw IllegalStateException("$parent role is not a built-in role or is not registered.") } private fun getGlobalParentRole(parent: String?): GlobalRole? { if (parent == null) { return null } else if (Roles.GLOBAL_ROLES.contains(parent)) { val parentRole = globalRoles[parent] if (parentRole != null) { return parentRole } } throw IllegalStateException("$parent role is not a built-in role or is not registered.") } private fun getGlobalFunctionsFromGlobalParent(parent: String?): List<Class<out GlobalFunction>> { return getGlobalParentRole(parent) ?.globalFunctions?.toList() ?: listOf() } private fun getProjectFunctionsFromGlobalParent(parent: String?): List<Class<out ProjectFunction>> { return getGlobalParentRole(parent) ?.projectFunctions?.toList() ?: listOf() } private fun getProjectFunctionsFromProjectParent(parent: String?): List<Class<out ProjectFunction>> { return getProjectParentRole(parent) ?.functions?.toList() ?: listOf() } private fun register(id: String, name: String, description: String, globalFunctions: List<Class<out GlobalFunction>>, projectFunctions: List<Class<out ProjectFunction>>) { // Global functions and contributions val gfns = LinkedHashSet(globalFunctions) roleContributors.forEach { roleContributor -> roleContributor.globalFunctionContributionsForGlobalRoles[id]?.forEach { fn -> if (Roles.GLOBAL_ROLES.contains(id)) { checkFunctionForContribution(fn) } gfns.add(fn) } } // Project functions val pfns = LinkedHashSet(projectFunctions) roleContributors.forEach { roleContributor -> roleContributor.projectFunctionContributionsForGlobalRoles[id]?.forEach { fn -> if (Roles.GLOBAL_ROLES.contains(id)) { checkFunctionForContribution(fn) } pfns.add(fn) } } // OK register(GlobalRole( id, name, description, gfns, pfns )) } private fun register(role: GlobalRole) { globalRoles[role.id] = role } }
mit
4ea37a74e3aaac705ef319bae4f251ee
37.899471
201
0.576986
5.631559
false
false
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GithubPullRequestsDataLoaderImpl.kt
1
3221
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.google.common.cache.CacheBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.application.runInEdt import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.util.EventDispatcher import git4idea.commands.Git import git4idea.repo.GitRemote import git4idea.repo.GitRepository import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubFullPath import org.jetbrains.plugins.github.api.GithubServerPath import java.util.* internal class GithubPullRequestsDataLoaderImpl(private val project: Project, private val progressManager: ProgressManager, private val git: Git, private val requestExecutor: GithubApiRequestExecutor, private val repository: GitRepository, private val remote: GitRemote, private val serverPath: GithubServerPath, private val repoPath: GithubFullPath) : GithubPullRequestsDataLoader, Disposable { private var isDisposed = false private val cache = CacheBuilder.newBuilder() .removalListener<Long, GithubPullRequestDataProviderImpl> { runInEdt { Disposer.dispose(it.value) invalidationEventDispatcher.multicaster.providerChanged(it.key) } } .maximumSize(5) .build<Long, GithubPullRequestDataProviderImpl>() private val invalidationEventDispatcher = EventDispatcher.create(DataInvalidatedListener::class.java) init { requestExecutor.addListener(this) { invalidateAllData() } } @CalledInAwt override fun invalidateAllData() { cache.invalidateAll() } @CalledInAwt override fun getDataProvider(number: Long): GithubPullRequestDataProvider { if (isDisposed) throw IllegalStateException("Already disposed") return cache.get(number) { GithubPullRequestDataProviderImpl(project, progressManager, git, requestExecutor, repository, remote, serverPath, repoPath.user, repoPath.repository, number) } } @CalledInAwt override fun findDataProvider(number: Long): GithubPullRequestDataProvider? = cache.getIfPresent(number) override fun addInvalidationListener(disposable: Disposable, listener: (Long) -> Unit) = invalidationEventDispatcher.addListener(object : DataInvalidatedListener { override fun providerChanged(pullRequestNumber: Long) { listener(pullRequestNumber) } }, disposable) override fun dispose() { invalidateAllData() isDisposed = true } private interface DataInvalidatedListener : EventListener { fun providerChanged(pullRequestNumber: Long) } }
apache-2.0
64565445d3043b8311f13686df250e27
39.78481
140
0.700093
5.487223
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/util/ktx/ActivityExt.kt
2
762
package quickbeer.android.util.ktx import android.app.Activity import android.view.View import android.view.ViewGroup import androidx.viewbinding.ViewBinding fun Activity.hideKeyboard() { hideKeyboard(currentFocus ?: View(this)) } /** * Lazy ViewBinding creator for Activities that use the alternative * constructor with layout passed in arguments. */ fun <T : ViewBinding> Activity.viewBinding(bind: (View) -> T): Lazy<T> = object : Lazy<T> { private var binding: T? = null override fun isInitialized(): Boolean = binding != null override val value: T get() = binding ?: bind(contentView()).also { binding = it } private fun contentView() = findViewById<ViewGroup>(android.R.id.content).getChildAt(0) }
gpl-3.0
cf1ba4b2b3e2a43c24cd4ca5e75bc263
26.214286
91
0.700787
4.233333
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentChainEntityImpl.kt
1
7608
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.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.extractOneToAbstractOneChild import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent 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 ParentChainEntityImpl(val dataSource: ParentChainEntityData) : ParentChainEntity, WorkspaceEntityBase() { companion object { internal val ROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentChainEntity::class.java, CompositeAbstractEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true) val connections = listOf<ConnectionId>( ROOT_CONNECTION_ID, ) } override val root: CompositeAbstractEntity? get() = snapshot.extractOneToAbstractOneChild(ROOT_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ParentChainEntityData?) : ModifiableWorkspaceEntityBase<ParentChainEntity>(), ParentChainEntity.Builder { constructor() : this(ParentChainEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ParentChainEntity 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") } } 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 ParentChainEntity 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 root: CompositeAbstractEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneChild(ROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, ROOT_CONNECTION_ID)] as? CompositeAbstractEntity } else { this.entityLinks[EntityLink(true, ROOT_CONNECTION_ID)] as? CompositeAbstractEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, ROOT_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.updateOneToAbstractOneChildOfParent(ROOT_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, ROOT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, ROOT_CONNECTION_ID)] = value } changedProperty.add("root") } override fun getEntityData(): ParentChainEntityData = result ?: super.getEntityData() as ParentChainEntityData override fun getEntityClass(): Class<ParentChainEntity> = ParentChainEntity::class.java } } class ParentChainEntityData : WorkspaceEntityData<ParentChainEntity>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentChainEntity> { val modifiable = ParentChainEntityImpl.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): ParentChainEntity { return getCached(snapshot) { val entity = ParentChainEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ParentChainEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ParentChainEntity(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 ParentChainEntityData 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 ParentChainEntityData 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
df49e3d187e291e6c6323bbe8faea02a
34.222222
150
0.70807
5.283333
false
false
false
false
apollographql/apollo-android
tests/sample-server/src/main/kotlin/com/apollographql/apollo/sample/server/MyApolloSubscriptionHooks.kt
1
1082
package com.apollographql.apollo.sample.server import com.expediagroup.graphql.server.spring.subscriptions.ApolloSubscriptionHooks import org.springframework.web.reactive.socket.CloseStatus import org.springframework.web.reactive.socket.WebSocketSession class MyApolloSubscriptionHooks : ApolloSubscriptionHooks { override fun onConnectWithContext(connectionParams: Map<String, String>, session: WebSocketSession, graphQLContext: Map<*, Any>?): Map<*, Any>? { val returns = connectionParams["return"] if (returns != null) { when { returns == "success"-> Unit returns == "error" -> throw IllegalStateException("Error") returns.startsWith("close") -> { val code = Regex("close\\(([0-9]*)\\)").matchEntire(`returns`) ?.let { it.groupValues[1].toIntOrNull() } ?: 1001 session.close(CloseStatus(code)).block() } } } return super.onConnectWithContext(connectionParams, session, graphQLContext) } }
mit
c41ac516b0ee2656187e38dccccaa1e9
36.310345
83
0.638632
4.895928
false
false
false
false
StepicOrg/stepik-android
model/src/main/java/org/stepik/android/model/user/User.kt
1
1748
package org.stepik.android.model.user import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import ru.nobird.app.core.model.Identifiable import java.util.Date @Parcelize data class User( @SerializedName("id") override val id: Long = 0, @SerializedName("profile") val profile: Long = 0, @SerializedName("first_name") val firstName: String? = null, @SerializedName("last_name") val lastName: String? = null, @SerializedName("full_name") val fullName: String? = null, @SerializedName("short_bio") val shortBio: String? = null, @SerializedName("details") val details: String? = null, @SerializedName("avatar") val avatar: String? = null, @SerializedName("cover") val cover: String? = null, @SerializedName("is_private") val isPrivate: Boolean = false, @SerializedName("is_guest") val isGuest: Boolean = false, @SerializedName("is_organization") val isOrganization: Boolean = false, @SerializedName("social_profiles") val socialProfiles: List<Long> = emptyList(), @SerializedName("knowledge") val knowledge: Long = 0, @SerializedName("knowledge_rank") val knowledgeRank: Long = 0, @SerializedName("reputation") val reputation: Long = 0, @SerializedName("reputation_rank") val reputationRank: Long = 0, @SerializedName("created_courses_count") val createdCoursesCount: Long = 0, @SerializedName("followers_count") val followersCount: Long = 0, @SerializedName("issued_certificates_count") val issuedCertificatesCount: Long = 0, @SerializedName("join_date") val joinDate: Date? ) : Parcelable, Identifiable<Long>
apache-2.0
bdae17c99e970db18e61609939e8a7a7
27.672131
49
0.689359
4.14218
false
false
false
false
square/okio
okio/src/commonMain/kotlin/okio/BufferedSink.kt
1
10880
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 okio /** * A sink that keeps a buffer internally so that callers can do small writes without a performance * penalty. */ expect sealed interface BufferedSink : Sink { /** This sink's internal buffer. */ val buffer: Buffer fun write(byteString: ByteString): BufferedSink fun write(byteString: ByteString, offset: Int, byteCount: Int): BufferedSink /** Like [OutputStream.write], this writes a complete byte array to this sink. */ fun write(source: ByteArray): BufferedSink /** Like [OutputStream.write], this writes `byteCount` bytes of `source`, starting at `offset`. */ fun write(source: ByteArray, offset: Int, byteCount: Int): BufferedSink /** * Removes all bytes from `source` and appends them to this sink. Returns the number of bytes read * which will be 0 if `source` is exhausted. */ fun writeAll(source: Source): Long /** Removes `byteCount` bytes from `source` and appends them to this sink. */ fun write(source: Source, byteCount: Long): BufferedSink /** * Encodes `string` in UTF-8 and writes it to this sink. * ``` * Buffer buffer = new Buffer(); * buffer.writeUtf8("Uh uh uh!"); * buffer.writeByte(' '); * buffer.writeUtf8("You didn't say the magic word!"); * * assertEquals("Uh uh uh! You didn't say the magic word!", buffer.readUtf8()); * ``` */ fun writeUtf8(string: String): BufferedSink /** * Encodes the characters at `beginIndex` up to `endIndex` from `string` in UTF-8 and writes it to * this sink. * ``` * Buffer buffer = new Buffer(); * buffer.writeUtf8("I'm a hacker!\n", 6, 12); * buffer.writeByte(' '); * buffer.writeUtf8("That's what I said: you're a nerd.\n", 29, 33); * buffer.writeByte(' '); * buffer.writeUtf8("I prefer to be called a hacker!\n", 24, 31); * * assertEquals("hacker nerd hacker!", buffer.readUtf8()); * ``` */ fun writeUtf8(string: String, beginIndex: Int, endIndex: Int): BufferedSink /** Encodes `codePoint` in UTF-8 and writes it to this sink. */ fun writeUtf8CodePoint(codePoint: Int): BufferedSink /** Writes a byte to this sink. */ fun writeByte(b: Int): BufferedSink /** * Writes a big-endian short to this sink using two bytes. * ``` * Buffer buffer = new Buffer(); * buffer.writeShort(32767); * buffer.writeShort(15); * * assertEquals(4, buffer.size()); * assertEquals((byte) 0x7f, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x0f, buffer.readByte()); * assertEquals(0, buffer.size()); * ``` */ fun writeShort(s: Int): BufferedSink /** * Writes a little-endian short to this sink using two bytes. * ``` * Buffer buffer = new Buffer(); * buffer.writeShortLe(32767); * buffer.writeShortLe(15); * * assertEquals(4, buffer.size()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0x7f, buffer.readByte()); * assertEquals((byte) 0x0f, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals(0, buffer.size()); * ``` */ fun writeShortLe(s: Int): BufferedSink /** * Writes a big-endian int to this sink using four bytes. * ``` * Buffer buffer = new Buffer(); * buffer.writeInt(2147483647); * buffer.writeInt(15); * * assertEquals(8, buffer.size()); * assertEquals((byte) 0x7f, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x0f, buffer.readByte()); * assertEquals(0, buffer.size()); * ``` */ fun writeInt(i: Int): BufferedSink /** * Writes a little-endian int to this sink using four bytes. * ``` * Buffer buffer = new Buffer(); * buffer.writeIntLe(2147483647); * buffer.writeIntLe(15); * * assertEquals(8, buffer.size()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0x7f, buffer.readByte()); * assertEquals((byte) 0x0f, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals(0, buffer.size()); * ``` */ fun writeIntLe(i: Int): BufferedSink /** * Writes a big-endian long to this sink using eight bytes. * ``` * Buffer buffer = new Buffer(); * buffer.writeLong(9223372036854775807L); * buffer.writeLong(15); * * assertEquals(16, buffer.size()); * assertEquals((byte) 0x7f, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x0f, buffer.readByte()); * assertEquals(0, buffer.size()); * ``` */ fun writeLong(v: Long): BufferedSink /** * Writes a little-endian long to this sink using eight bytes. * ``` * Buffer buffer = new Buffer(); * buffer.writeLongLe(9223372036854775807L); * buffer.writeLongLe(15); * * assertEquals(16, buffer.size()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0xff, buffer.readByte()); * assertEquals((byte) 0x7f, buffer.readByte()); * assertEquals((byte) 0x0f, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals((byte) 0x00, buffer.readByte()); * assertEquals(0, buffer.size()); * ``` */ fun writeLongLe(v: Long): BufferedSink /** * Writes a long to this sink in signed decimal form (i.e., as a string in base 10). * ``` * Buffer buffer = new Buffer(); * buffer.writeDecimalLong(8675309L); * buffer.writeByte(' '); * buffer.writeDecimalLong(-123L); * buffer.writeByte(' '); * buffer.writeDecimalLong(1L); * * assertEquals("8675309 -123 1", buffer.readUtf8()); * ``` */ fun writeDecimalLong(v: Long): BufferedSink /** * Writes a long to this sink in hexadecimal form (i.e., as a string in base 16). * ``` * Buffer buffer = new Buffer(); * buffer.writeHexadecimalUnsignedLong(65535L); * buffer.writeByte(' '); * buffer.writeHexadecimalUnsignedLong(0xcafebabeL); * buffer.writeByte(' '); * buffer.writeHexadecimalUnsignedLong(0x10L); * * assertEquals("ffff cafebabe 10", buffer.readUtf8()); * ``` */ fun writeHexadecimalUnsignedLong(v: Long): BufferedSink /** * Writes all buffered data to the underlying sink, if one exists. Then that sink is recursively * flushed which pushes data as far as possible towards its ultimate destination. Typically that * destination is a network socket or file. * ``` * BufferedSink b0 = new Buffer(); * BufferedSink b1 = Okio.buffer(b0); * BufferedSink b2 = Okio.buffer(b1); * * b2.writeUtf8("hello"); * assertEquals(5, b2.buffer().size()); * assertEquals(0, b1.buffer().size()); * assertEquals(0, b0.buffer().size()); * * b2.flush(); * assertEquals(0, b2.buffer().size()); * assertEquals(0, b1.buffer().size()); * assertEquals(5, b0.buffer().size()); * ``` */ override fun flush() /** * Writes all buffered data to the underlying sink, if one exists. Like [flush], but weaker. Call * this before this buffered sink goes out of scope so that its data can reach its destination. * ``` * BufferedSink b0 = new Buffer(); * BufferedSink b1 = Okio.buffer(b0); * BufferedSink b2 = Okio.buffer(b1); * * b2.writeUtf8("hello"); * assertEquals(5, b2.buffer().size()); * assertEquals(0, b1.buffer().size()); * assertEquals(0, b0.buffer().size()); * * b2.emit(); * assertEquals(0, b2.buffer().size()); * assertEquals(5, b1.buffer().size()); * assertEquals(0, b0.buffer().size()); * * b1.emit(); * assertEquals(0, b2.buffer().size()); * assertEquals(0, b1.buffer().size()); * assertEquals(5, b0.buffer().size()); * ``` */ fun emit(): BufferedSink /** * Writes complete segments to the underlying sink, if one exists. Like [flush], but weaker. Use * this to limit the memory held in the buffer to a single segment. Typically application code * will not need to call this: it is only necessary when application code writes directly to this * [sink's buffer][buffer]. * ``` * BufferedSink b0 = new Buffer(); * BufferedSink b1 = Okio.buffer(b0); * BufferedSink b2 = Okio.buffer(b1); * * b2.buffer().write(new byte[20_000]); * assertEquals(20_000, b2.buffer().size()); * assertEquals( 0, b1.buffer().size()); * assertEquals( 0, b0.buffer().size()); * * b2.emitCompleteSegments(); * assertEquals( 3_616, b2.buffer().size()); * assertEquals( 0, b1.buffer().size()); * assertEquals(16_384, b0.buffer().size()); // This example assumes 8192 byte segments. * ``` */ fun emitCompleteSegments(): BufferedSink }
apache-2.0
36b3ec1e328e09ff2a064cd8aa89d1a0
33.649682
100
0.646415
3.772538
false
false
false
false
DmytroTroynikov/aemtools
inspection/src/main/kotlin/com/aemtools/inspection/html/RedundantDataSlyUnwrapInspection.kt
1
1262
package com.aemtools.inspection.html import com.aemtools.common.constant.const.htl.DATA_SLY_UNWRAP import com.aemtools.inspection.service.InspectionService import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.htmlInspections.HtmlLocalInspectionTool import com.intellij.psi.xml.XmlAttribute /** * @author Dmytro Troynikov */ class RedundantDataSlyUnwrapInspection : HtmlLocalInspectionTool() { override fun getGroupDisplayName(): String = "HTL" override fun getDisplayName(): String = "data-sly-unwrap is redundant inside sly tag" override fun getStaticDescription(): String? { return """ <html> <body> This inspection verifies that <i>data-sly-unwrap</i> is <b>not</b> used inside of <i>sly</i> tag </body> </html> """.trimIndent() } public override fun checkAttribute(attribute: XmlAttribute, holder: ProblemsHolder, isOnTheFly: Boolean) { val inspectionService = InspectionService.getInstance(attribute.project) ?: return if (!inspectionService.validTarget(attribute)) { return } if (attribute.text == DATA_SLY_UNWRAP && attribute.parent?.name?.equals("sly", true) == true) { inspectionService.redundantDataSlyUnwrap(holder, attribute) } } }
gpl-3.0
e965583dad71b77c0f62458577aafdc2
29.780488
108
0.736926
4.206667
false
false
false
false
allotria/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/lang/parser/GFMCommentAwareMarkerProcessor.kt
4
3268
// 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.intellij.plugins.markdown.lang.parser import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.flavours.commonmark.CommonMarkMarkerProcessor import org.intellij.markdown.flavours.gfm.GFMConstraints import org.intellij.markdown.flavours.gfm.GFMTokenTypes import org.intellij.markdown.flavours.gfm.table.GitHubTableMarkerProvider import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.MarkerProcessorFactory import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider import org.intellij.markdown.parser.markerblocks.providers.AtxHeaderProvider import org.intellij.markdown.parser.markerblocks.providers.LinkReferenceDefinitionProvider import org.intellij.markdown.parser.sequentialparsers.SequentialParser import kotlin.math.min class GFMCommentAwareMarkerProcessor(productionHolder: ProductionHolder, constraintsBase: MarkdownConstraints) : CommonMarkMarkerProcessor(productionHolder, constraintsBase) { private val markerBlockProviders = super.getMarkerBlockProviders() .filterNot { it is AtxHeaderProvider } .filterNot { it is LinkReferenceDefinitionProvider } .plus(listOf( GitHubTableMarkerProvider(), AtxHeaderProvider(false), CommentAwareLinkReferenceDefinitionProvider())) override fun populateConstraintsTokens(pos: LookaheadText.Position, constraints: MarkdownConstraints, productionHolder: ProductionHolder) { if (constraints !is GFMConstraints || !constraints.hasCheckbox()) { super.populateConstraintsTokens(pos, constraints, productionHolder) return } val line = pos.currentLine var offset = pos.offsetInCurrentLine while (offset < line.length && line[offset] != '[') { offset++ } if (offset == line.length) { super.populateConstraintsTokens(pos, constraints, productionHolder) return } val type = when (constraints.getLastType()) { '>' -> MarkdownTokenTypes.BLOCK_QUOTE '.', ')' -> MarkdownTokenTypes.LIST_NUMBER else -> MarkdownTokenTypes.LIST_BULLET } val middleOffset = pos.offset - pos.offsetInCurrentLine + offset val endOffset = min(pos.offset - pos.offsetInCurrentLine + constraints.getCharsEaten(pos.currentLine), pos.nextLineOrEofOffset) productionHolder.addProduction(listOf( SequentialParser.Node(pos.offset..middleOffset, type), SequentialParser.Node(middleOffset..endOffset, GFMTokenTypes.CHECK_BOX) )) } override fun getMarkerBlockProviders(): List<MarkerBlockProvider<StateInfo>> { return markerBlockProviders } object Factory : MarkerProcessorFactory { override fun createMarkerProcessor(productionHolder: ProductionHolder): MarkerProcessor<*> { return GFMCommentAwareMarkerProcessor(productionHolder, GFMConstraints.BASE) } } }
apache-2.0
98bf42b23cd1699409a9854264105ef1
42.013158
140
0.756732
5.114241
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/EditorComponentInlaysManager.kt
1
5114
// 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.github.pullrequest.comment.ui import com.intellij.openapi.Disposable import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.impl.EditorEmbeddedComponentManager import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.view.FontLayoutService import com.intellij.openapi.util.Disposer import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.JBUI import org.jetbrains.annotations.CalledInAwt import java.awt.Dimension import java.awt.Font import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.JComponent import javax.swing.ScrollPaneConstants import kotlin.math.ceil import kotlin.math.max import kotlin.math.min class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable { private val managedInlays = mutableMapOf<ComponentWrapper, Disposable>() private val editorWidthWatcher = EditorTextWidthWatcher() init { editor.scrollPane.viewport.addComponentListener(editorWidthWatcher) Disposer.register(this, Disposable { editor.scrollPane.viewport.removeComponentListener(editorWidthWatcher) }) EditorUtil.disposeWithEditor(editor, this) } @CalledInAwt fun insertAfter(lineIndex: Int, component: JComponent): Disposable? { if (Disposer.isDisposed(this)) return null val wrappedComponent = ComponentWrapper(component) val offset = editor.document.getLineEndOffset(lineIndex) return EditorEmbeddedComponentManager.getInstance() .addComponent(editor, wrappedComponent, EditorEmbeddedComponentManager.Properties(EditorEmbeddedComponentManager.ResizePolicy.none(), true, false, 0, offset))?.also { managedInlays[wrappedComponent] = it Disposer.register(it, Disposable { managedInlays.remove(wrappedComponent) }) } } private inner class ComponentWrapper(private val component: JComponent) : JBScrollPane(component) { init { isOpaque = false viewport.isOpaque = false border = JBUI.Borders.empty() viewportBorder = JBUI.Borders.empty() horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER verticalScrollBar.preferredSize = Dimension(0, 0) setViewportView(component) component.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent) = dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED)) }) } override fun getPreferredSize(): Dimension { return Dimension(editorWidthWatcher.editorTextWidth, component.preferredSize.height) } } override fun dispose() { managedInlays.values.forEach(Disposer::dispose) } private inner class EditorTextWidthWatcher : ComponentAdapter() { var editorTextWidth: Int = 0 private val maximumEditorTextWidth: Int private val verticalScrollbarFlipped: Boolean init { val metrics = editor.getFontMetrics(Font.PLAIN) val spaceWidth = FontLayoutService.getInstance().charWidth2D(metrics, ' '.toInt()) // -4 to create some space maximumEditorTextWidth = ceil(spaceWidth * (editor.settings.getRightMargin(editor.project)) - 4).toInt() val scrollbarFlip = editor.scrollPane.getClientProperty(JBScrollPane.Flip::class.java) verticalScrollbarFlipped = scrollbarFlip == JBScrollPane.Flip.HORIZONTAL || scrollbarFlip == JBScrollPane.Flip.BOTH } override fun componentResized(e: ComponentEvent) = updateWidthForAllInlays() override fun componentHidden(e: ComponentEvent) = updateWidthForAllInlays() override fun componentShown(e: ComponentEvent) = updateWidthForAllInlays() private fun updateWidthForAllInlays() { val newWidth = calcWidth() if (editorTextWidth == newWidth) return editorTextWidth = newWidth managedInlays.keys.forEach { it.dispatchEvent(ComponentEvent(it, ComponentEvent.COMPONENT_RESIZED)) it.invalidate() } } private fun calcWidth(): Int { val visibleEditorTextWidth = editor.scrollPane.viewport.width - getVerticalScrollbarWidth() - getGutterTextGap() return min(max(visibleEditorTextWidth, 0), maximumEditorTextWidth) } private fun getVerticalScrollbarWidth(): Int { val width = editor.scrollPane.verticalScrollBar.width return if (!verticalScrollbarFlipped) width * 2 else width } private fun getGutterTextGap(): Int { return if (verticalScrollbarFlipped) { val gutter = (editor as EditorEx).gutterComponentEx gutter.width - gutter.whitespaceSeparatorOffset } else 0 } } }
apache-2.0
59064468b8b99930a1c55f3348ba589c
37.458647
140
0.718224
5.008815
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-telemetry/src/main/kotlin/slatekit/telemetry/Ratio.kt
1
322
package slatekit.telemetry data class Ratio(val name:String, val count:Long, val total:Long) { val value : Double = if(total == 0L) 0.0 else count / total.toDouble() operator fun compareTo(other:Double) = this.value.compareTo(other) operator fun compareTo(other:Ratio) = this.value.compareTo(other.value) }
apache-2.0
17151f5e1f0534a396388d11b9816c86
34.777778
75
0.726708
3.577778
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/application/options/editor/EditorTabsConfigurable.kt
1
6164
// 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.application.options.editor import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettings.Companion.TABS_NONE import com.intellij.openapi.application.ApplicationBundle.message import com.intellij.openapi.options.BoundSearchableConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.registry.Registry import com.intellij.ui.layout.* import com.intellij.ui.tabs.impl.JBTabsImpl import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutInfo import com.intellij.ui.tabs.layout.TabsLayoutSettingsUi import javax.swing.* import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener import kotlin.math.max class EditorTabsConfigurable : BoundSearchableConfigurable( message("configurable.editor.tabs.display.name"), "reference.settingsdialog.IDE.editor.tabs", ID ), EditorOptionsProvider { private lateinit var myEditorTabPlacement: JComboBox<Int> private lateinit var myOneRowCheckbox: JCheckBox override fun createPanel(): DialogPanel { return panel { titledRow(message("group.tab.appearance")) { if (JBTabsImpl.NEW_TABS) { val tabPlacementComboBoxModel: DefaultComboBoxModel<Int> = DefaultComboBoxModel(TAB_PLACEMENTS) val myTabsLayoutComboBox: JComboBox<TabsLayoutInfo> = TabsLayoutSettingsUi.tabsLayoutComboBox(tabPlacementComboBoxModel) row { cell { label(message("combobox.editor.tab.tabslayout") + ":") val builder = myTabsLayoutComboBox() TabsLayoutSettingsUi.prepare(builder, myTabsLayoutComboBox) } } row { cell { label(TAB_PLACEMENT + ":") myEditorTabPlacement = tabPlacementComboBox(tabPlacementComboBoxModel).component } } updateTabPlacementComboBoxVisibility(tabPlacementComboBoxModel) tabPlacementComboBoxModel.addListDataListener(MyAnyChangeOfListListener { updateTabPlacementComboBoxVisibility(tabPlacementComboBoxModel) }) } else { row { cell { label(TAB_PLACEMENT + ":") myEditorTabPlacement = tabPlacementComboBox().component } } row { myOneRowCheckbox = checkBox(showTabsInOneRow) .enableIf(myEditorTabPlacement.selectedValueIs(SwingConstants.TOP)).component row { cell(false, false, { checkBox(hideTabsIfNeeded).enableIf( myEditorTabPlacement.selectedValueMatches { it == SwingConstants.TOP || it == SwingConstants.BOTTOM } and myOneRowCheckbox.selected).component }) } } } row { checkBox(showPinnedTabsInASeparateRow).enableIf(myEditorTabPlacement.selectedValueIs(SwingConstants.TOP)) } row { checkBox(useSmallFont).enableIfTabsVisible() } row { checkBox(showFileIcon).enableIfTabsVisible() } row { checkBox(showFileExtension).enableIfTabsVisible() } row { checkBox(showDirectoryForNonUniqueFilenames).enableIfTabsVisible() } row { checkBox(markModifiedTabsWithAsterisk).enableIfTabsVisible() } row { checkBox(showTabsTooltips).enableIfTabsVisible() } row { cell { label(CLOSE_BUTTON_POSITION + ":") closeButtonPositionComboBox() } }.enableIf((myEditorTabPlacement.selectedValueMatches { it != TABS_NONE })) } titledRow(message("group.tab.order")) { row { checkBox(sortTabsAlphabetically) } row { checkBox(openTabsAtTheEnd) } } titledRow(message("group.tab.opening.policy")) { row { checkBox(openInPreviewTabIfPossible) } row { checkBox(reuseNotModifiedTabs) } row { checkBox(openTabsInMainWindow) } } titledRow(message("group.tab.closing.policy")) { row { cell { label(message("editbox.tab.limit")) intTextField(ui::editorTabLimit, 4, 1..max(10, Registry.intValue("ide.max.editor.tabs", 100))) } } row { buttonGroup(ui::closeNonModifiedFilesFirst) { checkBoxGroup(message("label.when.number.of.opened.editors.exceeds.tab.limit")) { row { radioButton(message("radio.close.non.modified.files.first"), value = true) } row { radioButton(message("radio.close.less.frequently.used.files"), value = false) }.largeGapAfter() } } } row { buttonGroup(message("label.when.closing.active.editor")) { row { radioButton(message("radio.activate.left.neighbouring.tab")).apply { onReset { component.isSelected = !ui.activeRightEditorOnClose && !ui.activeMruEditorOnClose } } } row { radioButton(message("radio.activate.right.neighbouring.tab"), ui::activeRightEditorOnClose) } row { radioButton(message("radio.activate.most.recently.opened.tab"), ui::activeMruEditorOnClose) }.largeGapAfter() } } } } } private fun updateTabPlacementComboBoxVisibility(tabPlacementComboBoxModel: DefaultComboBoxModel<Int>) { myEditorTabPlacement.isEnabled = tabPlacementComboBoxModel.size > 1 } private fun <T : JComponent> CellBuilder<T>.enableIfTabsVisible() { enableIf(myEditorTabPlacement.selectedValueMatches { it != TABS_NONE }) } override fun apply() { val uiSettingsChanged = isModified super.apply() if (uiSettingsChanged) { UISettings.instance.fireUISettingsChanged() } } private class MyAnyChangeOfListListener(val action: () -> Unit) : ListDataListener { override fun contentsChanged(e: ListDataEvent?) { action() } override fun intervalRemoved(e: ListDataEvent?) { action() } override fun intervalAdded(e: ListDataEvent?) { action() } } }
apache-2.0
cb307092369a2f61027e3db0b8d6ca94
39.025974
140
0.659637
4.978998
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Guide_ORM.kt
1
24074
package slatekit.examples import slatekit.common.* import slatekit.common.conf.Config import slatekit.common.crypto.Encryptor import slatekit.common.data.* import slatekit.db.Db import slatekit.entities.* import slatekit.common.data.Mapper import slatekit.common.utils.ListMap import slatekit.common.utils.RecordMap import slatekit.entities.repos.InMemoryRepo import slatekit.meta.Schema import slatekit.meta.models.FieldCategory import slatekit.meta.models.ModelMapper import slatekit.orm.OrmMapper import slatekit.query.Op import slatekit.query.Query import slatekit.results.Success import slatekit.results.Try import java.util.* /** * Created by kreddy on 3/15/2016. */ class Guide_ORM : Command("types") { override fun execute(request: CommandRequest): Try<Any> { //<doc:setup> model() // The entities are dependent on the database connections setup. // See Example_Database.kt for more info return Success("") } // Sample model data class City(override val id:Long, val name:String, val alias:String) : EntityWithId<Long> { override fun isPersisted(): Boolean { return id > 0 } } fun con() { // Connection // 1. Explicit creation val con1 = DbConString(Vendor.MySql.driver, "jdbc:mysql://localhost/default", "user1", "pswd3210") // 2. From config val cfg = Config.of("env.dev.conf") val con2 = cfg.dbCon("db") // Connections ( collection of multiple connections ) // 1. From single connection val cons1 = Connections.of(con1) // 2. From config: Shortcut for Connections.of(conf.dbCon("db")) val cons2 = Connections.from(cfg) // 3. From multiple named connections val cons3 = Connections.named( listOf( Pair("db1", con1), Pair("db2", con2) )) } fun db() { val con1 = DbConString(Vendor.MySql.driver, "jdbc:mysql://localhost/default", "user1", "pswd3210") val db = Db(con1) // Inserts val id1 = db.insert("insert into `city`(`name`) values( 'ny' )") val id2 = db.insert("insert into `city`(`name`) values( ? )", listOf("ny")) val id3 = db.insertGetId("insert into `city`(`name`) values( ? )", listOf("ny")).toLong() // Updates val updated1 = db.update("update `city` set `alias` = 'nyc' where id = 2") val updated2 = db.update("update `city` set `alias` = 'nyc' where id = ?", listOf(id2)) // Deletes val deleted1 = db.update("delete from `city` where id = 2") val deleted2 = db.update("delete from `city` where id = ?", listOf(2)) // Procs val procUpdate1 = db.callUpdate("dbtests_activate_by_id", listOf(2)) val procQuery1 = db.callQuery("dbtests_max_by_id", callback = { rs -> rs.getString(0) }, inputs = listOf(id2)) // Queries ( mapOne, mapMany ) val city1 = db.mapOne<City>("select * from `city` where id = ?", listOf(1)) { rs -> City(rs.getLong("id"), rs.getString("name"), rs.getString("alias")) } val city2 = db.mapAll<City>("select * from `city` where id < ?", listOf(2)) { rs -> City(rs.getLong("id"), rs.getString("name"), rs.getString("alias")) } // Scalar calls val total1 = db.getScalarBool("select isActive from users where userid = ?", listOf(1)) val total2 = db.getScalarInt("select age from users where userid = ?", listOf(1)) val total3 = db.getScalarLong("select account from users where userid = ?", listOf(1)) val total4 = db.getScalarFloat("select salary from users where userid = ?", listOf(1)) val total5 = db.getScalarDouble("select total from users where userid = ?", listOf(1)) val total6 = db.getScalarString("select email from users where userid = ?", listOf(1)) val total7 = db.getScalarLocalDate("select startDate from users where userid = ?", listOf(1)) val total8 = db.getScalarLocalTime("select startHour from users where userid = ?", listOf(1)) val total9 = db.getScalarLocalDateTime("select registered from users where userid = ?", listOf(1)) val total10 = db.getScalarZonedDateTime("select activated from users where userid = ?", listOf(1)) } fun records(){ // Sample connection/DB val con1 = DbConString(Vendor.MySql.driver, "jdbc:mysql://localhost/default", "user1", "pswd3210") val db = Db(con1) // Record via wrapped JDBC ResultSet val city = db.mapOne<City>("select * from `city` where id = ?", listOf(1)) { rs:Record -> City( rs.getLong("id"), rs.getString("name"), rs.getString("alias") ) } // Simulating a Record from a list of key/value pairs val record:Record = RecordMap( ListMap( listOf( Pair("id", 1L), Pair("uuid", "ABC"), Pair("email", "[email protected]"), Pair("isActive", true), Pair("age", 35), Pair("status", Status.InActive), Pair("salary", 400.5), Pair("uid", UUID.fromString("ad6ec896-bc1e-4430-b13c-88e3d4924a6a")), Pair("createdAt", DateTimes.of(2017, 1, 1, 12, 0, 0, 0)) ) ) ) // There are getX methods, getXOrNull, getXOrDefault println(record.getBool("isActive")) println(record.getBoolOrNull("isActive")) println(record.getBoolOrElse("isActive", false)) // There are several methods for various types println(record.getString("email")) println(record.getBool("isActive")) println(record.getInt("age")) println(record.getLong("id")) println(record.getDouble("salary")) println(record.getUUID("uuid")) println(record.getZonedDateTime("createdAt")) } fun h2(){ // 1. Connection val conh2 = DbConString(Vendor.H2.driver, "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "") // 2. Database ( JDBC abstraction ) val db = Db(conh2).open() // 3. Database usage db.execute("CREATE TABLE PERSON(id int primary key, name varchar(255))") db.insert("INSERT INTO PERSON" + "(id, name) values" + "(?,?)", listOf(1,"[email protected]")) val users = db.mapAll( "select * from PERSON", null) { User(it.getInt("id").toLong(),it.getString("name")) } } fun h2_repo(){ // 1. Connection val con = DbConString(Vendor.H2.driver, "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "") // 2. Database ( thin JDBC abstraction to support Server + Android ) val db = Db.open(con) // 3. Mapper: manual field mapping val mapper = object: Mapper<Long, User> { override fun encode(model:User, action: DataAction, enc: Encryptor?): Values { return listOf( Value("id", model.id), Value("firstname", model.first), Value("lastname", model.last), Value("email", model.email) ) } override fun decode(record: Record, enc: Encryptor?): User? { return User( id = record.getInt("id").toLong(), first = record.getString("first"), last = record.getString("last"), email = record.getString("email") ) } } // 4. Repo : CRUD repository val repo1 = Repo.h2<Long, User>(db, mapper) db.execute("CREATE TABLE PERSON(id int primary key, name varchar(255))") } fun mapper():Mapper<Long, City> { val mapper = object: Mapper<Long, City> { override fun encode(model:City, action: DataAction, enc: Encryptor?): Values { return listOf( Value("id", model.id), Value("name", model.name), Value("alias", model.alias) ) } override fun decode(record: Record, enc: Encryptor?): City? { return City( id = record.getInt("id").toLong(), name = record.getString("name"), alias = record.getString("alias") ) } } return mapper } fun repo() { // 1. Connection val con = DbConString(Vendor.H2.driver, "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "") // 2. Database ( thin JDBC abstraction to support Server + Android ) val db = Db.open(con) val repo = InMemoryRepo.of<Long, City>() // CRUD val city = City(0, "Brooklyn", "bk") // Create val id = repo.create(city) repo.save(City(0, "New York", "NYC")) // Checks repo.any() repo.count() // Gets repo.getAll() repo.getById(1) repo.getByIds(listOf(1, 2)) repo.first() repo.last() repo.recent(10) repo.oldest(10) // Finds val item1 = repo.findOneByField("name", Op.Eq, "Brooklyn") val items2 = repo.findByField("name", Op.Eq, "Brooklyn") val items3 = repo.findByFields(listOf(Pair("name", "Brooklyn"))) val items4= repo.findIn("name", listOf("Queens", "Brooklyn")) repo.find(repo.query()) // Updates val updated = city.copy(id = id, name = "Queens") repo.update(updated) repo.patchById(id, listOf(Pair("name", "Queens City"), Pair("alias", "QCity"))) repo.patchByFields(listOf("name" to "Queens"), listOf("name" to "Queens City")) repo.patchByField("tag", "test") repo.updateByProc("update_alias", listOf(1, "QCity")) // Deletes repo.deleteAll() repo.delete(city) repo.deleteById(2) repo.deleteByIds(listOf(1, 2)) repo.deleteByField(City::id.name, Op.Eq, 1) repo.deleteByQuery(repo.query().where(City::id.name, Op.Eq, 1)) } fun service(){ // Setup: This is boiler-plate that can be moved // to a helper function/builder // 1. connection // 2. database // 3. mapper // 4. repo // 5. service val con = DbConString(Vendor.H2.driver, "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "") val db = Db.open(con) val mapper:Mapper<Long, City> = mapper() val repo = Repo.h2<Long, City>(db, mapper) val service = EntityService<Long, City>(repo) // CRUD operations val city = City(0, "Brooklyn", "bk") // Create val id = service.create(city) service.save(City(0, "New York", "NYC")) // Checks service.any() service.count() // Gets service.getAll() service.getById(1) service.getByIds(listOf(1, 2)) service.first() service.last() service.recent(10) service.oldest(10) // Finds val item1 = service.findOneByField(User::email, Op.Eq,"Brooklyn") val items2 = service.findByField(City::name, Op.Eq, "Brooklyn") val items3 = service.findByFields(listOf(Pair("name", "Brooklyn"))) val items4= service.findIn(City::name, listOf("Queens", "Brooklyn")) val items5 = service.findByQuery(Query().where(City::name.name, Op.Eq, "Brooklyn")) // Updates val updated = city.copy(id = id, name = "Queens") service.update(updated) service.patch(id, listOf(Pair("name", "Queens City"), Pair("alias", "QCity"))) service.patchByFields(City::name, "Queens", "Queens City") service.patchByField(City::name, "test") service.updateByProc("update_alias", listOf(1, "QCity")) // Deletes service.deleteAll() service.delete(city) service.deleteById(2) service.deleteByIds(listOf(1, 2)) service.deleteByField(City::id, Op.Eq, 1) service.deleteByQuery(Query().where(City::id.name, Op.Eq, 1)) } data class User( val id:Long = 0L, val email:String, val first:String = "", val last:String = "", val active:Boolean = false, val age:Int = 35, val salary:Double = 100.00, val registered:DateTime? = null, val createdAt:DateTime = DateTime.now(), val updatedAt:DateTime = DateTime.now() ) object UserSchema : Schema<Long, User>(Long::class, User::class, "user") { val id = id (User::id ) val email = field (User::email , min = 10, max = 50, indexed = true) val first = field (User::first , min = 10, max = 50) val last = field (User::last , min = 10, max = 50) val age = field (User::age ) val salary = field (User::salary ) val active = field (User::active ) val registered = field (User::registered) val createdAt = field (User::updatedAt , category = FieldCategory.Meta) val updatedAt = field (User::updatedAt , category = FieldCategory.Meta) } fun model(){ val model = UserSchema.model model.fields.forEach { println("field: name=${it.name}, ${it.storedName}, ${it.isRequired}, ${it.dataTpe}") } val model2 = ModelMapper.loadSchema(User::class) println("done") } fun orm(){ // Setup: This is boiler-plate that can be moved // to a helper function/builder // 1. connection // 2. database // 3. mapper // 4. repo // 5. service val con = DbConString(Vendor.H2.driver, "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "") val db = Db.open(con) val model = UserSchema.model val mapper:Mapper<Long, City> = OrmMapper<Long, City>(model, db, Long::class, City::class) val repo = Repo.h2<Long, City>(db, mapper) val service = EntityService<Long, City>(repo) service.save(City(0, "New York", "NYC")) // CRUD operations service.any() service.count() service.getById(1) } // val con2 = default(ConfFuncs.readDbCon("user://.slate/db_default.txt")!!) // // // 2. Create a Connections using an explicit connection string // // NOTE: Avoid using explicit connection strings in code. // val dbLookup2 = default( // DbConString( // "com.mysql.jdbc.Driver", // "jdbc:mysql://localhost/default", // "root", // "abcdefghi" // ) // ) // // // 3. Create a Connections using multiple named databases. // val dbLookup3 = named(listOf( // Pair( // "movies", DbConString( // "com.mysql.jdbc.Driver", // "jdbc:mysql://localhost/movies", // "root", // "abcdefghi" // ) // ), // Pair( // "files", DbConString( // "com.mysql.jdbc.Driver", // "jdbc:mysql://localhost/files", // "root", // "abcdefghi" // ) // ) // )) // // } /* fun service() { // ================================================================================= // The Service layer initialized with an repository . // Purpose of the service layer is to: // // 1. Delegate to underlying repository for CRUD operations after applying any business logic. // 2. Provide a layer to insert business logic during other operations. // 3. Has some( not all ) methods that match the repository CRUD, Find, Delete methods // 4. Subclassed to perform more complex business logic that may still involve using the repo. // val ctx = AppContext.simple("sampleapp1") val ent = Entities() val service = MovieService(ctx, ent, InMemoryRepo<Movie>(Movie::class)) // CASE 1: Create 3-4 users for showing use-cases service.create(Movie(0L, "Batman Begins" , "action", false, 50, 4.2, DateTimes.of(2005,1,1))) service.create(Movie(0L, "Dark Knight" , "action", false, 100,4.5, DateTimes.of(2012,1,1))) service.create(Movie(0L, "Dark Knight Rises", "action", false, 120,4.2, DateTimes.of(2012,1,1))) // CASE 2: Get by id printOne("2", service.get(2)) // CASE 3: Update val item2 = service.get(2) item2?.let { item -> val updated = item.copy(title = "Batman: Dark Knight") service.update(updated) } // CASE 4: Get all printAll("all", service.getAll()) // CASE 5: Get recent/last 2 printAll("recent", service.recent(2)) // CASE 6: Get oldest 2 printAll("oldest", service.oldest(2)) // CASE 7: Get first one ( oldest ) printOne("first", service.first()) // CASE 8: Get last one ( recent ) printOne("last", service.last()) // CASE 9: Delete by id service.deleteById(4) // CASE 10: Get total ( 4 ) println(service.count()) // CASE 11: Type-Safe queryusing property type reference println(service.findByField(Movie::playing, true)) // CASE 12: Query println(service.findByQuery(Query().where("playing", "=", true))) // More docs coming soon. } fun repo_setup():Unit { // ================================================================================= // CASE 1: In-memory ( non-persisted ) repository has limited functionality // but is very useful for rapid prototyping of a data model when you are trying to // figure out what fields/properties should exist on the model val repo = InMemoryRepo<Movie>(Movie::class) // CASE 2: My-sql ( persisted ) repository can be easily setup // More examples of database setup/entity registration available in Setup/Registration docs. // 2.1: First setup the database val db = Db(DbConString("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/user_db", "root", "abcdefghi")) // 2.2: Setup the mapper // NOTE: This assumes the entity has annotations on the properties. // If you do not want to use annotations, looks at the mapper/model // examples for alternative approaches. val model = ModelMapper.loadSchema(Movie::class) val mapper = EntityMapper(model, MySqlConverter) // 2.3: Now create the repo with database and mapper val repoMySql = MySqlRepo<Movie>(db, Movie::class, null, mapper) } fun repo_usage():Unit { val repo = InMemoryRepo<Movie>(Movie::class) // CASE 1: Create 3-4 users for showing use-cases repo.create(Movie(0L, "Batman Begins" , "action", false, 50, 4.2, DateTime.of(2005,1,1))) repo.create(Movie(0L, "Dark Knight" , "action", false, 100,4.5, DateTime.of(2012,1,1))) repo.create(Movie(0L, "Dark Knight Rises", "action", false, 120,4.2, DateTime.of(2012,1,1))) // CASE 2: Get by id printOne("2", repo.get(2)) // CASE 3: Update val item2 = repo.get(2) item2?.let { item -> val updated = item.copy(title = "Batman: Dark Knight") repo.update(updated) } // CASE 4: Get all printAll("all", repo.getAll()) // CASE 5: Get recent/last 2 printAll("recent", repo.recent(2)) // CASE 6: Get oldest 2 printAll("oldest", repo.oldest(2)) // CASE 7: Get first one ( oldest ) printOne("first", repo.first()) // CASE 8: Get last one ( recent ) printOne("last", repo.last()) // CASE 9: Delete by id repo.delete(4) // CASE 10: Get total ( 4 ) println(repo.count()) // CASE 11: Query println(repo.find(Query().where("playing", "=", true))) } fun mapper_setup():Unit { // CASE 1: Load the schema from the annotations on the model val schema1 = ModelMapper.loadSchema(Movie::class) // CASE 2: Load the schema manually using properties for type-safety val schema2 = Model(Movie::class) .addId(Movie::id, true) .add(Movie::title , "Title of movie" , 5, 30) .add(Movie::category , "Category (action|drama)", 1, 20) .add(Movie::playing , "Whether its playing now") .add(Movie::rating , "Rating from users" ) .add(Movie::released , "Date of release" ) .add(Movie::createdAt , "Who created record" ) .add(Movie::createdBy , "When record was created") .add(Movie::updatedAt , "Who updated record" ) .add(Movie::updatedBy , "When record was updated") // CASE 3: Load the schema manually using named fields val schema3 = Model(Example_Mapper.Movie::class) .addId(Movie::id, true) .addText ("title" , "Title of movie" , true, 1, 30) .addText ("category" , "Category (action|drama)", true, 1, 20) .addBool ("playing" , "Whether its playing now") .addDouble ("rating" , "Rating from users" ) .addDateTime("released" , "Date of release" ) .addDateTime("createdAt" , "Who created record" ) .addLong ("createdBy" , "When record was created") .addDateTime("updatedAt" , "Who updated record" ) .addLong ("updatedBy" , "When record was updated") } fun mapper_usage():Unit { val schema = ModelMapper.loadSchema(Movie::class) // CASE 1: Create mapper with the schema val mapper = EntityMapper (schema, MySqlConverter) // Create sample instance to demo the mapper val movie = Example_Mapper.Movie( title = "Man Of Steel", category = "action", playing = false, cost = 100, rating = 4.0, released = DateTime.of(2015, 7, 4) ) // CASE 2: Get the sql for create val sqlCreate = mapper.mapFields(null, movie, schema, false) println(sqlCreate) // CASE 3: Get the sql for update val sqlForUpdate = mapper.mapFields(null, movie, schema, true) println(sqlForUpdate) // CASE 4: Generate the table schema for mysql from the model //println("table sql : " + buildAddTable(MySqlBuilder(), schema)) } fun showResults(desc: String, regInfo: EntityContext) { println(desc) println(regInfo.toStringDetail()) println() } fun printAll(tag: String, models: List<Movie>) { println() println(tag.toUpperCase()) for (model in models) printOne(null, model) } fun printOne(tag: String?, model: Movie?) { tag?.let { t -> println() println(t.toUpperCase()) } model?.let { m -> println("User: " + m.id + ", " + m.title + ", " + m.category) } } */ }
apache-2.0
f13f970fabe6c3d27b5a8dd829782189
34.455081
112
0.538589
4.061751
false
false
false
false
humorousz/Exercises
MyApplication/lint_tools/src/main/java/com/humrousz/lint/ViewIdDetector.kt
1
1961
package com.humrousz.lint import com.android.SdkConstants import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.LayoutDetector import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.XmlContext import org.w3c.dom.Element /** * Description: * ViewId检查 * author:zhangzhiquan * Date: 2022/4/17 */ class ViewIdDetector : LayoutDetector() { override fun getApplicableElements(): Collection<String>? { return listOf( SdkConstants.TEXT_VIEW, SdkConstants.IMAGE_VIEW, SdkConstants.BUTTON ) } override fun visitElement(context: XmlContext, element: Element) { if (!element.hasAttributeNS(SdkConstants.ANDROID_URI, SdkConstants.ATTR_ID)) { return } val attr = element.getAttributeNodeNS(SdkConstants.ANDROID_URI, SdkConstants.ATTR_ID) val value = attr.value if (value.startsWith(SdkConstants.NEW_ID_PREFIX)) { val idValue = value.substring(SdkConstants.NEW_ID_PREFIX.length) var matchRule = true var expMsg = "" when (element.tagName) { SdkConstants.TEXT_VIEW -> { expMsg = "tv" matchRule = idValue.startsWith(expMsg) } } if (!matchRule) { context.report( ISSUE, attr, context.getLocation(attr), "ViewIdName建议使用view的缩写_xxx; ${element.tagName} 建议使用 `${expMsg}_xxx`" ) } } } companion object { val ISSUE: Issue = Issue.create( "ViewCheck", "ViewId命名不规范", "建议tv_开头", Category.CORRECTNESS, 5, Severity.ERROR, Implementation( ViewIdDetector::class.java, RESOURCE_FILE_SCOPE ) ) } }
apache-2.0
580fb92984daac2bd559ab8fb821107a
26.768116
89
0.668407
3.675624
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/ObjectConfirmationGraphic.kt
1
4443
/* * 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.firebase.ml.md.kotlin.objectdetection import android.graphics.Canvas import android.graphics.Paint import android.graphics.Paint.Cap import android.graphics.Paint.Style import android.graphics.RectF import androidx.core.content.ContextCompat import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay.Graphic import com.google.firebase.ml.md.R import com.google.firebase.ml.md.kotlin.settings.PreferenceUtils /** * Similar to the camera reticle but with additional progress ring to indicate an object is getting * confirmed for a follow up processing, e.g. product search. */ class ObjectConfirmationGraphic internal constructor( overlay: GraphicOverlay, private val confirmationController: ObjectConfirmationController ) : Graphic(overlay) { private val outerRingFillPaint: Paint private val outerRingStrokePaint: Paint private val innerRingPaint: Paint private val progressRingStrokePaint: Paint private val outerRingFillRadius: Int private val outerRingStrokeRadius: Int private val innerRingStrokeRadius: Int init { val resources = overlay.resources outerRingFillPaint = Paint().apply { style = Style.FILL color = ContextCompat.getColor(context, R.color.object_reticle_outer_ring_fill) } outerRingStrokePaint = Paint().apply { style = Style.STROKE strokeWidth = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_width).toFloat() strokeCap = Cap.ROUND color = ContextCompat.getColor(context, R.color.object_reticle_outer_ring_stroke) } progressRingStrokePaint = Paint().apply { style = Style.STROKE strokeWidth = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_width).toFloat() strokeCap = Cap.ROUND color = ContextCompat.getColor(context, R.color.white) } innerRingPaint = Paint() if (PreferenceUtils.isMultipleObjectsMode(overlay.context)) { innerRingPaint.style = Style.FILL innerRingPaint.color = ContextCompat.getColor(context, R.color.object_reticle_inner_ring) } else { innerRingPaint.style = Style.STROKE innerRingPaint.strokeWidth = resources.getDimensionPixelOffset(R.dimen.object_reticle_inner_ring_stroke_width).toFloat() innerRingPaint.strokeCap = Cap.ROUND innerRingPaint.color = ContextCompat.getColor(context, R.color.white) } outerRingFillRadius = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_fill_radius) outerRingStrokeRadius = resources.getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_radius) innerRingStrokeRadius = resources.getDimensionPixelOffset(R.dimen.object_reticle_inner_ring_stroke_radius) } override fun draw(canvas: Canvas) { val cx = canvas.width / 2f val cy = canvas.height / 2f canvas.drawCircle(cx, cy, outerRingFillRadius.toFloat(), outerRingFillPaint) canvas.drawCircle(cx, cy, outerRingStrokeRadius.toFloat(), outerRingStrokePaint) canvas.drawCircle(cx, cy, innerRingStrokeRadius.toFloat(), innerRingPaint) val progressRect = RectF( cx - outerRingStrokeRadius, cy - outerRingStrokeRadius, cx + outerRingStrokeRadius, cy + outerRingStrokeRadius ) val sweepAngle = confirmationController.progress * 360 canvas.drawArc( progressRect, /* startAngle= */ 0f, sweepAngle, /* useCenter= */ false, progressRingStrokePaint ) } }
apache-2.0
37b6423eeae5546a710a6da83fd3077f
40.138889
117
0.697727
4.465327
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/ArraysTest/flattenArray.kt
2
489
import kotlin.test.* fun box() { val arr1: Array<Array<Int>> = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6)) val arr2: Array<out Array<Int>> = arr1 val arr3: Array<out Array<out Int>> = arr1 val arr4: Array<Array<out Int>> = arr1 as Array<Array<out Int>> val expected = listOf(1, 2, 3, 4, 5, 6) assertEquals(expected, arr1.flatten()) assertEquals(expected, arr2.flatten()) assertEquals(expected, arr3.flatten()) assertEquals(expected, arr4.flatten()) }
apache-2.0
699c67a4d6e6d30e98a0411319982552
33.928571
77
0.650307
3.134615
false
true
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/inplace/SelectableInlayButton.kt
12
1992
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.rename.inplace import com.intellij.codeInsight.hints.presentation.DynamicDelegatePresentation import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.openapi.editor.ex.EditorEx import com.intellij.refactoring.rename.inplace.SelectableInlayPresentation.SelectionListener import java.awt.Cursor import java.awt.Point import java.awt.event.MouseEvent open class SelectableInlayButton( private val editor: EditorEx, private val default: InlayPresentation, private val active: InlayPresentation, private val hovered: InlayPresentation ): DynamicDelegatePresentation(default), SelectableInlayPresentation { private val selectionListeners: MutableList<SelectionListener> = mutableListOf() override var isSelected = false set(value) { field = value selectionListeners.forEach { it.selectionChanged(value) } update() } override fun addSelectionListener(listener: SelectionListener) { selectionListeners.add(listener) } private var isHovered = false set(value) { field = value update() } private fun update(){ delegate = when { isSelected -> active isHovered -> hovered else -> default } } override fun mouseClicked(event: MouseEvent, translated: Point) { super<DynamicDelegatePresentation>.mouseClicked(event, translated) isSelected = true } override fun mouseExited() { super<DynamicDelegatePresentation>.mouseExited() editor.setCustomCursor(this, null) isHovered = false } override fun mouseMoved(event: MouseEvent, translated: Point) { super<DynamicDelegatePresentation>.mouseMoved(event, translated) val defaultCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) editor.setCustomCursor(this, defaultCursor) isHovered = true } }
apache-2.0
884a5db7686d2ec43e5f9ebc11a44f77
30.140625
140
0.758534
4.776978
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/multiplatformLibrary/jvm/jvm.kt
3
381
package sample actual class <!LINE_MARKER("descr='Has declaration in common module'")!>Sample<!> { actual fun <!LINE_MARKER("descr='Has declaration in common module'")!>checkMe<!>() = 42 } actual object <!LINE_MARKER("descr='Has declaration in common module'")!>Platform<!> { actual val <!LINE_MARKER("descr='Has declaration in common module'")!>name<!>: String = "JVM" }
apache-2.0
10ba2f9142cb6aa16286f82766d374e9
41.444444
97
0.687664
4.233333
false
false
false
false
LouisCAD/Splitties
modules/views-recyclerview/src/androidMain/kotlin/splitties/views/recyclerview/GridLayoutManager.kt
1
1314
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.recyclerview import android.content.Context import androidx.annotation.IntegerRes import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import splitties.resources.int inline fun gridLayoutManager( spanCount: Int, reverseLayout: Boolean = false, setup: GridLayoutManager.() -> Unit = {} ) = GridLayoutManager(null, spanCount, RecyclerView.VERTICAL, reverseLayout).apply(setup) inline fun gridLayoutManager( context: Context, @IntegerRes spanCountRes: Int, reverseLayout: Boolean = false, setup: GridLayoutManager.() -> Unit = {} ) = gridLayoutManager(context.int(spanCountRes), reverseLayout, setup) inline fun horizontalGridLayoutManager( spanCount: Int, reverseLayout: Boolean = false, setup: GridLayoutManager.() -> Unit = {} ) = GridLayoutManager(null, spanCount, RecyclerView.HORIZONTAL, reverseLayout).apply(setup) inline fun horizontalGridLayoutManager( context: Context, @IntegerRes spanCountRes: Int, reverseLayout: Boolean = false, setup: GridLayoutManager.() -> Unit = {} ) = horizontalGridLayoutManager(context.int(spanCountRes), reverseLayout, setup)
apache-2.0
984b6fac1105fd2afe99d207d0ddde84
35.5
109
0.762557
4.830882
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantModalityModifierInspection.kt
3
1492
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.implicitModality import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix import org.jetbrains.kotlin.psi.declarationVisitor import org.jetbrains.kotlin.psi.psiUtil.modalityModifier class RedundantModalityModifierInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return declarationVisitor { declaration -> val modalityModifier = declaration.modalityModifier() ?: return@declarationVisitor val modalityModifierType = modalityModifier.node.elementType val implicitModality = declaration.implicitModality() if (modalityModifierType != implicitModality) return@declarationVisitor holder.registerProblem( modalityModifier, KotlinBundle.message("redundant.modality.modifier"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, IntentionWrapper(RemoveModifierFix(declaration, implicitModality, isRedundant = true)) ) } } }
apache-2.0
96daadae81ca2a2e7c25b8d3d7604bf6
48.733333
158
0.754692
5.525926
false
false
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/game/SceneRectangle.kt
1
2017
package org.runestar.client.api.game import org.runestar.client.api.game.live.Viewport import java.awt.Point import java.awt.Shape import java.awt.geom.Path2D data class SceneRectangle( val x: Int, val y: Int, val width: Int, val height: Int, val plane: Int ) { init { require(width > 0 && height > 0 && SceneTile.isPlaneLoaded(plane)) } val base: SceneTile get() = SceneTile(x, y, plane) fun outline(projection: Projection = Viewport): Shape { val tempPoint = Point() val path = Path2D.Float(Path2D.WIND_NON_ZERO, width * 2 + height * 2 + 2) var x = LocalValue(x, 0).value var y = LocalValue(y, 0).value if (!projection.toScreen(x, y, 0, plane, tempPoint)) return path path.moveTo(tempPoint.x.toFloat(), tempPoint.y.toFloat()) x += LocalValue.MAX_SUB lineTo(path, x, y, projection, tempPoint) repeat(width - 1) { x += LocalValue.MAX_SUB + 1 lineTo(path, x, y, projection, tempPoint) } y += LocalValue.MAX_SUB lineTo(path, x, y, projection, tempPoint) repeat(height - 1) { y += LocalValue.MAX_SUB + 1 lineTo(path, x, y, projection, tempPoint) } repeat(width - 1) { x -= LocalValue.MAX_SUB + 1 lineTo(path, x, y, projection, tempPoint) } x -= LocalValue.MAX_SUB lineTo(path, x, y, projection, tempPoint) repeat(height - 1) { y -= LocalValue.MAX_SUB + 1 lineTo(path, x, y, projection, tempPoint) } y -= LocalValue.MAX_SUB lineTo(path, x, y, projection, tempPoint) path.closePath() return path } private fun lineTo(path: Path2D.Float, localX: Int, localY: Int, projection: Projection, point: Point) { if (projection.toScreen(localX, localY, 0, plane, point)) { path.lineTo(point.x.toFloat(), point.y.toFloat()) } } }
mit
d69450238fc81654418d5a5dadae7da1
28.676471
108
0.570154
3.667273
false
false
false
false
Flank/flank
tool/json/src/main/kotlin/flank/json/JacksonXml.kt
1
991
package flank.json import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import java.util.Locale private val jsonFactory = JsonFactory() internal val jsonMapper = JsonMapper(jsonFactory) .registerModules(KotlinModule()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) internal val jsonPrettyWriter = jsonMapper.writerWithDefaultPrettyPrinter() internal class TimeSerializer : JsonSerializer<Double>() { override fun serialize(value: Double, gen: JsonGenerator, serializers: SerializerProvider) { gen.writeString( if (value == 0.0) "0.0" else String.format(Locale.US, "%.3f", value) ) } }
apache-2.0
7c55441610fe7e83687e1fd4359c39e7
35.703704
96
0.78002
4.484163
false
false
false
false
kickstarter/android-oss
app/src/internal/java/com/kickstarter/ui/views/DebugPushNotificationsView.kt
1
10599
package com.kickstarter.ui.views import android.content.Context import android.util.AttributeSet import android.widget.Button import android.widget.ScrollView import com.kickstarter.KSApplication import com.kickstarter.R import com.kickstarter.libs.DeviceRegistrarType import com.kickstarter.libs.PushNotifications import com.kickstarter.models.Activity import com.kickstarter.models.pushdata.GCM import com.kickstarter.services.apiresponses.PushNotificationEnvelope import javax.inject.Inject class DebugPushNotificationsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ScrollView(context, attrs, defStyleAttr) { @JvmField @Inject var deviceRegistrar: DeviceRegistrarType? = null @JvmField @Inject var pushNotifications: PushNotifications? = null override fun onFinishInflate() { super.onFinishInflate() if (isInEditMode) { return } (context.applicationContext as KSApplication).component().inject(this) findViewById<Button>(R.id.register_device_button).setOnClickListener { registerDeviceButtonClick() } findViewById<Button>(R.id.unregister_device_button).setOnClickListener { unregisterDeviceButtonClick() } findViewById<Button>(R.id.simulate_errored_pledge_button).setOnClickListener { simulateErroredPledgeButtonClick() } findViewById<Button>(R.id.simulate_friend_backing_button).setOnClickListener { simulateFriendBackingButtonClick() } findViewById<Button>(R.id.simulate_friend_follow_button).setOnClickListener { simulateFriendFollowButtonClick() } findViewById<Button>(R.id.simulate_message_button).setOnClickListener { simulateMessageButtonClick() } findViewById<Button>(R.id.simulate_project_cancellation_button).setOnClickListener { simulateProjectCancellationButtonClick() } findViewById<Button>(R.id.simulate_project_failure_button).setOnClickListener { simulateProjectFailureButtonClick() } findViewById<Button>(R.id.simulate_project_launch_button).setOnClickListener { simulateProjectLaunchButtonClick() } findViewById<Button>(R.id.simulate_project_reminder_button).setOnClickListener { simulateProjectReminderButtonClick() } findViewById<Button>(R.id.simulate_project_success_button).setOnClickListener { simulateProjectSuccessButtonClick() } findViewById<Button>(R.id.simulate_project_survey_button).setOnClickListener { simulateProjectSurveyButtonClick() } findViewById<Button>(R.id.simulate_project_update_button).setOnClickListener { simulateProjectUpdateButtonClick() } findViewById<Button>(R.id.simulate_burst_button).setOnClickListener { simulateBurstClick() } } fun registerDeviceButtonClick() { deviceRegistrar?.registerDevice() } fun unregisterDeviceButtonClick() { deviceRegistrar?.unregisterDevice() } fun simulateErroredPledgeButtonClick() { val gcm = GCM.builder() .title("Payment failure") .alert("Response needed! Get your reward for backing SKULL GRAPHIC TEE.") .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder() .gcm(gcm) .erroredPledge( PushNotificationEnvelope.ErroredPledge.builder() .projectId(PROJECT_ID) .build() ) .build() pushNotifications?.add(envelope) } fun simulateFriendBackingButtonClick() { val gcm = GCM.builder() .title("Check it out") .alert("Christopher Wright backed SKULL GRAPHIC TEE.") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_BACKING) .id(1) .projectId(PROJECT_ID) .projectPhoto(PROJECT_PHOTO) .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() pushNotifications?.add(envelope) } fun simulateFriendFollowButtonClick() { val gcm = GCM.builder() .title("You're in good company") .alert("Christopher Wright is following you on Kickstarter!") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_FOLLOW) .id(2) .userPhoto(USER_PHOTO) .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() pushNotifications?.add(envelope) } fun simulateMessageButtonClick() { val gcm = GCM.builder() .title("New message") .alert("Native Squad sent you a message about Help Me Transform This Pile of Wood.") .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder() .gcm(gcm) .message(PushNotificationEnvelope.Message.builder().messageThreadId(MESSAGE_THREAD_ID).projectId(PROJECT_ID).build()) .build() pushNotifications?.add(envelope) } fun simulateProjectCancellationButtonClick() { val gcm = GCM.builder() .title("Kickstarter") .alert("SKULL GRAPHIC TEE has been canceled.") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_CANCELLATION) .id(3) .projectId(PROJECT_ID) .projectPhoto(PROJECT_PHOTO) .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() pushNotifications?.add(envelope) } fun simulateProjectFailureButtonClick() { val gcm = GCM.builder() .title("Kickstarter") .alert("SKULL GRAPHIC TEE was not successfully funded.") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_FAILURE) .id(4) .projectId(PROJECT_ID) .projectPhoto(PROJECT_PHOTO) .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() pushNotifications?.add(envelope) } fun simulateProjectLaunchButtonClick() { val gcm = GCM.builder() .title("Want to be the first backer?") .alert("Taylor Moore just launched a project!") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_LAUNCH) .id(5) .projectId(PROJECT_ID) .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() pushNotifications?.add(envelope) } fun simulateProjectReminderButtonClick() { val gcm = GCM.builder() .title("Last call") .alert("Reminder! SKULL GRAPHIC TEE is ending soon.") .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder() .gcm(gcm) .project(PushNotificationEnvelope.Project.builder().id(PROJECT_ID).photo(PROJECT_PHOTO).build()) .build() pushNotifications?.add(envelope) } fun simulateProjectSuccessButtonClick() { pushNotifications?.add(projectSuccessEnvelope()) } fun simulateProjectSurveyButtonClick() { val gcm = GCM.builder() .title("Backer survey") .alert("Response needed! Get your reward for backing bugs in the office.") .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder() .gcm(gcm) .survey( PushNotificationEnvelope.Survey.builder() .id(18249859L) .projectId(PROJECT_ID) .build() ) .build() pushNotifications?.add(envelope) } fun simulateProjectUpdateButtonClick() { val gcm = GCM.builder() .title("News from Taylor Moore") .alert("Update #1 posted by SKULL GRAPHIC TEE.") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_UPDATE) .id(7) .projectId(PROJECT_ID) .projectPhoto(PROJECT_PHOTO) .updateId(1033848L) .build() val envelope: PushNotificationEnvelope = PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() pushNotifications?.add(envelope) } fun simulateBurstClick() { val baseEnvelope: PushNotificationEnvelope = projectSuccessEnvelope() for (i in 0..99) { // Create a different signature for each push notification val gcm: GCM = baseEnvelope.gcm().toBuilder().alert(Integer.toString(i)).build() pushNotifications?.add(baseEnvelope.toBuilder().gcm(gcm).build()) } } private fun projectSuccessEnvelope(): PushNotificationEnvelope { val gcm = GCM.builder() .title("Time to celebrate!") .alert("SKULL GRAPHIC TEE has been successfully funded.") .build() val activity = com.kickstarter.models.pushdata.Activity.builder() .category(Activity.CATEGORY_SUCCESS) .id(6) .projectId(PROJECT_ID) .projectPhoto(PROJECT_PHOTO) .build() return PushNotificationEnvelope.builder().activity(activity).gcm(gcm).build() } companion object { private const val MESSAGE_THREAD_ID = 17848074L private const val PROJECT_PHOTO = "https://ksr-ugc.imgix.net/projects/1176555/photo-original.png?v=1407175667&w=120&h=120&fit=crop&auto=format&q=92&s=2065d33620d4fef280c4c2d451c2fa93" private const val USER_PHOTO = "https://ksr-ugc.imgix.net/avatars/1583412/portrait.original.png?v=1330782076&w=120&h=120&fit=crop&auto=format&q=92&s=a9029da56a3deab8c4b87818433e3430" private const val PROJECT_ID = 1761344210L } }
apache-2.0
3b3a3dc94b560186a733e2ba3cc83ce0
37.682482
191
0.639683
4.721158
false
false
false
false
MyPureCloud/platform-client-sdk-common
resources/sdk/purecloudkotlin/tests/UserPresenceListener.kt
1
1134
package com.mypurecloud.sdk.v2 import com.mypurecloud.sdk.v2.extensions.notifications.NotificationEvent import com.mypurecloud.sdk.v2.extensions.notifications.NotificationListener import com.mypurecloud.sdk.v2.model.PresenceEventUserPresence class UserPresenceListener(userId: String) : NotificationListener<PresenceEventUserPresence?> { private val topic: String = "v2.users.$userId.presence" private var systemPresence = "" var presenceId = "" private set override fun getTopic(): String { return topic } override fun getEventBodyClass(): Class<PresenceEventUserPresence> { return PresenceEventUserPresence::class.java } override fun onEvent(event: NotificationEvent<*>?) { val notification = event?.getEventBody() as PresenceEventUserPresence systemPresence = notification.presenceDefinition?.systemPresence.toString() presenceId = notification.presenceDefinition?.id.toString() println("system presence -> " + ((event.getEventBody() as PresenceEventUserPresence).presenceDefinition?.systemPresence ?: "INVALID")) } }
mit
8e54dec1308fd641b61e5cea61ec8b8f
39.5
127
0.738977
4.68595
false
false
false
false
LateNightProductions/CardKeeper
app/src/main/java/com/awscherb/cardkeeper/ui/cards/CardsAdapter.kt
1
2712
package com.awscherb.cardkeeper.ui.cards import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.awscherb.cardkeeper.R import com.awscherb.cardkeeper.data.model.ScannedCode import com.google.zxing.BarcodeFormat.AZTEC import com.google.zxing.BarcodeFormat.DATA_MATRIX import com.google.zxing.BarcodeFormat.QR_CODE import com.google.zxing.WriterException import com.journeyapps.barcodescanner.BarcodeEncoder class CardsAdapter constructor( private val context: Context, private val onClickListener: (ScannedCode) -> Unit, private val deleteListener: (ScannedCode) -> Unit ) : RecyclerView.Adapter<CardViewHolder>() { private val encoder: BarcodeEncoder = BarcodeEncoder() var items: List<ScannedCode> = arrayListOf() set(value) { field = value notifyDataSetChanged() } override fun getItemCount() = items.size //================================================================================ // Adapter methods //================================================================================ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CardViewHolder( LayoutInflater.from(context).inflate( R.layout.adapter_code, parent, false ) ) override fun onBindViewHolder(holder: CardViewHolder, position: Int) { val item = items[position] holder.apply { // Set title codeTitle.text = item.title // Set image scaleType according to barcode type when (item.format) { QR_CODE, AZTEC, DATA_MATRIX -> codeImage.scaleType = ImageView.ScaleType.FIT_CENTER else -> codeImage.scaleType = ImageView.ScaleType.FIT_XY } // Load image try { codeImage.setImageBitmap( encoder.encodeBitmap(item.text, item.format, 200, 200) ) } catch (e: WriterException) { e.printStackTrace() } itemView.setOnClickListener { onClickListener(item) } // Setup delete itemView.setOnLongClickListener { deleteListener(item) true } } } } class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val codeTitle: TextView = itemView.findViewById(R.id.adapter_card_title) val codeImage: ImageView = itemView.findViewById(R.id.adapter_card_image) }
apache-2.0
afad5cee7789e85cd2fcbd2a088d2bb8
29.829545
99
0.612094
4.92196
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/references/ReadWriteAccessChecker.kt
2
2689
// 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.references import com.intellij.openapi.components.service import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.utils.addToStdlib.constant interface ReadWriteAccessChecker { fun readWriteAccessWithFullExpressionByResolve(assignment: KtBinaryExpression): Pair<ReferenceAccess, KtExpression>? = null fun readWriteAccessWithFullExpression( targetExpression: KtExpression, useResolveForReadWrite: Boolean ): Pair<ReferenceAccess, KtExpression> { var expression = targetExpression.getQualifiedExpressionForSelectorOrThis() loop@ while (true) { when (val parent = expression.parent) { is KtParenthesizedExpression, is KtAnnotatedExpression, is KtLabeledExpression -> expression = parent as KtExpression else -> break@loop } } val assignment = expression.getAssignmentByLHS() if (assignment != null) { when (assignment.operationToken) { KtTokens.EQ -> return ReferenceAccess.WRITE to assignment else -> { return ( if (useResolveForReadWrite) readWriteAccessWithFullExpressionByResolve(assignment) else null ) ?: (ReferenceAccess.READ_WRITE to assignment) } } } val unaryExpression = expression.parent as? KtUnaryExpression return if (unaryExpression != null && unaryExpression.operationToken in constant { setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) }) ReferenceAccess.READ_WRITE to unaryExpression else ReferenceAccess.READ to expression } companion object { fun getInstance(): ReadWriteAccessChecker = service() } } enum class ReferenceAccess(val isRead: Boolean, val isWrite: Boolean) { READ(true, false), WRITE(false, true), READ_WRITE(true, true) } fun KtExpression.readWriteAccess(useResolveForReadWrite: Boolean) = readWriteAccessWithFullExpression(useResolveForReadWrite).first fun KtExpression.readWriteAccessWithFullExpression(useResolveForReadWrite: Boolean): Pair<ReferenceAccess, KtExpression> = ReadWriteAccessChecker.getInstance().readWriteAccessWithFullExpression(this, useResolveForReadWrite)
apache-2.0
985367f74fa30f0cab3e915e983864c3
41.68254
158
0.707326
5.476578
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ui/tabs/layout/TabsLayoutSettingsUi.kt
3
4418
// 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.ui.tabs.layout import com.intellij.ide.ui.UISettings import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutInfo import javax.swing.ComboBoxModel import javax.swing.DefaultComboBoxModel import javax.swing.JComboBox import javax.swing.ListCellRenderer import javax.swing.SwingConstants.TOP class TabsLayoutSettingsUi { companion object { internal fun tabsLayoutComboBox(tabPlacementComboBoxModel: DefaultComboBoxModel<Int>): ComboBox<TabsLayoutInfo> { val model = DefaultComboBoxModel(TabsLayoutSettingsHolder.instance.installedInfos.toTypedArray()) val comboBox = comboBox(model, SimpleListCellRenderer.create<TabsLayoutInfo> { label, value, _ -> label.text = value.name }) comboBox.addActionListener { val selectedInfo = getSelectedInfo(comboBox) if (selectedInfo == null) { tabPlacementComboBoxModel.removeAllElements() tabPlacementComboBoxModel.addElement(TOP) return@addActionListener } val availableTabsPositions = selectedInfo.availableTabsPositions if (availableTabsPositions.isNullOrEmpty()) { tabPlacementComboBoxModel.removeAllElements() tabPlacementComboBoxModel.addElement(TOP) return@addActionListener } var needToResetSelected = true var selectedValue: Int? = null if (tabPlacementComboBoxModel.selectedItem is Int) { val prevSelectedValue = tabPlacementComboBoxModel.selectedItem as Int if (prevSelectedValue in availableTabsPositions) { selectedValue = prevSelectedValue needToResetSelected = false } } if (needToResetSelected) { selectedValue = availableTabsPositions[0] } tabPlacementComboBoxModel.removeAllElements() for (value in availableTabsPositions) { tabPlacementComboBoxModel.addElement(value) } tabPlacementComboBoxModel.selectedItem = selectedValue } return comboBox } private fun <T> comboBox(model: ComboBoxModel<T>, renderer: ListCellRenderer<T?>? = null): ComboBox<T> { val component = ComboBox(model) if (renderer != null) { component.renderer = renderer } else { component.renderer = SimpleListCellRenderer.create("") { it.toString() } } return component } fun prepare(builder: Cell<JComboBox<TabsLayoutInfo>>, comboBox: JComboBox<TabsLayoutInfo>) { builder.onApply { getSelectedInfo(comboBox)?.let{ UISettings.getInstance().selectedTabsLayoutInfoId = it.id } } builder.onReset { val savedSelectedInfoId = calculateSavedSelectedInfoId() val selectedInfo = getSelectedInfo(comboBox) val isWrongSelected = selectedInfo == null || selectedInfo.id != UISettings.getInstance().selectedTabsLayoutInfoId for (info in TabsLayoutSettingsHolder.instance.installedInfos) { if (isWrongSelected && info.id == savedSelectedInfoId) { comboBox.selectedItem = info } } } builder.onIsModified { val savedSelectedInfoId = calculateSavedSelectedInfoId() val selectedInfo = getSelectedInfo(comboBox) if (selectedInfo != null && selectedInfo.id != savedSelectedInfoId) { return@onIsModified true } return@onIsModified false } } private fun calculateSavedSelectedInfoId(): String? { var savedSelectedInfoId = UISettings.getInstance().selectedTabsLayoutInfoId if (StringUtil.isEmpty(savedSelectedInfoId)) { savedSelectedInfoId = TabsLayoutSettingsHolder.instance.defaultInfo.id } return savedSelectedInfoId } fun getSelectedInfo(comboBox: JComboBox<TabsLayoutInfo>) : TabsLayoutInfo? { val selectedInfo = comboBox.selectedItem selectedInfo?.let { return selectedInfo as TabsLayoutInfo } return null } } }
apache-2.0
31080c52ae407db3b3b0dd21b857a443
35.520661
122
0.67723
5.131243
false
false
false
false
jwren/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/service/KotlinVersionProviderService.kt
6
2832
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.core.service import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.DefaultRepository import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repositories import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repository import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version abstract class KotlinVersionProviderService : WizardService { abstract fun getKotlinVersion(projectKind: ProjectKind): WizardKotlinVersion protected fun kotlinVersionWithDefaultValues(version: Version) = WizardKotlinVersion( version, getKotlinVersionKind(version), getKotlinVersionRepository(version), getBuildSystemPluginRepository(getKotlinVersionKind(version), getDevVersionRepository()), ) private fun getKotlinVersionRepository(versionKind: KotlinVersionKind): Repository = when (versionKind) { KotlinVersionKind.STABLE, KotlinVersionKind.EAP, KotlinVersionKind.M -> DefaultRepository.MAVEN_CENTRAL KotlinVersionKind.DEV -> getDevVersionRepository() } protected open fun getDevVersionRepository(): Repository = Repositories.JETBRAINS_KOTLIN_DEV private fun getKotlinVersionRepository(version: Version) = getKotlinVersionRepository(getKotlinVersionKind(version)) private fun getKotlinVersionKind(version: Version) = when { "eap" in version.toString().toLowerCase() -> KotlinVersionKind.EAP "rc" in version.toString().toLowerCase() -> KotlinVersionKind.EAP "dev" in version.toString().toLowerCase() -> KotlinVersionKind.DEV "m" in version.toString().toLowerCase() -> KotlinVersionKind.M else -> KotlinVersionKind.STABLE } companion object { fun getBuildSystemPluginRepository( versionKind: KotlinVersionKind, devRepository: Repository ): (BuildSystemType) -> Repository? = when (versionKind) { KotlinVersionKind.STABLE, KotlinVersionKind.EAP, KotlinVersionKind.M -> { buildSystem -> when (buildSystem) { BuildSystemType.GradleKotlinDsl, BuildSystemType.GradleGroovyDsl -> DefaultRepository.GRADLE_PLUGIN_PORTAL BuildSystemType.Maven -> DefaultRepository.MAVEN_CENTRAL BuildSystemType.Jps -> null } } KotlinVersionKind.DEV -> { _ -> devRepository } } } }
apache-2.0
526f129536c6941a36c0b91811395118
48.701754
158
0.724223
5.40458
false
false
false
false
alisle/Penella
src/main/java/org/penella/store/StoreVertical.kt
1
4343
package org.penella.store import io.vertx.core.AbstractVerticle import io.vertx.core.Future import io.vertx.core.Handler import io.vertx.core.eventbus.Message import org.omg.PortableInterceptor.SUCCESSFUL import org.penella.MailBoxes import org.penella.codecs.* import org.penella.messages.* /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created by alisle on 1/14/17. */ class InvalidStoreSelected : Exception("Invalid Store Selected") class StoreVertical : AbstractVerticle() { companion object { val STORE_TYPE = "type" val SEED = "seed" val MAX_STRING = "max_string" } val storeType : String by lazy { config().getString(STORE_TYPE) } val storeSeed : Long by lazy { config().getLong(SEED) } val storeMaxString : Int by lazy { config().getInteger(MAX_STRING) } val store : IStore by lazy { when(storeType) { "BSTreeStore" -> BSTreeStore(storeSeed) "BTreeCompressedStore" -> BTreeCompressedStore(storeSeed, storeMaxString) else -> throw InvalidStoreSelected() } } val storeAddTripleHandler = Handler<Message<StoreAddTriple>> { msg -> store.add(msg.body().value) msg.reply(StatusMessage(Status.SUCESSFUL, "Successfully Added")) } val storeAddStringHandler = Handler<Message<StoreAddString>> { msg -> val hash = store.add(msg.body().string) msg.reply(StoreAddStringResponse(hash)) } val getStringHandler = Handler<Message<StoreGetString>> { msg -> val string = store.get(msg.body().value) msg.reply(StoreGetStringResponse(string)) } val getHashtripleHandler = Handler<Message<StoreGetHashTriple>> { msg -> val triple = store.get(msg.body().value) msg.reply(StoreGetHashTripleResponse(triple)) } val generateHashHandler = Handler<Message<StoreGenerateHash>> { msg -> val hash = store.generateHash(msg.body().value) msg.reply(StoreGenerateHashResponse(hash)) } fun registerCodecs() { vertx.eventBus().registerDefaultCodec(StoreAddString::class.java, StoreAddStringCodec()) vertx.eventBus().registerDefaultCodec(StoreAddStringResponse::class.java, StoreAddStringResponseCodec()) vertx.eventBus().registerDefaultCodec(StoreAddTriple::class.java, StoreAddTripleCodec()) vertx.eventBus().registerDefaultCodec(StoreGenerateHash::class.java, StoreGenerateHashCodec()) vertx.eventBus().registerDefaultCodec(StoreGenerateHashResponse::class.java, StoreGenerateHashResponseCodec()) vertx.eventBus().registerDefaultCodec(StoreGetHashTriple::class.java, StoreGetHashTripleCodec()) vertx.eventBus().registerDefaultCodec(StoreGetHashTripleResponse::class.java, StoreGetHashTripleResponseCodec()) vertx.eventBus().registerDefaultCodec(StoreGetString::class.java, StoreGetStringCodec()) vertx.eventBus().registerDefaultCodec(StoreGetStringResponse::class.java, StoreGetStringResponseCodec()) } override fun start(startFuture: Future<Void>?) { registerCodecs() vertx.eventBus().consumer<StoreAddString>(MailBoxes.STORE_ADD_STRING.mailbox).handler(storeAddStringHandler) vertx.eventBus().consumer<StoreAddTriple>(MailBoxes.STORE_ADD_TRIPLE.mailbox).handler(storeAddTripleHandler) vertx.eventBus().consumer<StoreGetString>(MailBoxes.STORE_GET_STRING.mailbox).handler(getStringHandler) vertx.eventBus().consumer<StoreGetHashTriple>(MailBoxes.STORE_GET_HASHTRIPLE.mailbox).handler(getHashtripleHandler) vertx.eventBus().consumer<StoreGenerateHash>(MailBoxes.STORE_GENERATE_HASH.mailbox).handler(generateHashHandler) startFuture?.complete() } override fun stop(stopFuture: Future<Void>?) { super.stop(stopFuture) } }
apache-2.0
4ad1320ff513c84841387b80a63b600a
40.361905
123
0.719318
4.245357
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/di/module/NetworkModule.kt
1
7134
package com.sedsoftware.yaptalker.di.module import com.sedsoftware.yaptalker.common.converter.HashSearchConverterFactory import com.sedsoftware.yaptalker.common.converter.VideoTokenConverterFactory import com.sedsoftware.yaptalker.data.network.external.AppUpdatesChecker import com.sedsoftware.yaptalker.data.network.external.GitHubLoader import com.sedsoftware.yaptalker.data.network.site.YapApi import com.sedsoftware.yaptalker.data.network.site.YapLoader import com.sedsoftware.yaptalker.data.network.site.YapSearchIdLoader import com.sedsoftware.yaptalker.data.network.site.YapVideoTokenLoader import com.sedsoftware.yaptalker.data.network.thumbnails.CoubLoader import com.sedsoftware.yaptalker.data.network.thumbnails.RutubeLoader import com.sedsoftware.yaptalker.data.network.thumbnails.VkLoader import com.sedsoftware.yaptalker.data.network.thumbnails.YapFileLoader import com.sedsoftware.yaptalker.data.network.thumbnails.YapVideoLoader import com.sedsoftware.yaptalker.di.module.network.HttpClientsModule import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import pl.droidsonroids.retrofit2.JspoonConverterFactory import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import javax.inject.Named import javax.inject.Singleton @Module(includes = [(HttpClientsModule::class)]) class NetworkModule { companion object { private const val SITE_BASE_URL = "https://www.yaplakal.com/" private const val SITE_YAPFILES_URL = "https://www.yapfiles.ru/" // Videos private const val COUB_BASE_URL = "https://coub.com/" private const val RUTUBE_BASE_URL = "https://rutube.ru/" private const val YAP_FILES_BASE_URL = "http://www.yapfiles.ru/" private const val YAP_API_BASE_URL = "http://api.yapfiles.ru/" private const val VK_API_BASE_URL = "https://api.vk.com/" private const val YAP_API_BASE_URL_NEW = "https://api.yaplakal.com/" // Misc private const val YAP_FILE_HASH_MARKER = "md5=" private const val YAP_SEARCH_ID_HASH_MARKER = "searchid=" // Github private const val GITHUB_BASE_URL = "https://raw.githubusercontent.com/" // Deploy private const val APP_DEPLOY_BASE_URL = "http://sedsoftware.com/" // Token private const val TOKEN_START_MARKER = "token=" private const val TOKEN_END_MARKER = "\"" } @Singleton @Provides fun provideYapLoader(@Named("siteClient") okHttpClient: OkHttpClient): YapLoader = Retrofit.Builder() .baseUrl(SITE_BASE_URL) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JspoonConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) .build() .create(YapLoader::class.java) @Singleton @Provides fun provideYapApi(@Named("apiClient") okHttpClient: OkHttpClient): YapApi = Retrofit.Builder() .baseUrl(YAP_API_BASE_URL_NEW) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) .build() .create(YapApi::class.java) @Singleton @Provides fun provideYapSearchIdLoader(@Named("siteClient") okHttpClient: OkHttpClient): YapSearchIdLoader = Retrofit.Builder() .baseUrl(SITE_BASE_URL) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(HashSearchConverterFactory.create(YAP_SEARCH_ID_HASH_MARKER)) .build() .create(YapSearchIdLoader::class.java) @Singleton @Provides fun provideYapVideoTokenLoader(@Named("siteClient") okHttpClient: OkHttpClient): YapVideoTokenLoader = Retrofit.Builder() .baseUrl(SITE_YAPFILES_URL) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(VideoTokenConverterFactory.create(TOKEN_START_MARKER, TOKEN_END_MARKER)) .build() .create(YapVideoTokenLoader::class.java) @Singleton @Provides fun provideCoubLoader(): CoubLoader = Retrofit.Builder() .baseUrl(COUB_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(CoubLoader::class.java) @Singleton @Provides fun provideRutubeLoader(): RutubeLoader = Retrofit.Builder() .baseUrl(RUTUBE_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(RutubeLoader::class.java) @Singleton @Provides fun provideYapFileLoader(@Named("siteClient") okHttpClient: OkHttpClient): YapFileLoader = Retrofit.Builder() .baseUrl(YAP_API_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(HashSearchConverterFactory.create(YAP_FILE_HASH_MARKER)) .client(okHttpClient) .build() .create(YapFileLoader::class.java) @Singleton @Provides fun provideYapVideoLoader(@Named("siteClient") okHttpClient: OkHttpClient): YapVideoLoader = Retrofit.Builder() .baseUrl(YAP_API_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() .create(YapVideoLoader::class.java) @Singleton @Provides fun provideVkLoader(): VkLoader = Retrofit.Builder() .baseUrl(VK_API_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(VkLoader::class.java) @Singleton @Provides fun provideGithubLoader(@Named("outerClient") okHttpClient: OkHttpClient): GitHubLoader = Retrofit.Builder() .baseUrl(GITHUB_BASE_URL) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) .build() .create(GitHubLoader::class.java) @Singleton @Provides fun provideAppUpdatesLoader(): AppUpdatesChecker = Retrofit.Builder() .baseUrl(APP_DEPLOY_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(AppUpdatesChecker::class.java) }
apache-2.0
4c98e44845d6d7ca551dad774a23ff12
39.078652
106
0.687553
4.578947
false
false
false
false
androidx/androidx
compose/ui/ui-tooling/src/androidAndroidTest/kotlin/androidx/compose/ui/tooling/animation/clock/AnimatedVisibilityClockTest.kt
3
7795
/* * 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.compose.ui.tooling.animation.clock import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.tooling.animation.Utils.assertEquals import androidx.compose.ui.tooling.animation.Utils.createTestAnimatedVisibility import androidx.compose.ui.tooling.animation.parseAnimatedVisibility import androidx.compose.ui.tooling.animation.states.AnimatedVisibilityState import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test class AnimatedVisibilityClockTest { @get:Rule val rule = createComposeRule() @Test fun checkClockAfterStateChanged() { val clock = setupClock() rule.runOnIdle { assertEquals(AnimatedVisibilityState.Enter, clock.state) assertEquals(380, clock.getMaxDuration(), 30) assertEquals(380, clock.getMaxDurationPerIteration(), 30) val transitions = clock.getTransitions(200L) assertEquals(3, transitions.size) transitions[0].let { assertEquals("Built-in InterruptionHandlingOffset", it.label) assertEquals(0, it.startTimeMillis) assertEquals(0, it.endTimeMillis) assertEquals("androidx.compose.animation.core.SpringSpec", it.specType) assertTrue(it.values.containsKey(0)) } transitions[1].let { assertEquals("Built-in alpha", it.label) assertEquals(0, it.startTimeMillis) assertTrue(it.endTimeMillis > 300) assertEquals("androidx.compose.animation.core.SpringSpec", it.specType) assertTrue(it.values.containsKey(0)) assertEquals(3, it.values.size) } transitions[2].let { assertEquals("Built-in shrink/expand", it.label) assertEquals(0, it.startTimeMillis) assertTrue(it.endTimeMillis > 300) assertEquals("androidx.compose.animation.core.SpringSpec", it.specType) assertTrue(it.values.containsKey(0)) assertEquals(3, it.values.size) } clock.state = AnimatedVisibilityState.Exit } rule.waitForIdle() rule.runOnIdle { assertEquals(AnimatedVisibilityState.Exit, clock.state) assertEquals(380, clock.getMaxDuration(), 30) assertEquals(380, clock.getMaxDurationPerIteration(), 30) val transitions = clock.getTransitions(200L) assertEquals(3, transitions.size) transitions[0].let { assertEquals("Built-in InterruptionHandlingOffset", it.label) assertEquals(0, it.startTimeMillis) assertEquals(0, it.endTimeMillis) assertEquals("androidx.compose.animation.core.SpringSpec", it.specType) assertTrue(it.values.containsKey(0)) } transitions[1].let { assertEquals("Built-in alpha", it.label) assertEquals(0, it.startTimeMillis) assertEquals(330, it.endTimeMillis, 30) assertEquals("androidx.compose.animation.core.SpringSpec", it.specType) assertTrue(it.values.containsKey(0)) assertEquals(3, it.values.size) } transitions[2].let { assertEquals("Built-in shrink/expand", it.label) assertEquals(0, it.startTimeMillis) assertEquals(380, it.endTimeMillis, 30) assertEquals("androidx.compose.animation.core.SpringSpec", it.specType) assertTrue(it.values.containsKey(0)) assertEquals(3, it.values.size) } } } @Test fun changeTime() { val clock = setupClock() rule.runOnIdle { val propertiesAt0 = clock.getAnimatedProperties() propertiesAt0[0].let { assertEquals("Built-in InterruptionHandlingOffset", it.label) assertEquals(IntOffset(0, 0), it.value) } propertiesAt0[1].let { assertEquals("Built-in alpha", it.label) assertEquals(0f, it.value) } propertiesAt0[2].let { assertEquals("Built-in shrink/expand", it.label) assertEquals(IntSize(0, 0), it.value) } clock.setClockTime(millisToNanos(400L)) val propertiesAt400 = clock.getAnimatedProperties() propertiesAt400[0].let { assertEquals("Built-in InterruptionHandlingOffset", it.label) assertEquals(IntOffset(0, 0), it.value) } propertiesAt400[1].let { assertEquals("Built-in alpha", it.label) assertEquals(1f, it.value) } propertiesAt400[2].let { assertEquals("Built-in shrink/expand", it.label) assertNotEquals(IntSize(0, 0), it.value) } // Change start and end state. clock.state = AnimatedVisibilityState.Exit } rule.waitForIdle() rule.runOnIdle { val propertiesAt0 = clock.getAnimatedProperties() propertiesAt0[0].let { assertEquals("Built-in InterruptionHandlingOffset", it.label) assertEquals(IntOffset(0, 0), it.value) } propertiesAt0[1].let { assertEquals("Built-in alpha", it.label) assertEquals(1f, it.value) } propertiesAt0[2].let { assertEquals("Built-in shrink/expand", it.label) assertNotEquals(IntSize(0, 0), it.value) } clock.setClockTime(millisToNanos(100L)) val propertiesAt400 = clock.getAnimatedProperties() propertiesAt400[0].let { assertEquals("Built-in InterruptionHandlingOffset", it.label) assertEquals(IntOffset(0, 0), it.value) } propertiesAt400[1].let { assertEquals("Built-in alpha", it.label) assertNotEquals(1f, it.value) } propertiesAt400[2].let { assertEquals("Built-in shrink/expand", it.label) assertNotEquals(IntSize(0, 0), it.value) } // Change start and end state. clock.state = AnimatedVisibilityState.Exit } } private fun setupClock(): AnimatedVisibilityClock { lateinit var clock: AnimatedVisibilityClock rule.setContent { val transition = createTestAnimatedVisibility() clock = AnimatedVisibilityClock(transition.parseAnimatedVisibility()) } rule.waitForIdle() rule.waitForIdle() rule.runOnIdle { clock.state = AnimatedVisibilityState.Enter clock.setClockTime(0) } rule.waitForIdle() return clock } }
apache-2.0
53941d781a9fc5b12978ce8e90e40349
40.68984
87
0.604875
4.779277
false
false
false
false
androidx/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/action/RunCallbackAction.kt
3
3057
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.action import android.content.Context import androidx.glance.GlanceId import androidx.glance.action.Action import androidx.glance.action.ActionParameters import androidx.glance.action.actionParametersOf internal class RunCallbackAction( val callbackClass: Class<out ActionCallback>, val parameters: ActionParameters ) : Action { companion object { suspend fun run( context: Context, className: String, glanceId: GlanceId, parameters: ActionParameters ) { val workClass = Class.forName(className) if (!ActionCallback::class.java.isAssignableFrom(workClass)) { error("Provided class must implement ActionCallback.") } val actionCallback = workClass.getDeclaredConstructor().newInstance() as ActionCallback actionCallback.onAction(context, glanceId, parameters) } } } /** * A callback executed in response to the user action, before the content is updated. The * implementing class must have a public zero argument constructor, this is used to instantiate * the class at runtime. */ interface ActionCallback { /** * Performs the work associated with this action. Called when the action is triggered. * * @param context the calling context * @param glanceId the [GlanceId] that triggered this action * @param parameters the parameters associated with the action */ suspend fun onAction( context: Context, glanceId: GlanceId, parameters: ActionParameters ) } /** * Creates an [Action] that executes a given [ActionCallback] implementation * * @param callbackClass the class that implements [ActionCallback] * @param parameters the parameters associated with the action */ fun <T : ActionCallback> actionRunCallback( callbackClass: Class<T>, parameters: ActionParameters = actionParametersOf() ): Action = RunCallbackAction(callbackClass, parameters) /** * Creates an [Action] that executes a given [ActionCallback] implementation * * @param parameters the parameters associated with the action */ @Suppress("MissingNullability") // Shouldn't need to specify @NonNull. b/199284086 inline fun <reified T : ActionCallback> actionRunCallback( parameters: ActionParameters = actionParametersOf() ): Action = actionRunCallback(T::class.java, parameters)
apache-2.0
a1527bde0d8c5b7ce4ecf41c473c4db8
33.738636
99
0.718351
4.761682
false
false
false
false
GunoH/intellij-community
plugins/completion-ml-ranking-models/src/com/jetbrains/completion/ml/ranker/ExperimentJavaRecommendersMLRankingProvider.kt
8
637
package com.jetbrains.completion.ml.ranker import com.intellij.completion.ml.ranker.ExperimentModelProvider import com.intellij.internal.ml.catboost.CatBoostJarCompletionModelProvider import com.intellij.lang.Language class ExperimentJavaRecommendersMLRankingProvider : CatBoostJarCompletionModelProvider( CompletionRankingModelsBundle.message("ml.completion.experiment.model.java"), "java_features_exp_rec", "java_model_exp_rec"), ExperimentModelProvider { override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("java", ignoreCase = true) == 0 override fun experimentGroupNumber(): Int = 14 }
apache-2.0
27ec37149625ba20f3970786c802bf36
44.5
119
0.825746
4.582734
false
false
false
false
YutaKohashi/FakeLineApp
app/src/main/java/jp/yuta/kohashi/fakelineapp/models/TalkData.kt
1
1591
package jp.yuta.kohashi.fakelineapp.models import android.os.Parcel import android.os.Parcelable import java.util.* /** * Author : yuta * Project name : FakeLineApp * Date : 23 / 08 / 2017 */ // このモデルをjsonに変換して保存する class TalkData(yourName: String, imgPath: String, calendar: Calendar, isRead: Boolean, items: MutableList<TalkItem>) : Parcelable { // トーク相手の名前 var yourName: String = yourName // 画像のパス var imgPath: String = imgPath // 日付情報 var calendar: Calendar = calendar // 既読チェックボックス var isRead: Boolean = isRead // トークアイテムリスト var items: MutableList<TalkItem> = items constructor(source: Parcel) : this( source.readString(), source.readString(), source.readSerializable() as Calendar, 1 == source.readInt(), source.createTypedArrayList(TalkItem.CREATOR) ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(yourName) writeString(imgPath) writeSerializable(calendar) writeInt((if (isRead) 1 else 0)) writeTypedList(items) } companion object { @JvmField val CREATOR: Parcelable.Creator<TalkData> = object : Parcelable.Creator<TalkData> { override fun createFromParcel(source: Parcel): TalkData = TalkData(source) override fun newArray(size: Int): Array<TalkData?> = arrayOfNulls(size) } } }
mit
ceb031259ad4e5b5401fd5e8a3eb4d55
25.571429
131
0.646268
3.902887
false
false
false
false
GunoH/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToStatic/fixes.kt
4
3717
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ConvertToStatic") package org.jetbrains.plugins.groovy.refactoring.convertToStatic import com.intellij.psi.PsiElement import com.intellij.psi.impl.light.LightElement import org.jetbrains.plugins.groovy.intentions.style.AddReturnTypeFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic private const val MAX_FIX_ITERATIONS = 5 fun applyErrorFixes(element: GroovyPsiElement) { if (!element.isPhysical) { return } repeat(MAX_FIX_ITERATIONS) { val checker = TypeChecker() element.accept(TypeCheckVisitor(checker)) if (checker.applyFixes() == 0) { return } } } fun applyDeclarationFixes(scope: GroovyPsiElement) { repeat(MAX_FIX_ITERATIONS) { collectReferencedEmptyDeclarations(scope).forEach { element -> when (element) { is GrMethod -> AddReturnTypeFix.applyFix(scope.project, element) is GrVariable -> { val psiType = element.typeGroovy ?: return@forEach element.setType(psiType) element.modifierList?.setModifierProperty(DEF, false) } } } } } fun collectReferencedEmptyDeclarations(scope: GroovyPsiElement, recursive: Boolean = true): List<PsiElement> { val declarationsVisitor = EmptyDeclarationTypeCollector(recursive) scope.accept(declarationsVisitor) return declarationsVisitor.elements } private class TypeCheckVisitor(val checker: TypeChecker) : GroovyRecursiveElementVisitor() { override fun visitElement(element: GroovyPsiElement) { if (isCompileStatic(element)) { element.accept(checker) } super.visitElement(element) } } private class EmptyDeclarationTypeCollector(private val recursive: Boolean) : GroovyElementVisitor() { val elements = mutableListOf<PsiElement>() override fun visitReferenceExpression(referenceExpression: GrReferenceExpression) { checkReference(referenceExpression) super.visitReferenceExpression(referenceExpression) } private fun checkReference(referenceExpression: GroovyReference) { val resolveResult = referenceExpression.advancedResolve() if (!resolveResult.isValidResult) return when (val element = resolveResult.element) { is GrAccessorMethod -> { checkField(element.property) } is GrField -> { checkField(element) } is LightElement -> return is GrMethod -> { if (element.isConstructor) return element.returnTypeElementGroovy?.let { return } elements += element } } } private fun checkField(element: GrField) { element.declaredType?.let { return } val initializer = element.initializerGroovy ?: return initializer.type ?: return elements += element } override fun visitElement(element: GroovyPsiElement) { if (recursive) { element.acceptChildren(this) } } }
apache-2.0
2d77bbcd8f0fde9518225d2e0b7cee05
34.409524
120
0.753565
4.48913
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/diagnosticsMessage/valOrVarOnParameter.kt
8
1034
// WITH_STDLIB class A { constructor(<error descr="[VAL_OR_VAR_ON_SECONDARY_CONSTRUCTOR_PARAMETER] 'val' on secondary constructor parameter is not allowed">val</error> <warning descr="[UNUSED_PARAMETER] Parameter 'x' is never used">x</warning>: Int) { for (<error descr="[VAL_OR_VAR_ON_LOOP_PARAMETER] 'val' on loop parameter is not allowed">val</error> z in 1..4) {} } fun foo(<error descr="[VAL_OR_VAR_ON_FUN_PARAMETER] 'var' on function parameter is not allowed">var</error> <warning descr="[UNUSED_PARAMETER] Parameter 'y' is never used">y</warning>: Int) { try { for (<error descr="[VAL_OR_VAR_ON_LOOP_PARAMETER] 'var' on loop parameter is not allowed">var</error> (<warning descr="[UNUSED_VARIABLE] Variable 'i' is never used">i</warning>, <warning descr="[UNUSED_VARIABLE] Variable 'j' is never used">j</warning>) in listOf(1 to 4)) {} } catch (<error descr="[VAL_OR_VAR_ON_CATCH_PARAMETER] 'val' on catch parameter is not allowed">val</error> e: Exception) { } } }
apache-2.0
380b5062c3cd6bc7440930935fd43186
72.928571
286
0.669246
3.553265
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspections/blockingCallsDetection/FlowOn.kt
5
741
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* fun flowOnMain(): Flow<Int> = flow { for (i in 1..3) { Thread.<warning descr="Inappropriate blocking method call">sleep</warning>(100) emit(i) } }.flowOn(Dispatchers.Main) fun flowSimple(): Flow<Int> = flow { for (i in 1..3) { Thread.<warning descr="Inappropriate blocking method call">sleep</warning>(100) emit(i) } } fun flowOnIO(): Flow<Int> = flow { for (i in 1..3) { Thread.sleep(100) emit(i) } }.flowOn(Dispatchers.IO) fun flowOnIOAndMap(): Flow<Unit> = flow { for (i in 1..3) { Thread.sleep(100) emit(i) } }.map { Thread.sleep(100) } .flowOn(Dispatchers.IO)
apache-2.0
e56e89804b2018168280db709a64eaf4
22.15625
87
0.59919
3.278761
false
false
false
false
vovagrechka/fucking-everything
attic/photlin/src/org/jetbrains/kotlin/js/translate/utils/astUtils.kt
1
3430
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.translate.utils.jsAstUtils import photlinc.* import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.translate.context.Namer import photlin.* import vgrechka.* fun JsFunction.addStatement(stmt: JsStatement) { body.statements.add(stmt) } fun JsFunction.addParameter(identifier: String, index: Int? = null): JsParameter { val name = scope.declareTemporaryName(identifier) val parameter = JsParameter(name) if (index == null) { parameters.add(parameter) } else { parameters.add(index, parameter) } return parameter } /** * Tests, if any node containing in receiver's AST matches, [predicate]. */ fun JsNode.any(predicate: (JsNode) -> Boolean): Boolean { val visitor = object : RecursiveJsVisitor() { var matched: Boolean = false override fun visitElement(node: JsNode) { matched = matched || predicate(node) if (!matched) { super.visitElement(node) } } } visitor.accept(this) return visitor.matched } fun JsExpression.toInvocationWith( leadingExtraArgs: List<JsExpression>, parameterCount: Int, thisExpr: JsExpression ): JsExpression { val qualifier: JsExpression fun padArguments(arguments: List<JsExpression>) = arguments + (1..(parameterCount - arguments.size)) .map { Namer.getUndefinedExpression() } when (this) { is JsNew -> { qualifier = Namer.getFunctionCallRef(constructorExpression) // `new A(a, b, c)` -> `A.call($this, a, b, c)` return JsInvocation(JsNameRef("__construct", thisExpr)-{o-> o.kind = PHPNameRefKind.FIELD }, leadingExtraArgs + arguments) // return JsInvocation(qualifier, listOf(thisExpr) + leadingExtraArgs + arguments) } is JsInvocation -> { qualifier = getQualifier() // `A(a, b, c)` -> `A(a, b, c, $this)` return JsInvocation(qualifier, leadingExtraArgs + padArguments(arguments) + thisExpr) } else -> throw IllegalStateException("Unexpected node type: " + javaClass) } } var JsWhile.test: JsExpression get() = condition set(value) { condition = value } var JsArrayAccess.index: JsExpression get() = indexExpression set(value) { indexExpression = value } var JsArrayAccess.array: JsExpression get() = arrayExpression set(value) { arrayExpression = value } var JsConditional.test: JsExpression get() = testExpression set(value) { testExpression = value } var JsConditional.then: JsExpression get() = thenExpression set(value) { thenExpression = value } var JsConditional.otherwise: JsExpression get() = elseExpression set(value) { elseExpression = value }
apache-2.0
1d2875a869c06f8725ed80033f6d9261
29.900901
104
0.667055
4.208589
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/FileHolderComposite.kt
10
2505
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.changes.CompositeFilePathHolder.IgnoredFilesCompositeHolder import com.intellij.openapi.vcs.changes.CompositeFilePathHolder.UnversionedFilesCompositeHolder internal class FileHolderComposite private constructor( private val project: Project, val unversionedFileHolder: UnversionedFilesCompositeHolder = UnversionedFilesCompositeHolder(project), val ignoredFileHolder: IgnoredFilesCompositeHolder = IgnoredFilesCompositeHolder(project), val modifiedWithoutEditingFileHolder: VirtualFileHolder = VirtualFileHolder(project), val lockedFileHolder: VirtualFileHolder = VirtualFileHolder(project), val logicallyLockedFileHolder: LogicallyLockedHolder = LogicallyLockedHolder(project), val rootSwitchFileHolder: SwitchedFileHolder = SwitchedFileHolder(project), val switchedFileHolder: SwitchedFileHolder = SwitchedFileHolder(project), val deletedFileHolder: DeletedFilesHolder = DeletedFilesHolder() ) : FileHolder { private val fileHolders get() = listOf(unversionedFileHolder, ignoredFileHolder, modifiedWithoutEditingFileHolder, lockedFileHolder, logicallyLockedFileHolder, rootSwitchFileHolder, switchedFileHolder, deletedFileHolder) override fun cleanAll() = fileHolders.forEach { it.cleanAll() } override fun cleanAndAdjustScope(scope: VcsModifiableDirtyScope) = fileHolders.forEach { it.cleanAndAdjustScope(scope) } override fun copy(): FileHolderComposite = FileHolderComposite(project, unversionedFileHolder.copy(), ignoredFileHolder.copy(), modifiedWithoutEditingFileHolder.copy(), lockedFileHolder.copy(), logicallyLockedFileHolder.copy(), rootSwitchFileHolder.copy(), switchedFileHolder.copy(), deletedFileHolder.copy()) override fun notifyVcsStarted(vcs: AbstractVcs) = fileHolders.forEach { it.notifyVcsStarted(vcs) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is FileHolderComposite) return false return fileHolders == other.fileHolders } override fun hashCode(): Int = fileHolders.hashCode() companion object { @JvmStatic fun create(project: Project): FileHolderComposite = FileHolderComposite(project) } }
apache-2.0
e62677a16211e80bef15dba11c30d0cf
51.208333
140
0.794012
4.604779
false
false
false
false
smmribeiro/intellij-community
java/java-features-trainer/src/com/intellij/java/ift/JavaLearningCourse.kt
1
6159
// 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.java.ift import com.intellij.java.ift.lesson.assistance.JavaEditorCodingAssistanceLesson import com.intellij.java.ift.lesson.basic.JavaContextActionsLesson import com.intellij.java.ift.lesson.basic.JavaSelectLesson import com.intellij.java.ift.lesson.basic.JavaSurroundAndUnwrapLesson import com.intellij.java.ift.lesson.completion.* import com.intellij.java.ift.lesson.navigation.* import com.intellij.java.ift.lesson.refactorings.JavaExtractMethodCocktailSortLesson import com.intellij.java.ift.lesson.refactorings.JavaRefactoringMenuLesson import com.intellij.java.ift.lesson.refactorings.JavaRenameLesson import com.intellij.java.ift.lesson.run.JavaDebugLesson import com.intellij.java.ift.lesson.run.JavaRunConfigurationLesson import com.intellij.lang.java.JavaLanguage import training.dsl.LessonUtil import training.learn.CourseManager import training.learn.LessonsBundle import training.learn.course.LearningCourseBase import training.learn.course.LearningModule import training.learn.course.LessonType import training.learn.lesson.general.* import training.learn.lesson.general.assistance.CodeFormatLesson import training.learn.lesson.general.assistance.LocalHistoryLesson import training.learn.lesson.general.assistance.ParameterInfoLesson import training.learn.lesson.general.assistance.QuickPopupsLesson import training.learn.lesson.general.navigation.FindInFilesLesson import training.learn.lesson.general.refactorings.ExtractVariableFromBubbleLesson class JavaLearningCourse : LearningCourseBase(JavaLanguage.INSTANCE.id) { override fun modules() = stableModules() + CourseManager.instance.findCommonModules("Git") private fun stableModules() = listOf( LearningModule(id = "Java.Essential", name = LessonsBundle.message("essential.module.name"), description = LessonsBundle.message("essential.module.description", LessonUtil.productName), primaryLanguage = langSupport, moduleType = LessonType.SCRATCH) { fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName") listOf( JavaContextActionsLesson(), GotoActionLesson(ls("00.Actions.java.sample"), firstLesson = false), JavaSearchEverywhereLesson(), JavaBasicCompletionLesson(), ) }, LearningModule(id = "Java.EditorBasics", name = LessonsBundle.message("editor.basics.module.name"), description = LessonsBundle.message("editor.basics.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SCRATCH) { fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName") listOf( JavaSelectLesson(), SingleLineCommentLesson(ls("02.Comment.java.sample")), DuplicateLesson(ls("04.Duplicate.java.sample")), MoveLesson("run()", ls("05.Move.java.sample")), CollapseLesson(ls("06.Collapse.java.sample")), JavaSurroundAndUnwrapLesson(), MultipleSelectionHtmlLesson(), ) }, LearningModule(id = "Java.CodeCompletion", name = LessonsBundle.message("code.completion.module.name"), description = LessonsBundle.message("code.completion.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SCRATCH) { listOf( JavaBasicCompletionLesson(), JavaSmartTypeCompletionLesson(), JavaPostfixCompletionLesson(), JavaStatementCompletionLesson(), JavaCompletionWithTabLesson(), ) }, LearningModule(id = "Java.Refactorings", name = LessonsBundle.message("refactorings.module.name"), description = LessonsBundle.message("refactorings.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SINGLE_EDITOR) { fun ls(sampleName: String) = loadSample("Refactorings/$sampleName") listOf( JavaRenameLesson(), ExtractVariableFromBubbleLesson(ls("ExtractVariable.java.sample")), JavaExtractMethodCocktailSortLesson(), JavaRefactoringMenuLesson(), ) }, LearningModule(id = "Java.CodeAssistance", name = LessonsBundle.message("code.assistance.module.name"), description = LessonsBundle.message("code.assistance.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SINGLE_EDITOR) { fun ls(sampleName: String) = loadSample("CodeAssistance/$sampleName") listOf( LocalHistoryLesson(), CodeFormatLesson(ls("CodeFormat.java.sample"), true), ParameterInfoLesson(ls("ParameterInfo.java.sample")), QuickPopupsLesson(ls("QuickPopups.java.sample")), JavaEditorCodingAssistanceLesson(ls("EditorCodingAssistance.java.sample")), ) }, LearningModule(id = "Java.Navigation", name = LessonsBundle.message("navigation.module.name"), description = LessonsBundle.message("navigation.module.description"), primaryLanguage = langSupport, moduleType = LessonType.PROJECT) { listOf( JavaSearchEverywhereLesson(), FindInFilesLesson("src/warehouse/FindInFilesSample.java"), JavaFileStructureLesson(), JavaDeclarationAndUsagesLesson(), JavaInheritanceHierarchyLesson(), JavaRecentFilesLesson(), JavaOccurrencesLesson(), ) }, LearningModule(id = "Java.RunAndDebug", name = LessonsBundle.message("run.debug.module.name"), description = LessonsBundle.message("run.debug.module.description"), primaryLanguage = langSupport, moduleType = LessonType.SINGLE_EDITOR) { listOf( JavaRunConfigurationLesson(), JavaDebugLesson(), ) }, ) }
apache-2.0
d6f0278537951cd552742b18f599e730
46.751938
140
0.692645
5.153975
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveAnnotationFix.kt
4
2110
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtFile class RemoveAnnotationFix(@Nls private val text: String, annotationEntry: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry) { override fun getText() = text override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.delete() } object JvmOverloads : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("remove.jvmoverloads.annotation"), annotationEntry) } } object JvmField : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("remove.jvmfield.annotation"), annotationEntry) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("fix.remove.annotation.text"), annotationEntry = annotationEntry) } } }
apache-2.0
b14ad0d4d9bb71f43489751c228e7cf5
44.891304
158
0.761611
5.424165
false
false
false
false
android/compose-samples
JetNews/app/src/main/java/com/example/jetnews/ui/home/PostCardTop.kt
1
3793
/* * 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.home import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.jetnews.R import com.example.jetnews.data.posts.impl.posts import com.example.jetnews.model.Post import com.example.jetnews.ui.theme.JetnewsTheme import com.example.jetnews.utils.CompletePreviews @Composable fun PostCardTop(post: Post, modifier: Modifier = Modifier) { // TUTORIAL CONTENT STARTS HERE val typography = MaterialTheme.typography Column( modifier = modifier .fillMaxWidth() .padding(16.dp) ) { val imageModifier = Modifier .heightIn(min = 180.dp) .fillMaxWidth() .clip(shape = MaterialTheme.shapes.medium) Image( painter = painterResource(post.imageId), contentDescription = null, // decorative modifier = imageModifier, contentScale = ContentScale.Crop ) Spacer(Modifier.height(16.dp)) Text( text = post.title, style = typography.titleLarge, modifier = Modifier.padding(bottom = 8.dp) ) Text( text = post.metadata.author.name, style = typography.labelLarge, modifier = Modifier.padding(bottom = 4.dp) ) Text( text = stringResource( id = R.string.home_post_min_read, formatArgs = arrayOf( post.metadata.date, post.metadata.readTimeMinutes ) ), style = typography.bodySmall ) } } // TUTORIAL CONTENT ENDS HERE /** * Preview of the [PostCardTop] composable. Fake data is passed into the composable. * * Learn more about Preview features in the [documentation](https://d.android.com/jetpack/compose/tooling#preview) */ @Preview @Composable fun PostCardTopPreview() { JetnewsTheme { Surface { PostCardTop(posts.highlightedPost) } } } /* * These previews will only show up on Android Studio Dolphin and later. * They showcase a feature called Multipreview Annotations. * * Read more in the [documentation](https://d.android.com/jetpack/compose/tooling#preview-multipreview) */ @CompletePreviews @Composable fun PostCardTopPreviews() { JetnewsTheme { Surface { PostCardTop(posts.highlightedPost) } } }
apache-2.0
834b134b346fa0be8f9b65ae456cdd77
31.418803
114
0.690219
4.334857
false
false
false
false
WillowChat/Kale
src/main/kotlin/chat/willow/kale/core/message/IrcMessage.kt
2
645
package chat.willow.kale.core.message data class IrcMessage(val tags: Map<String, String?> = emptyMap(), val prefix: String? = null, val command: String, val parameters: List<String> = emptyList()) { override fun toString(): String { val pieces = mutableListOf<String>() if (!tags.isEmpty()) { pieces += "tags=$tags" } if (!prefix.isNullOrEmpty()) { pieces += "prefix=$prefix" } pieces += "command=$command" if (!parameters.isEmpty()) { pieces += "parameters=$parameters" } return "IrcMessage(${pieces.joinToString()})" } }
isc
0d477255cce3322e06e311f783a82072
27.086957
161
0.567442
4.51049
false
false
false
false
ifabijanovic/swtor-holonet
android/app/src/main/java/com/ifabijanovic/holonet/forum/data/ForumPostRepository.kt
1
4013
package com.ifabijanovic.holonet.forum.data import com.ifabijanovic.holonet.app.model.Settings import com.ifabijanovic.holonet.forum.language.ForumLanguage import com.ifabijanovic.holonet.forum.model.ForumMaintenanceException import com.ifabijanovic.holonet.forum.model.ForumPost import com.ifabijanovic.holonet.forum.model.ForumThread import com.ifabijanovic.holonet.helper.StringHelper import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import org.jsoup.Jsoup import org.jsoup.nodes.Element /** * Created by Ivan Fabijanovic on 31/03/2017. */ interface ForumPostRepository { fun posts(language: ForumLanguage, thread: ForumThread, page: Int): Observable<List<ForumPost>> } class DefaultForumPostRepository(parser: ForumParser, service: ForumService, settings: Settings) : ForumRepositoryBase(parser, service, settings), ForumPostRepository { override fun posts(language: ForumLanguage, thread: ForumThread, page: Int): Observable<List<ForumPost>> { val localizedService = this.localizedSettings(language) val request: Observable<String> if (thread.isDevTracker) { request = this.service.devTracker(localizedService.pathPrefix, page) } else { request = this.service.thread(localizedService.pathPrefix, thread.id, page) } return request .subscribeOn(Schedulers.io()) .observeOn(Schedulers.computation()) .map { html -> val items = this.parse(html) if (items.isEmpty() && this.isMaintenance(html)) { throw ForumMaintenanceException() } return@map items } } private fun parse(html: String): List<ForumPost> { val items = mutableListOf<ForumPost>() Jsoup.parse(html) .select("#posts table.threadPost") .mapNotNullTo(items) { this.parsePost(it) } return items.toList() } private fun parsePost(element: Element): ForumPost? { // Id val idString = this.parser.linkParameter(element.select(".post .threadDate a")?.first(), this.settings.postQueryParam) var id: Int? try { id = idString?.toInt() } catch (e: Exception) { id = null } // Avatar url var avatarUrl: String? = null val avatarElement = element.select(".avatar img")?.first() if (avatarElement != null) { avatarUrl = avatarElement.attr("src") } // Username val username = element.select(".avatar > .resultCategory > a")?.first()?.text() // Date & Post number val dateElement = element.select(".post .threadDate")?.last() val date = this.parser.postDate(dateElement) val postNumber = this.parser.postNumber(dateElement) // Is Bioware post val imageElements = element.select(".post img.inlineimg") var isBiowarePost = imageElements .mapNotNull { it.attr("src") } .any { it == this.settings.devTrackerIconUrl } // Additional check for Dev Avatar (used on Dev Tracker) if (!isBiowarePost) { isBiowarePost = avatarUrl != null && avatarUrl == this.settings.devAvatarUrl } // Text val text = element.select(".post .forumPadding > .resultText")?.text() // Not parsed for now // Signature val lastPostRow = element.select(".post tr")?.last() val signature = lastPostRow?.select(".resultText")?.text() if (id == null) { return null } if (username == null) { return null } if (date == null) { return null } if (text == null) { return null } val finalUsername = StringHelper(username).stripNewLinesAndTabs().trimSpaces().collapseMultipleSpaces().value return ForumPost(id, avatarUrl, finalUsername, date, postNumber, isBiowarePost, text, signature) } }
gpl-3.0
29133b5170919149230300a430ecfa25
36.504673
168
0.632445
4.46882
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/categories/CategoryRepository.kt
1
3738
package ch.rmy.android.http_shortcuts.data.domains.categories import ch.rmy.android.framework.data.BaseRepository import ch.rmy.android.framework.data.RealmFactory import ch.rmy.android.framework.extensions.swap import ch.rmy.android.framework.utils.UUIDUtils.newUUID import ch.rmy.android.http_shortcuts.data.domains.getBase import ch.rmy.android.http_shortcuts.data.domains.getCategoryById import ch.rmy.android.http_shortcuts.data.enums.CategoryBackgroundType import ch.rmy.android.http_shortcuts.data.enums.CategoryLayoutType import ch.rmy.android.http_shortcuts.data.enums.ShortcutClickBehavior import ch.rmy.android.http_shortcuts.data.models.CategoryModel import io.realm.kotlin.deleteFromRealm import kotlinx.coroutines.flow.Flow import javax.inject.Inject class CategoryRepository @Inject constructor( realmFactory: RealmFactory, ) : BaseRepository(realmFactory) { suspend fun getCategories(): List<CategoryModel> = queryItem { getBase() } .categories fun getObservableCategories(): Flow<List<CategoryModel>> = observeList { getBase().findFirst()!!.categories } suspend fun getCategory(categoryId: CategoryId): CategoryModel = queryItem { getCategoryById(categoryId) } fun getObservableCategory(categoryId: CategoryId): Flow<CategoryModel> = observeItem { getCategoryById(categoryId) } suspend fun createCategory( name: String, layoutType: CategoryLayoutType, background: CategoryBackgroundType, clickBehavior: ShortcutClickBehavior?, ) { commitTransaction { val base = getBase() .findFirst() ?: return@commitTransaction val categories = base.categories val category = CategoryModel( name = name, categoryLayoutType = layoutType, categoryBackgroundType = background, clickBehavior = clickBehavior, ) category.id = newUUID() categories.add(copy(category)) } } suspend fun deleteCategory(categoryId: CategoryId) { commitTransaction { val category = getCategoryById(categoryId) .findFirst() ?: return@commitTransaction for (shortcut in category.shortcuts) { shortcut.headers.deleteAllFromRealm() shortcut.parameters.deleteAllFromRealm() } category.shortcuts.deleteAllFromRealm() category.deleteFromRealm() } } suspend fun updateCategory( categoryId: CategoryId, name: String, layoutType: CategoryLayoutType, background: CategoryBackgroundType, clickBehavior: ShortcutClickBehavior?, ) { commitTransaction { getCategoryById(categoryId) .findFirst() ?.let { category -> category.name = name category.categoryLayoutType = layoutType category.categoryBackgroundType = background category.clickBehavior = clickBehavior } } } suspend fun toggleCategoryHidden(categoryId: CategoryId, hidden: Boolean) { commitTransaction { getCategoryById(categoryId) .findFirst() ?.hidden = hidden } } suspend fun moveCategory(categoryId1: CategoryId, categoryId2: CategoryId) { commitTransaction { getBase().findFirst() ?.categories ?.swap(categoryId1, categoryId2) { id } } } }
mit
5c339bbdd1fe045e93ba6d50821b1a89
31.789474
80
0.627341
5.34
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/viewmodel/BaseViewModel.kt
1
6867
package ch.rmy.android.framework.viewmodel import android.app.Activity import android.app.Application import android.content.Intent import androidx.annotation.StringRes import androidx.annotation.UiThread import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import ch.rmy.android.framework.R import ch.rmy.android.framework.extensions.logException import ch.rmy.android.framework.extensions.runFor import ch.rmy.android.framework.ui.IntentBuilder import ch.rmy.android.framework.utils.localization.Localizable import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicInteger abstract class BaseViewModel<InitData : Any, ViewState : Any>(application: Application) : AndroidViewModel(application) { protected lateinit var initData: InitData private set private val eventChannel = Channel<ViewModelEvent>( capacity = Channel.UNLIMITED, ) val events: Flow<ViewModelEvent> = eventChannel.receiveAsFlow() private val mutableViewState = MutableStateFlow<ViewState?>(null) val viewState: Flow<ViewState> = mutableViewState.asStateFlow().filterNotNull() val latestViewState: ViewState? get() = mutableViewState.value protected var currentViewState: ViewState? = null private set private val inProgress = AtomicInteger() private var nothingInProgress: CompletableDeferred<Unit>? = null protected fun emitEvent(event: ViewModelEvent) { eventChannel.trySend(event) } private var suppressViewStatePublishing = false private val delayedViewStateUpdates = mutableListOf<ViewState.() -> ViewState>() private val delayedViewStateActions = mutableListOf<(ViewState) -> Unit>() @UiThread protected fun doWithViewState(action: (ViewState) -> Unit) { if (currentViewState != null) { action(currentViewState!!) } else { delayedViewStateActions.add(action) } } @UiThread protected fun updateViewState(mutation: ViewState.() -> ViewState) { if (currentViewState == null) { delayedViewStateUpdates.add(mutation) return } currentViewState = mutation(currentViewState!!) if (!suppressViewStatePublishing) { mutableViewState.value = currentViewState!! } } @UiThread protected fun emitCurrentViewState() { currentViewState ?.takeUnless { suppressViewStatePublishing } ?.let { mutableViewState.value = it } } @UiThread protected fun atomicallyUpdateViewState(action: () -> Unit) { if (suppressViewStatePublishing) { action() return } suppressViewStatePublishing = true action() suppressViewStatePublishing = false if (currentViewState != null) { mutableViewState.value = currentViewState!! } } private var isInitializationStarted = false protected var isInitialized: Boolean = false private set fun initialize(data: InitData) { if (isInitializationStarted) { if (data != initData) { logException(IllegalStateException("cannot re-initialize view model with different data")) } return } this.initData = data isInitializationStarted = true onInitializationStarted(data) } /** * Must eventually call finalizeInitialization or terminate the view */ protected open fun onInitializationStarted(data: InitData) { finalizeInitialization() } protected fun finalizeInitialization(silent: Boolean = false) { if (isInitialized) { error("view model already initialized") } val publishViewState = delayedViewStateUpdates.isNotEmpty() || !silent currentViewState = initViewState() .runFor(delayedViewStateUpdates) { it() } delayedViewStateUpdates.clear() if (publishViewState) { mutableViewState.value = currentViewState!! } isInitialized = true onInitialized() delayedViewStateActions.forEach { it(currentViewState!!) } delayedViewStateActions.clear() } protected open fun onInitialized() { } protected abstract fun initViewState(): ViewState protected fun launchWithProgressTracking(operation: suspend () -> Unit) = viewModelScope.launch { operation() } protected suspend fun withProgressTracking(operation: suspend () -> Unit) { if (inProgress.incrementAndGet() == 1) { nothingInProgress = CompletableDeferred() } try { operation() } finally { if (inProgress.decrementAndGet() == 0) { nothingInProgress?.complete(Unit) nothingInProgress = null } } } protected fun handleUnexpectedError(error: Throwable) { logException(error) showSnackbar(R.string.error_generic, long = true) } protected suspend fun waitForOperationsToFinish() { nothingInProgress?.await() } protected fun showSnackbar(@StringRes stringRes: Int, long: Boolean = false) { emitEvent(ViewModelEvent.ShowSnackbar(stringRes, long = long)) } protected fun showSnackbar(message: Localizable, long: Boolean = false) { emitEvent(ViewModelEvent.ShowSnackbar(message, long = long)) } protected fun showToast(@StringRes stringRes: Int, long: Boolean = false) { emitEvent(ViewModelEvent.ShowToast(stringRes, long = long)) } protected open fun finish(result: Int? = null, intent: Intent? = null, skipAnimation: Boolean = false) { emitEvent(ViewModelEvent.Finish(result, intent, skipAnimation)) } protected fun finishWithOkResult(intent: Intent? = null) { finish( result = Activity.RESULT_OK, intent = intent, ) } protected fun setResult(result: Int = Activity.RESULT_CANCELED, intent: Intent? = null) { emitEvent(ViewModelEvent.SetResult(result, intent)) } protected fun openURL(url: String) { emitEvent(ViewModelEvent.OpenURL(url)) } protected fun openActivity(intentBuilder: IntentBuilder) { emitEvent(ViewModelEvent.OpenActivity(intentBuilder)) } protected fun sendBroadcast(intent: Intent) { emitEvent(ViewModelEvent.SendBroadcast(intent)) } }
mit
259e2470b127db9a17cbaea4b35f199c
30.791667
121
0.670307
5.167043
false
false
false
false
dodyg/Kotlin101
src/Objects/DataClass/DataClass.kt
1
1442
package Objects.DataClass /* This sample demonstrates various features that you get from using a data class */ public data class Superhero(val firstName : String, val lastName : String) fun main(args : Array<String>) { var superman = Superhero("clark", "kent") //Automatic toString generation println("Superman is ${superman.toString()}") //Automatic hashCode println("Superman hashcode is ${superman.hashCode()}") var supermanAlias = Superhero("clark", "kent") //Auto generated equals var areTheyEqual = superman.equals(supermanAlias) println("Is superman equals supermanAlias? $areTheyEqual") //component methods are generated val isFirstName = superman.firstName.equals(superman.component1()) println("is .firstName equal to .component1? $isFirstName ") var isLastName = superman.lastName.equals(superman.component2()) println("is .lastName equals to .component2? $isLastName") //multi declarations val hero = { x : Superhero -> x } val(firstName, lastName ) = hero(superman) println("Our superhero name is $firstName $lastName") //another sample of multi declarations fun supercharge(x : Superhero) : Superhero { var m = Superhero(x.firstName.toUpperCase(), x.lastName.toUpperCase()) return m } val(firstName2, lastName2) = supercharge(superman) println("Our supercharged superhero name is $firstName2 $lastName2") }
bsd-3-clause
c65d892c523fa148ae42cade431d8b76
32.55814
84
0.706657
4.143678
false
false
false
false
liujoshua/BridgeAndroidSDK
sageresearch-app-sdk/src/main/java/org/sagebionetworks/research/sageresearch/viewmodel/ResearchStackUploadArchiveFactory.kt
1
8098
/* * BSD 3-Clause License * * Copyright 2018 Sage Bionetworks. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder(s) nor the names of any contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. No license is granted to the trademarks of * the copyright holders even if such marks are included in this software. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sagebionetworks.research.sageresearch.viewmodel import android.os.Build import com.google.common.collect.ImmutableList import org.joda.time.DateTime import org.researchstack.backbone.result.Result import org.sagebionetworks.bridge.android.BridgeConfig import org.sagebionetworks.bridge.android.manager.upload.ArchiveUtil import org.sagebionetworks.bridge.data.Archive import org.sagebionetworks.bridge.data.JsonArchiveFile import org.sagebionetworks.bridge.researchstack.TaskHelper import org.sagebionetworks.bridge.researchstack.factory.ArchiveFileFactory import org.sagebionetworks.bridge.rest.RestUtils import org.sagebionetworks.research.sageresearch.dao.room.ScheduledActivityEntity import org.sagebionetworks.research.sageresearch.dao.room.bridgeMetadataCopy import org.slf4j.LoggerFactory import java.util.UUID /** * The ResearchStackUploadArchiveFactory controls upload archive creation and allows for * easy sub-classing to change the functionality of the factory. */ open class ResearchStackUploadArchiveFactory: ArchiveFileFactory() { private val logger = LoggerFactory.getLogger(ResearchStackUploadArchiveFactory::class.java) /** * @param schedule of the task completed, if null, no metadata json file will be included * @param bridgeConfig to be used for accessing schema information for the schedule * @param userDataGroups the current data groups of the user * @param taskResult result of running the research stack task * @return a pair where first is the archive filename, and the second is the archive builder */ open fun buildResearchStackArchive( schedule: ScheduledActivityEntity?, bridgeConfig: BridgeConfig, userDataGroups: ImmutableList<String>, userExternalId: String?, taskResult: org.researchstack.backbone.result.TaskResult): Pair<String, Archive.Builder>? { // ResearchStack tasks don't use a UUID, so just assign a random one for naming conventions val rsTaskUuid = UUID.randomUUID() var taskId = taskResult.identifier var archiveFilename = taskId + rsTaskUuid // If the schedule is a survey, we should create the survey archive builder val builder: Archive.Builder = schedule?.activity?.survey?.let { val surveyGuid = it.guid var surveyCreatedOn = DateTime.now() it.createdOn?.toEpochMilli()?.let { epochMillis -> surveyCreatedOn = DateTime(epochMillis) } ?: run { logger.warn("No survey createdOn date was found for the schedule, using today's date") } // task is actually a survey, so use a survey archive builder Archive.Builder.forSurvey(surveyGuid, surveyCreatedOn) } ?: run { // First check the task result for the proper task identifier, because that is historically where it is // If that isn't available for whatever reason, let's assume the schedule has the correct task identifier if (bridgeConfig.taskToSchemaMap[taskId] == null) { taskId = schedule?.activityIdentifier() } val schemaKey = bridgeConfig.taskToSchemaMap[taskId] ?: run { logger.error("No schema key found for task with identifier ${taskId}, skipping upload.") return null } archiveFilename = schemaKey.id + schemaKey.revision + rsTaskUuid Archive.Builder.forActivity(schemaKey.id, schemaKey.revision) } val appVersion = "version ${bridgeConfig.appVersionName}, build ${bridgeConfig.appVersion}" builder.withAppVersionName(appVersion).withPhoneInfo(bridgeConfig.deviceName) schedule?.let { builder.addDataFile(createMetaDataFile(it, userDataGroups, userExternalId)) } ?: run { logger.warn("Failed to create metadata json file for S3 upload") } // Loop through the results and add the result files to the archive val flattenedResultList = TaskHelper.flattenResults(taskResult) addFiles(builder, flattenedResultList, taskId) return Pair(archiveFilename, builder) } /** * Creates a metadata file archive for upload to bridge * @param scheduledActivityEntity associated with the upload * @param dataGroups a list of the users' data groups * @param externalId if the user signed in with externalId this should be non-null, null otherwise */ protected open fun createMetaDataFile( scheduledActivityEntity: ScheduledActivityEntity, dataGroups: ImmutableList<String>, externalId: String?): JsonArchiveFile { val scheduledActivity = scheduledActivityEntity.bridgeMetadataCopy() val metaDataMap = ArchiveUtil.createMetaDataInfoMap(scheduledActivity, dataGroups, externalId) // Here we can add some of our own additional metadata to the uplaod scheduledActivity.activity?.survey?.identifier?.let { // Add survey identifier as taskIdentifier even though it's a survey // (base implementation doesn't do this) metaDataMap["taskIdentifier"] = it } metaDataMap["deviceTypeIdentifier"] = "${Build.PRODUCT} ${Build.MODEL} OS v${android.os.Build.VERSION.SDK_INT}" // Grab the end date val endDate = scheduledActivity.finishedOn ?: DateTime.now() val metaDataJson = RestUtils.GSON.toJson(metaDataMap) return JsonArchiveFile("metadata.json", endDate, metaDataJson) } /** * Can be overridden by sub-class for custom data archiving * @param archiveBuilder fill this builder up with files from the flattenedResultList * @param flattenedResultList read these and add them to the archiveBuilder * @param taskIdentifier of the task result that contained these flattened results */ protected open fun addFiles( archiveBuilder: Archive.Builder, flattenedResultList: List<Result>?, taskIdentifier: String) { flattenedResultList?.forEach { result -> fromResult(result)?.let { archiveBuilder.addDataFile(it) } ?: run { logger.error("Failed to convert Result to BridgeDataInput " + result.toString()) } } } }
apache-2.0
e93386b1924bae6bf9dbbc25dc8f07e8
47.208333
117
0.712892
4.803084
false
true
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/wallet/TransactionListItem.kt
1
9861
package com.breadwallet.ui.wallet import android.graphics.Paint import android.os.Build import android.text.format.DateUtils import android.view.View import androidx.core.content.ContextCompat import androidx.core.view.isVisible import com.breadwallet.R import com.breadwallet.breadbox.formatCryptoForUi import com.breadwallet.databinding.TxItemBinding import com.breadwallet.ui.formatFiatForUi import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.util.BRDateUtil import com.breadwallet.tools.util.Utils import com.breadwallet.util.isBitcoinLike import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.items.ModelAbstractItem private const val DP_120 = 120 private const val PROGRESS_FULL = 100 class TransactionListItem( transaction: WalletTransaction, var isCryptoPreferred: Boolean ) : ModelAbstractItem<WalletTransaction, TransactionListItem.ViewHolder>(transaction) { override val layoutRes: Int = R.layout.tx_item override val type: Int = R.id.transaction_item override var identifier: Long = model.txHash.hashCode().toLong() override fun getViewHolder(v: View) = ViewHolder(v) inner class ViewHolder( v: View ) : FastAdapter.ViewHolder<TransactionListItem>(v) { var binding: TxItemBinding? = null override fun bindView(item: TransactionListItem, payloads: List<Any>) { binding = TxItemBinding.bind(itemView) setTexts(binding!!, item.model, item.isCryptoPreferred) } override fun unbindView(item: TransactionListItem) { with(binding ?: return) { txAmount.text = null txDate.text = null txDescriptionValue.text = null txDescriptionLabel.text = null } binding = null } @Suppress("LongMethod", "ComplexMethod") private fun setTexts( binding: TxItemBinding, transaction: WalletTransaction, isCryptoPreferred: Boolean ) { val context = itemView.context val commentString = transaction.memo val received = transaction.isReceived binding.imageTransferDirection.setBackgroundResource( when { transaction.progress < PROGRESS_FULL -> R.drawable.transfer_in_progress transaction.isErrored -> R.drawable.transfer_failed transaction.gift != null -> when { transaction.gift.claimed -> R.drawable.transfer_gift_claimed transaction.gift.reclaimed -> R.drawable.transfer_gift_reclaimed else -> R.drawable.transfer_gift_unclaimed } received -> R.drawable.transfer_receive else -> R.drawable.transfer_send } ) binding.txAmount.setTextColor( context.getColor( when { received -> R.color.transaction_amount_received_color else -> R.color.total_assets_usd_color } ) ) val preferredCurrencyCode = when { isCryptoPreferred -> transaction.currencyCode else -> BRSharedPrefs.getPreferredFiatIso() } val amount = when { isCryptoPreferred -> transaction.amount else -> transaction.amountInFiat }.run { if (received) this else negate() } val formattedAmount = when { isCryptoPreferred -> amount.formatCryptoForUi(preferredCurrencyCode) else -> amount.formatFiatForUi(preferredCurrencyCode) } binding.txAmount.text = formattedAmount when { !transaction.gift?.recipientName.isNullOrBlank() -> { binding.txDescriptionLabel.text = context.getString(R.string.Transaction_toRecipient, "") binding.txDescriptionValue.text = transaction.gift?.recipientName } transaction.isStaking -> { binding.txDescriptionLabel.text = context.getString(R.string.Transaction_stakingTo, "") binding.txDescriptionValue.text = transaction.toAddress } commentString == null -> { binding.txDescriptionLabel.text = "" binding.txDescriptionValue.text = "" } commentString.isNotEmpty() -> { binding.txDescriptionLabel.text = "" binding.txDescriptionValue.text = commentString } transaction.isFeeForToken -> { binding.txDescriptionLabel.text = context.getString(R.string.Transaction_tokenTransfer, transaction.feeToken) binding.txDescriptionValue.text = commentString } received -> { if (transaction.isComplete) { if (transaction.currencyCode.isBitcoinLike()) { binding.txDescriptionLabel.text = context.getString(R.string.TransactionDetails_receivedVia, "") binding.txDescriptionValue.text = transaction.toAddress } else { binding.txDescriptionLabel.text = context.getString(R.string.TransactionDetails_receivedFrom, "") binding.txDescriptionValue.text = transaction.fromAddress } } else { if (transaction.currencyCode.isBitcoinLike()) { binding.txDescriptionLabel.text = context.getString(R.string.TransactionDetails_receivingVia, "") binding.txDescriptionValue.text = transaction.toAddress } else { binding.txDescriptionLabel.text = context.getString(R.string.TransactionDetails_receivingFrom, "") binding.txDescriptionValue.text = transaction.fromAddress } } } else -> if (transaction.isComplete) { binding.txDescriptionLabel.text = context.getString(R.string.Transaction_sentTo, "") binding.txDescriptionValue.text = transaction.toAddress } else { binding.txDescriptionLabel.text = context.getString(R.string.Transaction_sendingTo, "") binding.txDescriptionValue.text = transaction.toAddress } } val timeStamp = transaction.timeStamp binding.txDate.text = when { timeStamp == 0L || transaction.isPending -> buildString { append(transaction.confirmations) append('/') append(transaction.confirmationsUntilFinal) append(' ') append(context.getString(R.string.TransactionDetails_confirmationsLabel)) } DateUtils.isToday(timeStamp) -> BRDateUtil.getTime(timeStamp) else -> BRDateUtil.getShortDate(timeStamp) } // If this transaction failed, show the "FAILED" indicator in the cell if (transaction.isErrored) { showTransactionFailed() } else { showTransactionProgress(transaction.progress) } } private fun showTransactionProgress(progress: Int) { val context = itemView.context with(binding!!) { txDate.isVisible = true txAmount.isVisible = true imageTransferDirection.isVisible = true val textColor = context.getColor(R.color.total_assets_usd_color) txDate.setTextColor(textColor) txAmount.paintFlags = 0 // clear strike-through if (progress < PROGRESS_FULL) { if (imageTransferDirection.progressDrawable == null) { imageTransferDirection.progressDrawable = ContextCompat.getDrawable( context, R.drawable.transfer_progress_drawable ) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { imageTransferDirection.setProgress(progress, true) } else { imageTransferDirection.progress = progress } txDescriptionValue.maxWidth = Utils.getPixelsFromDps(context, DP_120) } else { imageTransferDirection.progressDrawable = null imageTransferDirection.progress = 0 } } } private fun showTransactionFailed() { val context = itemView.context with(binding!!) { imageTransferDirection.progressDrawable = null val errorColor = context.getColor(R.color.ui_error) txDate.setText(R.string.Transaction_failed) txDate.setTextColor(errorColor) txAmount.setTextColor(errorColor) txAmount.paintFlags = txAmount.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG } } } }
mit
31fd43bf51830a6053eea9b50c6ab177
41.50431
99
0.552378
5.647766
false
false
false
false
quran/quran_android
common/audio/src/test/java/com/quran/labs/androidquran/common/audio/cache/command/GappedAudioInfoCommandTest.kt
2
3006
package com.quran.labs.androidquran.common.audio.cache.command import com.google.common.truth.Truth import com.quran.data.core.QuranInfo import com.quran.data.pageinfo.common.MadaniDataSource import com.quran.labs.androidquran.common.audio.model.PartiallyDownloadedSura import okio.Path.Companion.toPath import okio.fakefilesystem.FakeFileSystem import org.junit.Test class GappedAudioInfoCommandTest { @Test fun testGappedAudio() { val qariPath = "/quran/audio/minshawi".toPath() val filesystem = FakeFileSystem() filesystem.createDirectories(qariPath) filesystem.createDirectories(qariPath / "103") filesystem.write(qariPath / "103" / "1.mp3") { } filesystem.write(qariPath / "103" / "2.mp3") { } filesystem.write(qariPath / "103" / "3.mp3") { } val quranInfo = QuranInfo(MadaniDataSource()) val gaplessAudioInfoCommand = GappedAudioInfoCommand(quranInfo, filesystem) val downloads = gaplessAudioInfoCommand.gappedDownloads(qariPath) Truth.assertThat(downloads.first).hasSize(1) Truth.assertThat(downloads.second).isEmpty() Truth.assertThat(downloads.first).containsExactly(103) } @Test fun testGappedAudioWithPartials() { val qariPath = "/quran/audio/minshawi".toPath() val filesystem = FakeFileSystem() filesystem.createDirectories(qariPath) filesystem.createDirectories(qariPath / "103") filesystem.createDirectories(qariPath / "114") filesystem.write(qariPath / "103" / "1.mp3") { } filesystem.write(qariPath / "103" / "2.mp3") { } filesystem.write(qariPath / "103" / "3.mp3") { } filesystem.write(qariPath / "114" / "1.mp3") { } val quranInfo = QuranInfo(MadaniDataSource()) val gappedAudioInfoCommand = GappedAudioInfoCommand(quranInfo, filesystem) val downloads = gappedAudioInfoCommand.gappedDownloads(qariPath) Truth.assertThat(downloads.first).hasSize(1) Truth.assertThat(downloads.second).hasSize(1) Truth.assertThat(downloads.first).containsExactly(103) Truth.assertThat(downloads.second).hasSize(1) Truth.assertThat(downloads.second.first()).isEqualTo( PartiallyDownloadedSura(114, 6, listOf(1)) ) } @Test fun testGappedAudioWithIllegalFilenames() { val qariPath = "/quran/audio/minshawi".toPath() val filesystem = FakeFileSystem() filesystem.createDirectories(qariPath) filesystem.createDirectories(qariPath / "114") filesystem.createDirectories(qariPath / "115") filesystem.write(qariPath / "test.mp3") { } filesystem.write(qariPath / "2.mp3") { } filesystem.write(qariPath / "115.mp3") { } filesystem.write(qariPath / "114" / "1.mp3.part") { } filesystem.write(qariPath / "115" / "1.mp3") { } val quranInfo = QuranInfo(MadaniDataSource()) val gappedAudioInfoCommand = GappedAudioInfoCommand(quranInfo, filesystem) val downloads = gappedAudioInfoCommand.gappedDownloads(qariPath) Truth.assertThat(downloads.first).isEmpty() Truth.assertThat(downloads.second).isEmpty() } }
gpl-3.0
1611c60758b60153ca74b80843a2fc30
39.621622
79
0.732535
3.724907
false
true
false
false
porokoro/paperboy
paperboy/src/main/kotlin/com/github/porokoro/paperboy/PaperboyConfiguration.kt
1
1032
/* * Copyright (C) 2015-2016 Dominik Hibbeln * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.porokoro.paperboy import android.util.SparseArray internal data class PaperboyConfiguration( var file: String? = "", var fileRes: Int = 0, var viewType: Int = ViewTypes.NONE, var sectionLayout: Int = 0, var typeLayout: Int = 0, var itemLayout: Int = 0, var sortItems: Boolean = false, var itemTypes: SparseArray<ItemType> = SparseArray())
apache-2.0
6ca085e5af873775f568d4a47a02e626
35.857143
75
0.697674
4.079051
false
false
false
false
pie-flavor/Kludge
src/main/kotlin/flavor/pie/kludge/items.kt
1
6049
package flavor.pie.kludge import org.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.block.BlockState import org.spongepowered.api.block.BlockType import org.spongepowered.api.data.key.Keys import org.spongepowered.api.item.ItemType import org.spongepowered.api.item.inventory.ItemStack import org.spongepowered.api.text.Text import org.spongepowered.api.world.Location /** * Creates a new [ItemStack] with quantity 1 and this item type. * @see ItemStack.of */ fun ItemType.toStack(): ItemStack = ItemStack.of(this, 1) /** * Creates a new [ItemStack] with this item type. * @see itemStackOf * @see ItemStack.Builder.itemType */ inline fun ItemType.toStack(fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().itemType(this).apply(fn).build() /** * Creates a new [ItemStack] with this item type and quantity [quantity]. * @see ItemStack.of */ fun ItemType.toStack(quantity: Int): ItemStack = ItemStack.of(this, quantity) /** * Creates a new [ItemStack] with this item type and quantity [quantity]. * @see itemStackOf * @see ItemStack.Builder.itemType * @see ItemStack.Builder.quantity */ inline fun ItemType.toStack(quantity: Int, fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().itemType(this).quantity(quantity).apply(fn).build() /** * Creates a new [ItemStack] from this block type with quantity 1. * @see BlockType.getItem * @see ItemStack.of */ fun BlockType.toStack(): ItemStack? = item.unwrap()?.let { ItemStack.of(it, 1) } /** * Creates a new [ItemStack] from this block type. * @see BlockType.getItem * @see itemStackOf * @see ItemStack.Builder.itemType */ inline fun BlockType.toStack(fn: ItemStack.Builder.() -> Unit): ItemStack? = item.unwrap()?.let { ItemStack.builder().itemType(it).apply(fn).build() } /** * Creates a new [ItemStack] from this block type with quantity [quantity]. * @see BlockType.getItem * @see ItemStack.of */ fun BlockType.toStack(quantity: Int): ItemStack? = item.unwrap()?.let { ItemStack.of(it, quantity) } /** * Creates a new [ItemStack] from this block type with quantity [quantity]. * @see BlockType.getItem * @see itemStackOf * @see ItemStack.Builder.itemType * @see ItemStack.Builder.quantity */ inline fun BlockType.toStack(quantity: Int, fn: ItemStack.Builder.() -> Unit): ItemStack? = item.unwrap()?.let { ItemStack.builder().itemType(it).quantity(quantity).apply(fn).build() } /** * Creates a new [ItemStack] from this block state. * @see ItemStack.Builder.fromBlockState */ fun BlockState.toStack(): ItemStack = ItemStack.builder().fromBlockState(this).build() /** * Creates a new [ItemStack] from this block state. * @see itemStackOf * @see ItemStack.Builder.fromBlockState */ inline fun BlockState.toStack(fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().fromBlockState(this).apply(fn).build() /** * Creates a new [ItemStack] from this block state and quantity [quantity]. * @see ItemStack.Builder.quantity * @see ItemStack.Builder.fromBlockState */ fun BlockState.toStack(quantity: Int): ItemStack = ItemStack.builder().fromBlockState(this).quantity(quantity).build() /** * Creates a new [ItemStack] from this block state and quantity [quantity]. * @see itemStackOf * @see ItemStack.Builder.quantity * @see ItemStack.Builder.fromBlockState */ inline fun BlockState.toStack(quantity: Int, fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().fromBlockState(this).quantity(quantity).apply(fn).build() /** * Creates a new [ItemStack] from this block snapshot. * @see ItemStack.Builder.fromBlockSnapshot */ fun BlockSnapshot.toStack(): ItemStack = ItemStack.builder().fromBlockSnapshot(this).build() /** * Creates a new [ItemStack] from this block snapshot. * @see itemStackOf * @see ItemStack.Builder.fromBlockSnapshot */ inline fun BlockSnapshot.toStack(fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().fromBlockSnapshot(this).apply(fn).build() /** * Creates a new [ItemStack] from this block snapshot with quantity [quantity]. * @see ItemStack.Builder.fromBlockSnapshot * @see ItemStack.Builder.quantity */ fun BlockSnapshot.toStack(quantity: Int): ItemStack = ItemStack.builder().fromBlockSnapshot(this).quantity(quantity).build() /** * Creates a new [ItemStack] from this block snapshot with quantity [quantity]. * @see ItemStack.Builder.fromBlockSnapshot * @see ItemStack.Builder.quantity * @see itemStackOf */ inline fun BlockSnapshot.toStack(quantity: Int, fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().fromBlockSnapshot(this).quantity(quantity).apply(fn).build() /** * Creates a new [ItemStack] from the block at this [Location]. * @see Location.createSnapshot * @see BlockSnapshot.toStack */ fun Location<*>.toStack(): ItemStack = createSnapshot().toStack() /** * Creates a new [ItemStack] from the block at this [Location]. * @see Location.createSnapshot * @see BlockSnapshot.toStack */ inline fun Location<*>.toStack(fn: ItemStack.Builder.() -> Unit): ItemStack = createSnapshot().toStack(fn) /** * Creates a new [ItemStack] from the block at this [Location] with quantity * [quantity]. * @see Location.createSnapshot * @see BlockSnapshot.toStack */ fun Location<*>.toStack(quantity: Int): ItemStack = createSnapshot().toStack(quantity) /** * Creates a new [ItemStack] from the block at this [Location] with quantity * [quantity]. * @see Location.createSnapshot * @see BlockSnapshot.toStack */ inline fun Location<*>.toStack(quantity: Int, fn: ItemStack.Builder.() -> Unit): ItemStack = createSnapshot().toStack(quantity, fn) /** * Shorthand for assigning [Keys.DISPLAY_NAME]. * @see ItemStack.Builder.add */ fun ItemStack.Builder.displayName(name: Text): ItemStack.Builder = add(Keys.DISPLAY_NAME, name) /** * Shorthand for assigning [Keys.ITEM_LORE]. * @see ItemStack.Builder.add */ fun ItemStack.Builder.lore(lore: List<Text>): ItemStack.Builder = add(Keys.ITEM_LORE, lore)
mit
2b72c2c0364c74fdf5a7be527bc057c9
33.375
118
0.724913
3.778264
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/tut11/blinnVsPhongLighting.kt
2
12922
package glNext.tut11 import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.MouseEvent import com.jogamp.opengl.GL2ES3.* import com.jogamp.opengl.GL3 import glNext.* import glm.f import glm.glm import glm.vec._3.Vec3 import glm.vec._4.Vec4 import glm.quat.Quat import glm.mat.Mat4 import main.framework.Framework import main.framework.Semantic import main.framework.component.Mesh import glNext.tut11.BlinnVsPhongLighting_Next.LightingModel.BlinnSpecular import glNext.tut11.BlinnVsPhongLighting_Next.LightingModel.PhongOnly import glNext.tut11.BlinnVsPhongLighting_Next.LightingModel.PhongSpecular import uno.buffer.destroy import uno.buffer.intBufferBig import uno.glm.MatrixStack import uno.glsl.programOf import uno.mousePole.* import uno.time.Timer /** * Created by GBarbieri on 24.03.2017. */ fun main(args: Array<String>) { BlinnVsPhongLighting_Next().setup("Tutorial 11 - Blinn vs Phong Lighting") } class BlinnVsPhongLighting_Next : Framework() { lateinit var programs: Array<ProgramPairs> lateinit var unlit: UnlitProgData val initialViewData = ViewData( Vec3(0.0f, 0.5f, 0.0f), Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f), 5.0f, 0.0f) val viewScale = ViewScale( 3.0f, 20.0f, 1.5f, 0.5f, 0.0f, 0.0f, //No camera movement. 90.0f / 250.0f) val initialObjectData = ObjectData( Vec3(0.0f, 0.5f, 0.0f), Quat(1.0f, 0.0f, 0.0f, 0.0f)) val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1) val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole) lateinit var cylinder: Mesh lateinit var plane: Mesh lateinit var cube: Mesh var lightModel = BlinnSpecular var drawColoredCyl = false var drawLightSource = false var scaleCyl = false var drawDark = false var lightHeight = 1.5f var lightRadius = 1.0f val lightAttenuation = 1.2f val darkColor = Vec4(0.2f, 0.2f, 0.2f, 1.0f) val lightColor = Vec4(1.0f) val lightTimer = Timer(Timer.Type.Loop, 5.0f) val projectionUniformBuffer = intBufferBig(1) override fun init(gl: GL3) = with(gl) { initializePrograms(gl) cylinder = Mesh(gl, javaClass, "tut11/UnitCylinder.xml") plane = Mesh(gl, javaClass, "tut11/LargePlane.xml") cube = Mesh(gl, javaClass, "tut11/UnitCube.xml") val depthZNear = 0.0f val depthZFar = 1.0f cullFace { enable() cullFace = back frontFace = cw } depth { test = true mask = true func = lEqual rangef = depthZNear .. depthZFar clamp = true } initUniformBuffer(projectionUniformBuffer) { data(Mat4.SIZE, GL_DYNAMIC_DRAW) //Bind the static buffers. range(Semantic.Uniform.PROJECTION, 0, Mat4.SIZE) } } fun initializePrograms(gl: GL3) { val FRAGMENTS = arrayOf("phong-lighting", "phong-only", "blinn-lighting", "blinn-only") programs = Array(LightingModel.MAX, { ProgramPairs(ProgramData(gl, "pn.vert", "${FRAGMENTS[it]}.frag"), ProgramData(gl, "pcn.vert", "${FRAGMENTS[it]}.frag")) }) unlit = UnlitProgData(gl, "pos-transform.vert", "uniform-color.frag") } override fun display(gl: GL3) = with(gl) { lightTimer.update() clear { color(0) depth() } val modelMatrix = MatrixStack() modelMatrix.setMatrix(viewPole.calcMatrix()) val worldLightPos = calcLightPosition() val lightPosCameraSpace = modelMatrix.top() * worldLightPos val whiteProg = programs[lightModel].whiteProgram val colorProg = programs[lightModel].colorProgram usingProgram(whiteProg.theProgram) { glUniform4f(whiteProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f) glUniform4f(whiteProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f) glUniform3f(whiteProg.cameraSpaceLightPosUnif, lightPosCameraSpace) glUniform1f(whiteProg.lightAttenuationUnif, lightAttenuation) glUniform1f(whiteProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel)) glUniform4f(whiteProg.baseDiffuseColorUnif, if (drawDark) darkColor else lightColor) name = colorProg.theProgram glUniform4f(colorProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f) glUniform4f(colorProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f) glUniform3f(colorProg.cameraSpaceLightPosUnif, lightPosCameraSpace) glUniform1f(colorProg.lightAttenuationUnif, lightAttenuation) glUniform1f(colorProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel)) } modelMatrix run { //Render the ground plane. run { val normMatrix = top().toMat3() normMatrix.inverse_().transpose_() usingProgram(whiteProg.theProgram) { whiteProg.modelToCameraMatrixUnif.mat4 = top() glUniformMatrix3f(whiteProg.normalModelToCameraMatrixUnif, normMatrix) plane.render(gl) } } //Render the Cylinder run { applyMatrix(objectPole.calcMatrix()) if (scaleCyl) scale(1.0f, 1.0f, 0.2f) val normMatrix = top().toMat3() normMatrix.inverse_().transpose_() val prog = if (drawColoredCyl) colorProg else whiteProg usingProgram(prog.theProgram) { prog.modelToCameraMatrixUnif.mat4 = top() glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix) cylinder.render(gl, if (drawColoredCyl) "lit-color" else "lit") } } //Render the light if (drawLightSource) run { translate(worldLightPos) scale(0.1f) usingProgram(unlit.theProgram) { unlit.modelToCameraMatrixUnif.mat4 = top() glUniform4f(unlit.objectColorUnif, 0.8078f, 0.8706f, 0.9922f, 1.0f) cube.render(gl, "flat") } } } } fun calcLightPosition(): Vec4 { val currentTimeThroughLoop = lightTimer.getAlpha() val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f) ret.x = glm.cos(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius ret.z = glm.sin(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius return ret } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { val zNear = 1.0f val zFar = 1_000f val perspMatrix = MatrixStack() val proj = perspMatrix.perspective(45.0f, w.f / h, zNear, zFar).top() withUniformBuffer(projectionUniformBuffer) { subData(proj) } glViewport(w, h) } override fun mousePressed(e: MouseEvent) { viewPole.mousePressed(e) objectPole.mousePressed(e) } override fun mouseDragged(e: MouseEvent) { viewPole.mouseDragged(e) objectPole.mouseDragged(e) } override fun mouseReleased(e: MouseEvent) { viewPole.mouseReleased(e) objectPole.mouseReleased(e) } override fun mouseWheelMoved(e: MouseEvent) { viewPole.mouseWheel(e) } override fun keyPressed(e: KeyEvent) { var changedShininess = false when (e.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl KeyEvent.VK_I -> lightHeight += if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_K -> lightHeight -= if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_L -> lightRadius += if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_J -> lightRadius -= if (e.isShiftDown) 0.05f else 0.2f KeyEvent.VK_O -> { MaterialParameters.increment(lightModel, !e.isShiftDown) changedShininess = true } KeyEvent.VK_U -> { MaterialParameters.decrement(lightModel, !e.isShiftDown) changedShininess = true } KeyEvent.VK_Y -> drawLightSource = !drawLightSource KeyEvent.VK_T -> scaleCyl = !scaleCyl KeyEvent.VK_B -> lightTimer.togglePause() KeyEvent.VK_G -> drawDark = !drawDark KeyEvent.VK_H -> { if (e.isShiftDown) if (lightModel % 2 != 0) lightModel -= 1 else lightModel += 1 else lightModel = (lightModel + 2) % LightingModel.MAX println(when (lightModel) { PhongSpecular -> "PhongSpecular" PhongOnly -> "PhongOnly" BlinnSpecular -> "BlinnSpecular" else -> "BlinnOnly" }) } } if (lightRadius < 0.2f) lightRadius = 0.2f if (changedShininess) println("Shiny: " + MaterialParameters.getSpecularValue(lightModel)) } override fun end(gl: GL3) = with(gl) { programs.forEach { glDeletePrograms(it.whiteProgram.theProgram, it.colorProgram.theProgram) } glDeleteProgram(unlit.theProgram) glDeleteBuffer(projectionUniformBuffer) cylinder.dispose(gl) plane.dispose(gl) cube.dispose(gl) projectionUniformBuffer.destroy() } object LightingModel { val PhongSpecular = 0 val PhongOnly = 1 val BlinnSpecular = 2 val BlinnOnly = 3 val MAX = 4 } class ProgramPairs(var whiteProgram: ProgramData, var colorProgram: ProgramData) class ProgramData(gl: GL3, vertex: String, fragment: String) { val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment) val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity") val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity") val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix") val cameraSpaceLightPosUnif = gl.glGetUniformLocation(theProgram, "cameraSpaceLightPos") val lightAttenuationUnif = gl.glGetUniformLocation(theProgram, "lightAttenuation") val shininessFactorUnif = gl.glGetUniformLocation(theProgram, "shininessFactor") val baseDiffuseColorUnif = gl.glGetUniformLocation(theProgram, "baseDiffuseColor") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } class UnlitProgData(gl: GL3, vertex: String, fragment: String) { val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment) val objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor") val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } object MaterialParameters { private var phongExponent = 4.0f private var blinnExponent = 4.0f fun getSpecularValue(model: Int) = when (model) { PhongSpecular, PhongOnly -> phongExponent else -> blinnExponent } fun increment(model: Int, isLarge: Boolean) { when (model) { PhongSpecular, PhongOnly -> phongExponent += if (isLarge) 0.5f else 0.1f else -> blinnExponent += if (isLarge) 0.5f else 0.1f } clampParam(model) } fun decrement(model: Int, isLarge: Boolean) { when (model) { PhongSpecular, PhongOnly -> phongExponent -= if (isLarge) 0.5f else 0.1f else -> blinnExponent -= if (isLarge) 0.5f else 0.1f } clampParam(model) } fun clampParam(model: Int) { when (model) { PhongSpecular, PhongOnly -> if (phongExponent <= 0.0f) phongExponent = 0.0001f else -> if (blinnExponent <= 0.0f) blinnExponent = 0.0001f } } } }
mit
2256022dc2a2b0da179a547a892040ed
31.3075
131
0.598978
4.108744
false
false
false
false
MaibornWolff/codecharta
analysis/model/src/main/kotlin/de/maibornwolff/codecharta/model/ProjectWrapper.kt
1
680
package de.maibornwolff.codecharta.model import java.math.BigInteger import java.security.MessageDigest class ProjectWrapper( val data: Project, @Transient val projectJson: String ) { private val checksum: String init { if (data == null) throw IllegalStateException("no project data present") checksum = md5(projectJson) } fun md5(input: String): String { val md5Algorithm = MessageDigest.getInstance("MD5") return BigInteger(1, md5Algorithm.digest(input.toByteArray())).toString(16).padStart(32, '0') } override fun toString(): String { return "ProjectWrapper{checksum=$checksum, data=$data}" } }
bsd-3-clause
0d6cec15b354027eaed9ee9d91a619ae
25.153846
101
0.683824
4.25
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/falatron/FalatronModelsManager.kt
1
1438
package net.perfectdreams.loritta.cinnamon.discord.utils.falatron import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import net.perfectdreams.loritta.common.utils.JsonIgnoreUnknownKeys import kotlin.time.Duration.Companion.minutes class FalatronModelsManager { val http = HttpClient {} val models = MutableStateFlow<List<FalatronModel>>(emptyList()) val scope = CoroutineScope(Dispatchers.IO) fun startUpdater() { scope.launch { update() delay(30.minutes) } } private suspend fun update() { val response = http.get("https://falatron.com/static/models.json") models.emit(JsonIgnoreUnknownKeys.decodeFromString<FalatronModelResponse>(response.bodyAsText()).models) } @Serializable data class FalatronModelResponse( val models: List<FalatronModel> ) @Serializable data class FalatronModel( val author: String? = null, val category: String, val description: String, val dublador: String, val image: String, val name: String, val path: String ) }
agpl-3.0
aed9ad95cbbc54a2e553fd1220467f2b
28.979167
112
0.71975
4.384146
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/comment/ProfileCommentViewModel.kt
1
2868
package me.proxer.app.profile.comment import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import me.proxer.app.base.PagedViewModel import me.proxer.app.comment.LocalComment import me.proxer.app.util.ErrorUtils import me.proxer.app.util.data.ResettingMutableLiveData import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.subscribeAndLogErrors import me.proxer.app.util.extension.toParsedUserComment import me.proxer.library.enums.Category import me.proxer.library.enums.CommentContentType import org.threeten.bp.Instant import kotlin.properties.Delegates /** * @author Ruben Gees */ class ProfileCommentViewModel( private val userId: String?, private val username: String?, category: Category? ) : PagedViewModel<ParsedUserComment>() { override val itemsOnPage = 10 override val dataSingle: Single<List<ParsedUserComment>> get() = Single.fromCallable { validate() } .flatMap { api.user.comments(userId, username) .category(category) .page(page) .limit(itemsOnPage) .hasContent(CommentContentType.COMMENT, CommentContentType.RATING) .buildSingle() } .observeOn(Schedulers.computation()) .map { it.map { comment -> comment.toParsedUserComment() } } var category by Delegates.observable(category) { _, old, new -> if (old != new) reload() } val itemDeletionError = ResettingMutableLiveData<ErrorUtils.ErrorAction?>() private var deleteDisposable: Disposable? = null fun deleteComment(comment: ParsedUserComment) { deleteDisposable?.dispose() deleteDisposable = api.comment.update(comment.id) .comment("") .rating(0) .buildSingle() .doOnSuccess { storageHelper.deleteCommentDraft(comment.entryId) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeAndLogErrors( { data.value = data.value?.filter { it.id != comment.id } }, { itemDeletionError.value = ErrorUtils.handle(it) } ) } fun updateComment(comment: LocalComment) { data.value = data.value?.map { if (it.id == comment.id) { it.copy( ratingDetails = comment.ratingDetails, parsedContent = comment.parsedContent, overallRating = comment.overallRating, instant = Instant.now() ) } else { it } } } }
gpl-3.0
277f0e1abe60f39f7c5539b57c5408c2
32.741176
86
0.616457
4.852792
false
false
false
false
owntracks/android
project/app/src/test/java/org/owntracks/android/services/MqttHostnameVerifierTest.kt
1
4989
package org.owntracks.android.services import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import java.io.ByteArrayInputStream import java.security.Principal import java.security.cert.Certificate import java.security.cert.CertificateFactory import javax.net.ssl.SSLSession import javax.net.ssl.SSLSessionContext import javax.security.cert.X509Certificate class MqttHostnameVerifierTest { private val letsEncryptRootCert = this.javaClass.getResource("/letsEncryptRootCA.pem")!!.readBytes() private val letsEncryptSignedLeaf = this.javaClass.getResource("/letsEncryptSignedLeafX509Certificate.pem")!!.readBytes() private val selfSignedCert = this.javaClass.getResource("/selfSignedX509Certificate.pem")!!.readBytes() @Test fun `Given a standard signed certificate, MqttHostnameVerifier should delegate to HTTPS implementation and succeed if hostnames are the same`() { val testCA = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(letsEncryptRootCert)) val testLeaf = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(letsEncryptSignedLeaf)) val sslSession = TestSSLSession(listOf(testLeaf, testCA)) assertTrue(MqttHostnameVerifier(testCA).verify("valid-isrgrootx1.letsencrypt.org", sslSession)) } @Test fun `Given a standard signed certificate, MqttHostnameVerifier should delegate to HTTPS implementation and fail if hostnames are the different`() { val testCA = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(letsEncryptRootCert)) val testLeaf = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(letsEncryptSignedLeaf)) val sslSession = TestSSLSession(listOf(testLeaf, testCA)) assertFalse(MqttHostnameVerifier(testCA).verify("host.evil.org", sslSession)) } @Test fun `Given a self-signed certificate, MqttHostnameVerifier should skip validation and succeed even if hostnames are different`() { val selfSigned = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(selfSignedCert)) val sslSession = TestSSLSession(listOf(selfSigned)) assertTrue(MqttHostnameVerifier(selfSigned).verify("host.evil.org", sslSession)) } @Test fun `Given a self-signed certificate, MqttHostnameVerifier should skip validation and succeed even if hostnames are the same`() { val selfSigned = CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(selfSignedCert)) val sslSession = TestSSLSession(listOf(selfSigned)) assertTrue(MqttHostnameVerifier(selfSigned).verify("test.example.com", sslSession)) } private class TestSSLSession(private val testPeerCertificates: List<Certificate>) : SSLSession { override fun getId(): ByteArray { TODO("Not implemented") } override fun getSessionContext(): SSLSessionContext { TODO("Not implemented") } override fun getCreationTime(): Long { TODO("Not implemented") } override fun getLastAccessedTime(): Long { TODO("Not implemented") } override fun invalidate() { TODO("Not implemented") } override fun isValid(): Boolean { TODO("Not implemented") } override fun putValue(name: String?, value: Any?) { TODO("Not implemented") } override fun getValue(name: String?): Any { TODO("Not implemented") } override fun removeValue(name: String?) { TODO("Not implemented") } override fun getValueNames(): Array<String> { TODO("Not implemented") } override fun getPeerCertificates(): Array<Certificate> { return testPeerCertificates.toTypedArray() } override fun getLocalCertificates(): Array<Certificate> { TODO("Not implemented") } override fun getPeerCertificateChain(): Array<X509Certificate> { TODO("Not implemented") } override fun getPeerPrincipal(): Principal { TODO("Not implemented") } override fun getLocalPrincipal(): Principal { TODO("Not implemented") } override fun getCipherSuite(): String { TODO("Not implemented") } override fun getProtocol(): String { TODO("Not implemented") } override fun getPeerHost(): String { TODO("Not implemented") } override fun getPeerPort(): Int { TODO("Not implemented") } override fun getPacketBufferSize(): Int { TODO("Not implemented") } override fun getApplicationBufferSize(): Int { TODO("Not implemented") } } }
epl-1.0
0516d07c8f251e168601fdacb4b935e6
36.231343
151
0.67729
5.085627
false
true
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/ui/main/battery/doze/DozeWhitelistFragment.kt
1
10316
package com.androidvip.hebf.ui.main.battery.doze import android.annotation.SuppressLint import android.app.Dialog import android.os.Build import android.os.Bundle import android.text.TextUtils import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.androidvip.hebf.R import com.androidvip.hebf.adapters.ForceStopAppsAdapter import com.androidvip.hebf.models.App import com.androidvip.hebf.runSafeOnUiThread import com.androidvip.hebf.show import com.androidvip.hebf.toast import com.androidvip.hebf.ui.base.BaseActivity import com.androidvip.hebf.ui.base.BaseFragment import com.androidvip.hebf.utils.Doze import com.androidvip.hebf.utils.Logger import com.androidvip.hebf.utils.PackagesManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import com.topjohnwu.superuser.Shell import kotlinx.android.synthetic.main.fragment_doze_whitelist.* import kotlinx.coroutines.launch import java.util.ArrayList import kotlin.Comparator @RequiresApi(api = Build.VERSION_CODES.M) class DozeWhitelistFragment : BaseFragment() { private val packagesManager: PackagesManager by lazy { PackagesManager(findContext()) } private val whitelistedApps = mutableListOf<App>() private lateinit var adapter: RecyclerView.Adapter<*> private lateinit var fab: FloatingActionButton override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_doze_whitelist, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycleScope.launch { if (!isRooted()) { rootRequired.show() } } with (rvDozeWhitelist) { setHasFixedSize(true) layoutManager = GridLayoutManager(findContext(), defineRecyclerViewColumns()) addItemDecoration(DividerItemDecoration(this.context, RecyclerView.VERTICAL)) itemAnimator = null } val typedValueAccent = TypedValue() activity?.theme?.resolveAttribute(R.attr.colorAccent, typedValueAccent, true) dozeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(findContext(), typedValueAccent.resourceId)) dozeRefreshLayout.setOnRefreshListener { getWhitelistedApps() } if (isActivityAlive) { fab = requireActivity().findViewById(R.id.doze_fab) } getWhitelistedApps() } private fun getWhitelistedApps() { dozeRefreshLayout.isRefreshing = true Logger.logDebug("Retrieving whitelisted apps", findContext()) lifecycleScope.launch (workerContext) { whitelistedApps.clear() whitelistedApps.addAll(Doze.getWhitelistedApps(findContext())) whitelistedApps.sortWith(Comparator { o1, o2 -> o1.label.compareTo(o2.label) }) runSafeOnUiThread { dozeRefreshLayout.isRefreshing = false adapter = AppsAdapter(requireActivity() as BaseActivity, whitelistedApps) rvDozeWhitelist.adapter = adapter } } } override fun onResume() { super.onResume() runCatching { fab.show() fab.setOnClickListener { showPickAppsDialog() } } } override fun onPause() { super.onPause() runCatching { fab.hide() } } private fun showPickAppsDialog() { if (!Shell.rootAccess()) return val snackbar = Snackbar.make(fab, R.string.loading, Snackbar.LENGTH_INDEFINITE) snackbar.show() val builder = AlertDialog.Builder(findContext()) val dialogView = layoutInflater.inflate(R.layout.dialog_list_force_stop_apps, null) builder.setTitle(R.string.choose_package) builder.setView(dialogView) lifecycleScope.launch(workerContext) { val allPackages = packagesManager.installedPackages val allApps = ArrayList<App>() val whitelistedSet = whitelistedApps.map { it.packageName } allPackages.forEach { allApps.add(App().apply { packageName = it label = packagesManager.getAppLabel(it) icon = packagesManager.getAppIcon(it) isChecked = whitelistedSet.contains(it) }) } allApps.sortBy { it.label } whitelistedApps.forEach { if (allApps.contains(it)) { allApps.remove(it) } } runSafeOnUiThread { val rv = dialogView.findViewById<RecyclerView>(R.id.force_stop_apps_rv) val layoutManager = LinearLayoutManager(findContext(), RecyclerView.VERTICAL, false) rv.layoutManager = layoutManager val adapter = ForceStopAppsAdapter(requireActivity(), allApps) rv.adapter = adapter builder.setNegativeButton(android.R.string.cancel) { _, _ ->} builder.setPositiveButton(android.R.string.ok) { _, _ -> val appSet = adapter.selectedApps val stringSet = appSet.map { it.packageName } if (appSet.isNotEmpty()) { Logger.logInfo("Doze whitelisting $stringSet", findContext()) launch (workerContext) { Doze.whitelist(stringSet) runSafeOnUiThread { getWhitelistedApps() } } } } builder.setNegativeButton(android.R.string.cancel) { _, _ -> } builder.show() snackbar.dismiss() } } } private fun defineRecyclerViewColumns(): Int { return runCatching { if (isAdded) { val isTablet = resources.getBoolean(R.bool.is_tablet) val isLandscape = resources.getBoolean(R.bool.is_landscape) return if (isTablet || isLandscape) 2 else 1 } return 1 }.getOrDefault(1) } private class AppsAdapter( private val activity: BaseActivity, private val mDataSet: MutableList<App> ) : RecyclerView.Adapter<AppsAdapter.ViewHolder>() { class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var appName: TextView = v.findViewById(R.id.app_name) var appPackageName: TextView = v.findViewById(R.id.app_package_name) var appType: TextView = v.findViewById(R.id.app_type) var appStatus: TextView = v.findViewById(R.id.app_status) var appIcon: ImageView = v.findViewById(R.id.app_icon) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(activity).inflate(R.layout.list_item_apps_manager, parent, false) return ViewHolder(v) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val app = mDataSet[position] val packageName = app.packageName holder.appType.text = "user" holder.appName.text = app.label val id = app.id.toString() if (id != "0") holder.appStatus.text = id holder.appPackageName.apply { setSingleLine(true) text = packageName ellipsize = TextUtils.TruncateAt.MARQUEE isSelected = true marqueeRepeatLimit = 5 } holder.appIcon.setImageDrawable(app.icon) holder.itemView.setBackgroundColor(ContextCompat.getColor(activity, android.R.color.transparent)) if (app.isSystemApp) { holder.appType.text = "system" } holder.itemView.setOnClickListener { activity.toast("Long press to whitelist") } holder.itemView.setOnLongClickListener { MaterialAlertDialogBuilder(activity) .setTitle(android.R.string.dialog_alert_title) .setMessage(R.string.doze_whitelist_remove_app) .setNegativeButton(android.R.string.cancel) { _, _ -> } .setPositiveButton(android.R.string.ok) { _, _ -> val appToRemove = mDataSet[holder.adapterPosition] if (appToRemove.isDozeProtected) Toast.makeText(activity, R.string.doze_blacklist_gms, Toast.LENGTH_LONG).show() else { runCatching { mDataSet.removeAt(holder.adapterPosition) notifyDataSetChanged() } activity.toast(String.format(activity.getString(R.string.doze_blacklist_app_added), appToRemove.label)) activity.lifecycleScope.launch(activity.workerContext) { Doze.blacklist(appToRemove.packageName) } } } .show() true } } override fun getItemCount(): Int { return mDataSet.size } } }
apache-2.0
620ecc7f6f2e0d10af58aae96ef9b9e7
36.926471
135
0.609345
5.225937
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsMainController.kt
2
2336
package eu.kanade.tachiyomi.ui.setting import android.support.v7.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.util.getResourceColor class SettingsMainController : SettingsController() { override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { titleRes = R.string.label_settings val tintColor = context.getResourceColor(R.attr.colorAccent) preference { iconRes = R.drawable.ic_tune_black_24dp iconTint = tintColor titleRes = R.string.pref_category_general onClick { navigateTo(SettingsGeneralController()) } } preference { iconRes = R.drawable.ic_chrome_reader_mode_black_24dp iconTint = tintColor titleRes = R.string.pref_category_reader onClick { navigateTo(SettingsReaderController()) } } preference { iconRes = R.drawable.ic_file_download_black_24dp iconTint = tintColor titleRes = R.string.pref_category_downloads onClick { navigateTo(SettingsDownloadController()) } } preference { iconRes = R.drawable.ic_sync_black_24dp iconTint = tintColor titleRes = R.string.pref_category_tracking onClick { navigateTo(SettingsTrackingController()) } } preference { iconRes = R.drawable.ic_backup_black_24dp iconTint = tintColor titleRes = R.string.backup onClick { navigateTo(SettingsBackupController()) } } preference { iconRes = R.drawable.ic_code_black_24dp iconTint = tintColor titleRes = R.string.pref_category_advanced onClick { navigateTo(SettingsAdvancedController()) } } preference { iconRes = R.drawable.ic_help_black_24dp iconTint = tintColor titleRes = R.string.pref_category_about onClick { navigateTo(SettingsAboutController()) } } } private fun navigateTo(controller: SettingsController) { router.pushController(controller.withFadeTransaction()) } }
apache-2.0
8d23dc5b1cce2d3d2bc99f559eb0a0ff
36.327869
81
0.615582
4.949153
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/network/CloudflareInterceptor.kt
1
2762
package eu.kanade.tachiyomi.network import com.squareup.duktape.Duktape import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response class CloudflareInterceptor : Interceptor { private val operationPattern = Regex("""setTimeout\(function\(\)\{\s+(var (?:\w,)+f.+?\r?\n[\s\S]+?a\.value =.+?)\r?\n""") private val passPattern = Regex("""name="pass" value="(.+?)"""") private val challengePattern = Regex("""name="jschl_vc" value="(\w+)"""") private val serverCheck = arrayOf("cloudflare-nginx", "cloudflare") @Synchronized override fun intercept(chain: Interceptor.Chain): Response { val response = chain.proceed(chain.request()) // Check if Cloudflare anti-bot is on if (response.code() == 503 && serverCheck.contains(response.header("Server"))) { return chain.proceed(resolveChallenge(response)) } return response } private fun resolveChallenge(response: Response): Request { Duktape.create().use { duktape -> val originalRequest = response.request() val url = originalRequest.url() val domain = url.host() val content = response.body()!!.string() // CloudFlare requires waiting 4 seconds before resolving the challenge Thread.sleep(4000) val operation = operationPattern.find(content)?.groups?.get(1)?.value val challenge = challengePattern.find(content)?.groups?.get(1)?.value val pass = passPattern.find(content)?.groups?.get(1)?.value if (operation == null || challenge == null || pass == null) { throw RuntimeException("Failed resolving Cloudflare challenge") } val js = operation .replace(Regex("""a\.value =(.+?) \+.*"""), "$1") .replace(Regex("""\s{3,}[a-z](?: = |\.).+"""), "") .replace("\n", "") val result = (duktape.evaluate(js) as Double).toInt() val answer = "${result + domain.length}" val cloudflareUrl = HttpUrl.parse("${url.scheme()}://$domain/cdn-cgi/l/chk_jschl")!! .newBuilder() .addQueryParameter("jschl_vc", challenge) .addQueryParameter("pass", pass) .addQueryParameter("jschl_answer", answer) .toString() val cloudflareHeaders = originalRequest.headers() .newBuilder() .add("Referer", url.toString()) .build() return GET(cloudflareUrl, cloudflareHeaders) } } }
apache-2.0
d810205bc0f2399eb03d93c94b4462dd
35.351351
126
0.552498
4.649832
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/development/controller.kt
1
12820
package at.cpickl.gadsu.development import at.cpickl.gadsu.appointment.Appointment import at.cpickl.gadsu.appointment.AppointmentSavedEvent import at.cpickl.gadsu.appointment.AppointmentService import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.ClientCategory import at.cpickl.gadsu.client.ClientDonation import at.cpickl.gadsu.client.ClientService import at.cpickl.gadsu.client.ClientUpdatedEvent import at.cpickl.gadsu.client.Contact import at.cpickl.gadsu.client.CurrentClient import at.cpickl.gadsu.client.Gender import at.cpickl.gadsu.client.forClient import at.cpickl.gadsu.client.xprops.model.CProps import at.cpickl.gadsu.global.QuitEvent import at.cpickl.gadsu.image.MyImage import at.cpickl.gadsu.service.CurrentEvent import at.cpickl.gadsu.service.Logged import at.cpickl.gadsu.service.minutes import at.cpickl.gadsu.tcm.model.Meridian import at.cpickl.gadsu.treatment.CurrentTreatment import at.cpickl.gadsu.treatment.Treatment import at.cpickl.gadsu.treatment.TreatmentCreatedEvent import at.cpickl.gadsu.treatment.TreatmentService import at.cpickl.gadsu.treatment.dyn.DynTreatment import at.cpickl.gadsu.treatment.dyn.DynTreatments import at.cpickl.gadsu.treatment.dyn.DynTreatmentsCallback import at.cpickl.gadsu.treatment.dyn.treats.BloodPressure import at.cpickl.gadsu.treatment.dyn.treats.BloodPressureMeasurement import at.cpickl.gadsu.treatment.dyn.treats.HaraDiagnosis import at.cpickl.gadsu.treatment.dyn.treats.MeridianAndPosition import at.cpickl.gadsu.treatment.dyn.treats.PulseDiagnosis import at.cpickl.gadsu.treatment.dyn.treats.PulseProperty import at.cpickl.gadsu.treatment.dyn.treats.TongueDiagnosis import at.cpickl.gadsu.treatment.dyn.treats.TongueProperty import at.cpickl.gadsu.treatment.forTreatment import at.cpickl.gadsu.view.MainFrame import com.google.common.eventbus.EventBus import com.google.common.eventbus.Subscribe import org.joda.time.DateTime import javax.inject.Inject @Logged @Suppress("UNUSED_PARAMETER") open class DevelopmentController @Inject constructor( private val clientService: ClientService, private val treatmentService: TreatmentService, private val appointmentService: AppointmentService, private val bus: EventBus, private val mainFrame: MainFrame, private val currentClient: CurrentClient, private val currentTreatment: CurrentTreatment, private val screenshotInserter: ScreenshotDataInserter ) { private var devFrame: DevelopmentFrame? = null @Subscribe open fun onShowDevWindowEvent(event: ShowDevWindowEvent) { devFrame = DevelopmentFrame(mainFrame.dockPositionRight) devFrame!!.updateClient(currentClient.data) devFrame!!.updateTreatment(currentTreatment.data) devFrame!!.start() } @Subscribe open fun onCurrentEvent(event: CurrentEvent) { event.forClient { devFrame?.updateClient(it) } event.forTreatment{ devFrame?.updateTreatment(it) } } @Subscribe fun onAny(event: Any) { devFrame?.addEvent(event) } @Subscribe open fun onDevelopmentResetDataEvent(event: DevelopmentResetDataEvent) { deleteAll() arrayOf( Client.REAL_DUMMY, Client.INSERT_PROTOTYPE.copy( firstName = "Xnna", lastName = "Xym", contact = Contact.EMPTY.copy(mail = "[email protected]"), gender = Gender.FEMALE, picture = MyImage.DEFAULT_PROFILE_WOMAN, donation = ClientDonation.MONEY, cprops = CProps.empty ), Client.INSERT_PROTOTYPE.copy( firstName = "Alien", contact = Contact.EMPTY.copy(mail = "[email protected]"), wantReceiveMails = false, gender = Gender.UNKNOWN, category = ClientCategory.C, // picture = MyImage.DEFAULT_PROFILE_ALIEN, cprops = CProps.empty ), Client.INSERT_PROTOTYPE.copy( firstName = "Soon" ), Client.INSERT_PROTOTYPE.copy( firstName = "Later" ), Client.INSERT_PROTOTYPE.copy( firstName = "Latest" ) ).forEach { val saved = clientService.insertOrUpdate(it) if (saved.firstName == "Xnna") { bus.post(TreatmentCreatedEvent(treatmentService.insert( Treatment.insertPrototype(clientId = saved.id!!, number = 1, date = DateTime.now().minusDays(20)) ))) } else if (saved.firstName == "Soon") { bus.post(AppointmentSavedEvent(appointmentService.insertOrUpdate(Appointment.insertPrototype(saved.id!!, DateTime.now().plusDays(7))))) } else if (saved.firstName == "Later") { bus.post(TreatmentCreatedEvent(treatmentService.insert( Treatment.insertPrototype(clientId = saved.id!!, number = 1, date = DateTime.now().minusDays(42)) ))) } else if (saved.firstName == "Latest") { bus.post(TreatmentCreatedEvent(treatmentService.insert( Treatment.insertPrototype(clientId = saved.id!!, number = 1, date = DateTime.now().minusDays(99)) ))) } else if (saved.firstName == Client.REAL_DUMMY.firstName) { val clientId = saved.id!! val clientWithPic = saved.copy(picture = it.picture) clientService.savePicture(clientWithPic) bus.post(ClientUpdatedEvent(clientWithPic)) arrayOf( Treatment.insertPrototype( clientId = clientId, number = 1, date = DateTime.now().minusDays(2), duration = minutes(20), aboutDiagnosis = "Ihm gings ganz ganz schlecht.", aboutContent = "Den Herzmeridian hab ich behandelt.", aboutHomework = "Er soll mehr sport machen, eh kloa. Und weniger knoblauch essen!", note = "Aja, und der kommentar passt sonst nirgends rein ;)", treatedMeridians = listOf(Meridian.GallBladder, Meridian.UrinaryBladder, Meridian.Stomach), dynTreatments = listOf( HaraDiagnosis( kyos = listOf(MeridianAndPosition.UrinaryBladderBottom), jitsus = listOf(MeridianAndPosition.Liver), bestConnection = MeridianAndPosition.UrinaryBladderBottom to MeridianAndPosition.Liver, note = "* rechts mehr kyo\n* insgesamt sehr hohe spannung" ), TongueDiagnosis( color = listOf(TongueProperty.Color.RedTip, TongueProperty.Color.Pink), shape = listOf(TongueProperty.Shape.Long), coat = listOf(TongueProperty.Coat.Yellow, TongueProperty.Coat.Thick), special = emptyList(), note = "* zunge gruen"), PulseDiagnosis( properties = listOf(PulseProperty.Ascending, PulseProperty.Deep, PulseProperty.Soft), note = "* war irgendwie \"zaeh\"" ), BloodPressure( before = BloodPressureMeasurement(90, 110, 80), after = BloodPressureMeasurement(80, 100, 70) ) ) ), Treatment.insertPrototype( clientId = clientId, number = 2, date = DateTime.now().minusDays(2), dynTreatments = emptyList() ), Treatment.insertPrototype( clientId = clientId, number = 3, date = DateTime.now().minusDays(3), note = "A my note for treatment 3 for maxiiii. my note for treatment 3 for maxiiii. \nB my note for treatment 3 for maxiiii.\n\n\nXXX nmy note for treatment 3 for maxiiii. ", dynTreatments = emptyList() ), Treatment.insertPrototype( clientId = clientId, number = 4, date = DateTime.now().minusDays(4), duration = minutes(30), note = "Was a quick one", dynTreatments = DynTreatments.values().map { it.call(object : DynTreatmentsCallback<DynTreatment> { override fun onHaraDiagnosis() = HaraDiagnosis( kyos = listOf(MeridianAndPosition.LargeIntestineLeft), jitsus = listOf(MeridianAndPosition.Liver), bestConnection = Pair(MeridianAndPosition.LargeIntestineLeft, MeridianAndPosition.Liver), note = "* oberer bereich war hart" ) override fun onTongueDiagnosis() = TongueDiagnosis( color = listOf(TongueProperty.Color.DarkRed), shape = listOf(TongueProperty.Shape.Flaccid), coat = listOf(TongueProperty.Coat.Yellow), special = listOf(TongueProperty.Special.MiddleCrack), note = "* grooosser mittelrisse!" ) override fun onPulseDiagnosis() = PulseDiagnosis( properties = listOf(PulseProperty.Deep, PulseProperty.Full), note = "* helle, zarte haut beim palpieren" ) override fun onBloodPressure() = BloodPressure( before = BloodPressureMeasurement(80, 120, 60), after = BloodPressureMeasurement(70, 110, 50) ) }) } ), Treatment.insertPrototype( clientId = clientId, number = 5, date = DateTime.now().minusDays(5), dynTreatments = emptyList() ), Treatment.insertPrototype( clientId = clientId, number = 6, date = DateTime.now().minusDays(6), dynTreatments = emptyList() ) ).forEach { treatmentService.insert(it) bus.post(TreatmentCreatedEvent(it)) } } } } @Subscribe open fun onDevelopmentResetScreenshotDataEvent(event: DevelopmentResetScreenshotDataEvent) { deleteAll() screenshotInserter.insertData() } @Subscribe open fun onDevelopmentClearDataEvent(event: DevelopmentClearDataEvent) { deleteAll() } @Subscribe open fun onQuitEvent(event: QuitEvent) { devFrame?.close() } private fun deleteAll() { clientService.findAll().forEach { // not directly supported in service, as this is a DEV feature only! clientService.delete(it) } } }
apache-2.0
f801591993c1e98121fc1afcfec7fc77
50.485944
206
0.519657
5.284419
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/data/DataManager.kt
1
26097
package com.ghstudios.android.data import android.app.Application import android.content.Context import com.ghstudios.android.components.WeaponListEntry import com.ghstudios.android.data.classes.* import com.ghstudios.android.data.classes.meta.ArmorMetadata import com.ghstudios.android.data.classes.meta.ItemMetadata import com.ghstudios.android.data.classes.meta.MonsterMetadata import com.ghstudios.android.data.cursors.ArmorCursor import com.ghstudios.android.data.cursors.CombiningCursor import com.ghstudios.android.data.cursors.ComponentCursor import com.ghstudios.android.data.cursors.DecorationCursor import com.ghstudios.android.data.cursors.GatheringCursor import com.ghstudios.android.data.cursors.HornMelodiesCursor import com.ghstudios.android.data.cursors.HuntingRewardCursor import com.ghstudios.android.data.cursors.ItemCursor import com.ghstudios.android.data.cursors.ItemToMaterialCursor import com.ghstudios.android.data.cursors.ItemToSkillTreeCursor import com.ghstudios.android.data.cursors.LocationCursor import com.ghstudios.android.data.cursors.MonsterAilmentCursor import com.ghstudios.android.data.cursors.MonsterCursor import com.ghstudios.android.data.cursors.MonsterDamageCursor import com.ghstudios.android.data.cursors.MonsterHabitatCursor import com.ghstudios.android.data.cursors.MonsterToQuestCursor import com.ghstudios.android.data.cursors.MonsterWeaknessCursor import com.ghstudios.android.data.cursors.PalicoArmorCursor import com.ghstudios.android.data.cursors.PalicoWeaponCursor import com.ghstudios.android.data.cursors.QuestCursor import com.ghstudios.android.data.cursors.QuestRewardCursor import com.ghstudios.android.data.cursors.SkillCursor import com.ghstudios.android.data.cursors.SkillTreeCursor import com.ghstudios.android.data.cursors.WeaponCursor import com.ghstudios.android.data.cursors.WishlistComponentCursor import com.ghstudios.android.data.cursors.WishlistCursor import com.ghstudios.android.data.cursors.WishlistDataCursor import com.ghstudios.android.data.cursors.WyporiumTradeCursor import com.ghstudios.android.data.database.* import com.ghstudios.android.data.util.SearchFilter import com.ghstudios.android.util.first import com.ghstudios.android.util.firstOrNull import com.ghstudios.android.util.toList import java.util.ArrayList import java.util.HashMap /* * Singleton class */ class DataManager private constructor(private val mAppContext: Context) { companion object { private const val TAG = "DataManager" // note: not using lateinit due to incompatibility error with @JvmStatic private var sDataManager: DataManager? = null @JvmStatic fun bindApplication(app: Application) { if (sDataManager == null) { // Use the application context to avoid leaking activities sDataManager = DataManager(app.applicationContext) } } @JvmStatic fun get(): DataManager { if (sDataManager == null) { throw UninitializedPropertyAccessException("Cannot call get without first binding the application") } return sDataManager!! } } private val mHelper = MonsterHunterDatabaseHelper.getInstance(mAppContext) // additional query objects. These handle different types of queries private val metadataDao = MetadataDao(mHelper) private val monsterDao = MonsterDao(mHelper) private val itemDao = ItemDao(mHelper) private val huntingRewardsDao = HuntingRewardsDao(mHelper) private val gatheringDao = GatheringDao(mHelper) private val skillDao = SkillDao(mHelper) val asbManager = ASBManager(mAppContext, this, mHelper) val wishlistManager = WishlistManager(mAppContext, this, mHelper) /** * Returns a map of supported language codes. */ fun getLanguages() = listOf( "en", "es", "fr", "de", "it" ) /********************************* ARMOR QUERIES */ fun getArmorSetMetadataByFamily(familyId: Long): List<ArmorMetadata> { return metadataDao.queryArmorSetMetadataByFamily(familyId) } fun getArmorSetMetadataByArmor(armorId: Long): List<ArmorMetadata> { return metadataDao.queryArmorSetMetadataByArmor(armorId) } /* Get a Cursor that has a list of all Armors */ fun queryArmor(): ArmorCursor { return itemDao.queryArmor() } fun queryArmorSearch(searchTerm: String): ArmorCursor { return itemDao.queryArmorSearch(searchTerm) } /* Get a specific Armor */ fun getArmor(id: Long): Armor? { return itemDao.queryArmor(id) } fun getArmorByFamily(id: Long): List<Armor> { return itemDao.queryArmorByFamily(id) } /* Get an array of Armor based on hunter type */ fun queryArmorArrayType(type: Int): List<Armor> { val cursor = itemDao.queryArmorType(type) return cursor.toList { it.armor } } /** * Get a list of armor based on hunter type with a list of all awarded skill points. * If "BOTH" is passed, then its equivalent to querying all armor */ fun queryArmorSkillPointsByType(armorSlot: String, hunterType: Int): List<ArmorSkillPoints> { return itemDao.queryArmorSkillPointsByType(armorSlot, hunterType) } fun queryArmorFamilies(type: Int): List<ArmorFamily> { return itemDao.queryArmorFamilies(type) } /** * Returns an armor families cursor * @param searchFilter the search predicate to filter on * @param skipSolos true to skip armor families with a single child, otherwise returns all. */ @JvmOverloads fun queryArmorFamilyBaseSearch(filter: String, skipSolos: Boolean=false): List<ArmorFamilyBase> { return itemDao.queryArmorFamilyBaseSearch(filter, skipSolos) } /********************************* COMBINING QUERIES */ /* Get a Cursor that has a list of all Combinings */ fun queryCombinings(): CombiningCursor { return itemDao.queryCombinings() } fun queryCombiningOnItemID(id: Long): CombiningCursor { return itemDao.queryCombinationsOnItemID(id) } /********************************* COMPONENT QUERIES */ /* Get a Cursor that has a list of Components based on the created Item */ fun queryComponentCreated(id: Long): ComponentCursor { return mHelper.queryComponentCreated(id) } fun queryComponentCreateByArmorFamily(familyId: Long): ComponentCursor { return itemDao.queryComponentsByArmorFamily(familyId) } /* Get a Cursor that has a list of Components based on the component Item */ fun queryComponentComponent(id: Long): ComponentCursor { return mHelper.queryComponentComponent(id) } /* Get an array of paths for a created Item */ fun queryComponentCreateImprove(id: Long): ArrayList<String> { // Gets all the component Items val cursor = mHelper.queryComponentCreated(id) cursor.moveToFirst() val paths = ArrayList<String>() // Only get distinct paths while (!cursor.isAfterLast) { val type = cursor.component!!.type // Check if not a duplicate if (!paths.contains(type)) { paths.add(type) } cursor.moveToNext() } cursor.close() return paths } /********************************* DECORATION QUERIES */ /* Get a Cursor that has a list of all Decorations */ fun queryDecorations(): DecorationCursor { return mHelper.queryDecorations() } /** * Gets a cursor that has a list of decorations that pass the filter. * Having a null or empty filter is the same as calling without a filter */ fun queryDecorationsSearch(filter: String?): DecorationCursor { return mHelper.queryDecorationsSearch(filter ?: "") } /* Get a specific Decoration */ fun getDecoration(id: Long): Decoration? { var decoration: Decoration? = null val cursor = mHelper.queryDecoration(id) cursor.moveToFirst() if (!cursor.isAfterLast) decoration = cursor.decoration cursor.close() return decoration } /********************************* GATHERING QUERIES */ /* Get a Cursor that has a list of Gathering based on Item */ fun queryGatheringItem(id: Long): GatheringCursor { return mHelper.queryGatheringItem(id) } /* Get a Cursor that has a list of Gathering based on Location */ fun queryGatheringLocation(id: Long): GatheringCursor { return mHelper.queryGatheringLocation(id) } /* Get a Cursor that has a list of Gathering based on Location and Quest rank */ fun queryGatheringLocationRank(id: Long, rank: String): GatheringCursor { return mHelper.queryGatheringLocationRank(id, rank) } fun queryGatheringForQuest(questId: Long, locationId: Long, rank: String): GatheringCursor { return gatheringDao.queryGatheringsForQuest(questId, if(locationId>=100) locationId-100 else locationId, rank) } /********************************* HUNTING REWARD QUERIES */ /* Get a Cursor that has a list of HuntingReward based on Item */ fun queryHuntingRewardItem(id: Long): HuntingRewardCursor { return huntingRewardsDao.queryHuntingRewardItem(id) } /* Get a Cursor that has a list of HuntingReward based on Item and Rank*/ fun queryHuntingRewardForQuest(id: Long, rank: String): HuntingRewardCursor { return huntingRewardsDao.queryHuntingRewardForQuest(id,rank) } /* Get a Cursor that has a list of HuntingReward based on Monster */ fun queryHuntingRewardMonster(id: Long): HuntingRewardCursor { return huntingRewardsDao.queryHuntingRewardMonster(id) } /* Get a Cursor that has a list of HuntingReward based on Monster and Rank */ fun queryHuntingRewardMonsterRank(id: Long, rank: String): HuntingRewardCursor { return huntingRewardsDao.queryHuntingRewardMonsterRank(id, rank) } /********************************* ITEM QUERIES */ /** * Performs a query to receive item metadata * @param id * @return */ fun queryItemMetadata(id: Long): ItemMetadata? { return metadataDao.queryItemMetadata(id) } /** * Returns a cursor that iterates over regular items. * Regular items are items that you can find in the item box * @return */ fun queryBasicItems(): ItemCursor { return itemDao.queryBasicItems("") } /** * Returns a cursor that iterates over regular items (filterable). * Regular items are items that you can find in the item box * @return */ fun queryBasicItems(searchTerm: String): ItemCursor { return itemDao.queryBasicItems(searchTerm) } /* Get a Cursor that has a list of all Items */ fun queryItems(): ItemCursor { return itemDao.queryItems() } /* Get a specific Item */ fun getItem(id: Long): Item? { return itemDao.queryItem(id) } /* Get a Cursor that has a list of filtered Items through search */ @JvmOverloads fun queryItemSearch(search: String, includeTypes: List<ItemType> = emptyList()): ItemCursor { return itemDao.queryItemSearch(search, includeTypes) } /********************************* ITEM TO SKILL TREE QUERIES */ /* Get a Cursor that has a list of ItemToSkillTree based on Item */ fun queryItemToSkillTreeItem(id: Long): ItemToSkillTreeCursor { return mHelper.queryItemToSkillTreeItem(id) } /* Get a Cursor that has a list of ItemToSkillTree based on SkillTree */ fun queryItemToSkillTreeSkillTree(id: Long, type: ItemType): ItemToSkillTreeCursor { return mHelper.queryItemToSkillTreeSkillTree(id, ItemTypeConverter.serialize(type)) } /** Get an array of ItemToSkillTree based on Item */ fun queryItemToSkillTreeArrayItem(id: Long): ArrayList<ItemToSkillTree> { val itst = ArrayList<ItemToSkillTree>() val cursor = mHelper.queryItemToSkillTreeItem(id) cursor.moveToFirst() while (!cursor.isAfterLast) { itst.add(cursor.itemToSkillTree) cursor.moveToNext() } cursor.close() return itst } /** Get an array of ItemToSkillTree based on Item */ fun queryItemToSkillTreeArrayByArmorFamily(id: Long): HashMap<Long, List<ItemToSkillTree>> { val skills = skillDao.queryItemToSkillTreeForArmorFamily(id) val results = HashMap<Long, List<ItemToSkillTree>>() for (item in skills) { val key = item.item!!.id val items = results.getOrPut(key) { ArrayList() } with(items as ArrayList) { items.add(item) } } return results } /** * Return a list of ItemToSkillTree, where the Item is an Armor object. */ fun queryArmorSkillTreePointsBySkillTree(skillTreeId: Long): List<ItemToSkillTree> { return itemDao.queryArmorSkillTreePointsBySkillTree(skillTreeId) } /********************************* ITEM TO MATERIAL QUERIES */ fun queryItemsForMaterial(mat_item_id: Long): ItemToMaterialCursor { return mHelper.queryItemsForMaterial(mat_item_id) } /********************************* LOCATION QUERIES */ /* Get a Cursor that has a list of all Locations */ fun queryLocations(): LocationCursor { return mHelper.queryLocations() } /* Get a specific Location */ fun getLocation(id: Long): Location? { return mHelper.queryLocation(id) } fun queryLocationsSearch(searchTerm: String): List<Location> { // todo: we could also create a cursor wrapper implementation that filters in memory...without first converting to objects val locations = queryLocations().toList { it.location } if (searchTerm.isBlank()) { return locations } val filter = SearchFilter(searchTerm) return locations.filter { filter.matches(it.name) } } /********************************* MELODY QUERIES */ /* Get a Cursor that has a list of all Melodies from a specific set of notes */ fun queryMelodiesFromNotes(notes: String): HornMelodiesCursor { return mHelper.queryMelodiesFromNotes(notes) } /********************************* MONSTER QUERIES */ /* Get a Cursor that has a list of all Monster */ fun queryMonsterMetadata(id: Long): MonsterMetadata? { return metadataDao.queryMonsterMetadata(id) } /** * Returns a cursor that iterates over all monsters of a particular type */ fun queryMonsters(monsterClass: MonsterClass?): MonsterCursor { return monsterDao.queryMonsters(monsterClass) } fun questDeviantMonsterNames(): Array<String> { return monsterDao.queryDeviantMonsterNames() } fun queryMonstersSearch(searchTerm: String): MonsterCursor { return monsterDao.queryMonstersSearch(searchTerm) } /* Get a specific Monster */ fun getMonster(id: Long): Monster? { return monsterDao.queryMonster(id) } /********************************* MONSTER AILMENT QUERIES */ /* Get a cursor that lists all the ailments a particular monster can inflict */ fun queryAilmentsFromId(id: Long): MonsterAilmentCursor { return mHelper.queryAilmentsFromMonster(id) } /********************************* MONSTER DAMAGE QUERIES */ /* Get a Cursor that has a list of MonsterDamage for a specific Monster */ fun queryMonsterDamage(id: Long): MonsterDamageCursor { return mHelper.queryMonsterDamage(id) } /* Get an array of MonsterDamage for a specific Monster */ fun queryMonsterDamageArray(id: Long): List<MonsterDamage> { val cursor = queryMonsterDamage(id) return cursor.toList { it.monsterDamage } } /********************************* MONSTER STATUS QUERIES */ /* Get an array of status objects for a monster */ fun queryMonsterStatus(id: Long): List<MonsterStatus> { val cursor = mHelper.queryMonsterStatus(id) return cursor.toList { it.status } } /********************************* MONSTER TO QUEST QUERIES */ /* Get a Cursor that has a list of MonsterToQuest based on Monster */ fun queryMonsterToQuestMonster(id: Long): MonsterToQuestCursor { return mHelper.queryMonsterToQuestMonster(id) } /* Get a Cursor that has a list of MonsterToQuest based on Quest */ fun queryMonsterToQuestQuest(id: Long): MonsterToQuestCursor { return mHelper.queryMonsterToQuestQuest(id) } /********************************* MONSTER HABITAT QUERIES */ /* Get a Cursor that has a list of MonsterHabitats based on Monster */ fun queryHabitatMonster(id: Long): MonsterHabitatCursor { return mHelper.queryHabitatMonster(id) } /* Get a Cursor that has a list of MonsterHabitats based on Location */ fun queryHabitatLocation(id: Long): MonsterHabitatCursor { return mHelper.queryHabitatLocation(id) } /********************************* MONSTER WEAKNESS QUERIES */ /* Get a cursor that has all a monsters weaknesses */ fun queryWeaknessFromMonster(id: Long): MonsterWeaknessCursor { return mHelper.queryWeaknessFromMonster(id) } /* Get an array of MonsterWeakness for a specific Monster */ fun queryMonsterWeaknessArray(id: Long): List<MonsterWeakness> { val cursor = queryWeaknessFromMonster(id) return cursor.toList { it.weakness } } /********************************* QUEST QUERIES */ /* Get a Cursor that has a list of all Quests */ fun queryQuests(): QuestCursor { return mHelper.queryQuests() } fun queryQuestsSearch(searchTerm: String): QuestCursor { return mHelper.queryQuestsSearch(searchTerm) } /* Get a specific Quests */ fun getQuest(id: Long): Quest? { return mHelper.queryQuest(id).firstOrNull { it.quest } } /* Get an array of Quest based on hub */ fun queryQuestArrayHub(hub: QuestHub): List<Quest> { return this.queryQuestHub(hub).toList { it.quest } } /* Get a Cursor that has a list of Quest based on hub */ fun queryQuestHub(hub: QuestHub): QuestCursor { return mHelper.queryQuestHub(hub) } /* Get a Cursor that has a list of Quest based on hub and stars */ fun queryQuestHubStar(hub: QuestHub, stars: String): QuestCursor { return mHelper.queryQuestHubStar(hub, stars) } /********************************* QUEST REWARD QUERIES */ /* Get a Cursor that has a list of QuestReward based on Item */ fun queryQuestRewardItem(id: Long): QuestRewardCursor { return mHelper.queryQuestRewardItem(id) } /* Get a Cursor that has a list of QuestReward based on Quest */ fun queryQuestRewardQuest(id: Long): QuestRewardCursor { return mHelper.queryQuestRewardQuest(id) } /********************************* SKILL QUERIES */ // public SkillCursor querySkill(long id) { // return mHelper.querySkill(id); // } /* Get a Cursor that has a list of all Skills from a specific SkillTree */ fun querySkillsFromTree(id: Long): SkillCursor { return mHelper.querySkillsFromTree(id) } /********************************* SKILL TREE QUERIES */ /* Get a Cursor that has a list of all SkillTree */ fun querySkillTrees(): SkillTreeCursor { return mHelper.querySkillTrees() } fun querySkillTreesSearch(searchTerm: String): SkillTreeCursor { return mHelper.querySkillTreesSearch(searchTerm) } /** Get a specific SkillTree */ fun getSkillTree(id: Long): SkillTree? { return mHelper.querySkillTree(id) } /********************************* WEAPON QUERIES */ /* Get a Cursor that has a list of all Weapons */ fun queryWeapon(): WeaponCursor { return mHelper.queryWeapon() } /* Get a specific Weapon */ fun getWeapon(id: Long): Weapon? { var weapon: Weapon? = null val cursor = mHelper.queryWeapon(id) cursor.moveToFirst() if (!cursor.isAfterLast) weapon = cursor.weapon cursor.close() return weapon } /* Get a Cursor that has a list of Weapons based on weapon type */ fun queryWeaponType(type: String): WeaponCursor { return mHelper.queryWeaponType(type, false) } fun getWeaponType(id: Long): String { val c = mHelper.queryWeaponTypeForWeapon(id) c.moveToFirst() val wtype = c.getString(0) c.close() return wtype } /* Get an array of weapon expandable list items * */ fun queryWeaponTreeArray(type: String): ArrayList<WeaponListEntry> { val cursor = mHelper.queryWeaponType(type, false) cursor.moveToFirst() val weapons = ArrayList<WeaponListEntry>() val weaponDict = HashMap<Long, WeaponListEntry>() var currentEntry: WeaponListEntry var currentWeapon: Weapon? while (!cursor.isAfterLast) { currentWeapon = cursor.weapon currentEntry = WeaponListEntry(currentWeapon) weaponDict[currentWeapon.id] = currentEntry cursor.moveToNext() } var parent_id: Int cursor.moveToFirst() while (!cursor.isAfterLast) { currentWeapon = cursor.weapon currentEntry = weaponDict[currentWeapon.id]!! parent_id = currentWeapon.parentId if (parent_id != 0) { weaponDict[parent_id.toLong()]?.addChild(currentEntry) } weapons.add(currentEntry) cursor.moveToNext() } return weapons } /* * Get an array of weapon expandable list items consisting only of the final upgrades */ fun queryWeaponTreeArrayFinal(type: String): ArrayList<WeaponListEntry> { val cursor = mHelper.queryWeaponType(type, true) val weapons = ArrayList<WeaponListEntry>() cursor.moveToFirst() while (!cursor.isAfterLast) { weapons.add(WeaponListEntry(cursor.weapon)) cursor.moveToNext() } return weapons } /* Get a Cursor that has a list of Weapons in the weapon tree for a specified weapon */ fun queryWeaponTree(id: Long): WeaponCursor { return mHelper.queryWeaponFamily(id) } /** * Returns the first weapon of each family tree that led up to the family tree of id. */ fun queryWeaponOrigins(id: Long): List<Weapon>{ val weapons = ArrayList<Weapon>() // Iteratively does the following: // - get the first weapon of the tree: (id && S.WEAPON_FAMILY_MASK) + 1 // - get the parent of that weapon // - get the first weapon of that tree and cycle again // note: (id && S.WEAPON_FAMILY_MASK) + 1 is the FIRST weapon of the tree. var currentId = (id and S.WEAPON_FAMILY_MASK) + 1 while(true) { // This particular weapon cursor returns incomplete info // todo: consider making either a WeaponBase superclass, a WeaponBasic class, or return full info from queryWeaponTreeParent val weaponBase = mHelper.queryWeaponTreeParent(currentId) .firstOrNull { it.weapon } ?: break // Query the full weapon data for the weapon cursor val weapon = mHelper.queryWeapon(weaponBase.id).first { it.weapon } // add to results, and then get the id of the first weapon of that tree and iterate again weapons.add(weapon) currentId = (weapon.id and S.WEAPON_FAMILY_MASK) + 1 } return weapons } fun queryWeaponBranches(id:Long): List<Weapon> { val wt = mHelper.queryWeaponFamilyBranches(id).toList { it.weapon } val weapons = ArrayList<Weapon>() for(w in wt){ val wCur = mHelper.queryWeapon(w.id).firstOrNull { it.weapon } if(wCur!=null) weapons.add(wCur) } return weapons } /** * Queries all final weapons that can be derived from this one */ fun queryWeaponFinal(id: Long): List<Weapon> { val results = mutableListOf<Weapon>() // Get the final of this tree val final = mHelper.queryWeaponTreeFinal(id) if (final != null) { results.add(final) } // Get the branch weapons, and recursively get their final weapons val otherBranches = this.queryWeaponBranches(id) val branchFinals = otherBranches.map { queryWeaponFinal(it.id) }.flatten() results.addAll(branchFinals) return results } fun queryPalicoWeapons(): PalicoWeaponCursor { return mHelper.queryPalicoWeapons() } fun getPalicoWeapon(id: Long): PalicoWeapon? { val cursor = mHelper.queryPalicoWeapon(id) cursor.moveToFirst() val w = cursor.weapon cursor.close() return w } fun queryPalicoArmor(): PalicoArmorCursor { return mHelper.queryPalicoArmors() } fun getPalicoArmor(id: Long): PalicoArmor { val cursor = mHelper.queryPalicoArmor(id) cursor.moveToFirst() val w = cursor.armor cursor.close() return w } /**************************** WYPORIUM TRADE DATA QUERIES */ /* Get a Cursor that has a list of all wyporium trades */ fun queryWyporiumTrades(): WyporiumTradeCursor { return mHelper.queryWyporiumTrades() } /* Get a specific wyporium trade */ fun getWyporiumTrade(id: Long): WyporiumTrade? { var wyporiumTrade: WyporiumTrade? = null val cursor = mHelper.queryWyporiumTrades(id) cursor.moveToFirst() if (!cursor.isAfterLast) wyporiumTrade = cursor.wyporiumTrade cursor.close() return wyporiumTrade } }
mit
e386c8808539ce59bd9c034edc9ab54f
33.982574
136
0.652872
4.413496
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/selectors/typeselector.kt
1
1428
/* * Copyright 2016 Karl Tauber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.devcharly.kotlin.ant import org.apache.tools.ant.types.selectors.TypeSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface ITypeSelectorNested : INestedComponent { fun type( type: FileType? = null, error: String? = null) { _addTypeSelector(TypeSelector().apply { component.project.setProjectReference(this); _init(type, error) }) } fun _addTypeSelector(value: TypeSelector) } fun TypeSelector._init( type: FileType?, error: String?) { if (type != null) setType(TypeSelector.FileType().apply { this.value = type.value }) if (error != null) setError(error) } enum class FileType(val value: String) { FILE("file"), DIR("dir") }
apache-2.0
169dea0c09380c03ebde8291d224e71a
28.142857
79
0.642157
4.056818
false
false
false
false
mastizada/focus-android
app/src/main/java/org/mozilla/focus/whatsnew/WhatsNew.kt
4
4957
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.whatsnew import android.content.Context import android.preference.PreferenceManager import android.support.annotation.VisibleForTesting import org.mozilla.focus.ext.appVersionName /** * Helper class tracking whether the application was recently updated in order to show "What's new" * menu items and indicators in the application UI. * * The application is considered updated when the application's version name changes (versionName * in the manifest). The applications version code would be a good candidates too, but it might * change more often (RC builds) without the application actually changing from the user's point * of view. * * Whenever the application was updated we still consider the application to be "recently updated" * for the next couple of (process) starts. */ class WhatsNew { companion object { @VisibleForTesting const val PREFERENCE_KEY_APP_NAME = "whatsnew-lastKnownAppVersionName" private const val PREFERENCE_KEY_SESSION_COUNTER = "whatsnew-updateSessionCounter" /** * How many "sessions" do we consider the app to be updated? In this case a session means * process creations. */ private const val SESSIONS_PER_UPDATE = 3 @VisibleForTesting internal var wasUpdatedRecently: Boolean? = null /** * Should we highlight the "What's new" menu item because this app been updated recently? * * This method returns true either if this is the first start of the application since it * was updated or this is a later start but still recent enough to consider the app to be * updated recently. */ @JvmStatic fun shouldHighlightWhatsNew(context: Context): Boolean { // Cache the value for the lifetime of this process (or until userViewedWhatsNew() is called) if (wasUpdatedRecently == null) { wasUpdatedRecently = wasUpdatedRecentlyInner(context) } return wasUpdatedRecently!! } private fun wasUpdatedRecentlyInner(context: Context): Boolean = when { hasAppBeenUpdated(context) -> { // The app has just been updated. Remember the new app version name and // reset the session counter so that we will still consider the app to be // updated for the next app starts. saveAppVersionName(context) setSessionCounter(context, SESSIONS_PER_UPDATE) true } else -> { // If the app has been updated recently then decrement our session // counter. If the counter reaches 0 we will not consider the app to // be updated anymore (until the app version name changes again) decrementAndGetSessionCounter(context) > 0 } } /** * Reset the "updated" state and continue as if the app was not updated recently. */ @JvmStatic fun userViewedWhatsNew(context: Context) { wasUpdatedRecently = false setSessionCounter(context, 0) } private fun hasAppBeenUpdated(context: Context): Boolean { val lastKnownAppVersionName = getLastKnownAppVersionName(context) if (lastKnownAppVersionName.isNullOrEmpty()) { saveAppVersionName(context) return false } return !lastKnownAppVersionName.equals(context.appVersionName) } private fun getLastKnownAppVersionName(context: Context): String? { return PreferenceManager.getDefaultSharedPreferences(context) .getString(PREFERENCE_KEY_APP_NAME, null) } private fun saveAppVersionName(context: Context) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putString(PREFERENCE_KEY_APP_NAME, context.appVersionName) .apply() } private fun setSessionCounter(context: Context, count: Int) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putInt(PREFERENCE_KEY_SESSION_COUNTER, count) .apply() } private fun decrementAndGetSessionCounter(context: Context): Int { val cachedSessionCounter = PreferenceManager.getDefaultSharedPreferences(context) .getInt(PREFERENCE_KEY_SESSION_COUNTER, 0) val newSessionCounter = maxOf(cachedSessionCounter - 1, 0) setSessionCounter(context, newSessionCounter) return newSessionCounter } } }
mpl-2.0
7f37eb65cc27bc1ad972e9a7a84b2f4e
41.367521
105
0.643131
5.196017
false
false
false
false
Shynixn/PetBlocks
petblocks-sponge-plugin/src/main/java/com/github/shynixn/petblocks/sponge/logic/business/pathfinder/PathfinderAfraidOfWater.kt
1
2783
package com.github.shynixn.petblocks.sponge.logic.business.pathfinder import com.flowpowered.math.vector.Vector3d import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.business.enumeration.MaterialType import com.github.shynixn.petblocks.api.business.proxy.PetProxy import com.github.shynixn.petblocks.api.business.service.ItemTypeService import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.business.service.ParticleService import com.github.shynixn.petblocks.api.persistence.entity.AIAfraidOfWater import com.github.shynixn.petblocks.core.logic.business.pathfinder.BasePathfinder import com.github.shynixn.petblocks.sponge.logic.business.extension.toPosition import com.github.shynixn.petblocks.sponge.logic.business.extension.toVector import org.spongepowered.api.entity.Transform import org.spongepowered.api.entity.living.Living import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.world.World class PathfinderAfraidOfWater( private val pet: PetProxy, private val aiAfraidOfWater: AIAfraidOfWater, private val livingEntity: Living ) : BasePathfinder(aiAfraidOfWater) { private var lastPlayTime = 0L private val particleService = PetBlocksApi.resolve(ParticleService::class.java) private val loggingService = PetBlocksApi.resolve(LoggingService::class.java) private val itemTypeService = PetBlocksApi.resolve(ItemTypeService::class.java) /** * Should the goal be executed. */ override fun shouldGoalBeExecuted(): Boolean { try { val currentMilliseconds = System.currentTimeMillis() if (itemTypeService.findItemType<Any>(livingEntity.location.block.type) == itemTypeService.findItemType(MaterialType.WATER) || itemTypeService.findItemType<Any>( livingEntity.location.block.type ) == itemTypeService.findItemType<Any>(MaterialType.STATIONARY_WATER) ) { if (currentMilliseconds - lastPlayTime > this.aiAfraidOfWater.stoppingDelay * 1000) { lastPlayTime = currentMilliseconds particleService.playParticle(livingEntity.transform, aiAfraidOfWater.particle, pet.getPlayer<Player>()) val escape = pet.getPlayer<Player>().transform.toPosition().subtract(pet.getLocation<Transform<World>>().toPosition()).toVector().normalize() .mul(2.0) pet.setVelocity(Vector3d(escape.x, 1.5, escape.z)) } } } catch (e: Exception) { loggingService.warn("Failed to execute PathfinderAfraidOfWater.", e) } return false } }
apache-2.0
58c08c3772612fa9dde5cccc1adea82b
44.639344
173
0.726913
4.375786
false
false
false
false
thermatk/FastHub-Libre
app/src/main/java/com/fastaccess/ui/modules/main/drawer/MainDrawerFragment.kt
1
3738
package com.fastaccess.ui.modules.main.drawer import android.content.Intent import android.os.Bundle import android.support.design.widget.NavigationView import android.view.MenuItem import android.view.View import com.fastaccess.R import com.fastaccess.data.dao.model.Login import com.fastaccess.helper.PrefGetter import com.fastaccess.ui.base.BaseActivity import com.fastaccess.ui.base.BaseFragment import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.fastaccess.ui.modules.about.FastHubAboutActivity import com.fastaccess.ui.modules.gists.GistsListActivity import com.fastaccess.ui.modules.main.MainActivity import com.fastaccess.ui.modules.main.MainMvp import com.fastaccess.ui.modules.main.playstore.PlayStoreWarningActivity import com.fastaccess.ui.modules.notification.NotificationActivity import com.fastaccess.ui.modules.pinned.PinnedReposActivity import com.fastaccess.ui.modules.repos.issues.create.CreateIssueActivity import com.fastaccess.ui.modules.trending.TrendingActivity import com.fastaccess.ui.modules.user.UserPagerActivity import kotlinx.android.synthetic.main.main_nav_fragment_layout.* /** * Created by Kosh on 25.03.18. */ class MainDrawerFragment : BaseFragment<MainMvp.View, BasePresenter<MainMvp.View>>(), NavigationView.OnNavigationItemSelectedListener { private val userModel by lazy { Login.getUser() } override fun fragmentLayout() = R.layout.main_nav_fragment_layout override fun providePresenter() = BasePresenter<MainMvp.View>() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { mainNav.setNavigationItemSelectedListener(this) } override fun onNavigationItemSelected(item: MenuItem): Boolean { val activity = activity as? BaseActivity<*, *>? ?: return false activity.closeDrawer() if (item.isChecked) return false mainNav.postDelayed({ if (!activity.isFinishing()) { when { item.itemId == R.id.navToRepo -> activity.onNavToRepoClicked() item.itemId == R.id.gists -> GistsListActivity.startActivity(activity) item.itemId == R.id.pinnedMenu -> PinnedReposActivity.startActivity(activity) item.itemId == R.id.mainView -> { if (activity !is MainActivity) { val intent = Intent(activity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP activity.startActivity(intent) activity.finish() } } item.itemId == R.id.profile -> userModel?.let { UserPagerActivity.startActivity(activity, it.login, false, PrefGetter.isEnterprise(), 0) } item.itemId == R.id.settings -> activity.onOpenSettings() item.itemId == R.id.about -> activity.startActivity(Intent(activity, FastHubAboutActivity::class.java)) item.itemId == R.id.orgs -> activity.onOpenOrgsDialog() item.itemId == R.id.notifications -> activity.startActivity(Intent(activity, NotificationActivity::class.java)) item.itemId == R.id.trending -> activity.startActivity(Intent(activity, TrendingActivity::class.java)) item.itemId == R.id.reportBug -> activity.startActivity(CreateIssueActivity.startForResult(activity)) item.itemId == R.id.faq -> activity.startActivity(Intent(activity, PlayStoreWarningActivity::class.java)) } } }, 250) return true } fun getMenu() = mainNav?.menu }
gpl-3.0
c07275dae240992cad503aa2248b612a
48.184211
135
0.674692
4.666667
false
false
false
false
charbgr/CliffHanger
cliffhanger/feature-browser/src/main/kotlin/com/github/charbgr/cliffhanger/feature/browser/BrowserController.kt
1
3098
package com.github.charbgr.cliffhanger.feature.browser import android.content.Context import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.widget.RelativeLayout import android.widget.TextView import com.github.charbgr.cliffhanger.domain.MovieCategory import com.github.charbgr.cliffhanger.shared.views.BackInterceptor import com.github.charbgr.cliffhanger.feature.browser.arch.BrowserPresenter import com.github.charbgr.cliffhanger.feature.browser.arch.BrowserView import com.github.charbgr.cliffhanger.feature.browser.arch.BrowserViewModel import com.github.charbgr.cliffhanger.feature.browser.arch.UiBinder import com.github.charbgr.cliffhanger.feature.browser.arch.state.PartialChange import io.reactivex.Observable import kotlin.properties.Delegates class BrowserController : RelativeLayout, BrowserView, BackInterceptor { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super( context, attrs, defStyleAttr, defStyleRes) companion object { fun inflateWith( movieCategory: MovieCategory, inflater: LayoutInflater, parent: ViewGroup? = null, attachToRoot: Boolean = false ): BrowserController { val controller = inflater.inflate(R.layout.controller_movie_browser, parent, attachToRoot) as BrowserController controller.presenter = BrowserPresenter(movieCategory) return controller } } private var screenTitle: TextView by Delegates.notNull() private set var movieList: RecyclerView by Delegates.notNull() private set private lateinit var presenter: BrowserPresenter private set private val uiBinder: UiBinder = UiBinder( this) override fun onFinishInflate() { super.onFinishInflate() if (isInEditMode) return findViews() uiBinder.onFinishInflate() } override fun onAttachedToWindow() { super.onAttachedToWindow() presenter.init(this) presenter.bindIntents() uiBinder.onAttachedToWindow() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() presenter.destroy() } override fun onBackPressed(): Boolean = false fun viewModel(): BrowserViewModel = presenter.viewModel() fun setScreenTitle(title: CharSequence) { screenTitle.text = title } private fun findViews() { screenTitle = findViewById(R.id.screen_title) movieList = findViewById(R.id.movie_browser_list) } override fun loadDataIntent(): Observable<Any> = uiBinder.loadDataIntent() override fun infiniteScrollIntent(): Observable<Any> = uiBinder.infiniteScrollIntent() override fun render( movieBrowserViewModel: BrowserViewModel, partialChange: PartialChange ) = uiBinder.render(movieBrowserViewModel, partialChange) }
mit
d7ba63ffec3a9a7cc13b15dd13818d0d
31.957447
100
0.76856
4.744257
false
false
false
false
toastkidjp/Jitte
image/src/main/java/jp/toastkid/image/list/ImageViewerFragment.kt
1
7443
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.image.list import android.Manifest import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import jp.toastkid.image.R import jp.toastkid.image.databinding.FragmentImageViewerBinding import jp.toastkid.image.setting.ExcludingSettingFragment import jp.toastkid.lib.ContentScrollable import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.fragment.CommonFragmentAction import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.lib.view.RecyclerViewScroller import jp.toastkid.lib.viewmodel.PageSearcherViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch /** * @author toastkidjp */ class ImageViewerFragment : Fragment(), CommonFragmentAction, ContentScrollable { private lateinit var binding: FragmentImageViewerBinding private lateinit var bucketLoader: BucketLoader private lateinit var imageLoader: ImageLoader private lateinit var preferenceApplier: PreferenceApplier private lateinit var imageLoaderUseCase: ImageLoaderUseCase private lateinit var imageFilterUseCase: ImageFilterUseCase private var adapter: Adapter? = null private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { if (it) { imageLoaderUseCase() return@registerForActivityResult } activity?.let { ViewModelProvider(it).get(ContentViewModel::class.java) .snackShort(R.string.message_audio_file_is_not_found) } activity?.supportFragmentManager?.popBackStack() } private val disposables: Job by lazy { Job() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false) binding.fragment = this setHasOptionsMenu(true) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val context = view.context val contentResolver = context.contentResolver ?: return bucketLoader = BucketLoader(contentResolver) imageLoader = ImageLoader(contentResolver) preferenceApplier = PreferenceApplier(context) val viewModelProvider = ViewModelProvider(this) val viewModel = viewModelProvider.get(ImageViewerFragmentViewModel::class.java) adapter = Adapter(parentFragmentManager, viewModel) val viewLifecycleOwner = viewLifecycleOwner viewModel.onClick.observe(viewLifecycleOwner, { CoroutineScope(Dispatchers.IO).launch(disposables) { imageLoaderUseCase(it) } }) viewModel.onLongClick.observe(viewLifecycleOwner, { preferenceApplier.addExcludeItem(it) imageLoaderUseCase() }) viewModel.refresh.observe(viewLifecycleOwner, { attemptLoad() }) observePageSearcherViewModel() binding.images.adapter = adapter binding.images.layoutManager = GridLayoutManager(context, 2, RecyclerView.VERTICAL, false) imageLoaderUseCase = ImageLoaderUseCase( preferenceApplier, adapter, BucketLoader(contentResolver), imageLoader, this::refreshContent ) imageFilterUseCase = ImageFilterUseCase( preferenceApplier, adapter, imageLoaderUseCase, imageLoader, this::refreshContent ) parentFragmentManager.setFragmentResultListener( "excluding", viewLifecycleOwner, { _, _ -> refreshContent() } ) } private fun observePageSearcherViewModel() { val activity = activity ?: return ViewModelProvider(activity).get(PageSearcherViewModel::class.java) .also { viewModel -> viewModel.find.observe(viewLifecycleOwner, Observer { imageFilterUseCase(it) }) } } override fun pressBack(): Boolean { if (adapter?.isBucketMode() == true) { activity?.supportFragmentManager?.popBackStack() } else { imageLoaderUseCase.clearCurrentBucket() imageLoaderUseCase() } return true } override fun onStart() { super.onStart() attemptLoad() } private fun attemptLoad() { requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } private fun refreshContent() { activity?.runOnUiThread { adapter?.notifyDataSetChanged() RecyclerViewScroller.toTop(binding.images, adapter?.itemCount ?: 0) } } override fun toTop() { RecyclerViewScroller.toTop(binding.images, adapter?.itemCount ?: 0) } override fun toBottom() { RecyclerViewScroller.toBottom(binding.images, adapter?.itemCount ?: 0) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.image_viewer, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.excluding_items_setting -> { val fragment = ExcludingSettingFragment() fragment.show(parentFragmentManager, "setting") } R.id.sort_by_date -> { preferenceApplier.setImageViewerSort(Sort.DATE.name) imageLoaderUseCase() } R.id.sort_by_name -> { preferenceApplier.setImageViewerSort(Sort.NAME.name) imageLoaderUseCase() } R.id.sort_by_count -> { preferenceApplier.setImageViewerSort(Sort.ITEM_COUNT.name) imageLoaderUseCase() } } return super.onOptionsItemSelected(item) } override fun onDetach() { disposables.cancel() parentFragmentManager.clearFragmentResultListener("excluding") requestPermissionLauncher.unregister() super.onDetach() } companion object { @LayoutRes private val LAYOUT_ID = R.layout.fragment_image_viewer } }
epl-1.0
db8f71165738fde1f8a017d2359fe696
31.365217
89
0.665323
5.472794
false
false
false
false
pwoodworth/intellij-community
platform/configuration-store-impl/src/StateStorageManagerImpl.kt
1
10550
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.components.StateStorage.SaveSession import com.intellij.openapi.components.StateStorageChooserEx.Resolution import com.intellij.openapi.components.impl.stores.* import com.intellij.openapi.util.Couple import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PathUtilRt import com.intellij.util.ReflectionUtil import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import gnu.trove.THashMap import org.jdom.Element import org.picocontainer.MutablePicoContainer import org.picocontainer.PicoContainer import java.io.File import java.util.LinkedHashMap import java.util.UUID import java.util.concurrent.locks.ReentrantLock import java.util.regex.Pattern import kotlin.concurrent.withLock import kotlin.reflect.jvm.java abstract class StateStorageManagerImpl(private val pathMacroSubstitutor: TrackingPathMacroSubstitutor, protected val rootTagName: String, parentDisposable: Disposable, private val picoContainer: PicoContainer) : StateStorageManager, Disposable { private val macros = LinkedHashMap<String, String>() private val storageLock = ReentrantLock() private val storages = THashMap<String, StateStorage>() private var streamProvider: StreamProvider? = null init { Disposer.register(parentDisposable, this) } companion object { private val MACRO_PATTERN = Pattern.compile("(\\$[^\\$]*\\$)") } override fun getStreamProvider() = streamProvider override fun setStreamProvider(value: StreamProvider?) { streamProvider = value } override fun getMacroSubstitutor() = pathMacroSubstitutor synchronized override fun addMacro(macro: String, expansion: String) { assert(!macro.isEmpty()) macros.put(macro, expansion) } override fun getStateStorage(storageSpec: Storage): StateStorage { @suppress("USELESS_CAST") val storageClass = storageSpec.storageClass.java as Class<out StateStorage> val key = if (storageClass == javaClass<StateStorage>()) storageSpec.file else storageClass.getName() storageLock.withLock { var stateStorage: StateStorage? = storages.get(key) if (stateStorage == null) { stateStorage = createStateStorage(storageClass, storageSpec.file, storageSpec.roamingType, storageSpec.stateSplitter.java) storages.put(key, stateStorage) } return stateStorage } } override fun getStateStorage(fileSpec: String, roamingType: RoamingType): StateStorage? { storageLock.withLock { var stateStorage: StateStorage? = storages.get(fileSpec) if (stateStorage == null) { stateStorage = createStateStorage(javaClass<StateStorage>(), fileSpec, roamingType, javaClass<StateSplitterEx>()) storages.put(fileSpec, stateStorage) } return stateStorage } } override fun getCachedFileStateStorages(changed: Collection<String>, deleted: Collection<String>) = storageLock.withLock { Couple.of(getCachedFileStorages(changed), getCachedFileStorages(deleted)) } fun getCachedFileStorages(fileSpecs: Collection<String>): Collection<FileBasedStorage> { if (fileSpecs.isEmpty()) { return emptyList() } var result: MutableList<FileBasedStorage>? = null for (fileSpec in fileSpecs) { val storage = storages.get(fileSpec) if (storage is FileBasedStorage) { if (result == null) { result = SmartList<FileBasedStorage>() } result.add(storage) } } return result ?: emptyList<FileBasedStorage>() } override fun getStorageFileNames() = storageLock.withLock { storages.keySet() } // overridden in upsource protected fun createStateStorage(storageClass: Class<out StateStorage>, fileSpec: String, roamingType: RoamingType, SuppressWarnings("deprecation") stateSplitter: Class<out StateSplitter>): StateStorage { if (storageClass != javaClass<StateStorage>()) { val key = UUID.randomUUID().toString() (picoContainer as MutablePicoContainer).registerComponentImplementation(key, storageClass) return picoContainer.getComponentInstance(key) as StateStorage } val filePath = expandMacros(fileSpec) val file = File(filePath) //noinspection deprecation if (stateSplitter != javaClass<StateSplitter>() && stateSplitter != javaClass<StateSplitterEx>()) { return DirectoryBasedStorage(pathMacroSubstitutor, file, ReflectionUtil.newInstance(stateSplitter), this, createStorageTopicListener()) } if (!ApplicationManager.getApplication().isHeadlessEnvironment() && PathUtilRt.getFileName(filePath).lastIndexOf('.') < 0) { throw IllegalArgumentException("Extension is missing for storage file: " + filePath) } val effectiveRoamingType = if (roamingType == RoamingType.PER_USER && fileSpec == StoragePathMacros.WORKSPACE_FILE) RoamingType.DISABLED else roamingType beforeFileBasedStorageCreate() return object : FileBasedStorage(file, fileSpec, effectiveRoamingType, getMacroSubstitutor(fileSpec), rootTagName, this@StateStorageManagerImpl, createStorageTopicListener(), streamProvider) { override fun createStorageData() = [email protected](myFileSpec, getFilePath()) override fun isUseXmlProlog() = [email protected]() } } override fun clearStateStorage(file: String) { storageLock.withLock { storages.remove(file) } } protected open fun createStorageTopicListener(): StateStorage.Listener? = null protected open fun isUseXmlProlog(): Boolean = true protected open fun beforeFileBasedStorageCreate() { } protected open fun getMacroSubstitutor(fileSpec: String): TrackingPathMacroSubstitutor? = pathMacroSubstitutor protected abstract fun createStorageData(fileSpec: String, filePath: String): StorageData synchronized override fun expandMacros(file: String): String { val matcher = MACRO_PATTERN.matcher(file) while (matcher.find()) { val m = matcher.group(1) if (!macros.containsKey(m)) { throw IllegalArgumentException("Unknown macro: " + m + " in storage file spec: " + file) } } var expanded = file for (entry in macros.entrySet()) { expanded = StringUtil.replace(expanded, entry.getKey(), entry.getValue()) } return expanded } override fun collapseMacros(path: String): String { var result = path for (entry in macros.entrySet()) { result = StringUtil.replace(result, entry.getValue(), entry.getKey()) } return result } override fun startExternalization() = StateStorageManagerExternalizationSession(this) open class StateStorageManagerExternalizationSession(protected val storageManager: StateStorageManagerImpl) : StateStorageManager.ExternalizationSession { private val mySessions = LinkedHashMap<StateStorage, StateStorage.ExternalizationSession>() override fun setState(storageSpecs: Array<Storage>, component: Any, componentName: String, state: Any) { val stateStorageChooser = if (component is StateStorageChooserEx) component else null for (storageSpec in storageSpecs) { val resolution = if (stateStorageChooser == null) Resolution.DO else stateStorageChooser.getResolution(storageSpec, StateStorageOperation.WRITE) if (resolution === Resolution.SKIP) { continue } val stateStorage = storageManager.getStateStorage(storageSpec) val session = getExternalizationSession(stateStorage) session?.setState(component, componentName, if (storageSpec.deprecated || resolution === Resolution.CLEAR) Element("empty") else state, storageSpec) } } override fun setStateInOldStorage(component: Any, componentName: String, state: Any) { val stateStorage = storageManager.getOldStorage(component, componentName, StateStorageOperation.WRITE) if (stateStorage != null) { val session = getExternalizationSession(stateStorage) session?.setState(component, componentName, state, null) } } protected fun getExternalizationSession(stateStorage: StateStorage): StateStorage.ExternalizationSession? { var session: StateStorage.ExternalizationSession? = mySessions.get(stateStorage) if (session == null) { session = stateStorage.startExternalization() if (session != null) { mySessions.put(stateStorage, session) } } return session } override fun createSaveSessions(): List<SaveSession> { if (mySessions.isEmpty()) { return emptyList() } var saveSessions: MutableList<SaveSession>? = null val externalizationSessions = mySessions.values() for (session in externalizationSessions) { val saveSession = session.createSaveSession() if (saveSession != null) { if (saveSessions == null) { if (externalizationSessions.size() == 1) { return listOf(saveSession) } saveSessions = SmartList<SaveSession>() } saveSessions.add(saveSession) } } return ContainerUtil.notNullize(saveSessions) } } override fun getOldStorage(component: Any, componentName: String, operation: StateStorageOperation): StateStorage? { val oldStorageSpec = getOldStorageSpec(component, componentName, operation) @suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") return if (oldStorageSpec == null) null else getStateStorage(oldStorageSpec, if (component is com.intellij.openapi.util.RoamingTypeDisabled) RoamingType.DISABLED else RoamingType.PER_USER) } protected abstract fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? override fun dispose() { } }
apache-2.0
80eb290f745dc494c072479586d2e205
39.891473
245
0.738673
5.121359
false
true
false
false
google/horologist
audio-ui/src/main/java/com/google/android/horologist/audio/ui/components/actions/SettingsButton.kt
1
2508
/* * 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.audio.ui.components.actions import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.compose.material.Button import androidx.wear.compose.material.ButtonDefaults.buttonColors import androidx.wear.compose.material.Icon import androidx.wear.compose.material.MaterialTheme import com.google.android.horologist.audio.VolumeState import com.google.android.horologist.audio.ui.ExperimentalHorologistAudioUiApi import com.google.android.horologist.audio.ui.semantics.CustomSemanticsProperties.iconImageVector /** * Button to launch a screen to control the system volume. * * See [VolumeState] */ @OptIn(ExperimentalHorologistAudioUiApi::class) @Composable public fun SettingsButton( onClick: () -> Unit, imageVector: ImageVector, contentDescription: String, modifier: Modifier = Modifier, enabled: Boolean = true, iconSize: Dp = 26.dp, tapTargetSize: Dp = 52.dp ) { Button( modifier = modifier.size(tapTargetSize), onClick = onClick, colors = buttonColors( backgroundColor = Color.Transparent, disabledBackgroundColor = Color.Transparent, contentColor = MaterialTheme.colors.onSurface ), enabled = enabled ) { Icon( imageVector = imageVector, contentDescription = contentDescription, modifier = Modifier .size(iconSize) .align(Alignment.Center) .semantics { iconImageVector = imageVector } ) } }
apache-2.0
de30c26cb85b914e899b5588897ce39e
34.323944
97
0.730861
4.494624
false
false
false
false
devunt/ika
app/src/test/kotlin/org/ozinger/ika/handler/state/UserStateHandlerTests.kt
1
7704
package org.ozinger.ika.handler.state import org.junit.jupiter.api.Test import org.ozinger.ika.AbstractPacketTest import org.ozinger.ika.command.* import org.ozinger.ika.definition.Mode import org.ozinger.ika.definition.ModeChangelist import org.ozinger.ika.definition.Packet import org.ozinger.ika.definition.IRCUser import org.ozinger.ika.enumeration.OperatorType import org.ozinger.ika.state.IRCUsers import strikt.api.expect import strikt.api.expectThat import strikt.assertions.* import java.time.Duration import java.time.LocalDateTime import java.time.ZoneOffset class UserStateHandlerTests : AbstractPacketTest() { private val timestamp = LocalDateTime.now(ZoneOffset.UTC) private fun connectLocalUser1(): IRCUser { assumeAsReceived( Packet( localServerId, UID( userId = localUser1Id, timestamp = timestamp, nickname = "User1", host = "1.1.1.1", displayedHost = "1.1.1.1", ident = "user1", ipAddress = "1.1.1.1", signonAt = timestamp, modeChangelist = ModeChangelist(), realname = "User #1" ) ) ) return IRCUsers[localUser1Id] } private fun connectRemoteUser2(): IRCUser { assumeAsReceived( Packet( remoteServerId, UID( userId = remoteUser2Id, timestamp = timestamp, nickname = "User2", host = "2.2.2.2", displayedHost = "2.2.2.2", ident = "user2", ipAddress = "2.2.2.2", signonAt = timestamp, modeChangelist = ModeChangelist(), realname = "User #2" ) ) ) return IRCUsers[remoteUser2Id] } @Test fun `local user1 connected`() { val expected = IRCUser( id = localUser1Id, timestamp = timestamp, nickname = "User1", host = "1.1.1.1", displayedHost = "1.1.1.1", ident = "user1", ipAddress = "1.1.1.1", signonAt = timestamp, realname = "User #1" ) val actual = connectLocalUser1() expectThat(actual) .isEqualTo(expected) .get(IRCUser::isLocal).isTrue() } @Test fun `remote user2 connected`() { val expected = IRCUser( id = remoteUser2Id, timestamp = timestamp, nickname = "User2", host = "2.2.2.2", displayedHost = "2.2.2.2", ident = "user2", ipAddress = "2.2.2.2", signonAt = timestamp, realname = "User #2" ) val actual = connectRemoteUser2() expectThat(actual) .isEqualTo(expected) .get(IRCUser::isLocal).isFalse() } @Test fun `user1 mask check`() { val user1 = connectLocalUser1() expectThat(user1.mask).isEqualTo("[email protected]") } @Test fun `user1 nickname changed`() { val user1 = connectLocalUser1() assumeAsReceived(Packet(user1.id, NICK("User1-1", timestamp))) expectThat(user1.nickname).isEqualTo("User1-1") } @Test fun `user1 displayedHost changed`() { val user1 = connectLocalUser1() assumeAsReceived(Packet(user1.id, FHOST("1.1.1.2"))) expectThat(user1.displayedHost).isEqualTo("1.1.1.2") } @Test fun `user1 realname changed`() { val user1 = connectLocalUser1() assumeAsReceived(Packet(user1.id, FNAME("User #1-1"))) expectThat(user1.realname).isEqualTo("User #1-1") } @Test fun `user1 metadata changed`() { val user1 = connectLocalUser1() assumeAsReceived(Packet(remoteServerId, METADATA(user1.id, "accountname", "user_1"))) expectThat(user1.metadata) .hasSize(1) .hasEntry("accountname", "user_1") assumeAsReceived(Packet(remoteServerId, METADATA(user1.id, "accountname"))) expectThat(user1.metadata).isEmpty() } @Test fun `user1 away status changed`() { val user1 = connectLocalUser1() assumeAsReceived(Packet(user1.id, AWAY("auto-away"))) expectThat(user1) { get(IRCUser::isOnAway).isTrue() get(IRCUser::awayReason).isEqualTo("auto-away") } assumeAsReceived(Packet(user1.id, AWAY())) expectThat(user1.isOnAway).isFalse() } @Test fun `user1 operator authenticated`() { val user1 = connectLocalUser1() expectThat(user1) { get(IRCUser::isOperator).isFalse() get(IRCUser::modes).doesNotContain(Mode('o')) } assumeAsReceived(Packet(user1.id, OPERTYPE(OperatorType.NETADMIN))) expectThat(user1) { get(IRCUser::isOperator).isTrue() get(IRCUser::modes).containsExactly(Mode('o')) } } @Test fun `user1 changed itself's mode`() { val user1 = connectLocalUser1() expectThat(user1.modes).isEmpty() assumeAsReceived(Packet(user1.id, MODE(user1.id, ModeChangelist(adding = setOf(Mode('x')))))) expectThat(user1.modes) .hasSize(1) .elementAt(0) .isEqualTo(Mode('x')) } @Test fun `user1 changed user2's mode`() { val user1 = connectLocalUser1() val user2 = connectRemoteUser2() expectThat(user2.modes).isEmpty() assumeAsReceived(Packet(user1.id, MODE(user2.id, ModeChangelist(adding = setOf(Mode('x')))))) expectThat(user2.modes) .hasSize(1) .elementAt(0) .isEqualTo(Mode('x')) } @Test fun `server changed user1's mode`() { val user1 = connectLocalUser1() expectThat(user1.modes).isEmpty() assumeAsReceived( Packet( remoteServerId, FMODE(user1.id, timestamp, ModeChangelist(adding = setOf(Mode('x')))) ) ) expectThat(user1.modes) .hasSize(1) .elementAt(0) .isEqualTo(Mode('x')) } @Test fun `nickname change requested`() { val user1 = connectLocalUser1() assumeAsReceived(Packet(remoteServerId, SVSNICK(user1.id, "user1-svsnick", timestamp))) { expectThat(it) .hasSize(1) .first() .isEqualTo(Packet(user1.id, NICK(user1.nickname, user1.timestamp))) } } @Test fun `user2 requested user1's idle time`() { val user1 = connectLocalUser1() val user2 = connectRemoteUser2() assumeAsReceived(Packet(user2.id, IDLE(user1.id))) { expectThat(it) .hasSize(1) .first() .isEqualTo(Packet(user1.id, IDLE(user2.id, user1.signonAt, Duration.ZERO))) } } @Test fun `user1 quitted`() { val user1 = connectLocalUser1() expectThat(user1.id in IRCUsers).isTrue() assumeAsReceived(Packet(user1.id, QUIT())) expectThat(user1.id in IRCUsers).isFalse() } @Test fun `server net-splitted`() { val user1 = connectLocalUser1() val user2 = connectRemoteUser2() assumeAsReceived(Packet(remoteServerId, SQUIT(remoteServerId, ""))) expect { that(user1.id in IRCUsers).isTrue() that(user2.id in IRCUsers).isFalse() } } }
agpl-3.0
7de592d0d7d965054c1853c44fa69e0c
28.181818
101
0.551661
4.025078
false
true
false
false
canou/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ColorPickerDialog.kt
1
6711
package com.simplemobiletools.commons.dialogs import android.content.Context import android.graphics.Color import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.support.v7.app.AlertDialog import android.text.Editable import android.text.TextWatcher import android.view.* import android.view.View.OnTouchListener import android.widget.EditText import android.widget.ImageView import com.simplemobiletools.commons.R import com.simplemobiletools.commons.extensions.baseConfig import com.simplemobiletools.commons.extensions.setBackgroundWithStroke import com.simplemobiletools.commons.extensions.setupDialogStuff import com.simplemobiletools.commons.views.ColorPickerSquare import kotlinx.android.synthetic.main.dialog_color_picker.view.* // forked from https://github.com/yukuku/ambilwarna class ColorPickerDialog(val context: Context, color: Int, val callback: (color: Int) -> Unit) { lateinit var viewHue: View lateinit var viewSatVal: ColorPickerSquare lateinit var viewCursor: ImageView lateinit var viewNewColor: ImageView lateinit var viewTarget: ImageView lateinit var newHexField: EditText lateinit var viewContainer: ViewGroup val currentColorHsv = FloatArray(3) val backgroundColor: Int = context.baseConfig.backgroundColor init { Color.colorToHSV(color, currentColorHsv) val view = LayoutInflater.from(context).inflate(R.layout.dialog_color_picker, null).apply { viewHue = color_picker_hue viewSatVal = color_picker_square viewCursor = color_picker_hue_cursor viewNewColor = color_picker_new_color viewTarget = color_picker_cursor viewContainer = color_picker_holder newHexField = color_picker_new_hex viewSatVal.setHue(getHue()) viewNewColor.setBackgroundWithStroke(getColor(), backgroundColor) color_picker_old_color.setBackgroundWithStroke(color, backgroundColor) val hexCode = getHexCode(color) color_picker_old_hex.text = "#$hexCode" newHexField.setText(hexCode) } viewHue.setOnTouchListener(OnTouchListener { v, event -> if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) { var y = event.y if (y < 0f) y = 0f if (y > viewHue.measuredHeight) { y = viewHue.measuredHeight - 0.001f // to avoid jumping the cursor from bottom to top. } var hue = 360f - 360f / viewHue.measuredHeight * y if (hue == 360f) hue = 0f currentColorHsv[0] = hue newHexField.setText(getHexCode(getColor())) updateHue() return@OnTouchListener true } false }) viewSatVal.setOnTouchListener(OnTouchListener { v, event -> if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) { var x = event.x var y = event.y if (x < 0f) x = 0f if (x > viewSatVal.measuredWidth) x = viewSatVal.measuredWidth.toFloat() if (y < 0f) y = 0f if (y > viewSatVal.measuredHeight) y = viewSatVal.measuredHeight.toFloat() currentColorHsv[1] = 1f / viewSatVal.measuredWidth * x currentColorHsv[2] = 1f - 1f / viewSatVal.measuredHeight * y moveColorPicker() viewNewColor.setBackgroundWithStroke(getColor(), backgroundColor) newHexField.setText(getHexCode(getColor())) return@OnTouchListener true } false }) newHexField.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if ((count == 1 && s.length == 6) || (count == 6 && before == 0)) { val newColor = Color.parseColor("#$s") Color.colorToHSV(newColor, currentColorHsv) updateHue() moveColorPicker() } } }) val textColor = context.baseConfig.textColor AlertDialog.Builder(context) .setPositiveButton(R.string.ok, { dialog, which -> callback.invoke(getColor()) }) .setNegativeButton(R.string.cancel, null) .create().apply { context.setupDialogStuff(view, this) view.color_picker_arrow.colorFilter = PorterDuffColorFilter(textColor, PorterDuff.Mode.SRC_IN) view.color_picker_hex_arrow.colorFilter = PorterDuffColorFilter(textColor, PorterDuff.Mode.SRC_IN) viewCursor.colorFilter = PorterDuffColorFilter(textColor, PorterDuff.Mode.SRC_IN) } view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { moveHuePicker() moveColorPicker() view.viewTreeObserver.removeGlobalOnLayoutListener(this) } }) } private fun getHexCode(color: Int) = Integer.toHexString(color).substring(2).toUpperCase() private fun updateHue() { viewSatVal.setHue(getHue()) moveHuePicker() viewNewColor.setBackgroundWithStroke(getColor(), backgroundColor) } private fun moveHuePicker() { var y = viewHue.measuredHeight - getHue() * viewHue.measuredHeight / 360f if (y == viewHue.measuredHeight.toFloat()) y = 0f viewCursor.x = (viewHue.left - viewCursor.width).toFloat() viewCursor.y = viewHue.top + y - viewCursor.height / 2 } private fun moveColorPicker() { val x = getSat() * viewSatVal.measuredWidth val y = (1f - getVal()) * viewSatVal.measuredHeight viewTarget.x = viewSatVal.left + x - viewTarget.width / 2 viewTarget.y = viewSatVal.top + y - viewTarget.height / 2 } private fun getColor() = Color.HSVToColor(currentColorHsv) private fun getHue() = currentColorHsv[0] private fun getSat() = currentColorHsv[1] private fun getVal() = currentColorHsv[2] }
apache-2.0
ef1d2baa8314bc9814a0e9b518a1accf
39.427711
142
0.624497
4.683182
false
false
false
false
actions-on-google/actions-on-google-java
src/main/kotlin/com/google/actions/api/impl/DialogflowResponse.kt
1
2640
/* * Copyright 2018 Google Inc. All Rights Reserved. * * 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.actions.api.impl import com.google.actions.api.ActionContext import com.google.actions.api.ActionResponse import com.google.actions.api.SessionEntityType import com.google.actions.api.impl.io.ResponseSerializer import com.google.actions.api.response.ResponseBuilder import com.google.api.services.actions_fulfillment.v2.model.AppResponse import com.google.api.services.actions_fulfillment.v2.model.ExpectedIntent import com.google.api.services.actions_fulfillment.v2.model.RichResponse import com.google.api.services.dialogflow_fulfillment.v2.model.WebhookResponse internal class DialogflowResponse internal constructor( responseBuilder: ResponseBuilder) : ActionResponse { override val webhookResponse: WebhookResponse override val appResponse: AppResponse? = null override val expectUserResponse: Boolean? get() = googlePayload?.expectUserResponse internal var conversationData: MutableMap<String, Any>? = null internal var googlePayload: AogResponse? = null internal var contexts: MutableList<ActionContext>? = ArrayList() internal var sessionEntityTypes: MutableList<SessionEntityType>? = ArrayList() internal var sessionId: String? = null init { conversationData = responseBuilder.conversationData sessionId = responseBuilder.sessionId if (responseBuilder.webhookResponse != null) { webhookResponse = responseBuilder.webhookResponse!! } else { webhookResponse = WebhookResponse() } if (webhookResponse.fulfillmentText == null) { webhookResponse.fulfillmentText = responseBuilder.fulfillmentText } googlePayload = responseBuilder.buildAogResponse() } override val richResponse: RichResponse? get() = googlePayload?.richResponse override val helperIntent: ExpectedIntent? get() = googlePayload?.helperIntent override fun toJson(): String { return ResponseSerializer(sessionId).toJsonV2(this) } }
apache-2.0
7ec5d9ab428cf4bca48653e09ce2d2d5
39.615385
82
0.747727
4.591304
false
false
false
false
tatsuyuki25/AsyncTask
src/main/kotlin/tatsuyuki/asynctask/Async.kt
1
2472
package tatsuyuki.asynctask import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.thread /** * C# style async & await * @author tatsuyuki * @since 1.2.1 * @see async * @see await */ class Task<T> { private val LOCK: Lock = ReentrantLock() private var result: ((T?) -> Unit)? = null private var e: Exception? = null private var data: T? = null private val isSendResult: AtomicBoolean = AtomicBoolean(false) /** * Set callback, run callback on new thread * @param result the callback */ fun result(result: ((T?) -> Unit)) { this.result = result if ((e != null || data != null) && !isSendResult.get()) { isSendResult.set(true) thread { result(data) } } } /** * run method on async * @param body method body * @return Task<T>, using task.result{} set callback * @see await */ fun async(body: () -> T): Task<T> { thread { LOCK.lock() try { data = body() } catch(e: Exception) { this.e = e } finally { LOCK.unlock() } if (!isSendResult.get() && result != null) { isSendResult.set(true) result!!(data) } } return this } /** * Async method to block * @return async method return value, return on call await thread * @see async */ fun await(): T? { var result: T? = null var isGetResult = false this.result { result = it isGetResult = true } while (!isGetResult) { Thread.sleep(1) } this.LOCK.lock() this.LOCK.unlock() if (this.e != null) { throw Exception(this.e) } return result } } /** * run method on async * @param body method body * @return Task<T>, using task.result{} set callback * @see await */ fun <T> async(body: () -> T): Task<T> { val task: Task<T> = Task() return task.async(body) } /** * Async method to block * @param body async method * @return async method return value, return on call await thread * @see async */ fun <T> await(body: () -> Task<T>): T? { var task = body() return task.await() }
apache-2.0
369bf1b522a19bfac4cefe72ccd33665
21.888889
69
0.523867
3.880691
false
false
false
false